Compare commits

..

14 Commits

Author SHA1 Message Date
Zane Schepke 8e6a9bb309 fix: remove old nightly versions (#295) 2024-07-31 00:00:14 -04:00
Zane Schepke 594834a908 fix: tasker launch of shortcuts (#290) 2024-07-29 17:14:08 -04:00
Zane Schepke a5e9aa83b8 feat: check for always-on VPN (#289) 2024-07-28 22:21:32 -04:00
Languages add-on 5a77661fb3 Added translation using Weblate (Ukrainian) 2024-07-28 15:37:44 -04:00
Luiz Fellipe Carneiro ee5d3ea6a9 Translated using Weblate (Portuguese)
Currently translated at 18.5% (5 of 27 strings)

Translation: WG Tunnel/fastlane
Translate-URL: https://hosted.weblate.org/projects/wg-tunnel/fastlane/pt/
2024-07-28 15:37:06 -04:00
Languages add-on f6da0fe31b Added translation using Weblate (Portuguese) 2024-07-28 15:37:06 -04:00
Zane Schepke 80a02382e1 ci: add basic ci (#287)
- add ktlint
2024-07-28 14:49:35 -04:00
Zane Schepke b9a8400453 fix: app lock bypass (#286) 2024-07-28 14:24:22 -04:00
Zane Schepke 3a17d2855b fix: fastlane deploy (#285) 2024-07-28 14:05:15 -04:00
Zane Schepke 086b48c79d fix: signing config bug 2024-07-28 12:18:17 -04:00
Zane Schepke 1f561fbf38 Fix/app signature (#284) 2024-07-28 12:11:16 -04:00
Zane Schepke 45e63e9910 fix versioning (#280) 2024-07-28 03:27:12 -04:00
Zane Schepke 66e89c83e2 chore: fmt 2024-07-28 02:17:01 -04:00
Zane Schepke 470fa0191b fix: signing issue (#279) 2024-07-28 02:13:18 -04:00
128 changed files with 8257 additions and 7741 deletions
+22 -10
View File
@@ -1,8 +1,14 @@
[{*.kt,*.kts}]
indent_style = space
insert_final_newline = true
max_line_length = 100
root = true
[*]
charset = utf-8
indent_size = 4
indent_style = tab
max_line_length = 150
trim_trailing_whitespace = true
insert_final_newline = true
[{*.kt,*.kts}]
ij_continuation_indent_size = 4
ij_java_names_count_to_use_import_on_demand = 9999
ij_kotlin_align_in_columns_case_branch = false
@@ -11,8 +17,6 @@ ij_kotlin_align_multiline_extends_list = false
ij_kotlin_align_multiline_method_parentheses = false
ij_kotlin_align_multiline_parameters = true
ij_kotlin_align_multiline_parameters_in_calls = false
ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true
ij_kotlin_assignment_wrap = normal
ij_kotlin_blank_lines_after_class_header = 0
ij_kotlin_blank_lines_around_block_when_branches = 0
@@ -20,10 +24,7 @@ ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_
ij_kotlin_block_comment_at_first_column = true
ij_kotlin_call_parameters_new_line_after_left_paren = true
ij_kotlin_call_parameters_right_paren_on_new_line = false
ij_kotlin_call_parameters_wrap = on_every_item
ij_kotlin_catch_on_new_line = false
ij_kotlin_class_annotation_wrap = split_into_lines
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
ij_kotlin_continuation_indent_for_chained_calls = true
ij_kotlin_continuation_indent_for_expression_bodies = true
ij_kotlin_continuation_indent_in_argument_lists = true
@@ -52,7 +53,6 @@ ij_kotlin_method_annotation_wrap = split_into_lines
ij_kotlin_method_call_chain_wrap = normal
ij_kotlin_method_parameters_new_line_after_left_paren = true
ij_kotlin_method_parameters_right_paren_on_new_line = true
ij_kotlin_method_parameters_wrap = on_every_item
ij_kotlin_name_count_to_use_star_import = 9999
ij_kotlin_name_count_to_use_star_import_for_members = 9999
ij_kotlin_parameter_annotation_wrap = off
@@ -83,3 +83,15 @@ ij_kotlin_while_on_new_line = false
ij_kotlin_wrap_elvis_expressions = 1
ij_kotlin_wrap_expression_body_functions = 1
ij_kotlin_wrap_first_method_in_call_chain = false
#compose
ktlint_standard_filename = disabled
ktlint_standard_no-wildcard-imports = disabled
ktlint_standard_function-naming = disabled
ktlint_standard_property-naming = disabled
ktlint_standard_package-naming = disabled
ktlint_function_naming_ignore_when_annotated_with = Composable
ktlint_code_style = android_studio
ktlint_standard_import-ordering = disabled
ktlint_standard_package-naming = disabled
ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true
+23
View File
@@ -0,0 +1,23 @@
name: ci-android
on:
workflow_dispatch:
pull_request:
jobs:
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Run ktlint
run: ./gradlew ktlintCheck
+44 -19
View File
@@ -86,9 +86,12 @@ jobs:
# Build and sign APK ("-x test" argument is used to skip tests)
# add fdroid flavor for apk upload
- name: Build Fdroid Release APK
if: ${{ inputs.release_type != '' && inputs.release_type != 'nightly' }}
if: ${{ inputs.release_type != '' && inputs.release_type == 'release' }}
run: ./gradlew :app:assembleFdroidRelease -x test
- name: Build Fdroid Prerelease APK
if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }}
run: ./gradlew :app:assembleFdroidPrerelease -x test
- name: Build Fdroid Nightly APK
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
@@ -96,11 +99,13 @@ jobs:
- if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/nightly/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
- if: ${{ inputs.release_type != '' && inputs.release_type != 'nightly' }}
- if: ${{ inputs.release_type != '' && inputs.release_type == 'release' }}
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
- if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }}
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/prerelease/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
- name: Get version code
if: ${{ inputs.release_type == 'release' || inputs.release_type == 'prerelease' }}
if: ${{ inputs.release_type == 'release' }}
run: |
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
@@ -125,32 +130,32 @@ jobs:
repository: zaneschepke/fdroid
event-type: fdroid-update
- name: Set version release notes
if: ${{ inputs.release_type == 'release' || inputs.release_type == 'prerelease' }}
run: |
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
echo "$RELEASE_NOTES" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
- name: On nightly release
if: ${{ contains(env.TAG_NAME, 'nightly') }}
run: |
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
gh release delete nightly --yes || true
# Setup TAG_NAME, which is used as a general "name"
- if: github.event_name == 'workflow_dispatch'
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
- if: github.event_name == 'schedule'
run: echo "TAG_NAME=nightly" >> $GITHUB_ENV
- name: On nightly release
- name: Set version release notes
if: ${{ inputs.release_type == 'release' }}
run: |
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
echo "$RELEASE_NOTES" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
- name: On nightly release notes
if: ${{ contains(env.TAG_NAME, 'nightly') }}
run: |
echo "RELEASE_NOTES=Nightly build of the latest development version of the android client." >> $GITHUB_ENV
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
gh release delete nightly --yes || true
- name: On prerelease release notes
if: ${{ inputs.release_type == 'prerelease' }}
run: |
echo "RELEASE_NOTES=Testing version of app for specific feature." >> $GITHUB_ENV
gh release delete ${{ github.event.inputs.tag_name }} --yes || true
- name: Get checksum
id: checksum
run: echo "checksum=$(apksigner verify -print-certs ${{ env.APK_PATH }} | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT
@@ -200,6 +205,26 @@ jobs:
- name: Grant execute permission for gradlew
run: chmod +x gradlew
# Here we need to decode keystore.jks from base64 string and place it
# in the folder specified in the release signing configuration
- name: Decode Keystore
id: decode_keystore
uses: timheuer/base64-to-file@v1.2
with:
fileName: ${{ env.KEY_STORE_FILE }}
fileDir: ${{ env.KEY_STORE_LOCATION }}
encodedString: ${{ secrets.KEYSTORE }}
# create keystore path for gradle to read
- name: Create keystore path env var
run: |
store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }}
echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV
- name: Create service_account.json
id: createServiceAccount
run: echo '${{ secrets.SERVICE_ACCOUNT_JSON }}' > service_account.json
- name: Deploy with fastlane
uses: ruby/setup-ruby@v1
with:
+36 -21
View File
@@ -11,7 +11,6 @@ plugins {
android {
namespace = Constants.APP_ID
compileSdk = Constants.TARGET_SDK
compileSdkPreview = "VanillaIceCream"
androidResources {
generateLocaleConfig = true
@@ -21,8 +20,8 @@ android {
applicationId = Constants.APP_ID
minSdk = Constants.MIN_SDK
targetSdk = Constants.TARGET_SDK
versionCode = Constants.VERSION_CODE
versionName = Constants.VERSION_NAME
versionCode = determineVersionCode()
versionName = determineVersionName()
ksp { arg("room.schemaLocation", "$projectDir/schemas") }
@@ -49,16 +48,6 @@ android {
listOf("libwg-go.so", "libwg-quick.so", "libwg.so"),
)
applicationVariants.all {
val variant = this
variant.outputs
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
.forEach { output ->
val outputFileName =
"${Constants.APP_NAME}-${variant.flavorName}-${variant.buildType.name}-${variant.versionName}.apk"
output.outputFileName = outputFileName
}
}
release {
isDebuggable = false
isMinifyEnabled = true
@@ -71,10 +60,24 @@ android {
}
debug { isDebuggable = true }
create(Constants.PRERELEASE) {
initWith(buildTypes.getByName(Constants.RELEASE))
}
create(Constants.NIGHTLY) {
initWith(getByName("release"))
defaultConfig.versionName = nightlyVersionName()
defaultConfig.versionCode = nightlyVersionCode()
initWith(buildTypes.getByName(Constants.RELEASE))
}
applicationVariants.all {
val variant = this
variant.outputs
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
.forEach { output ->
val outputFileName =
"${Constants.APP_NAME}-${variant.flavorName}-" +
"${variant.buildType.name}-${variant.versionName}.apk"
output.outputFileName = outputFileName
}
}
}
flavorDimensions.add(Constants.TYPE)
@@ -138,7 +141,6 @@ dependencies {
// logging
implementation(libs.timber)
// compose navigation
implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.hilt.navigation.compose)
@@ -185,10 +187,23 @@ dependencies {
implementation(libs.androidx.core.splashscreen)
}
fun nightlyVersionCode() : Int {
return Constants.VERSION_CODE + Constants.NIGHTLY_CODE
fun determineVersionCode(): Int {
return with(getBuildTaskName().lowercase()) {
when {
contains(Constants.NIGHTLY) -> Constants.VERSION_CODE + Constants.NIGHTLY_CODE
contains(Constants.PRERELEASE) -> Constants.VERSION_CODE + Constants.PRERELEASE_CODE
else -> Constants.VERSION_CODE
}
}
}
fun nightlyVersionName() : String {
return Constants.VERSION_NAME + "-${grgitService.service.get().grgit.head().abbreviatedId}"
fun determineVersionName(): String {
return with(getBuildTaskName().lowercase()) {
when {
contains(Constants.NIGHTLY) || contains(Constants.PRERELEASE) ->
Constants.VERSION_NAME +
"-${grgitService.service.get().grgit.head().abbreviatedId}"
else -> Constants.VERSION_NAME
}
}
}
+5 -4
View File
@@ -71,7 +71,7 @@
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
@@ -81,19 +81,20 @@
android:name=".ui.MainActivity"
android:exported="true"
android:theme="@style/Theme.WireguardAutoTunnel">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
</intent-filter>
</activity>
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="screenOrientation" />
<activity
android:name=".service.shortcut.ShortcutsActivity"
android:enabled="true"
android:exported="true"
android:noHistory="true"
android:excludeFromRecents="true"
android:finishOnTaskLaunch="true"
android:launchMode="singleInstance"
android:theme="@android:style/Theme.NoDisplay" />
<service
@@ -14,7 +14,6 @@ import timber.log.Timber
@HiltAndroidApp
class WireGuardAutoTunnel : Application() {
override fun onCreate() {
super.onCreate()
instance = this
@@ -28,11 +27,12 @@ class WireGuardAutoTunnel : Application() {
.penaltyLog()
.build(),
)
} else Timber.plant(ReleaseTree())
} else {
Timber.plant(ReleaseTree())
}
}
companion object {
lateinit var instance: WireGuardAutoTunnel
private set
@@ -19,7 +19,7 @@ import java.io.IOException
class DataStoreManager(
private val context: Context,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) {
companion object {
val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
@@ -60,7 +60,6 @@ class DataStoreManager(
}
}
fun <T> getFromStoreFlow(key: Preferences.Key<T>) = context.dataStore.data.map { it[key] }
suspend fun <T> getFromStore(key: Preferences.Key<T>): T? {
@@ -74,7 +73,6 @@ class DataStoreManager(
}
}
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking {
context.dataStore.data.map { it[key] }.first()
}
@@ -5,7 +5,7 @@ data class GeneralState(
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
val isTunnelRunningFromManualStart: Boolean = TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
val activeTunnelId: Int? = null
val activeTunnelId: Int? = null,
) {
companion object {
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
@@ -4,6 +4,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
interface AppDataRepository {
suspend fun getPrimaryOrFirstTunnel(): TunnelConfig?
suspend fun getStartTunnelConfig(): TunnelConfig?
suspend fun toggleWatcherServicePause()
@@ -3,10 +3,12 @@ package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
import javax.inject.Inject
class AppDataRoomRepository @Inject constructor(
class AppDataRoomRepository
@Inject
constructor(
override val settings: SettingsRepository,
override val tunnels: TunnelConfigRepository,
override val appState: AppStateRepository
override val appState: AppStateRepository,
) : AppDataRepository {
override suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? {
return tunnels.findPrimary().firstOrNull() ?: tunnels.getAll().firstOrNull()
@@ -17,7 +19,9 @@ class AppDataRoomRepository @Inject constructor(
appState.getActiveTunnelId()?.let {
tunnels.getById(it)
}
} else null
} else {
null
}
}
override suspend fun toggleWatcherServicePause() {
@@ -5,15 +5,19 @@ import kotlinx.coroutines.flow.Flow
interface AppStateRepository {
suspend fun isLocationDisclosureShown(): Boolean
suspend fun setLocationDisclosureShown(shown: Boolean)
suspend fun isPinLockEnabled(): Boolean
suspend fun setPinLockEnabled(enabled: Boolean)
suspend fun isBatteryOptimizationDisableShown(): Boolean
suspend fun setBatteryOptimizationDisableShown(shown: Boolean)
suspend fun isTunnelRunningFromManualStart(): Boolean
suspend fun setTunnelRunningFromManualStart(id: Int)
suspend fun setManualStop()
@@ -25,5 +29,4 @@ interface AppStateRepository {
suspend fun setCurrentSsid(ssid: String)
val generalStateFlow: Flow<GeneralState>
}
@@ -74,13 +74,17 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
prefs?.let { pref ->
try {
GeneralState(
isLocationDisclosureShown = pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
isLocationDisclosureShown =
pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
isBatteryOptimizationDisableShown = pref[DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN]
isBatteryOptimizationDisableShown =
pref[DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN]
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
isTunnelRunningFromManualStart = pref[DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START]
isTunnelRunningFromManualStart =
pref[DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START]
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
isPinLockEnabled = pref[DataStoreManager.IS_PIN_LOCK_ENABLED]
isPinLockEnabled =
pref[DataStoreManager.IS_PIN_LOCK_ENABLED]
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
)
} catch (e: IllegalArgumentException) {
@@ -5,7 +5,6 @@ import com.zaneschepke.wireguardautotunnel.data.domain.Settings
import kotlinx.coroutines.flow.Flow
class RoomSettingsRepository(private val settingsDoa: SettingsDao) : SettingsRepository {
override suspend fun save(settings: Settings) {
settingsDoa.save(settings)
}
@@ -28,7 +28,6 @@ class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
),
)
}
}
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
@@ -5,7 +5,6 @@ import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
import kotlinx.coroutines.flow.Flow
interface TunnelConfigRepository {
fun getTunnelConfigsFlow(): Flow<TunnelConfigs>
suspend fun getAll(): TunnelConfigs
@@ -2,7 +2,7 @@ package com.zaneschepke.wireguardautotunnel.module
import android.content.Context
import com.zaneschepke.logcatter.LocalLogCollector
import com.zaneschepke.logcatter.LogcatHelper
import com.zaneschepke.logcatter.LogcatUtil
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
@@ -25,6 +25,6 @@ class AppModule {
@Singleton
@Provides
fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector {
return LogcatHelper.init(context = context)
return LogcatUtil.init(context = context)
}
}
@@ -66,10 +66,7 @@ class RepositoryModule {
@Singleton
@Provides
fun providePreferencesDataStore(
@ApplicationContext context: Context,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): DataStoreManager {
fun providePreferencesDataStore(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): DataStoreManager {
return DataStoreManager(context, ioDispatcher)
}
@@ -84,10 +81,8 @@ class RepositoryModule {
fun provideAppDataRepository(
settingsRepository: SettingsRepository,
tunnelConfigRepository: TunnelConfigRepository,
appStateRepository: AppStateRepository
appStateRepository: AppStateRepository,
): AppDataRepository {
return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository)
}
}
@@ -17,9 +17,7 @@ import dagger.hilt.android.scopes.ServiceScoped
abstract class ServiceModule {
@Binds
@ServiceScoped
abstract fun provideNotificationService(
wireGuardNotification: WireGuardNotification
): NotificationService
abstract fun provideNotificationService(wireGuardNotification: WireGuardNotification): NotificationService
@Binds
@ServiceScoped
@@ -27,13 +25,9 @@ abstract class ServiceModule {
@Binds
@ServiceScoped
abstract fun provideMobileDataService(
mobileDataService: MobileDataService
): NetworkService<MobileDataService>
abstract fun provideMobileDataService(mobileDataService: MobileDataService): NetworkService<MobileDataService>
@Binds
@ServiceScoped
abstract fun provideEthernetService(
ethernetService: EthernetService
): NetworkService<EthernetService>
abstract fun provideEthernetService(ethernetService: EthernetService): NetworkService<EthernetService>
}
@@ -57,7 +57,7 @@ class TunnelModule {
@Kernel kernelBackend: Provider<Backend>,
appDataRepository: AppDataRepository,
@ApplicationScope applicationScope: CoroutineScope,
@IoDispatcher ioDispatcher: CoroutineDispatcher
@IoDispatcher ioDispatcher: CoroutineDispatcher,
): VpnService {
return WireGuardTunnel(
amneziaBackend,
@@ -71,10 +71,7 @@ class TunnelModule {
@Provides
@Singleton
fun provideServiceManager(
appDataRepository: AppDataRepository,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): ServiceManager {
fun provideServiceManager(appDataRepository: AppDataRepository, @IoDispatcher ioDispatcher: CoroutineDispatcher): ServiceManager {
return ServiceManager(appDataRepository, ioDispatcher)
}
}
@@ -13,13 +13,9 @@ import kotlinx.coroutines.CoroutineDispatcher
@Module
@InstallIn(ViewModelComponent::class)
class ViewModelModule {
@ViewModelScoped
@Provides
fun provideFileUtils(
@ApplicationContext context: Context,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): FileUtils {
fun provideFileUtils(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): FileUtils {
return FileUtils(context, ioDispatcher)
}
}
@@ -14,7 +14,6 @@ import javax.inject.Inject
@AndroidEntryPoint
class BootReceiver : BroadcastReceiver() {
@Inject
lateinit var appDataRepository: AppDataRepository
@@ -4,5 +4,5 @@ enum class Action {
START,
START_FOREGROUND,
STOP,
STOP_FOREGROUND
STOP_FOREGROUND,
}
@@ -23,7 +23,8 @@ open class ForegroundService : LifecycleService() {
val action = intent.action
when (action) {
Action.START.name,
Action.START_FOREGROUND.name -> startService(intent.extras)
Action.START_FOREGROUND.name,
-> startService(intent.extras)
Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService()
Constants.ALWAYS_ON_VPN_ACTION -> {
@@ -12,15 +12,9 @@ import timber.log.Timber
class ServiceManager(
private val appDataRepository: AppDataRepository,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
) {
private fun <T : Service> actionOnService(
action: Action,
context: Context,
cls: Class<T>,
extras: Map<String, Int>? = null
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) {
private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) {
val intent =
Intent(context, cls).also {
it.action = action.name
@@ -29,7 +23,8 @@ class ServiceManager(
intent.component?.javaClass
try {
when (action) {
Action.START_FOREGROUND, Action.STOP_FOREGROUND -> context.startForegroundService(
Action.START_FOREGROUND, Action.STOP_FOREGROUND ->
context.startForegroundService(
intent,
)
@@ -40,11 +35,7 @@ class ServiceManager(
}
}
suspend fun startVpnService(
context: Context,
tunnelId: Int? = null,
isManualStart: Boolean = false
) {
suspend fun startVpnService(context: Context, tunnelId: Int? = null, isManualStart: Boolean = false) {
if (isManualStart) onManualStart(tunnelId)
actionOnService(
Action.START,
@@ -88,11 +79,7 @@ class ServiceManager(
}
}
suspend fun startVpnServiceForeground(
context: Context,
tunnelId: Int? = null,
isManualStart: Boolean = false
) {
suspend fun startVpnServiceForeground(context: Context, tunnelId: Int? = null, isManualStart: Boolean = false) {
withContext(ioDispatcher) {
if (isManualStart) onManualStart(tunnelId)
actionOnService(
@@ -104,9 +91,7 @@ class ServiceManager(
}
}
fun startWatcherServiceForeground(
context: Context,
) {
fun startWatcherServiceForeground(context: Context) {
actionOnService(
Action.START_FOREGROUND,
context,
@@ -7,50 +7,67 @@ data class WatcherState(
val isEthernetConnected: Boolean = false,
val isMobileDataConnected: Boolean = false,
val currentNetworkSSID: String = "",
val settings: Settings = Settings()
val settings: Settings = Settings(),
) {
fun isEthernetConditionMet(): Boolean {
return (isEthernetConnected &&
settings.isTunnelOnEthernetEnabled)
return (
isEthernetConnected &&
settings.isTunnelOnEthernetEnabled
)
}
fun isMobileDataConditionMet(): Boolean {
return (!isEthernetConnected &&
return (
!isEthernetConnected &&
settings.isTunnelOnMobileDataEnabled &&
!isWifiConnected &&
isMobileDataConnected)
isMobileDataConnected
)
}
fun isTunnelOffOnMobileDataConditionMet(): Boolean {
return (!isEthernetConnected &&
return (
!isEthernetConnected &&
!settings.isTunnelOnMobileDataEnabled &&
isMobileDataConnected &&
!isWifiConnected)
!isWifiConnected
)
}
fun isUntrustedWifiConditionMet(): Boolean {
return (!isEthernetConnected &&
return (
!isEthernetConnected &&
isWifiConnected &&
!settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
settings.isTunnelOnWifiEnabled)
settings.isTunnelOnWifiEnabled
)
}
fun isTrustedWifiConditionMet(): Boolean {
return (!isEthernetConnected &&
(isWifiConnected &&
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)))
return (
!isEthernetConnected &&
(
isWifiConnected &&
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)
)
)
}
fun isTunnelOffOnWifiConditionMet(): Boolean {
return (!isEthernetConnected &&
(isWifiConnected &&
!settings.isTunnelOnWifiEnabled))
return (
!isEthernetConnected &&
(
isWifiConnected &&
!settings.isTunnelOnWifiEnabled
)
)
}
fun isTunnelOffOnNoConnectivityMet(): Boolean {
return (!isEthernetConnected &&
return (
!isEthernetConnected &&
!isWifiConnected &&
!isMobileDataConnected)
!isMobileDataConnected
)
}
}
@@ -33,7 +33,6 @@ import timber.log.Timber
import java.net.InetAddress
import javax.inject.Inject
@AndroidEntryPoint
class WireGuardConnectivityWatcherService : ForegroundService() {
private val foregroundId = 122
@@ -80,7 +79,9 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
try {
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
launchWatcherPausedNotification()
} else launchWatcherNotification()
} else {
launchWatcherNotification()
}
} catch (e: Exception) {
Timber.e("Failed to start watcher service, not enough permissions")
}
@@ -110,9 +111,7 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
stopSelf()
}
private fun launchWatcherNotification(
description: String = getString(R.string.watcher_notification_text_active)
) {
private fun launchWatcherNotification(description: String = getString(R.string.watcher_notification_text_active)) {
val notification =
notificationService.createNotification(
channelId = getString(R.string.watcher_channel_id),
@@ -188,7 +187,6 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
Timber.i("Starting management watcher")
manageVpn()
}
}
}
@@ -236,13 +234,19 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
val tunnelConfig = vpnService.vpnState.value.tunnelConfig
tunnelConfig?.let {
val config = TunnelConfig.configFromWgQuick(it.wgQuick)
val results = config.peers.map { peer ->
val host = if (peer.endpoint.isPresent &&
peer.endpoint.get().resolved.isPresent)
val results =
config.peers.map { peer ->
val host =
if (peer.endpoint.isPresent &&
peer.endpoint.get().resolved.isPresent
) {
peer.endpoint.get().resolved.get().host
else Constants.DEFAULT_PING_IP
} else {
Constants.DEFAULT_PING_IP
}
Timber.i("Checking reachability of: $host")
val reachable = InetAddress.getByName(host)
val reachable =
InetAddress.getByName(host)
.isReachable(Constants.PING_TIMEOUT.toInt())
Timber.i("Result: reachable - $reachable")
reachable
@@ -266,7 +270,9 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
private suspend fun watchForSettingsChanges() {
appDataRepository.settings.getSettingsFlow().collect { settings ->
if (networkEventsFlow.value.settings.isAutoTunnelPaused != settings.isAutoTunnelPaused) {
if (networkEventsFlow.value.settings.isAutoTunnelPaused
!= settings.isAutoTunnelPaused
) {
when (settings.isAutoTunnelPaused) {
true -> launchWatcherPausedNotification()
false -> launchWatcherNotification()
@@ -339,7 +345,9 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
ssid?.let { name ->
if (name.contains(Constants.UNREADABLE_SSID)) {
Timber.w("SSID unreadable: missing permissions")
} else Timber.i("Detected valid SSID")
} else {
Timber.i("Detected valid SSID")
}
appDataRepository.appState.setCurrentSsid(name)
networkEventsFlow.update {
it.copy(
@@ -409,14 +417,19 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
watcherState.isUntrustedWifiConditionMet() -> {
if (tunnelConfig?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false ||
tunnelConfig == null) {
Timber.i("$autoTunnel - tunnel on ssid not associated with current tunnel condition met")
tunnelConfig == null
) {
Timber.i(
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met",
)
getSsidTunnel(watcherState.currentNetworkSSID)?.let {
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}")
if (isTunnelDown() || tunnelConfig?.id != it.id) serviceManager.startVpnServiceForeground(
if (isTunnelDown() || tunnelConfig?.id != it.id) {
serviceManager.startVpnServiceForeground(
context,
it.id,
)
}
} ?: suspend {
Timber.i("No tunnel associated with this SSID, using defaults")
val default = appDataRepository.getPrimaryOrFirstTunnel()
@@ -424,24 +437,29 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
default?.let {
serviceManager.startVpnServiceForeground(context, it.id)
}
}
}.invoke()
}
}
watcherState.isTrustedWifiConditionMet() -> {
Timber.i("$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off")
Timber.i(
"$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off",
)
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
}
watcherState.isTunnelOffOnWifiConditionMet() -> {
Timber.i("$autoTunnel - tunnel off on wifi condition met, turning vpn off")
Timber.i(
"$autoTunnel - tunnel off on wifi condition met, turning vpn off",
)
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
}
watcherState.isTunnelOffOnNoConnectivityMet() -> {
Timber.i("$autoTunnel - tunnel off on no connectivity met, turning vpn off")
Timber.i(
"$autoTunnel - tunnel off on no connectivity met, turning vpn off",
)
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
}
@@ -142,10 +142,7 @@ class WireGuardTunnelService : ForegroundService() {
stopSelf()
}
private fun launchVpnNotification(
title: String = getString(R.string.vpn_starting),
description: String = getString(R.string.attempt_connection)
) {
private fun launchVpnNotification(title: String = getString(R.string.vpn_starting), description: String = getString(R.string.attempt_connection)) {
val notification =
notificationService.createNotification(
channelId = getString(R.string.vpn_channel_id),
@@ -16,7 +16,7 @@ import kotlinx.coroutines.flow.map
abstract class BaseNetworkService<T : BaseNetworkService<T>>(
val context: Context,
networkCapability: Int
networkCapability: Int,
) : NetworkService<T> {
private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@@ -24,7 +24,8 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
private val wifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
override val networkStatus = callbackFlow {
override val networkStatus =
callbackFlow {
val networkStatusCallback =
when (Build.VERSION.SDK_INT) {
in Build.VERSION_CODES.S..Int.MAX_VALUE -> {
@@ -40,10 +41,7 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
trySend(NetworkStatus.Unavailable(network))
}
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
trySend(
NetworkStatus.CapabilitiesChanged(
network,
@@ -64,10 +62,7 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
trySend(NetworkStatus.Unavailable(network))
}
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
trySend(
NetworkStatus.CapabilitiesChanged(
network,
@@ -118,7 +113,7 @@ inline fun <Result> Flow<NetworkStatus>.map(
crossinline onUnavailable: suspend (network: Network) -> Result,
crossinline onAvailable: suspend (network: Network) -> Result,
crossinline onCapabilitiesChanged:
suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result
suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result,
): Flow<Result> = map { status ->
when (status) {
is NetworkStatus.Unavailable -> onUnavailable(status.network)
@@ -5,5 +5,9 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
class EthernetService @Inject constructor(@ApplicationContext context: Context) :
class EthernetService
@Inject
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET)
@@ -5,5 +5,9 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
class MobileDataService @Inject constructor(@ApplicationContext context: Context) :
class MobileDataService
@Inject
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR)
@@ -5,5 +5,9 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
class WifiService @Inject constructor(@ApplicationContext context: Context) :
class WifiService
@Inject
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI)
@@ -9,12 +9,15 @@ import android.content.Intent
import android.graphics.Color
import androidx.core.app.NotificationCompat
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.ui.MainActivity
import com.zaneschepke.wireguardautotunnel.ui.SplashActivity
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
class WireGuardNotification @Inject constructor(@ApplicationContext private val context: Context) :
class WireGuardNotification
@Inject
constructor(
@ApplicationContext private val context: Context,
) :
NotificationService {
private val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
@@ -15,7 +15,6 @@ import javax.inject.Inject
@AndroidEntryPoint
class ShortcutsActivity : ComponentActivity() {
@Inject
lateinit var appDataRepository: AppDataRepository
@@ -34,17 +33,22 @@ class ShortcutsActivity : ComponentActivity() {
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
WireGuardTunnelService::class.java.simpleName -> {
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
val tunnelConfig = tunnelName?.let {
val tunnelConfig =
tunnelName?.let {
appDataRepository.tunnels.getAll().firstOrNull {
it.name == tunnelName
}
}
when (intent.action) {
Action.START.name -> serviceManager.startVpnServiceForeground(
this@ShortcutsActivity, tunnelConfig?.id, isManualStart = true,
Action.START.name ->
serviceManager.startVpnServiceForeground(
this@ShortcutsActivity,
tunnelConfig?.id,
isManualStart = true,
)
Action.STOP.name -> serviceManager.stopVpnServiceForeground(
Action.STOP.name ->
serviceManager.stopVpnServiceForeground(
this@ShortcutsActivity,
isManualStop = true,
)
@@ -53,13 +57,15 @@ class ShortcutsActivity : ComponentActivity() {
WireGuardConnectivityWatcherService::class.java.simpleName -> {
when (intent.action) {
Action.START.name -> appDataRepository.settings.save(
Action.START.name ->
appDataRepository.settings.save(
settings.copy(
isAutoTunnelPaused = false,
),
)
Action.STOP.name -> appDataRepository.settings.save(
Action.STOP.name ->
appDataRepository.settings.save(
settings.copy(
isAutoTunnelPaused = true,
),
@@ -10,11 +10,8 @@ import androidx.lifecycle.lifecycleScope
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import com.zaneschepke.wireguardautotunnel.module.ServiceScope
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import timber.log.Timber
@@ -22,7 +19,6 @@ import javax.inject.Inject
@AndroidEntryPoint
class AutoTunnelControlTile : TileService(), LifecycleOwner {
@Inject
lateinit var appDataRepository: AppDataRepository
@@ -47,6 +43,7 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
setTileDescription(this@AutoTunnelControlTile.getString(R.string.active))
}
}
false -> {
setTileDescription(this@AutoTunnelControlTile.getString(R.string.disabled))
setUnavailable()
@@ -5,17 +5,14 @@ import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.ServiceLifecycleDispatcher
import androidx.lifecycle.lifecycleScope
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import timber.log.Timber
@@ -23,7 +20,6 @@ import javax.inject.Inject
@AndroidEntryPoint
class TunnelControlTile : TileService(), LifecycleOwner {
@Inject
lateinit var appDataRepository: AppDataRepository
@@ -49,7 +45,8 @@ class TunnelControlTile : TileService(), LifecycleOwner {
TunnelState.DOWN -> {
setInactive()
val config = appDataRepository.getStartTunnelConfig()?.also { config ->
val config =
appDataRepository.getStartTunnelConfig()?.also { config ->
manualStartConfig = config
} ?: appDataRepository.getPrimaryOrFirstTunnel()
config?.let {
@@ -79,7 +76,9 @@ class TunnelControlTile : TileService(), LifecycleOwner {
)
} else {
serviceManager.startVpnServiceForeground(
this@TunnelControlTile, manualStartConfig?.id, isManualStart = true,
this@TunnelControlTile,
manualStartConfig?.id,
isManualStart = true,
)
}
} catch (e: Exception) {
@@ -4,7 +4,8 @@ enum class HandshakeStatus {
HEALTHY,
STALE,
UNKNOWN,
NOT_STARTED;
NOT_STARTED,
;
companion object {
private const val WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC = 180
@@ -5,7 +5,8 @@ import com.wireguard.android.backend.Tunnel
enum class TunnelState {
UP,
DOWN,
TOGGLE;
TOGGLE,
;
fun toWgState(): Tunnel.State {
return when (this) {
@@ -6,5 +6,5 @@ import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStati
data class VpnState(
val status: TunnelState = TunnelState.DOWN,
val tunnelConfig: TunnelConfig? = null,
val statistics: TunnelStatistics? = null
val statistics: TunnelStatistics? = null,
)
@@ -37,12 +37,11 @@ constructor(
@Kernel private val kernelBackend: Provider<Backend>,
private val appDataRepository: AppDataRepository,
@ApplicationScope private val applicationScope: CoroutineScope,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : VpnService {
private val _vpnState = MutableStateFlow(VpnState())
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
private var statsJob: Job? = null
private var backendIsWgUserspace = true
@@ -72,9 +71,14 @@ constructor(
private fun setState(tunnelConfig: TunnelConfig?, tunnelState: TunnelState): TunnelState {
return if (backendIsAmneziaUserspace) {
Timber.i("Using Amnezia backend")
val config = tunnelConfig?.let {
if (it.amQuick != "") TunnelConfig.configFromAmQuick(it.amQuick) else {
Timber.w("Using backwards compatible wg config, amnezia specific config not found.")
val config =
tunnelConfig?.let {
if (it.amQuick != "") {
TunnelConfig.configFromAmQuick(it.amQuick)
} else {
Timber.w(
"Using backwards compatible wg config, amnezia specific config not found.",
)
TunnelConfig.configFromAmQuick(it.wgQuick)
}
}
@@ -84,7 +88,8 @@ constructor(
} else {
Timber.i("Using Wg backend")
val wgConfig = tunnelConfig?.let { TunnelConfig.configFromWgQuick(it.wgQuick) }
val state = backend().setState(
val state =
backend().setState(
this,
tunnelState.toWgState(),
wgConfig,
@@ -102,7 +107,9 @@ constructor(
if (config != null) {
emitTunnelConfig(config)
setState(config, TunnelState.UP)
} else throw Exception("No tunnels")
} else {
throw Exception("No tunnels")
}
} catch (e: BackendException) {
Timber.e("Failed to start tunnel with error: ${e.message}")
TunnelState.from(State.DOWN)
@@ -171,17 +178,19 @@ constructor(
}
override fun getState(): TunnelState {
return if (backendIsAmneziaUserspace) TunnelState.from(
return if (backendIsAmneziaUserspace) {
TunnelState.from(
userspaceAmneziaBackend.get().getState(this),
)
else TunnelState.from(backend().getState(this))
} else {
TunnelState.from(backend().getState(this))
}
}
override fun getName(): String {
return _vpnState.value.tunnelConfig?.name ?: ""
}
override fun onStateChange(newState: Tunnel.State) {
handleStateChange(TunnelState.from(newState))
}
@@ -210,7 +219,9 @@ constructor(
),
)
} else {
emitBackendStatistics(WireGuardStatistics(backend().getStatistics(this@WireGuardTunnel)))
emitBackendStatistics(
WireGuardStatistics(backend().getStatistics(this@WireGuardTunnel)),
)
}
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
}
@@ -5,5 +5,5 @@ data class AppUiState(
val snackbarMessageConsumed: Boolean = true,
val vpnPermissionAccepted: Boolean = false,
val notificationPermissionAccepted: Boolean = false,
val requestPermissions: Boolean = false
val requestPermissions: Boolean = false,
)
@@ -20,17 +20,16 @@ import javax.inject.Inject
class AppViewModel
@Inject
constructor() : ViewModel() {
val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance)
private val _appUiState = MutableStateFlow(
private val _appUiState =
MutableStateFlow(
AppUiState(
vpnPermissionAccepted = vpnIntent == null,
),
)
val appUiState = _appUiState.asStateFlow()
fun isRequiredPermissionGranted(): Boolean {
val allAccepted =
(_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted)
@@ -57,7 +56,8 @@ constructor() : ViewModel() {
fun openWebPage(url: String, context: Context) {
try {
val webpage: Uri = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, webpage).apply {
val intent =
Intent(Intent.ACTION_VIEW, webpage).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
@@ -10,6 +10,8 @@ import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
@@ -19,15 +21,19 @@ import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -41,11 +47,13 @@ import androidx.navigation.navArgument
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.InfoDialog
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen
@@ -65,7 +73,6 @@ import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var appStateRepository: AppStateRepository
@@ -98,10 +105,14 @@ class MainActivity : AppCompatActivity() {
val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle()
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
var showVpnPermissionDialog by remember { mutableStateOf(false) }
val notificationPermissionState =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS) else null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS)
} else {
null
}
val snackbarHostState = remember { SnackbarHostState() }
@@ -112,6 +123,8 @@ class MainActivity : AppCompatActivity() {
val accepted = (it.resultCode == RESULT_OK)
if (accepted) {
appViewModel.onVpnPermissionAccepted()
} else {
showVpnPermissionDialog = true
}
},
)
@@ -125,7 +138,8 @@ class MainActivity : AppCompatActivity() {
)
when (result) {
SnackbarResult.ActionPerformed,
SnackbarResult.Dismissed -> {
SnackbarResult.Dismissed,
-> {
snackbarHostState.currentSnackbarData?.dismiss()
}
}
@@ -137,15 +151,21 @@ class MainActivity : AppCompatActivity() {
appViewModel.permissionsRequested()
if (notificationPermissionState != null && !notificationPermissionState.status.isGranted
) {
showSnackBarMessage(StringValue.StringResource(R.string.notification_permission_required))
return@LaunchedEffect notificationPermissionState.launchPermissionRequest()
notificationPermissionState.launchPermissionRequest()
return@LaunchedEffect if (notificationPermissionState.status.shouldShowRationale || !notificationPermissionState.status.isGranted) {
showSnackBarMessage(
StringValue.StringResource(R.string.notification_permission_required),
)
} else {
Unit
}
}
if (!appUiState.vpnPermissionAccepted) {
return@LaunchedEffect appViewModel.vpnIntent?.let {
vpnActivityResultState.launch(
it,
)
}!!
} ?: Unit
}
}
}
@@ -166,6 +186,21 @@ class MainActivity : AppCompatActivity() {
val focusRequester = remember { FocusRequester() }
if (showVpnPermissionDialog) {
InfoDialog(
onDismiss = { showVpnPermissionDialog = false },
onAttest = { showVpnPermissionDialog = false },
title = { Text(text = stringResource(R.string.vpn_denied_dialog_title)) },
body = {
Column(verticalArrangement = Arrangement.spacedBy(15.dp)) {
Text(text = stringResource(R.string.vpn_denied_dialog_message))
Text(text = stringResource(R.string.vpn_denied_dialog_message2))
}
},
confirmText = { Text(text = stringResource(R.string.okay)) },
)
}
Scaffold(
snackbarHost = {
SnackbarHost(snackbarHostState) { snackbarData: SnackbarData ->
@@ -180,7 +215,8 @@ class MainActivity : AppCompatActivity() {
}
},
// TODO refactor
modifier = Modifier
modifier =
Modifier
.focusable()
.focusProperties {
when (navBackStackEntry?.destination?.route) {
@@ -202,7 +238,8 @@ class MainActivity : AppCompatActivity() {
NavHost(
navController,
startDestination = (if (isPinLockEnabled == true) Screen.Lock.route else Screen.Main.route),
modifier = Modifier
modifier =
Modifier
.padding(padding)
.fillMaxSize(),
) {
@@ -251,7 +288,8 @@ class MainActivity : AppCompatActivity() {
),
) {
val id = it.arguments?.getString("id")
val configType = ConfigType.valueOf(
val configType =
ConfigType.valueOf(
it.arguments?.getString("configType") ?: ConfigType.WIREGUARD.name,
)
if (!id.isNullOrBlank()) {
@@ -39,6 +39,7 @@ sealed class Screen(val route: String) {
}
data object Config : Screen("config")
data object Lock : Screen("lock")
data object Option : Screen("option")
@@ -23,7 +23,6 @@ import javax.inject.Inject
@SuppressLint("CustomSplashScreen")
@AndroidEntryPoint
class SplashActivity : ComponentActivity() {
@Inject
lateinit var appStateRepository: AppStateRepository
@@ -52,7 +51,8 @@ class SplashActivity : ComponentActivity() {
PinManager.initialize(WireGuardAutoTunnel.instance)
}
val intent = Intent(this@SplashActivity, MainActivity::class.java).apply {
val intent =
Intent(this@SplashActivity, MainActivity::class.java).apply {
putExtra(IS_PIN_LOCK_ENABLED_KEY, pinLockEnabled)
}
startActivity(intent)
@@ -65,4 +65,3 @@ class SplashActivity : ComponentActivity() {
const val IS_PIN_LOCK_ENABLED_KEY = "is_pin_lock_enabled"
}
}
@@ -12,13 +12,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
@Composable
fun ClickableIconButton(
onClick: () -> Unit,
onIconClick: () -> Unit,
text: String,
icon: ImageVector,
enabled: Boolean
) {
fun ClickableIconButton(onClick: () -> Unit, onIconClick: () -> Unit, text: String, icon: ImageVector, enabled: Boolean) {
TextButton(
onClick = onClick,
enabled = enabled,
@@ -38,7 +38,8 @@ fun RowListItem(
) {
Box(
modifier =
Modifier.focusRequester(focusRequester)
Modifier
.focusRequester(focusRequester)
.animateContentSize()
.clip(RoundedCornerShape(30.dp))
.combinedClickable(
@@ -48,7 +49,8 @@ fun RowListItem(
) {
Column {
Row(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 15.dp, vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -16,7 +16,7 @@ fun ConfigurationTextBox(
onValueChange: (String) -> Unit,
keyboardActions: KeyboardActions,
label: String,
modifier: Modifier
modifier: Modifier,
) {
OutlinedTextField(
modifier = modifier,
@@ -13,24 +13,20 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
@Composable
fun ConfigurationToggle(
label: String,
enabled: Boolean,
checked: Boolean,
padding: Dp,
onCheckChanged: () -> Unit,
modifier: Modifier = Modifier
) {
fun ConfigurationToggle(label: String, enabled: Boolean, checked: Boolean, padding: Dp, onCheckChanged: () -> Unit, modifier: Modifier = Modifier) {
Row(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(padding),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
label, textAlign = TextAlign.Start,
modifier = Modifier
label,
textAlign = TextAlign.Start,
modifier =
Modifier
.weight(
weight = 1.0f,
fill = false,
@@ -0,0 +1,37 @@
package com.zaneschepke.wireguardautotunnel.ui.common.dialog
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.zaneschepke.wireguardautotunnel.R
@Composable
fun InfoDialog(
onAttest: () -> Unit,
onDismiss: () -> Unit,
title: @Composable () -> Unit,
body: @Composable () -> Unit,
confirmText: @Composable () -> Unit,
) {
AlertDialog(
onDismissRequest = { onDismiss() },
confirmButton = {
TextButton(
onClick = {
onAttest()
},
) {
confirmText()
}
},
dismissButton = {
TextButton(onClick = { onDismiss() }) {
Text(text = stringResource(R.string.cancel))
}
},
title = { title() },
text = { body() },
)
}
@@ -24,7 +24,8 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
val navBackStackEntry by navController.currentBackStackEntryAsState()
// TODO find a better way to hide nav bar
showBottomBar = when (navBackStackEntry?.destination?.route) {
showBottomBar =
when (navBackStackEntry?.destination?.route) {
Screen.Lock.route -> false
else -> true
}
@@ -32,7 +33,8 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
NavigationBar(
containerColor = if (!showBottomBar) Color.Transparent else MaterialTheme.colorScheme.background,
) {
if (showBottomBar) bottomNavItems.forEach { item ->
if (showBottomBar) {
bottomNavItems.forEach { item ->
val selected = item.route == backStackEntry.value?.destination?.route
NavigationBarItem(
@@ -54,3 +56,4 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
}
}
}
}
@@ -15,7 +15,8 @@ fun AuthorizationPrompt(onSuccess: () -> Unit, onFailure: () -> Unit, onError: (
val context = LocalContext.current
val biometricManager = BiometricManager.from(context)
val bio = biometricManager.canAuthenticate(BIOMETRIC_WEAK or DEVICE_CREDENTIAL)
val isBiometricAvailable = remember {
val isBiometricAvailable =
remember {
when (bio) {
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
onError("Biometrics not available")
@@ -71,9 +72,7 @@ fun AuthorizationPrompt(onSuccess: () -> Unit, onFailure: () -> Unit, onError: (
onFailure()
}
override fun onAuthenticationSucceeded(
result: BiometricPrompt.AuthenticationResult
) {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
onSuccess()
}
@@ -25,11 +25,7 @@ import androidx.compose.ui.unit.dp
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
@Composable
fun CustomSnackBar(
message: String,
isRtl: Boolean = true,
containerColor: Color = MaterialTheme.colorScheme.surface
) {
fun CustomSnackBar(message: String, isRtl: Boolean = true, containerColor: Color = MaterialTheme.colorScheme.surface) {
Snackbar(
containerColor = containerColor,
modifier =
@@ -44,7 +40,8 @@ fun CustomSnackBar(
LocalLayoutDirection provides if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr,
) {
Row(
modifier = Modifier
modifier =
Modifier
.width(IntrinsicSize.Max)
.height(IntrinsicSize.Min),
verticalAlignment = Alignment.CenterVertically,
@@ -16,7 +16,8 @@ fun LoadingScreen() {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.focusable()
.padding(),
@@ -14,7 +14,8 @@ import androidx.compose.ui.unit.dp
@Composable
fun LogTypeLabel(color: Color, content: @Composable () -> Unit) {
Box(
modifier = Modifier
modifier =
Modifier
.size(20.dp)
.clip(RoundedCornerShape(2.dp))
.background(color),
@@ -95,7 +95,7 @@ fun ConfigScreen(
navController: NavController,
appViewModel: AppViewModel,
tunnelId: String,
configType: ConfigType
configType: ConfigType,
) {
val context = LocalContext.current
val clipboardManager: ClipboardManager = LocalClipboardManager.current
@@ -128,16 +128,23 @@ fun ConfigScreen(
val fillMaxWidth = .85f
val screenPadding = 5.dp
val applicationButtonText = buildAnnotatedString {
val applicationButtonText =
buildAnnotatedString {
append(stringResource(id = R.string.tunneling_apps))
append(": ")
if (uiState.isAllApplicationsEnabled) {
append(stringResource(id = R.string.all))
} else {
append("${uiState.checkedPackageNames.size} ")
(if (uiState.include) append(stringResource(id = R.string.included)) else append(
(
if (uiState.include) {
append(stringResource(id = R.string.included))
} else {
append(
stringResource(id = R.string.excluded),
))
)
}
)
}
}
@@ -149,11 +156,15 @@ fun ConfigScreen(
},
onError = {
showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authentication_failed))
appViewModel.showSnackbarMessage(
context.getString(R.string.error_authentication_failed),
)
},
onFailure = {
showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authorization_failed))
appViewModel.showSnackbarMessage(
context.getString(R.string.error_authorization_failed),
)
},
)
}
@@ -175,7 +186,8 @@ fun ConfigScreen(
.fillMaxHeight(if (uiState.isAllApplicationsEnabled) 1 / 5f else 4 / 5f),
) {
Column(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth(),
) {
Row(
@@ -246,7 +258,8 @@ fun ConfigScreen(
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.padding(5.dp),
) {
@@ -275,9 +288,11 @@ fun ConfigScreen(
Checkbox(
modifier = Modifier.fillMaxSize(),
checked =
(uiState.checkedPackageNames.contains(
(
uiState.checkedPackageNames.contains(
pack.packageName,
)),
)
),
onCheckedChange = {
if (it) {
viewModel.onAddCheckedPackage(pack.packageName)
@@ -292,7 +307,8 @@ fun ConfigScreen(
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.padding(top = 5.dp),
horizontalArrangement = Arrangement.Center,
@@ -321,7 +337,9 @@ fun ConfigScreen(
},
onClick = {
viewModel.onSaveAllChanges(configType).onSuccess {
appViewModel.showSnackbarMessage(context.getString(R.string.config_changes_saved))
appViewModel.showSnackbarMessage(
context.getString(R.string.config_changes_saved),
)
navController.navigate(Screen.Main.route)
}.onFailure {
appViewModel.showSnackbarMessage(it.getMessage(context))
@@ -354,19 +372,22 @@ fun ConfigScreen(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
(
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier
.fillMaxHeight(fillMaxHeight)
.fillMaxWidth(fillMaxWidth)
} else {
Modifier.fillMaxWidth(fillMaxWidth)
})
}
)
.padding(bottom = 10.dp),
) {
Column(
horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top,
modifier = Modifier
modifier =
Modifier
.padding(15.dp)
.focusGroup(),
) {
@@ -380,19 +401,23 @@ fun ConfigScreen(
keyboardActions = keyboardActions,
label = stringResource(R.string.name),
hint = stringResource(R.string.tunnel_name).lowercase(),
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
OutlinedTextField(
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.clickable { showAuthPrompt = true },
value = uiState.interfaceProxy.privateKey,
visualTransformation =
if ((tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated)
if ((tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated) {
VisualTransformation.None
else PasswordVisualTransformation(),
} else {
PasswordVisualTransformation()
},
enabled = (tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated,
onValueChange = { value -> viewModel.onPrivateKeyChange(value) },
trailingIcon = {
@@ -450,7 +475,8 @@ fun ConfigScreen(
keyboardActions = keyboardActions,
label = stringResource(R.string.addresses),
hint = stringResource(R.string.comma_separated_list),
modifier = Modifier
modifier =
Modifier
.fillMaxWidth(3 / 5f)
.padding(end = 5.dp),
)
@@ -470,7 +496,8 @@ fun ConfigScreen(
keyboardActions = keyboardActions,
label = stringResource(R.string.dns_servers),
hint = stringResource(R.string.comma_separated_list),
modifier = Modifier
modifier =
Modifier
.fillMaxWidth(3 / 5f)
.padding(end = 5.dp),
)
@@ -486,11 +513,15 @@ fun ConfigScreen(
if (configType == ConfigType.AMNEZIA) {
ConfigurationTextBox(
value = uiState.interfaceProxy.junkPacketCount,
onValueChange = { value -> viewModel.onJunkPacketCountChanged(value) },
onValueChange = {
value ->
viewModel.onJunkPacketCountChanged(value)
},
keyboardActions = keyboardActions,
label = stringResource(R.string.junk_packet_count),
hint = stringResource(R.string.junk_packet_count).lowercase(),
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
@@ -503,8 +534,12 @@ fun ConfigScreen(
},
keyboardActions = keyboardActions,
label = stringResource(R.string.junk_packet_minimum_size),
hint = stringResource(R.string.junk_packet_minimum_size).lowercase(),
modifier = Modifier
hint =
stringResource(
R.string.junk_packet_minimum_size,
).lowercase(),
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
@@ -517,8 +552,12 @@ fun ConfigScreen(
},
keyboardActions = keyboardActions,
label = stringResource(R.string.junk_packet_maximum_size),
hint = stringResource(R.string.junk_packet_maximum_size).lowercase(),
modifier = Modifier
hint =
stringResource(
R.string.junk_packet_maximum_size,
).lowercase(),
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
@@ -532,27 +571,42 @@ fun ConfigScreen(
keyboardActions = keyboardActions,
label = stringResource(R.string.init_packet_junk_size),
hint = stringResource(R.string.init_packet_junk_size).lowercase(),
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
ConfigurationTextBox(
value = uiState.interfaceProxy.responsePacketJunkSize,
onValueChange = { value -> viewModel.onResponsePacketJunkSize(value) },
onValueChange = {
value ->
viewModel.onResponsePacketJunkSize(value)
},
keyboardActions = keyboardActions,
label = stringResource(R.string.response_packet_junk_size),
hint = stringResource(R.string.response_packet_junk_size).lowercase(),
modifier = Modifier
hint =
stringResource(
R.string.response_packet_junk_size,
).lowercase(),
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
ConfigurationTextBox(
value = uiState.interfaceProxy.initPacketMagicHeader,
onValueChange = { value -> viewModel.onInitPacketMagicHeader(value) },
onValueChange = {
value ->
viewModel.onInitPacketMagicHeader(value)
},
keyboardActions = keyboardActions,
label = stringResource(R.string.init_packet_magic_header),
hint = stringResource(R.string.init_packet_magic_header).lowercase(),
modifier = Modifier
hint =
stringResource(
R.string.init_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
@@ -565,8 +619,12 @@ fun ConfigScreen(
},
keyboardActions = keyboardActions,
label = stringResource(R.string.response_packet_magic_header),
hint = stringResource(R.string.response_packet_magic_header).lowercase(),
modifier = Modifier
hint =
stringResource(
R.string.response_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
@@ -579,8 +637,12 @@ fun ConfigScreen(
},
keyboardActions = keyboardActions,
label = stringResource(R.string.underload_packet_magic_header),
hint = stringResource(R.string.underload_packet_magic_header).lowercase(),
modifier = Modifier
hint =
stringResource(
R.string.underload_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
@@ -593,15 +655,20 @@ fun ConfigScreen(
},
keyboardActions = keyboardActions,
label = stringResource(R.string.transport_packet_magic_header),
hint = stringResource(R.string.transport_packet_magic_header).lowercase(),
modifier = Modifier
hint =
stringResource(
R.string.transport_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.padding(top = 5.dp),
horizontalArrangement = Arrangement.Center,
@@ -619,26 +686,30 @@ fun ConfigScreen(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
(
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier
.fillMaxHeight(fillMaxHeight)
.fillMaxWidth(fillMaxWidth)
} else {
Modifier.fillMaxWidth(fillMaxWidth)
})
}
)
.padding(top = 10.dp, bottom = 10.dp),
) {
Column(
horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top,
modifier = Modifier
modifier =
Modifier
.padding(horizontal = 15.dp)
.padding(bottom = 10.dp),
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp),
) {
@@ -724,7 +795,8 @@ fun ConfigScreen(
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.padding(bottom = 140.dp),
) {
@@ -16,7 +16,7 @@ data class ConfigUiState(
val loading: Boolean = true,
val tunnel: TunnelConfig? = null,
val tunnelName: String = "",
val isAmneziaEnabled: Boolean = false
val isAmneziaEnabled: Boolean = false,
) {
companion object {
fun from(config: Config): ConfigUiState {
@@ -40,16 +40,14 @@ class ConfigViewModel
constructor(
private val settingsRepository: SettingsRepository,
private val appDataRepository: AppDataRepository,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : ViewModel() {
private val packageManager = WireGuardAutoTunnel.instance.packageManager
private val _uiState = MutableStateFlow(ConfigUiState())
val uiState = _uiState.asStateFlow()
fun init(tunnelId: String) =
viewModelScope.launch(ioDispatcher) {
fun init(tunnelId: String) = viewModelScope.launch(ioDispatcher) {
val packages = getQueriedPackages("")
val state =
if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) {
@@ -58,11 +56,17 @@ constructor(
.firstOrNull { it.id.toString() == tunnelId }
val isAmneziaEnabled = settingsRepository.getSettings().isAmneziaEnabled
if (tunnelConfig != null) {
(if (isAmneziaEnabled) {
(
if (isAmneziaEnabled) {
val amConfig =
if (tunnelConfig.amQuick == "") tunnelConfig.wgQuick else tunnelConfig.amQuick
ConfigUiState.from(TunnelConfig.configFromAmQuick(amConfig))
} else ConfigUiState.from(TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick))).copy(
} else {
ConfigUiState.from(
TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick),
)
}
).copy(
packages = packages,
loading = false,
tunnel = tunnelConfig,
@@ -111,7 +115,7 @@ constructor(
}
fun getPackageLabel(packageInfo: PackageInfo): String {
return packageInfo.applicationInfo.loadLabel(packageManager).toString()
return packageInfo.applicationInfo?.loadLabel(packageManager).toString()
}
private fun getAllInternetCapablePackages(): List<PackageInfo> {
@@ -133,11 +137,9 @@ constructor(
return _uiState.value.isAllApplicationsEnabled
}
private fun saveConfig(tunnelConfig: TunnelConfig) =
viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) }
private fun saveConfig(tunnelConfig: TunnelConfig) = viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) }
private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) =
viewModelScope.launch {
private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) = viewModelScope.launch {
if (tunnelConfig != null) {
saveConfig(tunnelConfig).join()
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
@@ -183,14 +185,23 @@ constructor(
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) {
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim())
}
if (_uiState.value.interfaceProxy.mtu.isNotEmpty())
if (_uiState.value.interfaceProxy.mtu.isNotEmpty()) {
builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim())
}
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
}
if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
if (_uiState.value.include) builder.includeApplications(_uiState.value.checkedPackageNames)
if (!_uiState.value.include) builder.excludeApplications(_uiState.value.checkedPackageNames)
if (_uiState.value.include) {
builder.includeApplications(
_uiState.value.checkedPackageNames,
)
}
if (!_uiState.value.include) {
builder.excludeApplications(
_uiState.value.checkedPackageNames,
)
}
return builder.build()
}
@@ -201,16 +212,27 @@ constructor(
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) {
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim())
}
if (_uiState.value.interfaceProxy.mtu.isNotEmpty())
if (_uiState.value.interfaceProxy.mtu.isNotEmpty()) {
builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim())
}
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
}
if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
if (_uiState.value.include) builder.includeApplications(_uiState.value.checkedPackageNames)
if (!_uiState.value.include) builder.excludeApplications(_uiState.value.checkedPackageNames)
if (_uiState.value.include) {
builder.includeApplications(
_uiState.value.checkedPackageNames,
)
}
if (!_uiState.value.include) {
builder.excludeApplications(
_uiState.value.checkedPackageNames,
)
}
if (_uiState.value.interfaceProxy.junkPacketCount.isNotEmpty()) {
builder.setJunkPacketCount(_uiState.value.interfaceProxy.junkPacketCount.trim().toInt())
builder.setJunkPacketCount(
_uiState.value.interfaceProxy.junkPacketCount.trim().toInt(),
)
}
if (_uiState.value.interfaceProxy.junkPacketMinSize.isNotEmpty()) {
builder.setJunkPacketMinSize(
@@ -264,24 +286,32 @@ constructor(
private fun buildAmConfig(): org.amnezia.awg.config.Config {
val peerList = buildAmPeerListFromProxyPeers()
val amInterface = buildAmInterfaceListFromProxyInterface()
return org.amnezia.awg.config.Config.Builder().addPeers(peerList).setInterface(amInterface)
return org.amnezia.awg.config.Config.Builder().addPeers(
peerList,
).setInterface(amInterface)
.build()
}
fun onSaveAllChanges(configType: ConfigType): Result<Unit> {
return try {
val wgQuick = buildConfig().toWgQuickString()
val amQuick = if (configType == ConfigType.AMNEZIA) {
val amQuick =
if (configType == ConfigType.AMNEZIA) {
buildAmConfig().toAwgQuickString()
} else TunnelConfig.AM_QUICK_DEFAULT
val tunnelConfig = when (uiState.value.tunnel) {
null -> TunnelConfig(
} else {
TunnelConfig.AM_QUICK_DEFAULT
}
val tunnelConfig =
when (uiState.value.tunnel) {
null ->
TunnelConfig(
name = _uiState.value.tunnelName,
wgQuick = wgQuick,
amQuick = amQuick,
)
else -> uiState.value.tunnel!!.copy(
else ->
uiState.value.tunnel!!.copy(
name = _uiState.value.tunnelName,
wgQuick = wgQuick,
amQuick = amQuick,
@@ -292,7 +322,8 @@ constructor(
} catch (e: Exception) {
Timber.e(e)
val message = e.message?.substringAfter(":", missingDelimiterValue = "")
val stringValue = message?.let {
val stringValue =
message?.let {
StringValue.DynamicString(message)
} ?: StringValue.StringResource(R.string.unknown_error)
Result.failure(WgTunnelExceptions.ConfigParseError(stringValue))
@@ -392,7 +423,6 @@ constructor(
interfaceProxy = _uiState.value.interfaceProxy.copy(addresses = value),
)
}
}
fun onListenPortChanged(value: String) {
@@ -423,7 +453,6 @@ constructor(
interfaceProxy = _uiState.value.interfaceProxy.copy(publicKey = value),
)
}
}
fun onPrivateKeyChange(value: String) {
@@ -483,7 +512,10 @@ constructor(
fun onResponsePacketJunkSize(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(responsePacketJunkSize = value),
interfaceProxy =
_uiState.value.interfaceProxy.copy(
responsePacketJunkSize = value,
),
)
}
}
@@ -491,7 +523,10 @@ constructor(
fun onInitPacketMagicHeader(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(initPacketMagicHeader = value),
interfaceProxy =
_uiState.value.interfaceProxy.copy(
initPacketMagicHeader = value,
),
)
}
}
@@ -499,7 +534,10 @@ constructor(
fun onResponsePacketMagicHeader(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(responsePacketMagicHeader = value),
interfaceProxy =
_uiState.value.interfaceProxy.copy(
responsePacketMagicHeader = value,
),
)
}
}
@@ -507,7 +545,10 @@ constructor(
fun onTransportPacketMagicHeader(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(transportPacketMagicHeader = value),
interfaceProxy =
_uiState.value.interfaceProxy.copy(
transportPacketMagicHeader = value,
),
)
}
}
@@ -515,7 +556,10 @@ constructor(
fun onUnderloadPacketMagicHeader(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(underloadPacketMagicHeader = value),
interfaceProxy =
_uiState.value.interfaceProxy.copy(
underloadPacketMagicHeader = value,
),
)
}
}
@@ -49,24 +49,69 @@ data class InterfaceProxy(
""
},
mtu = if (i.mtu.isPresent) i.mtu.get().toString().trim() else "",
junkPacketCount = if (i.junkPacketCount.isPresent) i.junkPacketCount.get()
.toString() else "",
junkPacketMinSize = if (i.junkPacketMinSize.isPresent) i.junkPacketMinSize.get()
.toString() else "",
junkPacketMaxSize = if (i.junkPacketMaxSize.isPresent) i.junkPacketMaxSize.get()
.toString() else "",
initPacketJunkSize = if (i.initPacketJunkSize.isPresent) i.initPacketJunkSize.get()
.toString() else "",
responsePacketJunkSize = if (i.responsePacketJunkSize.isPresent) i.responsePacketJunkSize.get()
.toString() else "",
initPacketMagicHeader = if (i.initPacketMagicHeader.isPresent) i.initPacketMagicHeader.get()
.toString() else "",
responsePacketMagicHeader = if (i.responsePacketMagicHeader.isPresent) i.responsePacketMagicHeader.get()
.toString() else "",
transportPacketMagicHeader = if (i.transportPacketMagicHeader.isPresent) i.transportPacketMagicHeader.get()
.toString() else "",
underloadPacketMagicHeader = if (i.underloadPacketMagicHeader.isPresent) i.underloadPacketMagicHeader.get()
.toString() else "",
junkPacketCount =
if (i.junkPacketCount.isPresent) {
i.junkPacketCount.get()
.toString()
} else {
""
},
junkPacketMinSize =
if (i.junkPacketMinSize.isPresent) {
i.junkPacketMinSize.get()
.toString()
} else {
""
},
junkPacketMaxSize =
if (i.junkPacketMaxSize.isPresent) {
i.junkPacketMaxSize.get()
.toString()
} else {
""
},
initPacketJunkSize =
if (i.initPacketJunkSize.isPresent) {
i.initPacketJunkSize.get()
.toString()
} else {
""
},
responsePacketJunkSize =
if (i.responsePacketJunkSize.isPresent) {
i.responsePacketJunkSize.get()
.toString()
} else {
""
},
initPacketMagicHeader =
if (i.initPacketMagicHeader.isPresent) {
i.initPacketMagicHeader.get()
.toString()
} else {
""
},
responsePacketMagicHeader =
if (i.responsePacketMagicHeader.isPresent) {
i.responsePacketMagicHeader.get()
.toString()
} else {
""
},
transportPacketMagicHeader =
if (i.transportPacketMagicHeader.isPresent) {
i.transportPacketMagicHeader.get()
.toString()
} else {
""
},
underloadPacketMagicHeader =
if (i.underloadPacketMagicHeader.isPresent) {
i.underloadPacketMagicHeader.get()
.toString()
} else {
""
},
)
}
}
@@ -7,7 +7,7 @@ data class PeerProxy(
val preSharedKey: String = "",
val persistentKeepalive: String = "",
val endpoint: String = "",
val allowedIps: String = IPV4_WILDCARD.joinToString(", ").trim()
val allowedIps: String = IPV4_WILDCARD.joinToString(", ").trim(),
) {
companion object {
fun from(peer: Peer): PeerProxy {
@@ -2,5 +2,5 @@ package com.zaneschepke.wireguardautotunnel.ui.screens.main
enum class ConfigType {
AMNEZIA,
WIREGUARD
WIREGUARD,
}
@@ -43,7 +43,6 @@ import androidx.compose.material.icons.rounded.Info
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material.icons.rounded.Smartphone
import androidx.compose.material.icons.rounded.Star
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FabPosition
import androidx.compose.material3.HorizontalDivider
@@ -103,6 +102,7 @@ import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
import com.zaneschepke.wireguardautotunnel.ui.Screen
import com.zaneschepke.wireguardautotunnel.ui.common.RowListItem
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.InfoDialog
import com.zaneschepke.wireguardautotunnel.ui.common.screen.LoadingScreen
import com.zaneschepke.wireguardautotunnel.ui.theme.corn
import com.zaneschepke.wireguardautotunnel.ui.theme.mint
@@ -120,7 +120,7 @@ fun MainScreen(
viewModel: MainViewModel = hiltViewModel(),
appViewModel: AppViewModel,
focusRequester: FocusRequester,
navController: NavController
navController: NavController,
) {
val haptic = LocalHapticFeedback.current
val context = LocalContext.current
@@ -132,7 +132,8 @@ fun MainScreen(
var configType by remember { mutableStateOf(ConfigType.WIREGUARD) }
// Nested scroll for control FAB
val nestedScrollConnection = remember {
val nestedScrollConnection =
remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
// Hide FAB
@@ -149,7 +150,6 @@ fun MainScreen(
}
}
var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) }
var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) }
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
@@ -190,7 +190,9 @@ fun MainScreen(
name.startsWith(Constants.ANDROID_TV_EXPLORER_STUB)
}
) {
appViewModel.showSnackbarMessage(context.getString(R.string.error_no_file_explorer))
appViewModel.showSnackbarMessage(
context.getString(R.string.error_no_file_explorer),
)
}
return intent
}
@@ -217,37 +219,31 @@ fun MainScreen(
},
)
AnimatedVisibility(showDeleteTunnelAlertDialog) {
AlertDialog(
onDismissRequest = { showDeleteTunnelAlertDialog = false },
confirmButton = {
TextButton(
onClick = {
if (showDeleteTunnelAlertDialog) {
InfoDialog(
onDismiss = { showDeleteTunnelAlertDialog = false },
onAttest = {
selectedTunnel?.let { viewModel.onDelete(it, context) }
showDeleteTunnelAlertDialog = false
selectedTunnel = null
},
) {
Text(text = stringResource(R.string.yes))
}
},
dismissButton = {
TextButton(onClick = { showDeleteTunnelAlertDialog = false }) {
Text(text = stringResource(R.string.cancel))
}
},
title = { Text(text = stringResource(R.string.delete_tunnel)) },
text = { Text(text = stringResource(R.string.delete_tunnel_message)) },
body = { Text(text = stringResource(R.string.delete_tunnel_message)) },
confirmText = { Text(text = stringResource(R.string.yes)) },
)
}
fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) {
if (appViewModel.isRequiredPermissionGranted()) {
if (checked) viewModel.onTunnelStart(tunnel, context) else viewModel.onTunnelStop(
if (checked) {
viewModel.onTunnelStart(tunnel, context)
} else {
viewModel.onTunnelStop(
context,
)
}
}
}
if (uiState.loading) {
return LoadingScreen()
@@ -274,7 +270,6 @@ fun MainScreen(
},
)
}
},
floatingActionButtonPosition = FabPosition.End,
floatingActionButton = {
@@ -282,7 +277,8 @@ fun MainScreen(
visible = isVisible.value,
enter = slideInVertically(initialOffsetY = { it * 2 }),
exit = slideOutVertically(targetOffsetY = { it * 2 }),
modifier = Modifier
modifier =
Modifier
.focusRequester(focusRequester)
.focusGroup(),
) {
@@ -293,16 +289,19 @@ fun MainScreen(
val fobIconColor =
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) Color.White else MaterialTheme.colorScheme.background
MultiFloatingActionButton(
fabIcon = FabIcon(
fabIcon =
FabIcon(
iconRes = R.drawable.add,
iconResAfterRotate = R.drawable.close,
iconRotate = 180f,
),
fabOption = FabOption(
fabOption =
FabOption(
iconTint = fobIconColor,
backgroundTint = fobColor,
),
itemsMultiFab = listOf(
itemsMultiFab =
listOf(
MultiFabItem(
label = {
Text(
@@ -312,11 +311,13 @@ fun MainScreen(
modifier = Modifier.padding(end = 10.dp),
)
},
modifier = Modifier
modifier =
Modifier
.size(40.dp),
icon = R.drawable.add,
value = ConfigType.AMNEZIA.name,
miniFabOption = FabOption(
miniFabOption =
FabOption(
backgroundTint = fobColor,
fobIconColor,
),
@@ -332,7 +333,8 @@ fun MainScreen(
},
icon = R.drawable.add,
value = ConfigType.WIREGUARD.name,
miniFabOption = FabOption(
miniFabOption =
FabOption(
backgroundTint = fobColor,
fobIconColor,
),
@@ -351,7 +353,6 @@ fun MainScreen(
ModalBottomSheet(
onDismissRequest = {
showBottomSheet = false
},
sheetState = sheetState,
) {
@@ -409,7 +410,7 @@ fun MainScreen(
.clickable {
showBottomSheet = false
navController.navigate(
"${Screen.Config.route}/${Constants.MANUAL_TUNNEL_CONFIG_ID}?configType=${configType}",
"${Screen.Config.route}/${Constants.MANUAL_TUNNEL_CONFIG_ID}?configType=$configType",
)
}
.padding(10.dp),
@@ -442,23 +443,29 @@ fun MainScreen(
) {
item {
AnimatedVisibility(
uiState.tunnels.isEmpty(), exit = fadeOut(), enter = fadeIn(),
uiState.tunnels.isEmpty(),
exit = fadeOut(),
enter = fadeIn(),
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
modifier =
Modifier
.padding(top = 100.dp)
.fillMaxSize(),
) {
val gettingStarted = buildAnnotatedString {
val gettingStarted =
buildAnnotatedString {
append(stringResource(id = R.string.see_the))
append(" ")
pushStringAnnotation(
tag = "gettingStarted",
annotation = stringResource(id = R.string.getting_started_url),
)
withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.primary)) {
withStyle(
style = SpanStyle(color = MaterialTheme.colorScheme.primary),
) {
append(stringResource(id = R.string.getting_started_guide))
}
pop()
@@ -471,10 +478,12 @@ fun MainScreen(
fontStyle = FontStyle.Italic,
)
ClickableText(
modifier = Modifier
modifier =
Modifier
.padding(vertical = 10.dp, horizontal = 24.dp),
text = gettingStarted,
style = MaterialTheme.typography.bodyMedium.copy(
style =
MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
),
@@ -490,27 +499,36 @@ fun MainScreen(
item {
if (uiState.settings.isAutoTunnelEnabled) {
val itemFocusRequester = remember { FocusRequester() }
val autoTunnelingLabel = buildAnnotatedString {
val autoTunnelingLabel =
buildAnnotatedString {
append(stringResource(id = R.string.auto_tunneling))
append(": ")
if (uiState.settings.isAutoTunnelPaused) append(
if (uiState.settings.isAutoTunnelPaused) {
append(
stringResource(id = R.string.paused),
) else append(
)
} else {
append(
stringResource(id = R.string.active),
)
}
}
RowListItem(
icon = {
val icon = Icons.Rounded.Bolt
Icon(
icon,
icon.name,
modifier = Modifier
modifier =
Modifier
.padding(end = 8.5.dp)
.size(25.dp),
tint =
if (uiState.settings.isAutoTunnelPaused) Color.Gray
else mint,
if (uiState.settings.isAutoTunnelPaused) {
Color.Gray
} else {
mint
},
)
},
text = autoTunnelingLabel.text,
@@ -539,7 +557,7 @@ fun MainScreen(
onHold = {},
expanded = false,
statistics = null,
focusRequester = focusRequester
focusRequester = focusRequester,
)
}
}
@@ -548,7 +566,8 @@ fun MainScreen(
key = { tunnel -> tunnel.id },
) { tunnel ->
val leadingIconColor =
(if (
(
if (
uiState.vpnState.tunnelConfig?.name == tunnel.name &&
uiState.vpnState.status == TunnelState.UP
) {
@@ -569,13 +588,15 @@ fun MainScreen(
}
} else {
Color.Gray
})
}
)
val itemFocusRequester = remember { FocusRequester() }
val expanded = remember { mutableStateOf(false) }
RowListItem(
icon = {
val circleIcon = Icons.Rounded.Circle
val icon = if (tunnel.isPrimaryTunnel) {
val icon =
if (tunnel.isPrimaryTunnel) {
Icons.Rounded.Star
} else if (tunnel.isMobileDataTunnel) {
Icons.Rounded.Smartphone
@@ -586,7 +607,8 @@ fun MainScreen(
icon,
icon.name,
tint = leadingIconColor,
modifier = Modifier
modifier =
Modifier
.padding(
end = if (icon == circleIcon) 12.5.dp else 10.dp,
start = if (icon == circleIcon) 2.5.dp else 0.dp,
@@ -600,7 +622,9 @@ fun MainScreen(
(uiState.vpnState.status == TunnelState.UP) &&
(tunnel.name == uiState.vpnState.tunnelConfig?.name)
) {
appViewModel.showSnackbarMessage(context.getString(R.string.turn_off_tunnel))
appViewModel.showSnackbarMessage(
context.getString(R.string.turn_off_tunnel),
)
return@RowListItem
}
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
@@ -668,15 +692,16 @@ fun MainScreen(
} else {
val checked by remember {
derivedStateOf {
(uiState.vpnState.status == TunnelState.UP &&
tunnel.name == uiState.vpnState.tunnelConfig?.name)
(
uiState.vpnState.status == TunnelState.UP &&
tunnel.name == uiState.vpnState.tunnelConfig?.name
)
}
}
if (!checked) expanded.value = false
@Composable
fun TunnelSwitch() =
Switch(
fun TunnelSwitch() = Switch(
modifier = Modifier.focusRequester(itemFocusRequester),
checked = checked,
onCheckedChange = { checked ->
@@ -8,5 +8,5 @@ data class MainUiState(
val settings: Settings = Settings(),
val tunnels: TunnelConfigs = emptyList(),
val vpnState: VpnState = VpnState(),
val loading: Boolean = true
val loading: Boolean = true,
)
@@ -37,9 +37,8 @@ constructor(
private val appDataRepository: AppDataRepository,
private val serviceManager: ServiceManager,
val vpnService: VpnService,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : ViewModel() {
val uiState =
combine(
appDataRepository.settings.getSettingsFlow(),
@@ -80,8 +79,7 @@ constructor(
)
}
fun onTunnelStart(tunnelConfig: TunnelConfig, context: Context) =
viewModelScope.launch {
fun onTunnelStart(tunnelConfig: TunnelConfig, context: Context) = viewModelScope.launch {
Timber.d("On start called!")
serviceManager.startVpnService(
context,
@@ -90,9 +88,7 @@ constructor(
)
}
fun onTunnelStop(context: Context) =
viewModelScope.launch {
fun onTunnelStop(context: Context) = viewModelScope.launch {
Timber.i("Stopping active tunnel")
serviceManager.stopVpnService(context, isManualStop = true)
}
@@ -139,16 +135,26 @@ constructor(
return withContext(ioDispatcher) {
try {
validateConfigString(result, configType)
val tunnelName = makeTunnelNameUnique(generateQrCodeTunnelName(result, configType))
val tunnelConfig = when (configType) {
val tunnelName =
makeTunnelNameUnique(generateQrCodeTunnelName(result, configType))
val tunnelConfig =
when (configType) {
ConfigType.AMNEZIA -> {
TunnelConfig(
name = tunnelName, amQuick = result,
wgQuick = TunnelConfig.configFromAmQuick(result).toWgQuickString(),
name = tunnelName,
amQuick = result,
wgQuick =
TunnelConfig.configFromAmQuick(
result,
).toWgQuickString(),
)
}
ConfigType.WIREGUARD -> TunnelConfig(name = tunnelName, wgQuick = result)
ConfigType.WIREGUARD ->
TunnelConfig(
name = tunnelName,
wgQuick = result,
)
}
addTunnel(tunnelConfig)
Result.success(Unit)
@@ -165,20 +171,17 @@ constructor(
var tunnelName = name
var num = 1
while (tunnels.any { it.name == tunnelName }) {
tunnelName = name + "(${num})"
tunnelName = name + "($num)"
num++
}
tunnelName
}
}
private fun saveTunnelConfigFromStream(
stream: InputStream,
fileName: String,
type: ConfigType
) {
private fun saveTunnelConfigFromStream(stream: InputStream, fileName: String, type: ConfigType) {
var amQuick: String? = null
val wgQuick = stream.use {
val wgQuick =
stream.use {
when (type) {
ConfigType.AMNEZIA -> {
val config = org.amnezia.awg.config.Config.parse(it)
@@ -207,11 +210,7 @@ constructor(
return context.applicationContext.contentResolver.openInputStream(uri)
}
suspend fun onTunnelFileSelected(
uri: Uri,
configType: ConfigType,
context: Context
): Result<Unit> {
suspend fun onTunnelFileSelected(uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
return withContext(ioDispatcher) {
try {
if (isValidUriContentScheme(uri)) {
@@ -220,7 +219,8 @@ constructor(
Constants.CONF_FILE_EXTENSION ->
saveTunnelFromConfUri(fileName, uri, configType, context)
Constants.ZIP_FILE_EXTENSION -> saveTunnelsFromZipUri(
Constants.ZIP_FILE_EXTENSION ->
saveTunnelsFromZipUri(
uri,
configType,
context,
@@ -238,11 +238,7 @@ constructor(
}
}
private suspend fun saveTunnelsFromZipUri(
uri: Uri,
configType: ConfigType,
context: Context
): Result<Unit> {
private suspend fun saveTunnelsFromZipUri(uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
return withContext(ioDispatcher) {
ZipInputStream(getInputStreamFromUri(uri, context)).use { zip ->
generateSequence { zip.nextEntry }
@@ -258,7 +254,10 @@ constructor(
val wgQuick =
when (configType) {
ConfigType.AMNEZIA -> {
val config = org.amnezia.awg.config.Config.parse(zip)
val config =
org.amnezia.awg.config.Config.parse(
zip,
)
amQuick = config.toAwgQuickString()
config.toWgQuickString()
}
@@ -285,12 +284,7 @@ constructor(
}
}
private suspend fun saveTunnelFromConfUri(
name: String,
uri: Uri,
configType: ConfigType,
context: Context
): Result<Unit> {
private suspend fun saveTunnelFromConfUri(name: String, uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
return withContext(ioDispatcher) {
val stream = getInputStreamFromUri(uri, context)
return@withContext if (stream != null) {
@@ -312,15 +306,17 @@ constructor(
if (firstTunnel) WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
}
fun pauseAutoTunneling() =
viewModelScope.launch {
appDataRepository.settings.save(uiState.value.settings.copy(isAutoTunnelPaused = true))
fun pauseAutoTunneling() = viewModelScope.launch {
appDataRepository.settings.save(
uiState.value.settings.copy(isAutoTunnelPaused = true),
)
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
}
fun resumeAutoTunneling() =
viewModelScope.launch {
appDataRepository.settings.save(uiState.value.settings.copy(isAutoTunnelPaused = false))
fun resumeAutoTunneling() = viewModelScope.launch {
appDataRepository.settings.save(
uiState.value.settings.copy(isAutoTunnelPaused = false),
)
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
}
@@ -349,8 +345,12 @@ constructor(
val index = getDisplayNameColumnIndex(cursor)
if (index != null) {
cursor.getString(index)
} else null
} else null
} else {
null
}
} else {
null
}
}
private fun isValidUriContentScheme(uri: Uri): Boolean {
@@ -374,9 +374,7 @@ constructor(
}
}
private fun saveSettings(settings: Settings) =
viewModelScope.launch { appDataRepository.settings.save(settings) }
private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
fun onCopyTunnel(tunnel: TunnelConfig?) = viewModelScope.launch {
tunnel?.let {
@@ -81,7 +81,7 @@ fun OptionsScreen(
navController: NavController,
appViewModel: AppViewModel,
focusRequester: FocusRequester,
tunnelId: String
tunnelId: String,
) {
val scrollState = rememberScrollState()
val uiState by optionsViewModel.uiState.collectAsStateWithLifecycle()
@@ -127,21 +127,25 @@ fun OptionsScreen(
visible = true,
enter = slideInVertically(initialOffsetY = { it * 2 }),
exit = slideOutVertically(targetOffsetY = { it * 2 }),
modifier = Modifier
modifier =
Modifier
.focusRequester(focusRequester)
.focusGroup(),
) {
MultiFloatingActionButton(
fabIcon = FabIcon(
fabIcon =
FabIcon(
iconRes = R.drawable.edit,
iconResAfterRotate = R.drawable.close,
iconRotate = 180f,
),
fabOption = FabOption(
fabOption =
FabOption(
iconTint = fobIconColor,
backgroundTint = fobColor,
),
itemsMultiFab = listOf(
itemsMultiFab =
listOf(
MultiFabItem(
label = {
Text(
@@ -151,11 +155,13 @@ fun OptionsScreen(
modifier = Modifier.padding(end = 10.dp),
)
},
modifier = Modifier
modifier =
Modifier
.size(40.dp),
icon = R.drawable.edit,
value = ConfigType.AMNEZIA.name,
miniFabOption = FabOption(
miniFabOption =
FabOption(
backgroundTint = fobColor,
fobIconColor,
),
@@ -171,7 +177,8 @@ fun OptionsScreen(
},
icon = R.drawable.edit,
value = ConfigType.WIREGUARD.name,
miniFabOption = FabOption(
miniFabOption =
FabOption(
backgroundTint = fobColor,
fobIconColor,
),
@@ -180,7 +187,7 @@ fun OptionsScreen(
onFabItemClicked = {
val configType = ConfigType.valueOf(it.value)
navController.navigate(
"${Screen.Config.route}/${tunnelId}?configType=${configType.name}",
"${Screen.Config.route}/$tunnelId?configType=${configType.name}",
)
},
shape = RoundedCornerShape(16.dp),
@@ -208,7 +215,8 @@ fun OptionsScreen(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
(
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier
.height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth)
@@ -217,7 +225,8 @@ fun OptionsScreen(
Modifier
.fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp)
})
}
)
.padding(bottom = 10.dp),
) {
Column(
@@ -233,7 +242,8 @@ fun OptionsScreen(
stringResource(R.string.set_primary_tunnel),
enabled = true,
checked = uiState.isDefaultTunnel,
modifier = Modifier
modifier =
Modifier
.focusRequester(focusRequester),
padding = screenPadding,
onCheckChanged = { optionsViewModel.onTogglePrimaryTunnel() },
@@ -246,7 +256,8 @@ fun OptionsScreen(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
(
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier
.height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth)
@@ -255,7 +266,8 @@ fun OptionsScreen(
Modifier
.fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp)
})
}
)
.padding(bottom = 10.dp),
) {
Column(
@@ -276,7 +288,8 @@ fun OptionsScreen(
)
Column {
FlowRow(
modifier = Modifier
modifier =
Modifier
.padding(screenPadding)
.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(5.dp),
@@ -292,7 +305,6 @@ fun OptionsScreen(
onIconClick = {
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus()
optionsViewModel.onDeleteRunSSID(ssid)
},
text = ssid,
icon = Icons.Filled.Close,
@@ -5,5 +5,5 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
data class OptionsUiState(
val id: String? = null,
val tunnel: TunnelConfig? = null,
val isDefaultTunnel: Boolean = false
val isDefaultTunnel: Boolean = false,
)
@@ -19,14 +19,15 @@ import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class OptionsViewModel @Inject
class OptionsViewModel
@Inject
constructor(
private val appDataRepository: AppDataRepository
private val appDataRepository: AppDataRepository,
) : ViewModel() {
private val _optionState = MutableStateFlow(OptionsUiState())
val uiState = combine(
val uiState =
combine(
appDataRepository.tunnels.getTunnelConfigsFlow(),
_optionState,
) { tunnels, optionState ->
@@ -34,7 +35,9 @@ constructor(
val tunnelConfig = tunnels.fastFirstOrNull { it.id.toString() == optionState.id }
val isPrimaryTunnel = tunnelConfig?.isPrimaryTunnel == true
OptionsUiState(optionState.id, tunnelConfig, isPrimaryTunnel)
} else OptionsUiState()
} else {
OptionsUiState()
}
}.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
@@ -52,7 +55,8 @@ constructor(
fun onDeleteRunSSID(ssid: String) = viewModelScope.launch {
uiState.value.tunnel?.let {
appDataRepository.tunnels.save(
tunnelConfig = it.copy(
tunnelConfig =
it.copy(
tunnelNetworks = (uiState.value.tunnel!!.tunnelNetworks - ssid).toMutableList(),
),
)
@@ -67,11 +71,13 @@ constructor(
suspend fun onSaveRunSSID(ssid: String): Result<Unit> {
val trimmed = ssid.trim()
val tunnelsWithName = withContext(viewModelScope.coroutineContext) {
val tunnelsWithName =
withContext(viewModelScope.coroutineContext) {
appDataRepository.tunnels.findByTunnelNetworksName(trimmed)
}
return if (uiState.value.tunnel?.tunnelNetworks?.contains(trimmed) != true &&
tunnelsWithName.isEmpty()) {
tunnelsWithName.isEmpty()
) {
uiState.value.tunnel?.tunnelNetworks?.add(trimmed)
saveTunnel(uiState.value.tunnel)
Result.success(Unit)
@@ -84,7 +90,9 @@ constructor(
uiState.value.tunnel?.let {
if (it.isMobileDataTunnel) {
appDataRepository.tunnels.updateMobileDataTunnel(null)
} else appDataRepository.tunnels.updateMobileDataTunnel(it)
} else {
appDataRepository.tunnels.updateMobileDataTunnel(it)
}
}
}
@@ -19,9 +19,14 @@ fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
PinLock(
title = { pinExists ->
Text(
text = if (pinExists) stringResource(id = R.string.enter_pin) else stringResource(
text =
if (pinExists) {
stringResource(id = R.string.enter_pin)
} else {
stringResource(
id = R.string.create_pin,
),
)
},
)
},
color = MaterialTheme.colorScheme.surface,
@@ -35,7 +40,6 @@ fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
navController.navigate(Screen.Main.route)
}
}
},
onPinIncorrect = {
// pin is incorrect, show error
@@ -121,7 +121,9 @@ fun SettingsScreen(
}
val startForResult =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
result.data
// Handle the Intent
@@ -131,28 +133,34 @@ fun SettingsScreen(
fun exportAllConfigs() {
try {
val wgFiles = uiState.tunnels.map { config ->
val wgFiles =
uiState.tunnels.map { config ->
val file = File(context.cacheDir, "${config.name}-wg.conf")
file.outputStream().use {
it.write(config.wgQuick.toByteArray())
}
file
}
val amFiles = uiState.tunnels.mapNotNull { config ->
val amFiles =
uiState.tunnels.mapNotNull { config ->
if (config.amQuick != TunnelConfig.AM_QUICK_DEFAULT) {
val file = File(context.cacheDir, "${config.name}-am.conf")
file.outputStream().use {
it.write(config.amQuick.toByteArray())
}
file
} else null
} else {
null
}
}
scope.launch {
viewModel.onExportTunnels(wgFiles + amFiles).onFailure {
appViewModel.showSnackbarMessage(it.getMessage(context))
}.onSuccess {
didExportFiles = true
appViewModel.showSnackbarMessage(context.getString(R.string.exported_configs_message))
appViewModel.showSnackbarMessage(
context.getString(R.string.exported_configs_message),
)
}
}
} catch (e: Exception) {
@@ -260,14 +268,16 @@ fun SettingsScreen(
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.verticalScroll(scrollState),
) {
Icon(
Icons.Rounded.LocationOff,
contentDescription = stringResource(id = R.string.map),
modifier = Modifier
modifier =
Modifier
.padding(30.dp)
.size(128.dp),
)
@@ -321,11 +331,15 @@ fun SettingsScreen(
},
onError = { _ ->
showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authentication_failed))
appViewModel.showSnackbarMessage(
context.getString(R.string.error_authentication_failed),
)
},
onFailure = {
showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authorization_failed))
appViewModel.showSnackbarMessage(
context.getString(R.string.error_authorization_failed),
)
},
)
}
@@ -365,7 +379,8 @@ fun SettingsScreen(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
(
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier
.height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth)
@@ -374,7 +389,8 @@ fun SettingsScreen(
Modifier
.fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp)
})
}
)
.padding(bottom = 10.dp),
) {
Column(
@@ -389,21 +405,26 @@ fun SettingsScreen(
ConfigurationToggle(
stringResource(id = R.string.tunnel_on_wifi),
enabled =
!(uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled),
!(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isTunnelOnWifiEnabled,
padding = screenPadding,
onCheckChanged = { viewModel.onToggleTunnelOnWifi() },
modifier =
if (uiState.settings.isAutoTunnelEnabled) Modifier
else
if (uiState.settings.isAutoTunnelEnabled) {
Modifier
.focusRequester(focusRequester),
} else {
Modifier
.focusRequester(focusRequester)
},
)
AnimatedVisibility(visible = uiState.settings.isTunnelOnWifiEnabled) {
Column {
FlowRow(
modifier = Modifier
modifier =
Modifier
.padding(screenPadding)
.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(5.dp),
@@ -419,13 +440,14 @@ fun SettingsScreen(
onIconClick = {
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus()
viewModel.onDeleteTrustedSSID(ssid)
},
text = ssid,
icon = Icons.Filled.Close,
enabled =
!(uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled),
!(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
)
}
if (uiState.settings.trustedNetworkSSIDs.isEmpty()) {
@@ -438,8 +460,10 @@ fun SettingsScreen(
}
OutlinedTextField(
enabled =
!(uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled),
!(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
value = currentText,
onValueChange = { currentText = it },
label = { Text(stringResource(R.string.add_trusted_ssid)) },
@@ -487,8 +511,10 @@ fun SettingsScreen(
ConfigurationToggle(
stringResource(R.string.tunnel_mobile_data),
enabled =
!(uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled),
!(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isTunnelOnMobileDataEnabled,
padding = screenPadding,
onCheckChanged = { viewModel.onToggleTunnelOnMobileData() },
@@ -496,8 +522,10 @@ fun SettingsScreen(
ConfigurationToggle(
stringResource(id = R.string.tunnel_on_ethernet),
enabled =
!(uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled),
!(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isTunnelOnEthernetEnabled,
padding = screenPadding,
onCheckChanged = { viewModel.onToggleTunnelOnEthernet() },
@@ -505,8 +533,10 @@ fun SettingsScreen(
ConfigurationToggle(
stringResource(R.string.restart_on_ping),
enabled =
!(uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled),
!(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isPingEnabled,
padding = screenPadding,
onCheckChanged = { viewModel.onToggleRestartOnPing() },
@@ -514,11 +544,15 @@ fun SettingsScreen(
Row(
verticalAlignment = Alignment.CenterVertically,
modifier =
(if (!uiState.settings.isAutoTunnelEnabled) Modifier
else
(
if (!uiState.settings.isAutoTunnelEnabled) {
Modifier
} else {
Modifier.focusRequester(
focusRequester,
))
)
}
)
.fillMaxSize()
.padding(top = 5.dp),
horizontalArrangement = Arrangement.Center,
@@ -533,12 +567,16 @@ fun SettingsScreen(
when (false) {
isBackgroundLocationGranted ->
appViewModel.showSnackbarMessage(
context.getString(R.string.background_location_required),
context.getString(
R.string.background_location_required,
),
)
fineLocationState.status.isGranted ->
appViewModel.showSnackbarMessage(
context.getString(R.string.precise_location_required),
context.getString(
R.string.precise_location_required,
),
)
viewModel.isLocationEnabled(context) ->
@@ -569,7 +607,8 @@ fun SettingsScreen(
shadowElevation = 2.dp,
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
modifier =
Modifier
.fillMaxWidth(fillMaxWidth)
.padding(vertical = 10.dp),
) {
@@ -585,9 +624,11 @@ fun SettingsScreen(
ConfigurationToggle(
stringResource(R.string.use_amnezia),
enabled =
!(uiState.settings.isAutoTunnelEnabled ||
!(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled ||
(uiState.vpnState.status == TunnelState.UP) || uiState.settings.isKernelEnabled),
(uiState.vpnState.status == TunnelState.UP) || uiState.settings.isKernelEnabled
),
checked = uiState.settings.isAmneziaEnabled,
padding = screenPadding,
onCheckChanged = {
@@ -598,9 +639,11 @@ fun SettingsScreen(
ConfigurationToggle(
stringResource(R.string.use_kernel),
enabled =
!(uiState.settings.isAutoTunnelEnabled ||
!(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled ||
(uiState.vpnState.status == TunnelState.UP)),
(uiState.vpnState.status == TunnelState.UP)
),
checked = uiState.settings.isKernelEnabled,
padding = screenPadding,
onCheckChanged = {
@@ -676,7 +719,8 @@ fun SettingsScreen(
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.padding(top = 5.dp),
horizontalArrangement = Arrangement.Center,
@@ -10,5 +10,5 @@ data class SettingsUiState(
val vpnState: VpnState = VpnState(),
val isLocationDisclosureShown: Boolean = true,
val isBatteryOptimizeDisableShown: Boolean = false,
val isPinLockEnabled: Boolean = false
val isPinLockEnabled: Boolean = false,
)
@@ -41,9 +41,8 @@ constructor(
private val rootShell: Provider<RootShell>,
private val fileUtils: FileUtils,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
vpnService: VpnService
vpnService: VpnService,
) : ViewModel() {
private val _kernelSupport = MutableStateFlow(false)
val kernelSupport = _kernelSupport.asStateFlow()
@@ -80,13 +79,11 @@ constructor(
}
}
fun setLocationDisclosureShown() =
viewModelScope.launch {
fun setLocationDisclosureShown() = viewModelScope.launch {
appDataRepository.appState.setLocationDisclosureShown(true)
}
fun setBatteryOptimizeDisableShown() =
viewModelScope.launch {
fun setBatteryOptimizeDisableShown() = viewModelScope.launch {
appDataRepository.appState.setBatteryOptimizationDisableShown(true)
}
@@ -111,8 +108,7 @@ constructor(
return fileUtils.saveFilesToZip(files)
}
fun onToggleAutoTunnel(context: Context) =
viewModelScope.launch {
fun onToggleAutoTunnel(context: Context) = viewModelScope.launch {
val isAutoTunnelEnabled = uiState.value.settings.isAutoTunnelEnabled
var isAutoTunnelPaused = uiState.value.settings.isAutoTunnelPaused
@@ -131,8 +127,7 @@ constructor(
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
}
fun onToggleAlwaysOnVPN() =
viewModelScope.launch {
fun onToggleAlwaysOnVPN() = viewModelScope.launch {
saveSettings(
uiState.value.settings.copy(
isAlwaysOnVpnEnabled = !uiState.value.settings.isAlwaysOnVpnEnabled,
@@ -140,8 +135,7 @@ constructor(
)
}
private fun saveSettings(settings: Settings) =
viewModelScope.launch { appDataRepository.settings.save(settings) }
private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
fun onToggleTunnelOnEthernet() {
saveSettings(
@@ -152,7 +146,10 @@ constructor(
}
fun isLocationEnabled(context: Context): Boolean {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val locationManager =
context.getSystemService(
Context.LOCATION_SERVICE,
) as LocationManager
return LocationManagerCompat.isLocationEnabled(locationManager)
}
@@ -207,7 +204,6 @@ constructor(
isAmneziaEnabled = false,
),
)
} catch (e: RootShell.RootShellException) {
Timber.e(e)
saveKernelMode(on = false)
@@ -229,7 +225,8 @@ constructor(
}
fun checkKernelSupport() = viewModelScope.launch {
val kernelSupport = withContext(ioDispatcher) {
val kernelSupport =
withContext(ioDispatcher) {
WgQuickBackend.hasKernelSupport()
}
_kernelSupport.update {
@@ -250,8 +247,8 @@ constructor(
fun onToggleRestartAtBoot() = viewModelScope.launch {
saveSettings(
uiState.value.settings.copy(
isRestoreOnBootEnabled = !uiState.value.settings.isRestoreOnBootEnabled
)
isRestoreOnBootEnabled = !uiState.value.settings.isRestoreOnBootEnabled,
),
)
}
}
@@ -57,7 +57,7 @@ fun SupportScreen(
viewModel: SupportViewModel = hiltViewModel(),
appViewModel: AppViewModel,
navController: NavController,
focusRequester: FocusRequester
focusRequester: FocusRequester,
) {
val context = LocalContext.current
val fillMaxWidth = .85f
@@ -79,7 +79,8 @@ fun SupportScreen(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
(
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier
.height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth)
@@ -88,7 +89,8 @@ fun SupportScreen(
Modifier
.fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp)
})
}
)
.padding(bottom = 25.dp),
) {
Column(modifier = Modifier.padding(20.dp)) {
@@ -113,7 +115,8 @@ fun SupportScreen(
context,
)
},
modifier = Modifier
modifier =
Modifier
.padding(vertical = 5.dp)
.focusRequester(focusRequester),
) {
@@ -128,7 +131,8 @@ fun SupportScreen(
Text(
stringResource(id = R.string.docs_description),
textAlign = TextAlign.Justify,
modifier = Modifier
modifier =
Modifier
.padding(start = 10.dp)
.weight(
weight = 1.0f,
@@ -295,12 +299,14 @@ fun SupportScreen(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(25.dp),
) {
val version = buildAnnotatedString {
val version =
buildAnnotatedString {
append(stringResource(id = R.string.version))
append(": ")
append(BuildConfig.VERSION_NAME)
}
val mode = buildAnnotatedString {
val mode =
buildAnnotatedString {
append(stringResource(R.string.mode))
append(": ")
when (uiState.settings.isKernelEnabled) {
@@ -11,9 +11,10 @@ import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
@HiltViewModel
class SupportViewModel @Inject constructor(settingsRepository: SettingsRepository) :
class SupportViewModel
@Inject
constructor(settingsRepository: SettingsRepository) :
ViewModel() {
val uiState =
settingsRepository
.getSettingsFlow()
@@ -42,7 +42,6 @@ import kotlinx.coroutines.launch
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
val logs = viewModel.logs
val context = LocalContext.current
@@ -87,7 +86,8 @@ fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.Top),
state = lazyColumnListState,
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.padding(horizontal = 24.dp),
) {
@@ -99,13 +99,16 @@ fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
Row(
horizontalArrangement = Arrangement.spacedBy(5.dp, Alignment.Start),
verticalAlignment = Alignment.Top,
modifier = Modifier
modifier =
Modifier
.fillMaxSize()
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = {
clipboardManager.setText(annotatedString = AnnotatedString(it.toString()))
clipboardManager.setText(
annotatedString = AnnotatedString(it.toString()),
)
},
),
) {
@@ -20,13 +20,13 @@ import javax.inject.Inject
@HiltViewModel
class LogsViewModel
@Inject constructor(
@Inject
constructor(
private val localLogCollector: LocalLogCollector,
private val fileUtils: FileUtils,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
@MainDispatcher private val mainDispatcher: CoroutineDispatcher
@MainDispatcher private val mainDispatcher: CoroutineDispatcher,
) : ViewModel() {
val logs = mutableStateListOf<LogMessage>()
init {
@@ -45,7 +45,8 @@ class LogsViewModel
}
suspend fun saveLogsToFile(): Result<Unit> {
val file = localLogCollector.getLogFile().getOrElse {
val file =
localLogCollector.getLogFile().getOrElse {
return Result.failure(it)
}
val fileContent = fileUtils.readBytesFromFile(file)
@@ -49,7 +49,7 @@ fun WireguardAutoTunnelTheme(
// Dynamic color is available on Android 12+
// turning off dynamic color for now
dynamicColor: Boolean = false,
content: @Composable () -> Unit
content: @Composable () -> Unit,
) {
val colorScheme =
when {
@@ -1,7 +1,6 @@
package com.zaneschepke.wireguardautotunnel.util
object Constants {
const val BASE_LOG_FILE_NAME = "wg_tunnel_logs"
const val LOG_BUFFER_SIZE = 3_000L
@@ -32,13 +31,10 @@ object Constants {
const val PING_INTERVAL = 60_000L
const val PING_COOLDOWN = PING_INTERVAL * 60 // one hour
const val ALLOWED_DISPLAY_NAME_LENGTH = 20
const val TUNNEL_EXTRA_KEY = "tunnelId"
const val UNREADABLE_SSID = "<unknown ssid>"
val amneziaProperties = listOf("Jc", "Jmin", "Jmax", "S1", "S2", "H1", "H2", "H3", "H4")
const val QR_CODE_NAME_PROPERTY = "# Name ="
}
@@ -89,8 +89,7 @@ fun Throwable.getMessage(context: Context): String {
* Borrowed from this [Stack Overflow question](https://stackoverflow.com/questions/51022533/kotlin-chunk-sequence-based-on-size-and-time).
*/
@OptIn(ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class)
fun <T> ReceiveChannel<T>.chunked(scope: CoroutineScope, size: Int, time: Duration) =
scope.produce<List<T>> {
fun <T> ReceiveChannel<T>.chunked(scope: CoroutineScope, size: Int, time: Duration) = scope.produce<List<T>> {
while (true) { // this loop goes over each chunk
val chunk = ConcurrentLinkedQueue<T>() // current chunk
val ticker = ticker(time.toMillis()) // time-limit for this chunk
@@ -143,6 +142,3 @@ fun <T> CoroutineScope.asChannel(flow: Flow<T>): ReceiveChannel<T> = produce {
channel.send(value)
}
}
@@ -21,7 +21,6 @@ class FileUtils(
private val context: Context,
private val ioDispatcher: CoroutineDispatcher,
) {
suspend fun readBytesFromFile(file: File): ByteArray {
return withContext(ioDispatcher) {
FileInputStream(file).use {
@@ -61,7 +60,9 @@ class FileUtils(
} else {
val target =
File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS,
),
fileName,
)
FileOutputStream(target).use { output ->
@@ -101,10 +102,7 @@ class FileUtils(
}
// TODO issue with android 9
private fun createDownloadsFileOutputStream(
fileName: String,
mimeType: String = Constants.ALLOWED_FILE_TYPES
): OutputStream? {
private fun createDownloadsFileOutputStream(fileName: String, mimeType: String = Constants.ALLOWED_FILE_TYPES): OutputStream? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val resolver = context.contentResolver
val contentValues =
@@ -4,14 +4,13 @@ import android.content.Context
import androidx.annotation.StringRes
sealed class StringValue {
data class DynamicString(val value: String) : StringValue()
data object Empty : StringValue()
class StringResource(
@StringRes val resId: Int,
vararg val args: Any
vararg val args: Any,
) : StringValue()
fun asString(context: Context?): String {
@@ -5,13 +5,19 @@ import com.zaneschepke.wireguardautotunnel.R
sealed class WgTunnelExceptions : Exception() {
abstract fun getMessage(context: Context): String
data class General(private val userMessage: StringValue) : WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
}
}
data class SsidConflict(private val userMessage: StringValue = StringValue.StringResource(R.string.error_ssid_exists)) :
data class SsidConflict(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_ssid_exists,
),
) :
WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
@@ -19,9 +25,10 @@ sealed class WgTunnelExceptions : Exception() {
}
data class ConfigExportFailed(
private val userMessage: StringValue = StringValue.StringResource(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.export_configs_failed,
)
),
) : WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
@@ -32,18 +39,29 @@ sealed class WgTunnelExceptions : Exception() {
WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return StringValue.StringResource(R.string.config_parse_error).asString(context) + (
if (appendMessage != StringValue.Empty) ": ${appendMessage.asString(context)}" else "")
if (appendMessage != StringValue.Empty) ": ${appendMessage.asString(context)}" else ""
)
}
}
data class RootDenied(private val userMessage: StringValue = StringValue.StringResource(R.string.error_root_denied)) :
data class RootDenied(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_root_denied,
),
) :
WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
}
}
data class InvalidQrCode(private val userMessage: StringValue = StringValue.StringResource(R.string.error_invalid_code)) :
data class InvalidQrCode(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_invalid_code,
),
) :
WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
@@ -51,16 +69,22 @@ sealed class WgTunnelExceptions : Exception() {
}
data class InvalidFileExtension(
private val userMessage: StringValue = StringValue.StringResource(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_file_extension,
)
),
) : WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
}
}
data class FileReadFailed(private val userMessage: StringValue = StringValue.StringResource(R.string.error_file_format)) :
data class FileReadFailed(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_file_format,
),
) :
WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
@@ -68,9 +92,10 @@ sealed class WgTunnelExceptions : Exception() {
}
data class AuthenticationFailed(
private val userMessage: StringValue = StringValue.StringResource(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_authentication_failed,
)
),
) : WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
@@ -78,9 +103,10 @@ sealed class WgTunnelExceptions : Exception() {
}
data class AuthorizationFailed(
private val userMessage: StringValue = StringValue.StringResource(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_authorization_failed,
)
),
) : WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
@@ -88,9 +114,10 @@ sealed class WgTunnelExceptions : Exception() {
}
data class BackgroundLocationRequired(
private val userMessage: StringValue = StringValue.StringResource(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.background_location_required,
)
),
) : WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
@@ -98,9 +125,10 @@ sealed class WgTunnelExceptions : Exception() {
}
data class LocationServicesRequired(
private val userMessage: StringValue = StringValue.StringResource(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.location_services_required,
)
),
) : WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
@@ -108,9 +136,10 @@ sealed class WgTunnelExceptions : Exception() {
}
data class PreciseLocationRequired(
private val userMessage: StringValue = StringValue.StringResource(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.precise_location_required,
)
),
) : WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
@@ -118,13 +147,13 @@ sealed class WgTunnelExceptions : Exception() {
}
data class FileExplorerRequired(
private val userMessage: StringValue = StringValue.StringResource(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_no_file_explorer,
)
),
) : WgTunnelExceptions() {
override fun getMessage(context: Context): String {
return userMessage.asString(context)
}
}
}
+3
View File
@@ -177,4 +177,7 @@
<string name="wireguard" translatable="false">WireGuard</string>
<string name="error_file_format">Invalid tunnel config format</string>
<string name="restart_at_boot">Restart on boot</string>
<string name="vpn_denied_dialog_title">Permission Denied</string>
<string name="vpn_denied_dialog_message">Permission to start the VPN has either been explicitly denied or is being blocked by the system.</string>
<string name="vpn_denied_dialog_message2">If VPN permission is being blocked by the system, please confirm no other app is using the Always-on VPN feature and try again.</string>
</resources>
+16
View File
@@ -6,4 +6,20 @@ plugins {
alias(libs.plugins.ksp) apply false
alias(libs.plugins.androidLibrary) apply false
alias(libs.plugins.compose.compiler) apply false
alias(libs.plugins.ktlint)
}
subprojects {
apply {
plugin(rootProject.libs.plugins.ktlint.get().pluginId)
}
ktlint {
debug.set(false)
verbose.set(true)
android.set(true)
outputToConsole.set(true)
ignoreFailures.set(false)
enableExperimentalRules.set(true)
}
}
+2
View File
@@ -14,8 +14,10 @@ object Constants {
const val RELEASE = "release"
const val NIGHTLY = "nightly"
const val PRERELEASE = "prerelease"
const val DEBUG = "debug"
const val TYPE = "type"
const val NIGHTLY_CODE = 42
const val PRERELEASE_CODE = 99
}
+12 -9
View File
@@ -3,13 +3,13 @@ import org.gradle.api.invocation.Gradle
import java.io.File
import java.util.Properties
private fun getCurrentFlavor(gradle: Gradle): String {
fun Project.getCurrentFlavor(): String {
val taskRequestsStr = gradle.startParameter.taskRequests.toString()
val pattern: java.util.regex.Pattern =
if (taskRequestsStr.contains("assemble")) {
java.util.regex.Pattern.compile("assemble(\\w+)(Release|Debug)")
if (taskRequestsStr.contains(":app:assemble")) {
java.util.regex.Pattern.compile(":app:assemble(\\w+)(Release|Debug)")
} else {
java.util.regex.Pattern.compile("bundle(\\w+)(Release|Debug)")
java.util.regex.Pattern.compile(":app:bundle(\\w+)(Release|Debug)")
}
val matcher = pattern.matcher(taskRequestsStr)
@@ -23,8 +23,15 @@ private fun getCurrentFlavor(gradle: Gradle): String {
return flavor
}
fun Project.getBuildTaskName(): String {
val taskRequestsStr = gradle.startParameter.taskRequests[0].toString()
return taskRequestsStr.also {
project.logger.lifecycle("Build task: $it")
}
}
fun getLocalProperty(key: String, file: String = "local.properties"): String? {
val properties = java.util.Properties()
val properties = Properties()
val localProperties = File(file)
if (localProperties.isFile) {
java.io.InputStreamReader(java.io.FileInputStream(localProperties), Charsets.UTF_8)
@@ -35,10 +42,6 @@ fun getLocalProperty(key: String, file: String = "local.properties"): String? {
return properties.getProperty(key)
}
fun Project.isGeneralFlavor(gradle: Gradle): Boolean {
return getCurrentFlavor(gradle) == "general"
}
fun Project.getSigningProperties(): Properties {
return Properties().apply {
@@ -0,0 +1,3 @@
Melhorias:
- Corrige o bug de permissões do Android 9
- Outras otimizações
@@ -0,0 +1,5 @@
Melhorias:
- Adicionada estatísticas do túnel na tela principal
- Melhoria de navegação de configurações na tela do AndroidTV
- Removida a vibração nas notificações
- Outras correções de bugs
@@ -0,0 +1,14 @@
Recursos
- Adiciona túneis por arquivos .conf, zip, manualmente ou por código QR
- Auto connecta à VPN baseado no nome (SSID) do Wi-Fi, ethernet ou dados móveis
- Túnel dividido por aplicativo com busca
- Suporte à WireGuard em modo kernel ou usuário
- Suporte à Amnezia em modo usuário para proteção contra censura e DPI (Inspeção Profunda de Pacote)
- Suporte à VPN sempre ligada
- Exportação de túneis Amnezia e WireGuard em arquivos zip
- Suporte à quick tile para ligar e desligar a VPN
- Atalhos para o túnel principal para integração com automações
- Intent automation para todos os túneis
- Início automático depois de reiniciar o aparelho
- Medidas para economia de bateria
@@ -0,0 +1 @@
Um cliente de VPN alternativo para WireGuard com recursos adicionais
@@ -0,0 +1 @@
WG Tunnel
+4 -2
View File
@@ -4,7 +4,7 @@ activityCompose = "1.9.1"
amneziawgAndroid = "1.2.0"
androidx-junit = "1.2.1"
appcompat = "1.7.0"
biometricKtx = "1.4.0-alpha01"
biometricKtx = "1.2.0-alpha05"
coreGoogleShortcuts = "1.1.0"
coreKtx = "1.13.1"
datastorePreferences = "1.1.1"
@@ -24,7 +24,7 @@ timber = "5.0.1"
tunnel = "1.0.20230706"
androidGradlePlugin = "8.5.1"
kotlin = "2.0.0"
ksp = "2.0.0-1.0.23"
ksp = "2.0.0-1.0.24"
composeBom = "2024.06.00"
compose = "1.6.8"
zxingAndroidEmbedded = "4.3.0"
@@ -33,6 +33,7 @@ gradlePlugins-grgit="5.2.2"
#plugins
material = "1.12.0"
gradlePlugins-ktlint="12.1.1"
[libraries]
@@ -101,4 +102,5 @@ ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
kotlinxSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
androidLibrary = { id = "com.android.library", version.ref = "androidGradlePlugin" }
compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
ktlint = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "gradlePlugins-ktlint" }
grgit = { id = "org.ajoberstar.grgit.service", version.ref = "gradlePlugins-grgit" }
+8 -4
View File
@@ -5,10 +5,10 @@ plugins {
android {
namespace = "com.zaneschepke.logcatter"
compileSdk = 34
compileSdk = Constants.TARGET_SDK
defaultConfig {
minSdk = 26
minSdk = Constants.MIN_SDK
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")
@@ -23,8 +23,12 @@ android {
)
}
create("nightly") {
initWith(getByName("release"))
create(Constants.PRERELEASE) {
initWith(getByName(Constants.RELEASE))
}
create(Constants.NIGHTLY) {
initWith(getByName(Constants.RELEASE))
}
}
compileOptions {
@@ -6,8 +6,10 @@ import java.io.File
interface LocalLogCollector {
fun start(onLogMessage: ((message: LogMessage) -> Unit)? = null)
fun stop()
suspend fun getLogFile(): Result<File>
val bufferedLogs: Flow<LogMessage>
}
@@ -0,0 +1,276 @@
package com.zaneschepke.logcatter
import android.content.Context
import com.zaneschepke.logcatter.model.LogLevel
import com.zaneschepke.logcatter.model.LogMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.BufferedReader
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
object LogcatUtil {
private const val MAX_FILE_SIZE = 2097152L // 2MB
private const val MAX_FOLDER_SIZE = 10485760L // 10MB
private val findKeyRegex = """[A-Za-z0-9+/]{42}[AEIMQUYcgkosw480]=""".toRegex()
private val findIpv6AddressRegex =
"""(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:)
|{1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:)
|{1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]
|{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)
|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9])
|{0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1
|{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))
""".trimMargin().toRegex()
private val findIpv4AddressRegex = """((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}""".toRegex()
private val findTunnelNameRegex = """(?<=tunnel ).*?(?= UP| DOWN)""".toRegex()
private const val CHORE = "Choreographer"
private object LogcatHelperInit {
var maxFileSize: Long = MAX_FILE_SIZE
var maxFolderSize: Long = MAX_FOLDER_SIZE
var pID: Int = 0
var publicAppDirectory = ""
var logcatPath = ""
}
fun init(maxFileSize: Long = MAX_FILE_SIZE, maxFolderSize: Long = MAX_FOLDER_SIZE, context: Context): LocalLogCollector {
if (maxFileSize > maxFolderSize) {
throw IllegalStateException("maxFileSize must be less than maxFolderSize")
}
synchronized(LogcatHelperInit) {
LogcatHelperInit.maxFileSize = maxFileSize
LogcatHelperInit.maxFolderSize = maxFolderSize
LogcatHelperInit.pID = android.os.Process.myPid()
context.getExternalFilesDir(null)?.let {
LogcatHelperInit.publicAppDirectory = it.absolutePath
LogcatHelperInit.logcatPath =
LogcatHelperInit.publicAppDirectory + File.separator + "logs"
val logDirectory = File(LogcatHelperInit.logcatPath)
if (!logDirectory.exists()) {
logDirectory.mkdir()
}
}
return Logcat
}
}
internal object Logcat : LocalLogCollector {
private var logcatReader: LogcatReader? = null
override fun start(onLogMessage: ((message: LogMessage) -> Unit)?) {
logcatReader ?: run {
logcatReader =
LogcatReader(
LogcatHelperInit.pID.toString(),
LogcatHelperInit.logcatPath,
onLogMessage,
)
}
logcatReader?.let { logReader ->
if (!logReader.isAlive) logReader.start()
}
}
override fun stop() {
logcatReader?.stopLogs()
logcatReader = null
}
private fun mergeLogsApi26(sourceDir: String, outputFile: File) {
val outputFilePath = Paths.get(outputFile.absolutePath)
val logcatPath = Paths.get(sourceDir)
Files.list(logcatPath).use {
it.sorted { o1, o2 ->
Files.getLastModifiedTime(o1).compareTo(Files.getLastModifiedTime(o2))
}
.flatMap(Files::lines).use { lines ->
lines.forEach { line ->
Files.write(
outputFilePath,
(line + System.lineSeparator()).toByteArray(),
StandardOpenOption.CREATE,
StandardOpenOption.APPEND,
)
}
}
}
}
override suspend fun getLogFile(): Result<File> {
stop()
return withContext(Dispatchers.IO) {
try {
val outputDir =
File(LogcatHelperInit.publicAppDirectory + File.separator + "output")
val outputFile = File(outputDir.absolutePath + File.separator + "logs.txt")
if (!outputDir.exists()) outputDir.mkdir()
if (outputFile.exists()) outputFile.delete()
mergeLogsApi26(LogcatHelperInit.logcatPath, outputFile)
Result.success(outputFile)
} catch (e: Exception) {
Result.failure(e)
} finally {
start()
}
}
}
private val _bufferedLogs =
MutableSharedFlow<LogMessage>(
replay = 10_000,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
override val bufferedLogs: Flow<LogMessage> = _bufferedLogs.asSharedFlow()
private class LogcatReader(
pID: String,
private val logcatPath: String,
private val callback: ((input: LogMessage) -> Unit)?,
) : Thread() {
private var logcatProc: Process? = null
private var reader: BufferedReader? = null
private var mRunning = true
private var command = ""
private var clearLogCommand = ""
private var outputStream: FileOutputStream? = null
init {
try {
outputStream = FileOutputStream(createLogFile(logcatPath))
} catch (e: FileNotFoundException) {
Timber.e(e)
}
command = "logcat -v epoch | grep \"($pID)\""
clearLogCommand = "logcat -c"
}
fun stopLogs() {
mRunning = false
}
fun clear() {
Runtime.getRuntime().exec(clearLogCommand)
}
private fun obfuscator(log: String): String {
return findKeyRegex.replace(log, "<crypto-key>").let { first ->
findIpv6AddressRegex.replace(first, "<ipv6-address>").let { second ->
findTunnelNameRegex.replace(second, "<tunnel>")
}
}.let { last -> findIpv4AddressRegex.replace(last, "<ipv4-address>") }
}
override fun run() {
if (outputStream == null) return
try {
clear()
logcatProc = Runtime.getRuntime().exec(command)
reader = BufferedReader(InputStreamReader(logcatProc!!.inputStream), 1024)
var line: String? = null
while (mRunning && run {
line = reader!!.readLine()
line
} != null
) {
if (!mRunning) {
break
}
if (line!!.isEmpty()) {
continue
}
if (outputStream!!.channel.size() >= LogcatHelperInit.maxFileSize) {
outputStream!!.close()
outputStream = FileOutputStream(createLogFile(logcatPath))
}
if (getFolderSize(logcatPath) >= LogcatHelperInit.maxFolderSize) {
deleteOldestFile(logcatPath)
}
line?.let { text ->
val obfuscated = obfuscator(text)
outputStream!!.write(
(obfuscated + System.lineSeparator()).toByteArray(),
)
try {
val logMessage = LogMessage.from(obfuscated)
when (logMessage.level) {
LogLevel.VERBOSE -> Unit
else -> {
if (!logMessage.tag.contains(CHORE)) {
_bufferedLogs.tryEmit(logMessage)
}
}
}
callback?.let {
it(logMessage)
}
} catch (e: Exception) {
Timber.e(e)
}
}
}
} catch (e: IOException) {
Timber.e(e)
} finally {
logcatProc?.destroy()
logcatProc = null
try {
reader?.close()
outputStream?.close()
reader = null
outputStream = null
} catch (e: IOException) {
Timber.e(e)
}
}
}
private fun getFolderSize(path: String): Long {
File(path).run {
var size = 0L
if (this.isDirectory && this.listFiles() != null) {
for (file in this.listFiles()!!) {
size += getFolderSize(file.absolutePath)
}
} else {
size = this.length()
}
return size
}
}
private fun createLogFile(dir: String): File {
return File(dir, "logcat_" + System.currentTimeMillis() + ".txt")
}
private fun deleteOldestFile(path: String) {
val directory = File(path)
if (directory.isDirectory) {
directory.listFiles()?.toMutableList()?.run {
this.sortBy { it.lastModified() }
this.first().delete()
}
}
}
}
}
}
@@ -1,271 +0,0 @@
package com.zaneschepke.logcatter
import android.content.Context
import com.zaneschepke.logcatter.model.LogLevel
import com.zaneschepke.logcatter.model.LogMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.BufferedReader
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
object LogcatHelper {
private const val MAX_FILE_SIZE = 2097152L // 2MB
private const val MAX_FOLDER_SIZE = 10485760L // 10MB
private val findKeyRegex = """[A-Za-z0-9+/]{42}[AEIMQUYcgkosw480]=""".toRegex()
private val findIpv6AddressRegex =
"""(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))""".toRegex()
private val findIpv4AddressRegex = """((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}""".toRegex()
private val findTunnelNameRegex = """(?<=tunnel ).*?(?= UP| DOWN)""".toRegex()
private const val CHORE = "Choreographer"
private object LogcatHelperInit {
var maxFileSize: Long = MAX_FILE_SIZE
var maxFolderSize: Long = MAX_FOLDER_SIZE
var pID: Int = 0
var publicAppDirectory = ""
var logcatPath = ""
}
fun init(
maxFileSize: Long = MAX_FILE_SIZE,
maxFolderSize: Long = MAX_FOLDER_SIZE,
context: Context
): LocalLogCollector {
if (maxFileSize > maxFolderSize) {
throw IllegalStateException("maxFileSize must be less than maxFolderSize")
}
synchronized(LogcatHelperInit) {
LogcatHelperInit.maxFileSize = maxFileSize
LogcatHelperInit.maxFolderSize = maxFolderSize
LogcatHelperInit.pID = android.os.Process.myPid()
context.getExternalFilesDir(null)?.let {
LogcatHelperInit.publicAppDirectory = it.absolutePath
LogcatHelperInit.logcatPath =
LogcatHelperInit.publicAppDirectory + File.separator + "logs"
val logDirectory = File(LogcatHelperInit.logcatPath)
if (!logDirectory.exists()) {
logDirectory.mkdir()
}
}
return Logcat
}
}
internal object Logcat : LocalLogCollector {
private var logcatReader: LogcatReader? = null
override fun start(onLogMessage: ((message: LogMessage) -> Unit)?) {
logcatReader ?: run {
logcatReader = LogcatReader(
LogcatHelperInit.pID.toString(),
LogcatHelperInit.logcatPath,
onLogMessage,
)
}
logcatReader?.let { logReader ->
if (!logReader.isAlive) logReader.start()
}
}
override fun stop() {
logcatReader?.stopLogs()
logcatReader = null
}
private fun mergeLogsApi26(sourceDir: String, outputFile: File) {
val outputFilePath = Paths.get(outputFile.absolutePath)
val logcatPath = Paths.get(sourceDir)
Files.list(logcatPath).use {
it.sorted { o1, o2 ->
Files.getLastModifiedTime(o1).compareTo(Files.getLastModifiedTime(o2))
}
.flatMap(Files::lines).use { lines ->
lines.forEach { line ->
Files.write(
outputFilePath,
(line + System.lineSeparator()).toByteArray(),
StandardOpenOption.CREATE,
StandardOpenOption.APPEND,
)
}
}
}
}
override suspend fun getLogFile(): Result<File> {
stop()
return withContext(Dispatchers.IO) {
try {
val outputDir =
File(LogcatHelperInit.publicAppDirectory + File.separator + "output")
val outputFile = File(outputDir.absolutePath + File.separator + "logs.txt")
if (!outputDir.exists()) outputDir.mkdir()
if (outputFile.exists()) outputFile.delete()
mergeLogsApi26(LogcatHelperInit.logcatPath, outputFile)
Result.success(outputFile)
} catch (e: Exception) {
Result.failure(e)
} finally {
start()
}
}
}
private val _bufferedLogs = MutableSharedFlow<LogMessage>(
replay = 10_000,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
override val bufferedLogs: Flow<LogMessage> = _bufferedLogs.asSharedFlow()
private class LogcatReader(
pID: String,
private val logcatPath: String,
private val callback: ((input: LogMessage) -> Unit)?,
) : Thread() {
private var logcatProc: Process? = null
private var reader: BufferedReader? = null
private var mRunning = true
private var command = ""
private var clearLogCommand = ""
private var outputStream: FileOutputStream? = null
init {
try {
outputStream = FileOutputStream(createLogFile(logcatPath))
} catch (e: FileNotFoundException) {
Timber.e(e)
}
command = "logcat -v epoch | grep \"($pID)\""
clearLogCommand = "logcat -c"
}
fun stopLogs() {
mRunning = false
}
fun clear() {
Runtime.getRuntime().exec(clearLogCommand)
}
private fun obfuscator(log: String): String {
return findKeyRegex.replace(log, "<crypto-key>").let { first ->
findIpv6AddressRegex.replace(first, "<ipv6-address>").let { second ->
findTunnelNameRegex.replace(second, "<tunnel>")
}
}.let { last -> findIpv4AddressRegex.replace(last, "<ipv4-address>") }
}
override fun run() {
if (outputStream == null) return
try {
clear()
logcatProc = Runtime.getRuntime().exec(command)
reader = BufferedReader(InputStreamReader(logcatProc!!.inputStream), 1024)
var line: String? = null
while (mRunning && run {
line = reader!!.readLine()
line
} != null
) {
if (!mRunning) {
break
}
if (line!!.isEmpty()) {
continue
}
if (outputStream!!.channel.size() >= LogcatHelperInit.maxFileSize) {
outputStream!!.close()
outputStream = FileOutputStream(createLogFile(logcatPath))
}
if (getFolderSize(logcatPath) >= LogcatHelperInit.maxFolderSize) {
deleteOldestFile(logcatPath)
}
line?.let { text ->
val obfuscated = obfuscator(text)
outputStream!!.write((obfuscated + System.lineSeparator()).toByteArray())
try {
val logMessage = LogMessage.from(obfuscated)
when (logMessage.level) {
LogLevel.VERBOSE -> Unit
else -> {
if (!logMessage.tag.contains(CHORE)) {
_bufferedLogs.tryEmit(logMessage)
}
}
}
callback?.let {
it(logMessage)
}
} catch (e: Exception) {
Timber.e(e)
}
}
}
} catch (e: IOException) {
Timber.e(e)
} finally {
logcatProc?.destroy()
logcatProc = null
try {
reader?.close()
outputStream?.close()
reader = null
outputStream = null
} catch (e: IOException) {
Timber.e(e)
}
}
}
private fun getFolderSize(path: String): Long {
File(path).run {
var size = 0L
if (this.isDirectory && this.listFiles() != null) {
for (file in this.listFiles()!!) {
size += getFolderSize(file.absolutePath)
}
} else {
size = this.length()
}
return size
}
}
private fun createLogFile(dir: String): File {
return File(dir, "logcat_" + System.currentTimeMillis() + ".txt")
}
private fun deleteOldestFile(path: String) {
val directory = File(path)
if (directory.isDirectory) {
directory.listFiles()?.toMutableList()?.run {
this.sortBy { it.lastModified() }
this.first().delete()
}
}
}
}
}
}
@@ -30,7 +30,7 @@ enum class LogLevel(val signifier: String) {
override fun color(): Long {
return 0xFF000000
}
};
}, ;
abstract fun color(): Long
+3 -1
View File
@@ -24,7 +24,9 @@ fun getLocalProperty(key: String, file: String = "local.properties"): String? {
.use { reader ->
properties.load(reader)
}
} else return null
} else {
return null
}
return properties.getProperty(key)
}