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}] root = true
indent_style = space
insert_final_newline = true [*]
max_line_length = 100 charset = utf-8
indent_size = 4 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_continuation_indent_size = 4
ij_java_names_count_to_use_import_on_demand = 9999 ij_java_names_count_to_use_import_on_demand = 9999
ij_kotlin_align_in_columns_case_branch = false 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_method_parentheses = false
ij_kotlin_align_multiline_parameters = true ij_kotlin_align_multiline_parameters = true
ij_kotlin_align_multiline_parameters_in_calls = false 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_assignment_wrap = normal
ij_kotlin_blank_lines_after_class_header = 0 ij_kotlin_blank_lines_after_class_header = 0
ij_kotlin_blank_lines_around_block_when_branches = 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_block_comment_at_first_column = true
ij_kotlin_call_parameters_new_line_after_left_paren = 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_right_paren_on_new_line = false
ij_kotlin_call_parameters_wrap = on_every_item
ij_kotlin_catch_on_new_line = false 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_chained_calls = true
ij_kotlin_continuation_indent_for_expression_bodies = true ij_kotlin_continuation_indent_for_expression_bodies = true
ij_kotlin_continuation_indent_in_argument_lists = 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_call_chain_wrap = normal
ij_kotlin_method_parameters_new_line_after_left_paren = true ij_kotlin_method_parameters_new_line_after_left_paren = true
ij_kotlin_method_parameters_right_paren_on_new_line = 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 = 9999
ij_kotlin_name_count_to_use_star_import_for_members = 9999 ij_kotlin_name_count_to_use_star_import_for_members = 9999
ij_kotlin_parameter_annotation_wrap = off 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_elvis_expressions = 1
ij_kotlin_wrap_expression_body_functions = 1 ij_kotlin_wrap_expression_body_functions = 1
ij_kotlin_wrap_first_method_in_call_chain = false 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) # Build and sign APK ("-x test" argument is used to skip tests)
# add fdroid flavor for apk upload # add fdroid flavor for apk upload
- name: Build Fdroid Release APK - 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 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 - name: Build Fdroid Nightly APK
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }} if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
@@ -96,11 +99,13 @@ jobs:
- if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }} - 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 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 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 - name: Get version code
if: ${{ inputs.release_type == 'release' || inputs.release_type == 'prerelease' }} if: ${{ inputs.release_type == 'release' }}
run: | run: |
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n') version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
@@ -125,32 +130,32 @@ jobs:
repository: zaneschepke/fdroid repository: zaneschepke/fdroid
event-type: fdroid-update 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" # Setup TAG_NAME, which is used as a general "name"
- if: github.event_name == 'workflow_dispatch' - if: github.event_name == 'workflow_dispatch'
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
- if: github.event_name == 'schedule' - if: github.event_name == 'schedule'
run: echo "TAG_NAME=nightly" >> $GITHUB_ENV 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') }} if: ${{ contains(env.TAG_NAME, 'nightly') }}
run: | 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 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 - name: Get checksum
id: checksum id: checksum
run: echo "checksum=$(apksigner verify -print-certs ${{ env.APK_PATH }} | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT 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 - name: Grant execute permission for gradlew
run: chmod +x 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 - name: Deploy with fastlane
uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1
with: with:
+36 -21
View File
@@ -11,7 +11,6 @@ plugins {
android { android {
namespace = Constants.APP_ID namespace = Constants.APP_ID
compileSdk = Constants.TARGET_SDK compileSdk = Constants.TARGET_SDK
compileSdkPreview = "VanillaIceCream"
androidResources { androidResources {
generateLocaleConfig = true generateLocaleConfig = true
@@ -21,8 +20,8 @@ android {
applicationId = Constants.APP_ID applicationId = Constants.APP_ID
minSdk = Constants.MIN_SDK minSdk = Constants.MIN_SDK
targetSdk = Constants.TARGET_SDK targetSdk = Constants.TARGET_SDK
versionCode = Constants.VERSION_CODE versionCode = determineVersionCode()
versionName = Constants.VERSION_NAME versionName = determineVersionName()
ksp { arg("room.schemaLocation", "$projectDir/schemas") } ksp { arg("room.schemaLocation", "$projectDir/schemas") }
@@ -49,16 +48,6 @@ android {
listOf("libwg-go.so", "libwg-quick.so", "libwg.so"), 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 { release {
isDebuggable = false isDebuggable = false
isMinifyEnabled = true isMinifyEnabled = true
@@ -71,10 +60,24 @@ android {
} }
debug { isDebuggable = true } debug { isDebuggable = true }
create(Constants.PRERELEASE) {
initWith(buildTypes.getByName(Constants.RELEASE))
}
create(Constants.NIGHTLY) { create(Constants.NIGHTLY) {
initWith(getByName("release")) initWith(buildTypes.getByName(Constants.RELEASE))
defaultConfig.versionName = nightlyVersionName() }
defaultConfig.versionCode = nightlyVersionCode()
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) flavorDimensions.add(Constants.TYPE)
@@ -138,7 +141,6 @@ dependencies {
// logging // logging
implementation(libs.timber) implementation(libs.timber)
// compose navigation // compose navigation
implementation(libs.androidx.navigation.compose) implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.hilt.navigation.compose) implementation(libs.androidx.hilt.navigation.compose)
@@ -185,10 +187,23 @@ dependencies {
implementation(libs.androidx.core.splashscreen) implementation(libs.androidx.core.splashscreen)
} }
fun nightlyVersionCode() : Int { fun determineVersionCode(): Int {
return Constants.VERSION_CODE + Constants.NIGHTLY_CODE 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 { fun determineVersionName(): String {
return Constants.VERSION_NAME + "-${grgitService.service.get().grgit.head().abbreviatedId}" 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.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" /> <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
</intent-filter> </intent-filter>
<meta-data <meta-data
android:name="android.app.shortcuts" android:name="android.app.shortcuts"
@@ -81,19 +81,20 @@
android:name=".ui.MainActivity" android:name=".ui.MainActivity"
android:exported="true" android:exported="true"
android:theme="@style/Theme.WireguardAutoTunnel"> android:theme="@style/Theme.WireguardAutoTunnel">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
</intent-filter>
</activity> </activity>
<activity <activity
android:name="com.journeyapps.barcodescanner.CaptureActivity" android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait" android:screenOrientation="portrait"
tools:replace="screenOrientation" /> tools:replace="screenOrientation" />
<activity <activity
android:name=".service.shortcut.ShortcutsActivity" android:name=".service.shortcut.ShortcutsActivity"
android:enabled="true" android:enabled="true"
android:exported="true" android:exported="true"
android:noHistory="true"
android:excludeFromRecents="true"
android:finishOnTaskLaunch="true" android:finishOnTaskLaunch="true"
android:launchMode="singleInstance"
android:theme="@android:style/Theme.NoDisplay" /> android:theme="@android:style/Theme.NoDisplay" />
<service <service
@@ -14,7 +14,6 @@ import timber.log.Timber
@HiltAndroidApp @HiltAndroidApp
class WireGuardAutoTunnel : Application() { class WireGuardAutoTunnel : Application() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
instance = this instance = this
@@ -28,11 +27,12 @@ class WireGuardAutoTunnel : Application() {
.penaltyLog() .penaltyLog()
.build(), .build(),
) )
} else Timber.plant(ReleaseTree()) } else {
Timber.plant(ReleaseTree())
}
} }
companion object { companion object {
lateinit var instance: WireGuardAutoTunnel lateinit var instance: WireGuardAutoTunnel
private set private set
@@ -19,7 +19,7 @@ import java.io.IOException
class DataStoreManager( class DataStoreManager(
private val context: Context, private val context: Context,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) { ) {
companion object { companion object {
val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN") 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] } fun <T> getFromStoreFlow(key: Preferences.Key<T>) = context.dataStore.data.map { it[key] }
suspend fun <T> getFromStore(key: Preferences.Key<T>): T? { suspend fun <T> getFromStore(key: Preferences.Key<T>): T? {
@@ -74,7 +73,6 @@ class DataStoreManager(
} }
} }
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking { fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking {
context.dataStore.data.map { it[key] }.first() context.dataStore.data.map { it[key] }.first()
} }
@@ -5,7 +5,7 @@ data class GeneralState(
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT, val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
val isTunnelRunningFromManualStart: Boolean = TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT, val isTunnelRunningFromManualStart: Boolean = TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT, val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
val activeTunnelId: Int? = null val activeTunnelId: Int? = null,
) { ) {
companion object { companion object {
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
@@ -4,6 +4,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
interface AppDataRepository { interface AppDataRepository {
suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? suspend fun getPrimaryOrFirstTunnel(): TunnelConfig?
suspend fun getStartTunnelConfig(): TunnelConfig? suspend fun getStartTunnelConfig(): TunnelConfig?
suspend fun toggleWatcherServicePause() suspend fun toggleWatcherServicePause()
@@ -3,10 +3,12 @@ package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
import javax.inject.Inject import javax.inject.Inject
class AppDataRoomRepository @Inject constructor( class AppDataRoomRepository
@Inject
constructor(
override val settings: SettingsRepository, override val settings: SettingsRepository,
override val tunnels: TunnelConfigRepository, override val tunnels: TunnelConfigRepository,
override val appState: AppStateRepository override val appState: AppStateRepository,
) : AppDataRepository { ) : AppDataRepository {
override suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? { override suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? {
return tunnels.findPrimary().firstOrNull() ?: tunnels.getAll().firstOrNull() return tunnels.findPrimary().firstOrNull() ?: tunnels.getAll().firstOrNull()
@@ -17,7 +19,9 @@ class AppDataRoomRepository @Inject constructor(
appState.getActiveTunnelId()?.let { appState.getActiveTunnelId()?.let {
tunnels.getById(it) tunnels.getById(it)
} }
} else null } else {
null
}
} }
override suspend fun toggleWatcherServicePause() { override suspend fun toggleWatcherServicePause() {
@@ -5,15 +5,19 @@ import kotlinx.coroutines.flow.Flow
interface AppStateRepository { interface AppStateRepository {
suspend fun isLocationDisclosureShown(): Boolean suspend fun isLocationDisclosureShown(): Boolean
suspend fun setLocationDisclosureShown(shown: Boolean) suspend fun setLocationDisclosureShown(shown: Boolean)
suspend fun isPinLockEnabled(): Boolean suspend fun isPinLockEnabled(): Boolean
suspend fun setPinLockEnabled(enabled: Boolean) suspend fun setPinLockEnabled(enabled: Boolean)
suspend fun isBatteryOptimizationDisableShown(): Boolean suspend fun isBatteryOptimizationDisableShown(): Boolean
suspend fun setBatteryOptimizationDisableShown(shown: Boolean) suspend fun setBatteryOptimizationDisableShown(shown: Boolean)
suspend fun isTunnelRunningFromManualStart(): Boolean suspend fun isTunnelRunningFromManualStart(): Boolean
suspend fun setTunnelRunningFromManualStart(id: Int) suspend fun setTunnelRunningFromManualStart(id: Int)
suspend fun setManualStop() suspend fun setManualStop()
@@ -25,5 +29,4 @@ interface AppStateRepository {
suspend fun setCurrentSsid(ssid: String) suspend fun setCurrentSsid(ssid: String)
val generalStateFlow: Flow<GeneralState> val generalStateFlow: Flow<GeneralState>
} }
@@ -74,13 +74,17 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
prefs?.let { pref -> prefs?.let { pref ->
try { try {
GeneralState( GeneralState(
isLocationDisclosureShown = pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN] isLocationDisclosureShown =
pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT, ?: 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, ?: 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, ?: 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, ?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
) )
} catch (e: IllegalArgumentException) { } catch (e: IllegalArgumentException) {
@@ -5,7 +5,6 @@ import com.zaneschepke.wireguardautotunnel.data.domain.Settings
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
class RoomSettingsRepository(private val settingsDoa: SettingsDao) : SettingsRepository { class RoomSettingsRepository(private val settingsDoa: SettingsDao) : SettingsRepository {
override suspend fun save(settings: Settings) { override suspend fun save(settings: Settings) {
settingsDoa.save(settings) settingsDoa.save(settings)
} }
@@ -28,7 +28,6 @@ class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
), ),
) )
} }
} }
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) { override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
@@ -5,7 +5,6 @@ import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface TunnelConfigRepository { interface TunnelConfigRepository {
fun getTunnelConfigsFlow(): Flow<TunnelConfigs> fun getTunnelConfigsFlow(): Flow<TunnelConfigs>
suspend fun getAll(): TunnelConfigs suspend fun getAll(): TunnelConfigs
@@ -2,7 +2,7 @@ package com.zaneschepke.wireguardautotunnel.module
import android.content.Context import android.content.Context
import com.zaneschepke.logcatter.LocalLogCollector import com.zaneschepke.logcatter.LocalLogCollector
import com.zaneschepke.logcatter.LogcatHelper import com.zaneschepke.logcatter.LogcatUtil
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
@@ -25,6 +25,6 @@ class AppModule {
@Singleton @Singleton
@Provides @Provides
fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector { fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector {
return LogcatHelper.init(context = context) return LogcatUtil.init(context = context)
} }
} }
@@ -66,10 +66,7 @@ class RepositoryModule {
@Singleton @Singleton
@Provides @Provides
fun providePreferencesDataStore( fun providePreferencesDataStore(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): DataStoreManager {
@ApplicationContext context: Context,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): DataStoreManager {
return DataStoreManager(context, ioDispatcher) return DataStoreManager(context, ioDispatcher)
} }
@@ -84,10 +81,8 @@ class RepositoryModule {
fun provideAppDataRepository( fun provideAppDataRepository(
settingsRepository: SettingsRepository, settingsRepository: SettingsRepository,
tunnelConfigRepository: TunnelConfigRepository, tunnelConfigRepository: TunnelConfigRepository,
appStateRepository: AppStateRepository appStateRepository: AppStateRepository,
): AppDataRepository { ): AppDataRepository {
return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository) return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository)
} }
} }
@@ -17,9 +17,7 @@ import dagger.hilt.android.scopes.ServiceScoped
abstract class ServiceModule { abstract class ServiceModule {
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideNotificationService( abstract fun provideNotificationService(wireGuardNotification: WireGuardNotification): NotificationService
wireGuardNotification: WireGuardNotification
): NotificationService
@Binds @Binds
@ServiceScoped @ServiceScoped
@@ -27,13 +25,9 @@ abstract class ServiceModule {
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideMobileDataService( abstract fun provideMobileDataService(mobileDataService: MobileDataService): NetworkService<MobileDataService>
mobileDataService: MobileDataService
): NetworkService<MobileDataService>
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideEthernetService( abstract fun provideEthernetService(ethernetService: EthernetService): NetworkService<EthernetService>
ethernetService: EthernetService
): NetworkService<EthernetService>
} }
@@ -57,7 +57,7 @@ class TunnelModule {
@Kernel kernelBackend: Provider<Backend>, @Kernel kernelBackend: Provider<Backend>,
appDataRepository: AppDataRepository, appDataRepository: AppDataRepository,
@ApplicationScope applicationScope: CoroutineScope, @ApplicationScope applicationScope: CoroutineScope,
@IoDispatcher ioDispatcher: CoroutineDispatcher @IoDispatcher ioDispatcher: CoroutineDispatcher,
): VpnService { ): VpnService {
return WireGuardTunnel( return WireGuardTunnel(
amneziaBackend, amneziaBackend,
@@ -71,10 +71,7 @@ class TunnelModule {
@Provides @Provides
@Singleton @Singleton
fun provideServiceManager( fun provideServiceManager(appDataRepository: AppDataRepository, @IoDispatcher ioDispatcher: CoroutineDispatcher): ServiceManager {
appDataRepository: AppDataRepository,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): ServiceManager {
return ServiceManager(appDataRepository, ioDispatcher) return ServiceManager(appDataRepository, ioDispatcher)
} }
} }
@@ -13,13 +13,9 @@ import kotlinx.coroutines.CoroutineDispatcher
@Module @Module
@InstallIn(ViewModelComponent::class) @InstallIn(ViewModelComponent::class)
class ViewModelModule { class ViewModelModule {
@ViewModelScoped @ViewModelScoped
@Provides @Provides
fun provideFileUtils( fun provideFileUtils(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): FileUtils {
@ApplicationContext context: Context,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): FileUtils {
return FileUtils(context, ioDispatcher) return FileUtils(context, ioDispatcher)
} }
} }
@@ -14,7 +14,6 @@ import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class BootReceiver : BroadcastReceiver() { class BootReceiver : BroadcastReceiver() {
@Inject @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@@ -4,5 +4,5 @@ enum class Action {
START, START,
START_FOREGROUND, START_FOREGROUND,
STOP, STOP,
STOP_FOREGROUND STOP_FOREGROUND,
} }
@@ -23,7 +23,8 @@ open class ForegroundService : LifecycleService() {
val action = intent.action val action = intent.action
when (action) { when (action) {
Action.START.name, 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() Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService()
Constants.ALWAYS_ON_VPN_ACTION -> { Constants.ALWAYS_ON_VPN_ACTION -> {
@@ -12,15 +12,9 @@ import timber.log.Timber
class ServiceManager( class ServiceManager(
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) {
private fun <T : Service> actionOnService(
action: Action,
context: Context,
cls: Class<T>,
extras: Map<String, Int>? = null
) { ) {
private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) {
val intent = val intent =
Intent(context, cls).also { Intent(context, cls).also {
it.action = action.name it.action = action.name
@@ -29,7 +23,8 @@ class ServiceManager(
intent.component?.javaClass intent.component?.javaClass
try { try {
when (action) { when (action) {
Action.START_FOREGROUND, Action.STOP_FOREGROUND -> context.startForegroundService( Action.START_FOREGROUND, Action.STOP_FOREGROUND ->
context.startForegroundService(
intent, intent,
) )
@@ -40,11 +35,7 @@ class ServiceManager(
} }
} }
suspend fun startVpnService( suspend fun startVpnService(context: Context, tunnelId: Int? = null, isManualStart: Boolean = false) {
context: Context,
tunnelId: Int? = null,
isManualStart: Boolean = false
) {
if (isManualStart) onManualStart(tunnelId) if (isManualStart) onManualStart(tunnelId)
actionOnService( actionOnService(
Action.START, Action.START,
@@ -88,11 +79,7 @@ class ServiceManager(
} }
} }
suspend fun startVpnServiceForeground( suspend fun startVpnServiceForeground(context: Context, tunnelId: Int? = null, isManualStart: Boolean = false) {
context: Context,
tunnelId: Int? = null,
isManualStart: Boolean = false
) {
withContext(ioDispatcher) { withContext(ioDispatcher) {
if (isManualStart) onManualStart(tunnelId) if (isManualStart) onManualStart(tunnelId)
actionOnService( actionOnService(
@@ -104,9 +91,7 @@ class ServiceManager(
} }
} }
fun startWatcherServiceForeground( fun startWatcherServiceForeground(context: Context) {
context: Context,
) {
actionOnService( actionOnService(
Action.START_FOREGROUND, Action.START_FOREGROUND,
context, context,
@@ -7,50 +7,67 @@ data class WatcherState(
val isEthernetConnected: Boolean = false, val isEthernetConnected: Boolean = false,
val isMobileDataConnected: Boolean = false, val isMobileDataConnected: Boolean = false,
val currentNetworkSSID: String = "", val currentNetworkSSID: String = "",
val settings: Settings = Settings() val settings: Settings = Settings(),
) { ) {
fun isEthernetConditionMet(): Boolean { fun isEthernetConditionMet(): Boolean {
return (isEthernetConnected && return (
settings.isTunnelOnEthernetEnabled) isEthernetConnected &&
settings.isTunnelOnEthernetEnabled
)
} }
fun isMobileDataConditionMet(): Boolean { fun isMobileDataConditionMet(): Boolean {
return (!isEthernetConnected && return (
!isEthernetConnected &&
settings.isTunnelOnMobileDataEnabled && settings.isTunnelOnMobileDataEnabled &&
!isWifiConnected && !isWifiConnected &&
isMobileDataConnected) isMobileDataConnected
)
} }
fun isTunnelOffOnMobileDataConditionMet(): Boolean { fun isTunnelOffOnMobileDataConditionMet(): Boolean {
return (!isEthernetConnected && return (
!isEthernetConnected &&
!settings.isTunnelOnMobileDataEnabled && !settings.isTunnelOnMobileDataEnabled &&
isMobileDataConnected && isMobileDataConnected &&
!isWifiConnected) !isWifiConnected
)
} }
fun isUntrustedWifiConditionMet(): Boolean { fun isUntrustedWifiConditionMet(): Boolean {
return (!isEthernetConnected && return (
!isEthernetConnected &&
isWifiConnected && isWifiConnected &&
!settings.trustedNetworkSSIDs.contains(currentNetworkSSID) && !settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
settings.isTunnelOnWifiEnabled) settings.isTunnelOnWifiEnabled
)
} }
fun isTrustedWifiConditionMet(): Boolean { fun isTrustedWifiConditionMet(): Boolean {
return (!isEthernetConnected && return (
(isWifiConnected && !isEthernetConnected &&
settings.trustedNetworkSSIDs.contains(currentNetworkSSID))) (
isWifiConnected &&
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)
)
)
} }
fun isTunnelOffOnWifiConditionMet(): Boolean { fun isTunnelOffOnWifiConditionMet(): Boolean {
return (!isEthernetConnected && return (
(isWifiConnected && !isEthernetConnected &&
!settings.isTunnelOnWifiEnabled)) (
isWifiConnected &&
!settings.isTunnelOnWifiEnabled
)
)
} }
fun isTunnelOffOnNoConnectivityMet(): Boolean { fun isTunnelOffOnNoConnectivityMet(): Boolean {
return (!isEthernetConnected && return (
!isEthernetConnected &&
!isWifiConnected && !isWifiConnected &&
!isMobileDataConnected) !isMobileDataConnected
)
} }
} }
@@ -33,7 +33,6 @@ import timber.log.Timber
import java.net.InetAddress import java.net.InetAddress
import javax.inject.Inject import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class WireGuardConnectivityWatcherService : ForegroundService() { class WireGuardConnectivityWatcherService : ForegroundService() {
private val foregroundId = 122 private val foregroundId = 122
@@ -80,7 +79,9 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
try { try {
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) { if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
launchWatcherPausedNotification() launchWatcherPausedNotification()
} else launchWatcherNotification() } else {
launchWatcherNotification()
}
} catch (e: Exception) { } catch (e: Exception) {
Timber.e("Failed to start watcher service, not enough permissions") Timber.e("Failed to start watcher service, not enough permissions")
} }
@@ -110,9 +111,7 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
stopSelf() stopSelf()
} }
private fun launchWatcherNotification( private fun launchWatcherNotification(description: String = getString(R.string.watcher_notification_text_active)) {
description: String = getString(R.string.watcher_notification_text_active)
) {
val notification = val notification =
notificationService.createNotification( notificationService.createNotification(
channelId = getString(R.string.watcher_channel_id), channelId = getString(R.string.watcher_channel_id),
@@ -188,7 +187,6 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
Timber.i("Starting management watcher") Timber.i("Starting management watcher")
manageVpn() manageVpn()
} }
} }
} }
@@ -236,13 +234,19 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
val tunnelConfig = vpnService.vpnState.value.tunnelConfig val tunnelConfig = vpnService.vpnState.value.tunnelConfig
tunnelConfig?.let { tunnelConfig?.let {
val config = TunnelConfig.configFromWgQuick(it.wgQuick) val config = TunnelConfig.configFromWgQuick(it.wgQuick)
val results = config.peers.map { peer -> val results =
val host = if (peer.endpoint.isPresent && config.peers.map { peer ->
peer.endpoint.get().resolved.isPresent) val host =
if (peer.endpoint.isPresent &&
peer.endpoint.get().resolved.isPresent
) {
peer.endpoint.get().resolved.get().host peer.endpoint.get().resolved.get().host
else Constants.DEFAULT_PING_IP } else {
Constants.DEFAULT_PING_IP
}
Timber.i("Checking reachability of: $host") Timber.i("Checking reachability of: $host")
val reachable = InetAddress.getByName(host) val reachable =
InetAddress.getByName(host)
.isReachable(Constants.PING_TIMEOUT.toInt()) .isReachable(Constants.PING_TIMEOUT.toInt())
Timber.i("Result: reachable - $reachable") Timber.i("Result: reachable - $reachable")
reachable reachable
@@ -266,7 +270,9 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
private suspend fun watchForSettingsChanges() { private suspend fun watchForSettingsChanges() {
appDataRepository.settings.getSettingsFlow().collect { settings -> appDataRepository.settings.getSettingsFlow().collect { settings ->
if (networkEventsFlow.value.settings.isAutoTunnelPaused != settings.isAutoTunnelPaused) { if (networkEventsFlow.value.settings.isAutoTunnelPaused
!= settings.isAutoTunnelPaused
) {
when (settings.isAutoTunnelPaused) { when (settings.isAutoTunnelPaused) {
true -> launchWatcherPausedNotification() true -> launchWatcherPausedNotification()
false -> launchWatcherNotification() false -> launchWatcherNotification()
@@ -339,7 +345,9 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
ssid?.let { name -> ssid?.let { name ->
if (name.contains(Constants.UNREADABLE_SSID)) { if (name.contains(Constants.UNREADABLE_SSID)) {
Timber.w("SSID unreadable: missing permissions") Timber.w("SSID unreadable: missing permissions")
} else Timber.i("Detected valid SSID") } else {
Timber.i("Detected valid SSID")
}
appDataRepository.appState.setCurrentSsid(name) appDataRepository.appState.setCurrentSsid(name)
networkEventsFlow.update { networkEventsFlow.update {
it.copy( it.copy(
@@ -409,14 +417,19 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
watcherState.isUntrustedWifiConditionMet() -> { watcherState.isUntrustedWifiConditionMet() -> {
if (tunnelConfig?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false || if (tunnelConfig?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false ||
tunnelConfig == null) { tunnelConfig == null
Timber.i("$autoTunnel - tunnel on ssid not associated with current tunnel condition met") ) {
Timber.i(
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met",
)
getSsidTunnel(watcherState.currentNetworkSSID)?.let { getSsidTunnel(watcherState.currentNetworkSSID)?.let {
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}") 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, context,
it.id, it.id,
) )
}
} ?: suspend { } ?: suspend {
Timber.i("No tunnel associated with this SSID, using defaults") Timber.i("No tunnel associated with this SSID, using defaults")
val default = appDataRepository.getPrimaryOrFirstTunnel() val default = appDataRepository.getPrimaryOrFirstTunnel()
@@ -424,24 +437,29 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
default?.let { default?.let {
serviceManager.startVpnServiceForeground(context, it.id) serviceManager.startVpnServiceForeground(context, it.id)
} }
} }
}.invoke() }.invoke()
} }
} }
watcherState.isTrustedWifiConditionMet() -> { 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) if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
} }
watcherState.isTunnelOffOnWifiConditionMet() -> { 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) if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
} }
watcherState.isTunnelOffOnNoConnectivityMet() -> { 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) if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
} }
@@ -142,10 +142,7 @@ class WireGuardTunnelService : ForegroundService() {
stopSelf() stopSelf()
} }
private fun launchVpnNotification( private fun launchVpnNotification(title: String = getString(R.string.vpn_starting), description: String = getString(R.string.attempt_connection)) {
title: String = getString(R.string.vpn_starting),
description: String = getString(R.string.attempt_connection)
) {
val notification = val notification =
notificationService.createNotification( notificationService.createNotification(
channelId = getString(R.string.vpn_channel_id), channelId = getString(R.string.vpn_channel_id),
@@ -16,7 +16,7 @@ import kotlinx.coroutines.flow.map
abstract class BaseNetworkService<T : BaseNetworkService<T>>( abstract class BaseNetworkService<T : BaseNetworkService<T>>(
val context: Context, val context: Context,
networkCapability: Int networkCapability: Int,
) : NetworkService<T> { ) : NetworkService<T> {
private val connectivityManager = private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@@ -24,7 +24,8 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
private val wifiManager = private val wifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
override val networkStatus = callbackFlow { override val networkStatus =
callbackFlow {
val networkStatusCallback = val networkStatusCallback =
when (Build.VERSION.SDK_INT) { when (Build.VERSION.SDK_INT) {
in Build.VERSION_CODES.S..Int.MAX_VALUE -> { in Build.VERSION_CODES.S..Int.MAX_VALUE -> {
@@ -40,10 +41,7 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
trySend(NetworkStatus.Unavailable(network)) trySend(NetworkStatus.Unavailable(network))
} }
override fun onCapabilitiesChanged( override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
network: Network,
networkCapabilities: NetworkCapabilities
) {
trySend( trySend(
NetworkStatus.CapabilitiesChanged( NetworkStatus.CapabilitiesChanged(
network, network,
@@ -64,10 +62,7 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
trySend(NetworkStatus.Unavailable(network)) trySend(NetworkStatus.Unavailable(network))
} }
override fun onCapabilitiesChanged( override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
network: Network,
networkCapabilities: NetworkCapabilities
) {
trySend( trySend(
NetworkStatus.CapabilitiesChanged( NetworkStatus.CapabilitiesChanged(
network, network,
@@ -118,7 +113,7 @@ inline fun <Result> Flow<NetworkStatus>.map(
crossinline onUnavailable: suspend (network: Network) -> Result, crossinline onUnavailable: suspend (network: Network) -> Result,
crossinline onAvailable: suspend (network: Network) -> Result, crossinline onAvailable: suspend (network: Network) -> Result,
crossinline onCapabilitiesChanged: crossinline onCapabilitiesChanged:
suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result,
): Flow<Result> = map { status -> ): Flow<Result> = map { status ->
when (status) { when (status) {
is NetworkStatus.Unavailable -> onUnavailable(status.network) is NetworkStatus.Unavailable -> onUnavailable(status.network)
@@ -5,5 +5,9 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class EthernetService @Inject constructor(@ApplicationContext context: Context) : class EthernetService
@Inject
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET) BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET)
@@ -5,5 +5,9 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class MobileDataService @Inject constructor(@ApplicationContext context: Context) : class MobileDataService
@Inject
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR) BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR)
@@ -5,5 +5,9 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class WifiService @Inject constructor(@ApplicationContext context: Context) : class WifiService
@Inject
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI) BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI)
@@ -9,12 +9,15 @@ import android.content.Intent
import android.graphics.Color import android.graphics.Color
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.ui.MainActivity
import com.zaneschepke.wireguardautotunnel.ui.SplashActivity import com.zaneschepke.wireguardautotunnel.ui.SplashActivity
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class WireGuardNotification @Inject constructor(@ApplicationContext private val context: Context) : class WireGuardNotification
@Inject
constructor(
@ApplicationContext private val context: Context,
) :
NotificationService { NotificationService {
private val notificationManager = private val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
@@ -15,7 +15,6 @@ import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class ShortcutsActivity : ComponentActivity() { class ShortcutsActivity : ComponentActivity() {
@Inject @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@@ -34,17 +33,22 @@ class ShortcutsActivity : ComponentActivity() {
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) { when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
WireGuardTunnelService::class.java.simpleName -> { WireGuardTunnelService::class.java.simpleName -> {
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY) val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
val tunnelConfig = tunnelName?.let { val tunnelConfig =
tunnelName?.let {
appDataRepository.tunnels.getAll().firstOrNull { appDataRepository.tunnels.getAll().firstOrNull {
it.name == tunnelName it.name == tunnelName
} }
} }
when (intent.action) { when (intent.action) {
Action.START.name -> serviceManager.startVpnServiceForeground( Action.START.name ->
this@ShortcutsActivity, tunnelConfig?.id, isManualStart = true, serviceManager.startVpnServiceForeground(
this@ShortcutsActivity,
tunnelConfig?.id,
isManualStart = true,
) )
Action.STOP.name -> serviceManager.stopVpnServiceForeground( Action.STOP.name ->
serviceManager.stopVpnServiceForeground(
this@ShortcutsActivity, this@ShortcutsActivity,
isManualStop = true, isManualStop = true,
) )
@@ -53,13 +57,15 @@ class ShortcutsActivity : ComponentActivity() {
WireGuardConnectivityWatcherService::class.java.simpleName -> { WireGuardConnectivityWatcherService::class.java.simpleName -> {
when (intent.action) { when (intent.action) {
Action.START.name -> appDataRepository.settings.save( Action.START.name ->
appDataRepository.settings.save(
settings.copy( settings.copy(
isAutoTunnelPaused = false, isAutoTunnelPaused = false,
), ),
) )
Action.STOP.name -> appDataRepository.settings.save( Action.STOP.name ->
appDataRepository.settings.save(
settings.copy( settings.copy(
isAutoTunnelPaused = true, isAutoTunnelPaused = true,
), ),
@@ -10,11 +10,8 @@ import androidx.lifecycle.lifecycleScope
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository 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 com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
@@ -22,7 +19,6 @@ import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class AutoTunnelControlTile : TileService(), LifecycleOwner { class AutoTunnelControlTile : TileService(), LifecycleOwner {
@Inject @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@@ -47,6 +43,7 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
setTileDescription(this@AutoTunnelControlTile.getString(R.string.active)) setTileDescription(this@AutoTunnelControlTile.getString(R.string.active))
} }
} }
false -> { false -> {
setTileDescription(this@AutoTunnelControlTile.getString(R.string.disabled)) setTileDescription(this@AutoTunnelControlTile.getString(R.string.disabled))
setUnavailable() setUnavailable()
@@ -5,17 +5,14 @@ import android.service.quicksettings.Tile
import android.service.quicksettings.TileService import android.service.quicksettings.TileService
import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.ServiceLifecycleDispatcher import androidx.lifecycle.ServiceLifecycleDispatcher
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository 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.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
@@ -23,7 +20,6 @@ import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class TunnelControlTile : TileService(), LifecycleOwner { class TunnelControlTile : TileService(), LifecycleOwner {
@Inject @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@@ -49,7 +45,8 @@ class TunnelControlTile : TileService(), LifecycleOwner {
TunnelState.DOWN -> { TunnelState.DOWN -> {
setInactive() setInactive()
val config = appDataRepository.getStartTunnelConfig()?.also { config -> val config =
appDataRepository.getStartTunnelConfig()?.also { config ->
manualStartConfig = config manualStartConfig = config
} ?: appDataRepository.getPrimaryOrFirstTunnel() } ?: appDataRepository.getPrimaryOrFirstTunnel()
config?.let { config?.let {
@@ -79,7 +76,9 @@ class TunnelControlTile : TileService(), LifecycleOwner {
) )
} else { } else {
serviceManager.startVpnServiceForeground( serviceManager.startVpnServiceForeground(
this@TunnelControlTile, manualStartConfig?.id, isManualStart = true, this@TunnelControlTile,
manualStartConfig?.id,
isManualStart = true,
) )
} }
} catch (e: Exception) { } catch (e: Exception) {
@@ -4,7 +4,8 @@ enum class HandshakeStatus {
HEALTHY, HEALTHY,
STALE, STALE,
UNKNOWN, UNKNOWN,
NOT_STARTED; NOT_STARTED,
;
companion object { companion object {
private const val WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC = 180 private const val WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC = 180
@@ -5,7 +5,8 @@ import com.wireguard.android.backend.Tunnel
enum class TunnelState { enum class TunnelState {
UP, UP,
DOWN, DOWN,
TOGGLE; TOGGLE,
;
fun toWgState(): Tunnel.State { fun toWgState(): Tunnel.State {
return when (this) { return when (this) {
@@ -6,5 +6,5 @@ import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStati
data class VpnState( data class VpnState(
val status: TunnelState = TunnelState.DOWN, val status: TunnelState = TunnelState.DOWN,
val tunnelConfig: TunnelConfig? = null, val tunnelConfig: TunnelConfig? = null,
val statistics: TunnelStatistics? = null val statistics: TunnelStatistics? = null,
) )
@@ -37,12 +37,11 @@ constructor(
@Kernel private val kernelBackend: Provider<Backend>, @Kernel private val kernelBackend: Provider<Backend>,
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
@ApplicationScope private val applicationScope: CoroutineScope, @ApplicationScope private val applicationScope: CoroutineScope,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : VpnService { ) : VpnService {
private val _vpnState = MutableStateFlow(VpnState()) private val _vpnState = MutableStateFlow(VpnState())
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow() override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
private var statsJob: Job? = null private var statsJob: Job? = null
private var backendIsWgUserspace = true private var backendIsWgUserspace = true
@@ -72,9 +71,14 @@ constructor(
private fun setState(tunnelConfig: TunnelConfig?, tunnelState: TunnelState): TunnelState { private fun setState(tunnelConfig: TunnelConfig?, tunnelState: TunnelState): TunnelState {
return if (backendIsAmneziaUserspace) { return if (backendIsAmneziaUserspace) {
Timber.i("Using Amnezia backend") Timber.i("Using Amnezia backend")
val config = tunnelConfig?.let { val config =
if (it.amQuick != "") TunnelConfig.configFromAmQuick(it.amQuick) else { tunnelConfig?.let {
Timber.w("Using backwards compatible wg config, amnezia specific config not found.") if (it.amQuick != "") {
TunnelConfig.configFromAmQuick(it.amQuick)
} else {
Timber.w(
"Using backwards compatible wg config, amnezia specific config not found.",
)
TunnelConfig.configFromAmQuick(it.wgQuick) TunnelConfig.configFromAmQuick(it.wgQuick)
} }
} }
@@ -84,7 +88,8 @@ constructor(
} else { } else {
Timber.i("Using Wg backend") Timber.i("Using Wg backend")
val wgConfig = tunnelConfig?.let { TunnelConfig.configFromWgQuick(it.wgQuick) } val wgConfig = tunnelConfig?.let { TunnelConfig.configFromWgQuick(it.wgQuick) }
val state = backend().setState( val state =
backend().setState(
this, this,
tunnelState.toWgState(), tunnelState.toWgState(),
wgConfig, wgConfig,
@@ -102,7 +107,9 @@ constructor(
if (config != null) { if (config != null) {
emitTunnelConfig(config) emitTunnelConfig(config)
setState(config, TunnelState.UP) setState(config, TunnelState.UP)
} else throw Exception("No tunnels") } else {
throw Exception("No tunnels")
}
} catch (e: BackendException) { } catch (e: BackendException) {
Timber.e("Failed to start tunnel with error: ${e.message}") Timber.e("Failed to start tunnel with error: ${e.message}")
TunnelState.from(State.DOWN) TunnelState.from(State.DOWN)
@@ -171,17 +178,19 @@ constructor(
} }
override fun getState(): TunnelState { override fun getState(): TunnelState {
return if (backendIsAmneziaUserspace) TunnelState.from( return if (backendIsAmneziaUserspace) {
TunnelState.from(
userspaceAmneziaBackend.get().getState(this), userspaceAmneziaBackend.get().getState(this),
) )
else TunnelState.from(backend().getState(this)) } else {
TunnelState.from(backend().getState(this))
}
} }
override fun getName(): String { override fun getName(): String {
return _vpnState.value.tunnelConfig?.name ?: "" return _vpnState.value.tunnelConfig?.name ?: ""
} }
override fun onStateChange(newState: Tunnel.State) { override fun onStateChange(newState: Tunnel.State) {
handleStateChange(TunnelState.from(newState)) handleStateChange(TunnelState.from(newState))
} }
@@ -210,7 +219,9 @@ constructor(
), ),
) )
} else { } else {
emitBackendStatistics(WireGuardStatistics(backend().getStatistics(this@WireGuardTunnel))) emitBackendStatistics(
WireGuardStatistics(backend().getStatistics(this@WireGuardTunnel)),
)
} }
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL) delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
} }
@@ -5,5 +5,5 @@ data class AppUiState(
val snackbarMessageConsumed: Boolean = true, val snackbarMessageConsumed: Boolean = true,
val vpnPermissionAccepted: Boolean = false, val vpnPermissionAccepted: Boolean = false,
val notificationPermissionAccepted: Boolean = false, val notificationPermissionAccepted: Boolean = false,
val requestPermissions: Boolean = false val requestPermissions: Boolean = false,
) )
@@ -20,17 +20,16 @@ import javax.inject.Inject
class AppViewModel class AppViewModel
@Inject @Inject
constructor() : ViewModel() { constructor() : ViewModel() {
val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance) val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance)
private val _appUiState = MutableStateFlow( private val _appUiState =
MutableStateFlow(
AppUiState( AppUiState(
vpnPermissionAccepted = vpnIntent == null, vpnPermissionAccepted = vpnIntent == null,
), ),
) )
val appUiState = _appUiState.asStateFlow() val appUiState = _appUiState.asStateFlow()
fun isRequiredPermissionGranted(): Boolean { fun isRequiredPermissionGranted(): Boolean {
val allAccepted = val allAccepted =
(_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted) (_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted)
@@ -57,7 +56,8 @@ constructor() : ViewModel() {
fun openWebPage(url: String, context: Context) { fun openWebPage(url: String, context: Context) {
try { try {
val webpage: Uri = Uri.parse(url) 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) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
} }
context.startActivity(intent) context.startActivity(intent)
@@ -10,6 +10,8 @@ import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.focusable 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.fillMaxSize
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -19,15 +21,19 @@ import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -41,11 +47,13 @@ import androidx.navigation.navArgument
import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager 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.navigation.BottomNavBar
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen
@@ -65,7 +73,6 @@ import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class MainActivity : AppCompatActivity() { class MainActivity : AppCompatActivity() {
@Inject @Inject
lateinit var appStateRepository: AppStateRepository lateinit var appStateRepository: AppStateRepository
@@ -98,10 +105,14 @@ class MainActivity : AppCompatActivity() {
val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle() val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle()
val navController = rememberNavController() val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState() val navBackStackEntry by navController.currentBackStackEntryAsState()
var showVpnPermissionDialog by remember { mutableStateOf(false) }
val notificationPermissionState = val notificationPermissionState =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS) else null rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS)
} else {
null
}
val snackbarHostState = remember { SnackbarHostState() } val snackbarHostState = remember { SnackbarHostState() }
@@ -112,6 +123,8 @@ class MainActivity : AppCompatActivity() {
val accepted = (it.resultCode == RESULT_OK) val accepted = (it.resultCode == RESULT_OK)
if (accepted) { if (accepted) {
appViewModel.onVpnPermissionAccepted() appViewModel.onVpnPermissionAccepted()
} else {
showVpnPermissionDialog = true
} }
}, },
) )
@@ -125,7 +138,8 @@ class MainActivity : AppCompatActivity() {
) )
when (result) { when (result) {
SnackbarResult.ActionPerformed, SnackbarResult.ActionPerformed,
SnackbarResult.Dismissed -> { SnackbarResult.Dismissed,
-> {
snackbarHostState.currentSnackbarData?.dismiss() snackbarHostState.currentSnackbarData?.dismiss()
} }
} }
@@ -137,15 +151,21 @@ class MainActivity : AppCompatActivity() {
appViewModel.permissionsRequested() appViewModel.permissionsRequested()
if (notificationPermissionState != null && !notificationPermissionState.status.isGranted if (notificationPermissionState != null && !notificationPermissionState.status.isGranted
) { ) {
showSnackBarMessage(StringValue.StringResource(R.string.notification_permission_required)) notificationPermissionState.launchPermissionRequest()
return@LaunchedEffect notificationPermissionState.launchPermissionRequest() return@LaunchedEffect if (notificationPermissionState.status.shouldShowRationale || !notificationPermissionState.status.isGranted) {
showSnackBarMessage(
StringValue.StringResource(R.string.notification_permission_required),
)
} else {
Unit
}
} }
if (!appUiState.vpnPermissionAccepted) { if (!appUiState.vpnPermissionAccepted) {
return@LaunchedEffect appViewModel.vpnIntent?.let { return@LaunchedEffect appViewModel.vpnIntent?.let {
vpnActivityResultState.launch( vpnActivityResultState.launch(
it, it,
) )
}!! } ?: Unit
} }
} }
} }
@@ -166,6 +186,21 @@ class MainActivity : AppCompatActivity() {
val focusRequester = remember { FocusRequester() } 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( Scaffold(
snackbarHost = { snackbarHost = {
SnackbarHost(snackbarHostState) { snackbarData: SnackbarData -> SnackbarHost(snackbarHostState) { snackbarData: SnackbarData ->
@@ -180,7 +215,8 @@ class MainActivity : AppCompatActivity() {
} }
}, },
// TODO refactor // TODO refactor
modifier = Modifier modifier =
Modifier
.focusable() .focusable()
.focusProperties { .focusProperties {
when (navBackStackEntry?.destination?.route) { when (navBackStackEntry?.destination?.route) {
@@ -202,7 +238,8 @@ class MainActivity : AppCompatActivity() {
NavHost( NavHost(
navController, navController,
startDestination = (if (isPinLockEnabled == true) Screen.Lock.route else Screen.Main.route), startDestination = (if (isPinLockEnabled == true) Screen.Lock.route else Screen.Main.route),
modifier = Modifier modifier =
Modifier
.padding(padding) .padding(padding)
.fillMaxSize(), .fillMaxSize(),
) { ) {
@@ -251,7 +288,8 @@ class MainActivity : AppCompatActivity() {
), ),
) { ) {
val id = it.arguments?.getString("id") val id = it.arguments?.getString("id")
val configType = ConfigType.valueOf( val configType =
ConfigType.valueOf(
it.arguments?.getString("configType") ?: ConfigType.WIREGUARD.name, it.arguments?.getString("configType") ?: ConfigType.WIREGUARD.name,
) )
if (!id.isNullOrBlank()) { if (!id.isNullOrBlank()) {
@@ -39,6 +39,7 @@ sealed class Screen(val route: String) {
} }
data object Config : Screen("config") data object Config : Screen("config")
data object Lock : Screen("lock") data object Lock : Screen("lock")
data object Option : Screen("option") data object Option : Screen("option")
@@ -23,7 +23,6 @@ import javax.inject.Inject
@SuppressLint("CustomSplashScreen") @SuppressLint("CustomSplashScreen")
@AndroidEntryPoint @AndroidEntryPoint
class SplashActivity : ComponentActivity() { class SplashActivity : ComponentActivity() {
@Inject @Inject
lateinit var appStateRepository: AppStateRepository lateinit var appStateRepository: AppStateRepository
@@ -52,7 +51,8 @@ class SplashActivity : ComponentActivity() {
PinManager.initialize(WireGuardAutoTunnel.instance) 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) putExtra(IS_PIN_LOCK_ENABLED_KEY, pinLockEnabled)
} }
startActivity(intent) startActivity(intent)
@@ -65,4 +65,3 @@ class SplashActivity : ComponentActivity() {
const val IS_PIN_LOCK_ENABLED_KEY = "is_pin_lock_enabled" 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 import androidx.compose.ui.graphics.vector.ImageVector
@Composable @Composable
fun ClickableIconButton( fun ClickableIconButton(onClick: () -> Unit, onIconClick: () -> Unit, text: String, icon: ImageVector, enabled: Boolean) {
onClick: () -> Unit,
onIconClick: () -> Unit,
text: String,
icon: ImageVector,
enabled: Boolean
) {
TextButton( TextButton(
onClick = onClick, onClick = onClick,
enabled = enabled, enabled = enabled,
@@ -38,7 +38,8 @@ fun RowListItem(
) { ) {
Box( Box(
modifier = modifier =
Modifier.focusRequester(focusRequester) Modifier
.focusRequester(focusRequester)
.animateContentSize() .animateContentSize()
.clip(RoundedCornerShape(30.dp)) .clip(RoundedCornerShape(30.dp))
.combinedClickable( .combinedClickable(
@@ -48,7 +49,8 @@ fun RowListItem(
) { ) {
Column { Column {
Row( Row(
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 15.dp, vertical = 5.dp), .padding(horizontal = 15.dp, vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -16,7 +16,7 @@ fun ConfigurationTextBox(
onValueChange: (String) -> Unit, onValueChange: (String) -> Unit,
keyboardActions: KeyboardActions, keyboardActions: KeyboardActions,
label: String, label: String,
modifier: Modifier modifier: Modifier,
) { ) {
OutlinedTextField( OutlinedTextField(
modifier = modifier, modifier = modifier,
@@ -13,24 +13,20 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
@Composable @Composable
fun ConfigurationToggle( fun ConfigurationToggle(label: String, enabled: Boolean, checked: Boolean, padding: Dp, onCheckChanged: () -> Unit, modifier: Modifier = Modifier) {
label: String,
enabled: Boolean,
checked: Boolean,
padding: Dp,
onCheckChanged: () -> Unit,
modifier: Modifier = Modifier
) {
Row( Row(
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(padding), .padding(padding),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
) { ) {
Text( Text(
label, textAlign = TextAlign.Start, label,
modifier = Modifier textAlign = TextAlign.Start,
modifier =
Modifier
.weight( .weight(
weight = 1.0f, weight = 1.0f,
fill = false, 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() val navBackStackEntry by navController.currentBackStackEntryAsState()
// TODO find a better way to hide nav bar // TODO find a better way to hide nav bar
showBottomBar = when (navBackStackEntry?.destination?.route) { showBottomBar =
when (navBackStackEntry?.destination?.route) {
Screen.Lock.route -> false Screen.Lock.route -> false
else -> true else -> true
} }
@@ -32,7 +33,8 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
NavigationBar( NavigationBar(
containerColor = if (!showBottomBar) Color.Transparent else MaterialTheme.colorScheme.background, 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 val selected = item.route == backStackEntry.value?.destination?.route
NavigationBarItem( 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 context = LocalContext.current
val biometricManager = BiometricManager.from(context) val biometricManager = BiometricManager.from(context)
val bio = biometricManager.canAuthenticate(BIOMETRIC_WEAK or DEVICE_CREDENTIAL) val bio = biometricManager.canAuthenticate(BIOMETRIC_WEAK or DEVICE_CREDENTIAL)
val isBiometricAvailable = remember { val isBiometricAvailable =
remember {
when (bio) { when (bio) {
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> { BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
onError("Biometrics not available") onError("Biometrics not available")
@@ -71,9 +72,7 @@ fun AuthorizationPrompt(onSuccess: () -> Unit, onFailure: () -> Unit, onError: (
onFailure() onFailure()
} }
override fun onAuthenticationSucceeded( override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
result: BiometricPrompt.AuthenticationResult
) {
super.onAuthenticationSucceeded(result) super.onAuthenticationSucceeded(result)
onSuccess() onSuccess()
} }
@@ -25,11 +25,7 @@ import androidx.compose.ui.unit.dp
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
@Composable @Composable
fun CustomSnackBar( fun CustomSnackBar(message: String, isRtl: Boolean = true, containerColor: Color = MaterialTheme.colorScheme.surface) {
message: String,
isRtl: Boolean = true,
containerColor: Color = MaterialTheme.colorScheme.surface
) {
Snackbar( Snackbar(
containerColor = containerColor, containerColor = containerColor,
modifier = modifier =
@@ -44,7 +40,8 @@ fun CustomSnackBar(
LocalLayoutDirection provides if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr, LocalLayoutDirection provides if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr,
) { ) {
Row( Row(
modifier = Modifier modifier =
Modifier
.width(IntrinsicSize.Max) .width(IntrinsicSize.Max)
.height(IntrinsicSize.Min), .height(IntrinsicSize.Min),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -16,7 +16,8 @@ fun LoadingScreen() {
Column( Column(
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top, verticalArrangement = Arrangement.Top,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.focusable() .focusable()
.padding(), .padding(),
@@ -14,7 +14,8 @@ import androidx.compose.ui.unit.dp
@Composable @Composable
fun LogTypeLabel(color: Color, content: @Composable () -> Unit) { fun LogTypeLabel(color: Color, content: @Composable () -> Unit) {
Box( Box(
modifier = Modifier modifier =
Modifier
.size(20.dp) .size(20.dp)
.clip(RoundedCornerShape(2.dp)) .clip(RoundedCornerShape(2.dp))
.background(color), .background(color),
@@ -95,7 +95,7 @@ fun ConfigScreen(
navController: NavController, navController: NavController,
appViewModel: AppViewModel, appViewModel: AppViewModel,
tunnelId: String, tunnelId: String,
configType: ConfigType configType: ConfigType,
) { ) {
val context = LocalContext.current val context = LocalContext.current
val clipboardManager: ClipboardManager = LocalClipboardManager.current val clipboardManager: ClipboardManager = LocalClipboardManager.current
@@ -128,16 +128,23 @@ fun ConfigScreen(
val fillMaxWidth = .85f val fillMaxWidth = .85f
val screenPadding = 5.dp val screenPadding = 5.dp
val applicationButtonText = buildAnnotatedString { val applicationButtonText =
buildAnnotatedString {
append(stringResource(id = R.string.tunneling_apps)) append(stringResource(id = R.string.tunneling_apps))
append(": ") append(": ")
if (uiState.isAllApplicationsEnabled) { if (uiState.isAllApplicationsEnabled) {
append(stringResource(id = R.string.all)) append(stringResource(id = R.string.all))
} else { } else {
append("${uiState.checkedPackageNames.size} ") 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), stringResource(id = R.string.excluded),
)) )
}
)
} }
} }
@@ -149,11 +156,15 @@ fun ConfigScreen(
}, },
onError = { onError = {
showAuthPrompt = false showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authentication_failed)) appViewModel.showSnackbarMessage(
context.getString(R.string.error_authentication_failed),
)
}, },
onFailure = { onFailure = {
showAuthPrompt = false 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), .fillMaxHeight(if (uiState.isAllApplicationsEnabled) 1 / 5f else 4 / 5f),
) { ) {
Column( Column(
modifier = Modifier modifier =
Modifier
.fillMaxWidth(), .fillMaxWidth(),
) { ) {
Row( Row(
@@ -246,7 +258,8 @@ fun ConfigScreen(
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(5.dp), .padding(5.dp),
) { ) {
@@ -275,9 +288,11 @@ fun ConfigScreen(
Checkbox( Checkbox(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
checked = checked =
(uiState.checkedPackageNames.contains( (
uiState.checkedPackageNames.contains(
pack.packageName, pack.packageName,
)), )
),
onCheckedChange = { onCheckedChange = {
if (it) { if (it) {
viewModel.onAddCheckedPackage(pack.packageName) viewModel.onAddCheckedPackage(pack.packageName)
@@ -292,7 +307,8 @@ fun ConfigScreen(
} }
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(top = 5.dp), .padding(top = 5.dp),
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
@@ -321,7 +337,9 @@ fun ConfigScreen(
}, },
onClick = { onClick = {
viewModel.onSaveAllChanges(configType).onSuccess { 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) navController.navigate(Screen.Main.route)
}.onFailure { }.onFailure {
appViewModel.showSnackbarMessage(it.getMessage(context)) appViewModel.showSnackbarMessage(it.getMessage(context))
@@ -354,19 +372,22 @@ fun ConfigScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.fillMaxHeight(fillMaxHeight) .fillMaxHeight(fillMaxHeight)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
} else { } else {
Modifier.fillMaxWidth(fillMaxWidth) Modifier.fillMaxWidth(fillMaxWidth)
}) }
)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Column( Column(
horizontalAlignment = Alignment.Start, horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top, verticalArrangement = Arrangement.Top,
modifier = Modifier modifier =
Modifier
.padding(15.dp) .padding(15.dp)
.focusGroup(), .focusGroup(),
) { ) {
@@ -380,19 +401,23 @@ fun ConfigScreen(
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.name), label = stringResource(R.string.name),
hint = stringResource(R.string.tunnel_name).lowercase(), hint = stringResource(R.string.tunnel_name).lowercase(),
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
OutlinedTextField( OutlinedTextField(
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.clickable { showAuthPrompt = true }, .clickable { showAuthPrompt = true },
value = uiState.interfaceProxy.privateKey, value = uiState.interfaceProxy.privateKey,
visualTransformation = visualTransformation =
if ((tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated) if ((tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated) {
VisualTransformation.None VisualTransformation.None
else PasswordVisualTransformation(), } else {
PasswordVisualTransformation()
},
enabled = (tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated, enabled = (tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated,
onValueChange = { value -> viewModel.onPrivateKeyChange(value) }, onValueChange = { value -> viewModel.onPrivateKeyChange(value) },
trailingIcon = { trailingIcon = {
@@ -450,7 +475,8 @@ fun ConfigScreen(
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.addresses), label = stringResource(R.string.addresses),
hint = stringResource(R.string.comma_separated_list), hint = stringResource(R.string.comma_separated_list),
modifier = Modifier modifier =
Modifier
.fillMaxWidth(3 / 5f) .fillMaxWidth(3 / 5f)
.padding(end = 5.dp), .padding(end = 5.dp),
) )
@@ -470,7 +496,8 @@ fun ConfigScreen(
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.dns_servers), label = stringResource(R.string.dns_servers),
hint = stringResource(R.string.comma_separated_list), hint = stringResource(R.string.comma_separated_list),
modifier = Modifier modifier =
Modifier
.fillMaxWidth(3 / 5f) .fillMaxWidth(3 / 5f)
.padding(end = 5.dp), .padding(end = 5.dp),
) )
@@ -486,11 +513,15 @@ fun ConfigScreen(
if (configType == ConfigType.AMNEZIA) { if (configType == ConfigType.AMNEZIA) {
ConfigurationTextBox( ConfigurationTextBox(
value = uiState.interfaceProxy.junkPacketCount, value = uiState.interfaceProxy.junkPacketCount,
onValueChange = { value -> viewModel.onJunkPacketCountChanged(value) }, onValueChange = {
value ->
viewModel.onJunkPacketCountChanged(value)
},
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.junk_packet_count), label = stringResource(R.string.junk_packet_count),
hint = stringResource(R.string.junk_packet_count).lowercase(), hint = stringResource(R.string.junk_packet_count).lowercase(),
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -503,8 +534,12 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.junk_packet_minimum_size), label = stringResource(R.string.junk_packet_minimum_size),
hint = stringResource(R.string.junk_packet_minimum_size).lowercase(), hint =
modifier = Modifier stringResource(
R.string.junk_packet_minimum_size,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -517,8 +552,12 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.junk_packet_maximum_size), label = stringResource(R.string.junk_packet_maximum_size),
hint = stringResource(R.string.junk_packet_maximum_size).lowercase(), hint =
modifier = Modifier stringResource(
R.string.junk_packet_maximum_size,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -532,27 +571,42 @@ fun ConfigScreen(
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.init_packet_junk_size), label = stringResource(R.string.init_packet_junk_size),
hint = stringResource(R.string.init_packet_junk_size).lowercase(), hint = stringResource(R.string.init_packet_junk_size).lowercase(),
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
ConfigurationTextBox( ConfigurationTextBox(
value = uiState.interfaceProxy.responsePacketJunkSize, value = uiState.interfaceProxy.responsePacketJunkSize,
onValueChange = { value -> viewModel.onResponsePacketJunkSize(value) }, onValueChange = {
value ->
viewModel.onResponsePacketJunkSize(value)
},
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.response_packet_junk_size), label = stringResource(R.string.response_packet_junk_size),
hint = stringResource(R.string.response_packet_junk_size).lowercase(), hint =
modifier = Modifier stringResource(
R.string.response_packet_junk_size,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
ConfigurationTextBox( ConfigurationTextBox(
value = uiState.interfaceProxy.initPacketMagicHeader, value = uiState.interfaceProxy.initPacketMagicHeader,
onValueChange = { value -> viewModel.onInitPacketMagicHeader(value) }, onValueChange = {
value ->
viewModel.onInitPacketMagicHeader(value)
},
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.init_packet_magic_header), label = stringResource(R.string.init_packet_magic_header),
hint = stringResource(R.string.init_packet_magic_header).lowercase(), hint =
modifier = Modifier stringResource(
R.string.init_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -565,8 +619,12 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.response_packet_magic_header), label = stringResource(R.string.response_packet_magic_header),
hint = stringResource(R.string.response_packet_magic_header).lowercase(), hint =
modifier = Modifier stringResource(
R.string.response_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -579,8 +637,12 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.underload_packet_magic_header), label = stringResource(R.string.underload_packet_magic_header),
hint = stringResource(R.string.underload_packet_magic_header).lowercase(), hint =
modifier = Modifier stringResource(
R.string.underload_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -593,15 +655,20 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.transport_packet_magic_header), label = stringResource(R.string.transport_packet_magic_header),
hint = stringResource(R.string.transport_packet_magic_header).lowercase(), hint =
modifier = Modifier stringResource(
R.string.transport_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
} }
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(top = 5.dp), .padding(top = 5.dp),
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
@@ -619,26 +686,30 @@ fun ConfigScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.fillMaxHeight(fillMaxHeight) .fillMaxHeight(fillMaxHeight)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
} else { } else {
Modifier.fillMaxWidth(fillMaxWidth) Modifier.fillMaxWidth(fillMaxWidth)
}) }
)
.padding(top = 10.dp, bottom = 10.dp), .padding(top = 10.dp, bottom = 10.dp),
) { ) {
Column( Column(
horizontalAlignment = Alignment.Start, horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top, verticalArrangement = Arrangement.Top,
modifier = Modifier modifier =
Modifier
.padding(horizontal = 15.dp) .padding(horizontal = 15.dp)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Row( Row(
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 5.dp), .padding(horizontal = 5.dp),
) { ) {
@@ -724,7 +795,8 @@ fun ConfigScreen(
Row( Row(
horizontalArrangement = Arrangement.SpaceEvenly, horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(bottom = 140.dp), .padding(bottom = 140.dp),
) { ) {
@@ -16,7 +16,7 @@ data class ConfigUiState(
val loading: Boolean = true, val loading: Boolean = true,
val tunnel: TunnelConfig? = null, val tunnel: TunnelConfig? = null,
val tunnelName: String = "", val tunnelName: String = "",
val isAmneziaEnabled: Boolean = false val isAmneziaEnabled: Boolean = false,
) { ) {
companion object { companion object {
fun from(config: Config): ConfigUiState { fun from(config: Config): ConfigUiState {
@@ -40,16 +40,14 @@ class ConfigViewModel
constructor( constructor(
private val settingsRepository: SettingsRepository, private val settingsRepository: SettingsRepository,
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : ViewModel() { ) : ViewModel() {
private val packageManager = WireGuardAutoTunnel.instance.packageManager private val packageManager = WireGuardAutoTunnel.instance.packageManager
private val _uiState = MutableStateFlow(ConfigUiState()) private val _uiState = MutableStateFlow(ConfigUiState())
val uiState = _uiState.asStateFlow() val uiState = _uiState.asStateFlow()
fun init(tunnelId: String) = fun init(tunnelId: String) = viewModelScope.launch(ioDispatcher) {
viewModelScope.launch(ioDispatcher) {
val packages = getQueriedPackages("") val packages = getQueriedPackages("")
val state = val state =
if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) { if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) {
@@ -58,11 +56,17 @@ constructor(
.firstOrNull { it.id.toString() == tunnelId } .firstOrNull { it.id.toString() == tunnelId }
val isAmneziaEnabled = settingsRepository.getSettings().isAmneziaEnabled val isAmneziaEnabled = settingsRepository.getSettings().isAmneziaEnabled
if (tunnelConfig != null) { if (tunnelConfig != null) {
(if (isAmneziaEnabled) { (
if (isAmneziaEnabled) {
val amConfig = val amConfig =
if (tunnelConfig.amQuick == "") tunnelConfig.wgQuick else tunnelConfig.amQuick if (tunnelConfig.amQuick == "") tunnelConfig.wgQuick else tunnelConfig.amQuick
ConfigUiState.from(TunnelConfig.configFromAmQuick(amConfig)) ConfigUiState.from(TunnelConfig.configFromAmQuick(amConfig))
} else ConfigUiState.from(TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick))).copy( } else {
ConfigUiState.from(
TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick),
)
}
).copy(
packages = packages, packages = packages,
loading = false, loading = false,
tunnel = tunnelConfig, tunnel = tunnelConfig,
@@ -111,7 +115,7 @@ constructor(
} }
fun getPackageLabel(packageInfo: PackageInfo): String { fun getPackageLabel(packageInfo: PackageInfo): String {
return packageInfo.applicationInfo.loadLabel(packageManager).toString() return packageInfo.applicationInfo?.loadLabel(packageManager).toString()
} }
private fun getAllInternetCapablePackages(): List<PackageInfo> { private fun getAllInternetCapablePackages(): List<PackageInfo> {
@@ -133,11 +137,9 @@ constructor(
return _uiState.value.isAllApplicationsEnabled return _uiState.value.isAllApplicationsEnabled
} }
private fun saveConfig(tunnelConfig: TunnelConfig) = private fun saveConfig(tunnelConfig: TunnelConfig) = viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) }
viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) }
private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) = private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) = viewModelScope.launch {
viewModelScope.launch {
if (tunnelConfig != null) { if (tunnelConfig != null) {
saveConfig(tunnelConfig).join() saveConfig(tunnelConfig).join()
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate() WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
@@ -183,14 +185,23 @@ constructor(
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) { if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) {
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim()) 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()) builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim())
}
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) { if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim()) builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
} }
if (isAllApplicationsEnabled()) emptyCheckedPackagesList() if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
if (_uiState.value.include) builder.includeApplications(_uiState.value.checkedPackageNames) if (_uiState.value.include) {
if (!_uiState.value.include) builder.excludeApplications(_uiState.value.checkedPackageNames) builder.includeApplications(
_uiState.value.checkedPackageNames,
)
}
if (!_uiState.value.include) {
builder.excludeApplications(
_uiState.value.checkedPackageNames,
)
}
return builder.build() return builder.build()
} }
@@ -201,16 +212,27 @@ constructor(
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) { if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) {
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim()) 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()) builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim())
}
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) { if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim()) builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
} }
if (isAllApplicationsEnabled()) emptyCheckedPackagesList() if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
if (_uiState.value.include) builder.includeApplications(_uiState.value.checkedPackageNames) if (_uiState.value.include) {
if (!_uiState.value.include) builder.excludeApplications(_uiState.value.checkedPackageNames) builder.includeApplications(
_uiState.value.checkedPackageNames,
)
}
if (!_uiState.value.include) {
builder.excludeApplications(
_uiState.value.checkedPackageNames,
)
}
if (_uiState.value.interfaceProxy.junkPacketCount.isNotEmpty()) { 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()) { if (_uiState.value.interfaceProxy.junkPacketMinSize.isNotEmpty()) {
builder.setJunkPacketMinSize( builder.setJunkPacketMinSize(
@@ -264,24 +286,32 @@ constructor(
private fun buildAmConfig(): org.amnezia.awg.config.Config { private fun buildAmConfig(): org.amnezia.awg.config.Config {
val peerList = buildAmPeerListFromProxyPeers() val peerList = buildAmPeerListFromProxyPeers()
val amInterface = buildAmInterfaceListFromProxyInterface() 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() .build()
} }
fun onSaveAllChanges(configType: ConfigType): Result<Unit> { fun onSaveAllChanges(configType: ConfigType): Result<Unit> {
return try { return try {
val wgQuick = buildConfig().toWgQuickString() val wgQuick = buildConfig().toWgQuickString()
val amQuick = if (configType == ConfigType.AMNEZIA) { val amQuick =
if (configType == ConfigType.AMNEZIA) {
buildAmConfig().toAwgQuickString() buildAmConfig().toAwgQuickString()
} else TunnelConfig.AM_QUICK_DEFAULT } else {
val tunnelConfig = when (uiState.value.tunnel) { TunnelConfig.AM_QUICK_DEFAULT
null -> TunnelConfig( }
val tunnelConfig =
when (uiState.value.tunnel) {
null ->
TunnelConfig(
name = _uiState.value.tunnelName, name = _uiState.value.tunnelName,
wgQuick = wgQuick, wgQuick = wgQuick,
amQuick = amQuick, amQuick = amQuick,
) )
else -> uiState.value.tunnel!!.copy( else ->
uiState.value.tunnel!!.copy(
name = _uiState.value.tunnelName, name = _uiState.value.tunnelName,
wgQuick = wgQuick, wgQuick = wgQuick,
amQuick = amQuick, amQuick = amQuick,
@@ -292,7 +322,8 @@ constructor(
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e) Timber.e(e)
val message = e.message?.substringAfter(":", missingDelimiterValue = "") val message = e.message?.substringAfter(":", missingDelimiterValue = "")
val stringValue = message?.let { val stringValue =
message?.let {
StringValue.DynamicString(message) StringValue.DynamicString(message)
} ?: StringValue.StringResource(R.string.unknown_error) } ?: StringValue.StringResource(R.string.unknown_error)
Result.failure(WgTunnelExceptions.ConfigParseError(stringValue)) Result.failure(WgTunnelExceptions.ConfigParseError(stringValue))
@@ -392,7 +423,6 @@ constructor(
interfaceProxy = _uiState.value.interfaceProxy.copy(addresses = value), interfaceProxy = _uiState.value.interfaceProxy.copy(addresses = value),
) )
} }
} }
fun onListenPortChanged(value: String) { fun onListenPortChanged(value: String) {
@@ -423,7 +453,6 @@ constructor(
interfaceProxy = _uiState.value.interfaceProxy.copy(publicKey = value), interfaceProxy = _uiState.value.interfaceProxy.copy(publicKey = value),
) )
} }
} }
fun onPrivateKeyChange(value: String) { fun onPrivateKeyChange(value: String) {
@@ -483,7 +512,10 @@ constructor(
fun onResponsePacketJunkSize(value: String) { fun onResponsePacketJunkSize(value: String) {
_uiState.update { _uiState.update {
it.copy( 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) { fun onInitPacketMagicHeader(value: String) {
_uiState.update { _uiState.update {
it.copy( 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) { fun onResponsePacketMagicHeader(value: String) {
_uiState.update { _uiState.update {
it.copy( 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) { fun onTransportPacketMagicHeader(value: String) {
_uiState.update { _uiState.update {
it.copy( 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) { fun onUnderloadPacketMagicHeader(value: String) {
_uiState.update { _uiState.update {
it.copy( 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 "", mtu = if (i.mtu.isPresent) i.mtu.get().toString().trim() else "",
junkPacketCount = if (i.junkPacketCount.isPresent) i.junkPacketCount.get() junkPacketCount =
.toString() else "", if (i.junkPacketCount.isPresent) {
junkPacketMinSize = if (i.junkPacketMinSize.isPresent) i.junkPacketMinSize.get() i.junkPacketCount.get()
.toString() else "", .toString()
junkPacketMaxSize = if (i.junkPacketMaxSize.isPresent) i.junkPacketMaxSize.get() } else {
.toString() else "", ""
initPacketJunkSize = if (i.initPacketJunkSize.isPresent) i.initPacketJunkSize.get() },
.toString() else "", junkPacketMinSize =
responsePacketJunkSize = if (i.responsePacketJunkSize.isPresent) i.responsePacketJunkSize.get() if (i.junkPacketMinSize.isPresent) {
.toString() else "", i.junkPacketMinSize.get()
initPacketMagicHeader = if (i.initPacketMagicHeader.isPresent) i.initPacketMagicHeader.get() .toString()
.toString() else "", } else {
responsePacketMagicHeader = if (i.responsePacketMagicHeader.isPresent) i.responsePacketMagicHeader.get() ""
.toString() else "", },
transportPacketMagicHeader = if (i.transportPacketMagicHeader.isPresent) i.transportPacketMagicHeader.get() junkPacketMaxSize =
.toString() else "", if (i.junkPacketMaxSize.isPresent) {
underloadPacketMagicHeader = if (i.underloadPacketMagicHeader.isPresent) i.underloadPacketMagicHeader.get() i.junkPacketMaxSize.get()
.toString() else "", .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 preSharedKey: String = "",
val persistentKeepalive: String = "", val persistentKeepalive: String = "",
val endpoint: String = "", val endpoint: String = "",
val allowedIps: String = IPV4_WILDCARD.joinToString(", ").trim() val allowedIps: String = IPV4_WILDCARD.joinToString(", ").trim(),
) { ) {
companion object { companion object {
fun from(peer: Peer): PeerProxy { fun from(peer: Peer): PeerProxy {
@@ -2,5 +2,5 @@ package com.zaneschepke.wireguardautotunnel.ui.screens.main
enum class ConfigType { enum class ConfigType {
AMNEZIA, 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.Settings
import androidx.compose.material.icons.rounded.Smartphone import androidx.compose.material.icons.rounded.Smartphone
import androidx.compose.material.icons.rounded.Star import androidx.compose.material.icons.rounded.Star
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FabPosition import androidx.compose.material3.FabPosition
import androidx.compose.material3.HorizontalDivider 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.AppViewModel
import com.zaneschepke.wireguardautotunnel.ui.Screen import com.zaneschepke.wireguardautotunnel.ui.Screen
import com.zaneschepke.wireguardautotunnel.ui.common.RowListItem 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.common.screen.LoadingScreen
import com.zaneschepke.wireguardautotunnel.ui.theme.corn import com.zaneschepke.wireguardautotunnel.ui.theme.corn
import com.zaneschepke.wireguardautotunnel.ui.theme.mint import com.zaneschepke.wireguardautotunnel.ui.theme.mint
@@ -120,7 +120,7 @@ fun MainScreen(
viewModel: MainViewModel = hiltViewModel(), viewModel: MainViewModel = hiltViewModel(),
appViewModel: AppViewModel, appViewModel: AppViewModel,
focusRequester: FocusRequester, focusRequester: FocusRequester,
navController: NavController navController: NavController,
) { ) {
val haptic = LocalHapticFeedback.current val haptic = LocalHapticFeedback.current
val context = LocalContext.current val context = LocalContext.current
@@ -132,7 +132,8 @@ fun MainScreen(
var configType by remember { mutableStateOf(ConfigType.WIREGUARD) } var configType by remember { mutableStateOf(ConfigType.WIREGUARD) }
// Nested scroll for control FAB // Nested scroll for control FAB
val nestedScrollConnection = remember { val nestedScrollConnection =
remember {
object : NestedScrollConnection { object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
// Hide FAB // Hide FAB
@@ -149,7 +150,6 @@ fun MainScreen(
} }
} }
var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) } var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) }
var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) } var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) }
val uiState by viewModel.uiState.collectAsStateWithLifecycle() val uiState by viewModel.uiState.collectAsStateWithLifecycle()
@@ -190,7 +190,9 @@ fun MainScreen(
name.startsWith(Constants.ANDROID_TV_EXPLORER_STUB) 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 return intent
} }
@@ -217,37 +219,31 @@ fun MainScreen(
}, },
) )
AnimatedVisibility(showDeleteTunnelAlertDialog) { if (showDeleteTunnelAlertDialog) {
AlertDialog( InfoDialog(
onDismissRequest = { showDeleteTunnelAlertDialog = false }, onDismiss = { showDeleteTunnelAlertDialog = false },
confirmButton = { onAttest = {
TextButton(
onClick = {
selectedTunnel?.let { viewModel.onDelete(it, context) } selectedTunnel?.let { viewModel.onDelete(it, context) }
showDeleteTunnelAlertDialog = false showDeleteTunnelAlertDialog = false
selectedTunnel = null 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)) }, 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) { fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) {
if (appViewModel.isRequiredPermissionGranted()) { if (appViewModel.isRequiredPermissionGranted()) {
if (checked) viewModel.onTunnelStart(tunnel, context) else viewModel.onTunnelStop( if (checked) {
viewModel.onTunnelStart(tunnel, context)
} else {
viewModel.onTunnelStop(
context, context,
) )
} }
} }
}
if (uiState.loading) { if (uiState.loading) {
return LoadingScreen() return LoadingScreen()
@@ -274,7 +270,6 @@ fun MainScreen(
}, },
) )
} }
}, },
floatingActionButtonPosition = FabPosition.End, floatingActionButtonPosition = FabPosition.End,
floatingActionButton = { floatingActionButton = {
@@ -282,7 +277,8 @@ fun MainScreen(
visible = isVisible.value, visible = isVisible.value,
enter = slideInVertically(initialOffsetY = { it * 2 }), enter = slideInVertically(initialOffsetY = { it * 2 }),
exit = slideOutVertically(targetOffsetY = { it * 2 }), exit = slideOutVertically(targetOffsetY = { it * 2 }),
modifier = Modifier modifier =
Modifier
.focusRequester(focusRequester) .focusRequester(focusRequester)
.focusGroup(), .focusGroup(),
) { ) {
@@ -293,16 +289,19 @@ fun MainScreen(
val fobIconColor = val fobIconColor =
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) Color.White else MaterialTheme.colorScheme.background if (WireGuardAutoTunnel.isRunningOnAndroidTv()) Color.White else MaterialTheme.colorScheme.background
MultiFloatingActionButton( MultiFloatingActionButton(
fabIcon = FabIcon( fabIcon =
FabIcon(
iconRes = R.drawable.add, iconRes = R.drawable.add,
iconResAfterRotate = R.drawable.close, iconResAfterRotate = R.drawable.close,
iconRotate = 180f, iconRotate = 180f,
), ),
fabOption = FabOption( fabOption =
FabOption(
iconTint = fobIconColor, iconTint = fobIconColor,
backgroundTint = fobColor, backgroundTint = fobColor,
), ),
itemsMultiFab = listOf( itemsMultiFab =
listOf(
MultiFabItem( MultiFabItem(
label = { label = {
Text( Text(
@@ -312,11 +311,13 @@ fun MainScreen(
modifier = Modifier.padding(end = 10.dp), modifier = Modifier.padding(end = 10.dp),
) )
}, },
modifier = Modifier modifier =
Modifier
.size(40.dp), .size(40.dp),
icon = R.drawable.add, icon = R.drawable.add,
value = ConfigType.AMNEZIA.name, value = ConfigType.AMNEZIA.name,
miniFabOption = FabOption( miniFabOption =
FabOption(
backgroundTint = fobColor, backgroundTint = fobColor,
fobIconColor, fobIconColor,
), ),
@@ -332,7 +333,8 @@ fun MainScreen(
}, },
icon = R.drawable.add, icon = R.drawable.add,
value = ConfigType.WIREGUARD.name, value = ConfigType.WIREGUARD.name,
miniFabOption = FabOption( miniFabOption =
FabOption(
backgroundTint = fobColor, backgroundTint = fobColor,
fobIconColor, fobIconColor,
), ),
@@ -351,7 +353,6 @@ fun MainScreen(
ModalBottomSheet( ModalBottomSheet(
onDismissRequest = { onDismissRequest = {
showBottomSheet = false showBottomSheet = false
}, },
sheetState = sheetState, sheetState = sheetState,
) { ) {
@@ -409,7 +410,7 @@ fun MainScreen(
.clickable { .clickable {
showBottomSheet = false showBottomSheet = false
navController.navigate( 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), .padding(10.dp),
@@ -442,23 +443,29 @@ fun MainScreen(
) { ) {
item { item {
AnimatedVisibility( AnimatedVisibility(
uiState.tunnels.isEmpty(), exit = fadeOut(), enter = fadeIn(), uiState.tunnels.isEmpty(),
exit = fadeOut(),
enter = fadeIn(),
) { ) {
Column( Column(
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center, verticalArrangement = Arrangement.Center,
modifier = Modifier modifier =
Modifier
.padding(top = 100.dp) .padding(top = 100.dp)
.fillMaxSize(), .fillMaxSize(),
) { ) {
val gettingStarted = buildAnnotatedString { val gettingStarted =
buildAnnotatedString {
append(stringResource(id = R.string.see_the)) append(stringResource(id = R.string.see_the))
append(" ") append(" ")
pushStringAnnotation( pushStringAnnotation(
tag = "gettingStarted", tag = "gettingStarted",
annotation = stringResource(id = R.string.getting_started_url), 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)) append(stringResource(id = R.string.getting_started_guide))
} }
pop() pop()
@@ -471,10 +478,12 @@ fun MainScreen(
fontStyle = FontStyle.Italic, fontStyle = FontStyle.Italic,
) )
ClickableText( ClickableText(
modifier = Modifier modifier =
Modifier
.padding(vertical = 10.dp, horizontal = 24.dp), .padding(vertical = 10.dp, horizontal = 24.dp),
text = gettingStarted, text = gettingStarted,
style = MaterialTheme.typography.bodyMedium.copy( style =
MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
), ),
@@ -490,27 +499,36 @@ fun MainScreen(
item { item {
if (uiState.settings.isAutoTunnelEnabled) { if (uiState.settings.isAutoTunnelEnabled) {
val itemFocusRequester = remember { FocusRequester() } val itemFocusRequester = remember { FocusRequester() }
val autoTunnelingLabel = buildAnnotatedString { val autoTunnelingLabel =
buildAnnotatedString {
append(stringResource(id = R.string.auto_tunneling)) append(stringResource(id = R.string.auto_tunneling))
append(": ") append(": ")
if (uiState.settings.isAutoTunnelPaused) append( if (uiState.settings.isAutoTunnelPaused) {
append(
stringResource(id = R.string.paused), stringResource(id = R.string.paused),
) else append( )
} else {
append(
stringResource(id = R.string.active), stringResource(id = R.string.active),
) )
} }
}
RowListItem( RowListItem(
icon = { icon = {
val icon = Icons.Rounded.Bolt val icon = Icons.Rounded.Bolt
Icon( Icon(
icon, icon,
icon.name, icon.name,
modifier = Modifier modifier =
Modifier
.padding(end = 8.5.dp) .padding(end = 8.5.dp)
.size(25.dp), .size(25.dp),
tint = tint =
if (uiState.settings.isAutoTunnelPaused) Color.Gray if (uiState.settings.isAutoTunnelPaused) {
else mint, Color.Gray
} else {
mint
},
) )
}, },
text = autoTunnelingLabel.text, text = autoTunnelingLabel.text,
@@ -539,7 +557,7 @@ fun MainScreen(
onHold = {}, onHold = {},
expanded = false, expanded = false,
statistics = null, statistics = null,
focusRequester = focusRequester focusRequester = focusRequester,
) )
} }
} }
@@ -548,7 +566,8 @@ fun MainScreen(
key = { tunnel -> tunnel.id }, key = { tunnel -> tunnel.id },
) { tunnel -> ) { tunnel ->
val leadingIconColor = val leadingIconColor =
(if ( (
if (
uiState.vpnState.tunnelConfig?.name == tunnel.name && uiState.vpnState.tunnelConfig?.name == tunnel.name &&
uiState.vpnState.status == TunnelState.UP uiState.vpnState.status == TunnelState.UP
) { ) {
@@ -569,13 +588,15 @@ fun MainScreen(
} }
} else { } else {
Color.Gray Color.Gray
}) }
)
val itemFocusRequester = remember { FocusRequester() } val itemFocusRequester = remember { FocusRequester() }
val expanded = remember { mutableStateOf(false) } val expanded = remember { mutableStateOf(false) }
RowListItem( RowListItem(
icon = { icon = {
val circleIcon = Icons.Rounded.Circle val circleIcon = Icons.Rounded.Circle
val icon = if (tunnel.isPrimaryTunnel) { val icon =
if (tunnel.isPrimaryTunnel) {
Icons.Rounded.Star Icons.Rounded.Star
} else if (tunnel.isMobileDataTunnel) { } else if (tunnel.isMobileDataTunnel) {
Icons.Rounded.Smartphone Icons.Rounded.Smartphone
@@ -586,7 +607,8 @@ fun MainScreen(
icon, icon,
icon.name, icon.name,
tint = leadingIconColor, tint = leadingIconColor,
modifier = Modifier modifier =
Modifier
.padding( .padding(
end = if (icon == circleIcon) 12.5.dp else 10.dp, end = if (icon == circleIcon) 12.5.dp else 10.dp,
start = if (icon == circleIcon) 2.5.dp else 0.dp, start = if (icon == circleIcon) 2.5.dp else 0.dp,
@@ -600,7 +622,9 @@ fun MainScreen(
(uiState.vpnState.status == TunnelState.UP) && (uiState.vpnState.status == TunnelState.UP) &&
(tunnel.name == uiState.vpnState.tunnelConfig?.name) (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 return@RowListItem
} }
haptic.performHapticFeedback(HapticFeedbackType.LongPress) haptic.performHapticFeedback(HapticFeedbackType.LongPress)
@@ -668,15 +692,16 @@ fun MainScreen(
} else { } else {
val checked by remember { val checked by remember {
derivedStateOf { 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 if (!checked) expanded.value = false
@Composable @Composable
fun TunnelSwitch() = fun TunnelSwitch() = Switch(
Switch(
modifier = Modifier.focusRequester(itemFocusRequester), modifier = Modifier.focusRequester(itemFocusRequester),
checked = checked, checked = checked,
onCheckedChange = { checked -> onCheckedChange = { checked ->
@@ -8,5 +8,5 @@ data class MainUiState(
val settings: Settings = Settings(), val settings: Settings = Settings(),
val tunnels: TunnelConfigs = emptyList(), val tunnels: TunnelConfigs = emptyList(),
val vpnState: VpnState = VpnState(), val vpnState: VpnState = VpnState(),
val loading: Boolean = true val loading: Boolean = true,
) )
@@ -37,9 +37,8 @@ constructor(
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
private val serviceManager: ServiceManager, private val serviceManager: ServiceManager,
val vpnService: VpnService, val vpnService: VpnService,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : ViewModel() { ) : ViewModel() {
val uiState = val uiState =
combine( combine(
appDataRepository.settings.getSettingsFlow(), appDataRepository.settings.getSettingsFlow(),
@@ -80,8 +79,7 @@ constructor(
) )
} }
fun onTunnelStart(tunnelConfig: TunnelConfig, context: Context) = fun onTunnelStart(tunnelConfig: TunnelConfig, context: Context) = viewModelScope.launch {
viewModelScope.launch {
Timber.d("On start called!") Timber.d("On start called!")
serviceManager.startVpnService( serviceManager.startVpnService(
context, context,
@@ -90,9 +88,7 @@ constructor(
) )
} }
fun onTunnelStop(context: Context) = viewModelScope.launch {
fun onTunnelStop(context: Context) =
viewModelScope.launch {
Timber.i("Stopping active tunnel") Timber.i("Stopping active tunnel")
serviceManager.stopVpnService(context, isManualStop = true) serviceManager.stopVpnService(context, isManualStop = true)
} }
@@ -139,16 +135,26 @@ constructor(
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
try { try {
validateConfigString(result, configType) validateConfigString(result, configType)
val tunnelName = makeTunnelNameUnique(generateQrCodeTunnelName(result, configType)) val tunnelName =
val tunnelConfig = when (configType) { makeTunnelNameUnique(generateQrCodeTunnelName(result, configType))
val tunnelConfig =
when (configType) {
ConfigType.AMNEZIA -> { ConfigType.AMNEZIA -> {
TunnelConfig( TunnelConfig(
name = tunnelName, amQuick = result, name = tunnelName,
wgQuick = TunnelConfig.configFromAmQuick(result).toWgQuickString(), amQuick = result,
wgQuick =
TunnelConfig.configFromAmQuick(
result,
).toWgQuickString(),
) )
} }
ConfigType.WIREGUARD -> TunnelConfig(name = tunnelName, wgQuick = result) ConfigType.WIREGUARD ->
TunnelConfig(
name = tunnelName,
wgQuick = result,
)
} }
addTunnel(tunnelConfig) addTunnel(tunnelConfig)
Result.success(Unit) Result.success(Unit)
@@ -165,20 +171,17 @@ constructor(
var tunnelName = name var tunnelName = name
var num = 1 var num = 1
while (tunnels.any { it.name == tunnelName }) { while (tunnels.any { it.name == tunnelName }) {
tunnelName = name + "(${num})" tunnelName = name + "($num)"
num++ num++
} }
tunnelName tunnelName
} }
} }
private fun saveTunnelConfigFromStream( private fun saveTunnelConfigFromStream(stream: InputStream, fileName: String, type: ConfigType) {
stream: InputStream,
fileName: String,
type: ConfigType
) {
var amQuick: String? = null var amQuick: String? = null
val wgQuick = stream.use { val wgQuick =
stream.use {
when (type) { when (type) {
ConfigType.AMNEZIA -> { ConfigType.AMNEZIA -> {
val config = org.amnezia.awg.config.Config.parse(it) val config = org.amnezia.awg.config.Config.parse(it)
@@ -207,11 +210,7 @@ constructor(
return context.applicationContext.contentResolver.openInputStream(uri) return context.applicationContext.contentResolver.openInputStream(uri)
} }
suspend fun onTunnelFileSelected( suspend fun onTunnelFileSelected(uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
uri: Uri,
configType: ConfigType,
context: Context
): Result<Unit> {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
try { try {
if (isValidUriContentScheme(uri)) { if (isValidUriContentScheme(uri)) {
@@ -220,7 +219,8 @@ constructor(
Constants.CONF_FILE_EXTENSION -> Constants.CONF_FILE_EXTENSION ->
saveTunnelFromConfUri(fileName, uri, configType, context) saveTunnelFromConfUri(fileName, uri, configType, context)
Constants.ZIP_FILE_EXTENSION -> saveTunnelsFromZipUri( Constants.ZIP_FILE_EXTENSION ->
saveTunnelsFromZipUri(
uri, uri,
configType, configType,
context, context,
@@ -238,11 +238,7 @@ constructor(
} }
} }
private suspend fun saveTunnelsFromZipUri( private suspend fun saveTunnelsFromZipUri(uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
uri: Uri,
configType: ConfigType,
context: Context
): Result<Unit> {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
ZipInputStream(getInputStreamFromUri(uri, context)).use { zip -> ZipInputStream(getInputStreamFromUri(uri, context)).use { zip ->
generateSequence { zip.nextEntry } generateSequence { zip.nextEntry }
@@ -258,7 +254,10 @@ constructor(
val wgQuick = val wgQuick =
when (configType) { when (configType) {
ConfigType.AMNEZIA -> { ConfigType.AMNEZIA -> {
val config = org.amnezia.awg.config.Config.parse(zip) val config =
org.amnezia.awg.config.Config.parse(
zip,
)
amQuick = config.toAwgQuickString() amQuick = config.toAwgQuickString()
config.toWgQuickString() config.toWgQuickString()
} }
@@ -285,12 +284,7 @@ constructor(
} }
} }
private suspend fun saveTunnelFromConfUri( private suspend fun saveTunnelFromConfUri(name: String, uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
name: String,
uri: Uri,
configType: ConfigType,
context: Context
): Result<Unit> {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
val stream = getInputStreamFromUri(uri, context) val stream = getInputStreamFromUri(uri, context)
return@withContext if (stream != null) { return@withContext if (stream != null) {
@@ -312,15 +306,17 @@ constructor(
if (firstTunnel) WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate() if (firstTunnel) WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
} }
fun pauseAutoTunneling() = fun pauseAutoTunneling() = viewModelScope.launch {
viewModelScope.launch { appDataRepository.settings.save(
appDataRepository.settings.save(uiState.value.settings.copy(isAutoTunnelPaused = true)) uiState.value.settings.copy(isAutoTunnelPaused = true),
)
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate() WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
} }
fun resumeAutoTunneling() = fun resumeAutoTunneling() = viewModelScope.launch {
viewModelScope.launch { appDataRepository.settings.save(
appDataRepository.settings.save(uiState.value.settings.copy(isAutoTunnelPaused = false)) uiState.value.settings.copy(isAutoTunnelPaused = false),
)
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate() WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
} }
@@ -349,8 +345,12 @@ constructor(
val index = getDisplayNameColumnIndex(cursor) val index = getDisplayNameColumnIndex(cursor)
if (index != null) { if (index != null) {
cursor.getString(index) cursor.getString(index)
} else null } else {
} else null null
}
} else {
null
}
} }
private fun isValidUriContentScheme(uri: Uri): Boolean { private fun isValidUriContentScheme(uri: Uri): Boolean {
@@ -374,9 +374,7 @@ constructor(
} }
} }
private fun saveSettings(settings: Settings) = private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
viewModelScope.launch { appDataRepository.settings.save(settings) }
fun onCopyTunnel(tunnel: TunnelConfig?) = viewModelScope.launch { fun onCopyTunnel(tunnel: TunnelConfig?) = viewModelScope.launch {
tunnel?.let { tunnel?.let {
@@ -81,7 +81,7 @@ fun OptionsScreen(
navController: NavController, navController: NavController,
appViewModel: AppViewModel, appViewModel: AppViewModel,
focusRequester: FocusRequester, focusRequester: FocusRequester,
tunnelId: String tunnelId: String,
) { ) {
val scrollState = rememberScrollState() val scrollState = rememberScrollState()
val uiState by optionsViewModel.uiState.collectAsStateWithLifecycle() val uiState by optionsViewModel.uiState.collectAsStateWithLifecycle()
@@ -127,21 +127,25 @@ fun OptionsScreen(
visible = true, visible = true,
enter = slideInVertically(initialOffsetY = { it * 2 }), enter = slideInVertically(initialOffsetY = { it * 2 }),
exit = slideOutVertically(targetOffsetY = { it * 2 }), exit = slideOutVertically(targetOffsetY = { it * 2 }),
modifier = Modifier modifier =
Modifier
.focusRequester(focusRequester) .focusRequester(focusRequester)
.focusGroup(), .focusGroup(),
) { ) {
MultiFloatingActionButton( MultiFloatingActionButton(
fabIcon = FabIcon( fabIcon =
FabIcon(
iconRes = R.drawable.edit, iconRes = R.drawable.edit,
iconResAfterRotate = R.drawable.close, iconResAfterRotate = R.drawable.close,
iconRotate = 180f, iconRotate = 180f,
), ),
fabOption = FabOption( fabOption =
FabOption(
iconTint = fobIconColor, iconTint = fobIconColor,
backgroundTint = fobColor, backgroundTint = fobColor,
), ),
itemsMultiFab = listOf( itemsMultiFab =
listOf(
MultiFabItem( MultiFabItem(
label = { label = {
Text( Text(
@@ -151,11 +155,13 @@ fun OptionsScreen(
modifier = Modifier.padding(end = 10.dp), modifier = Modifier.padding(end = 10.dp),
) )
}, },
modifier = Modifier modifier =
Modifier
.size(40.dp), .size(40.dp),
icon = R.drawable.edit, icon = R.drawable.edit,
value = ConfigType.AMNEZIA.name, value = ConfigType.AMNEZIA.name,
miniFabOption = FabOption( miniFabOption =
FabOption(
backgroundTint = fobColor, backgroundTint = fobColor,
fobIconColor, fobIconColor,
), ),
@@ -171,7 +177,8 @@ fun OptionsScreen(
}, },
icon = R.drawable.edit, icon = R.drawable.edit,
value = ConfigType.WIREGUARD.name, value = ConfigType.WIREGUARD.name,
miniFabOption = FabOption( miniFabOption =
FabOption(
backgroundTint = fobColor, backgroundTint = fobColor,
fobIconColor, fobIconColor,
), ),
@@ -180,7 +187,7 @@ fun OptionsScreen(
onFabItemClicked = { onFabItemClicked = {
val configType = ConfigType.valueOf(it.value) val configType = ConfigType.valueOf(it.value)
navController.navigate( navController.navigate(
"${Screen.Config.route}/${tunnelId}?configType=${configType.name}", "${Screen.Config.route}/$tunnelId?configType=${configType.name}",
) )
}, },
shape = RoundedCornerShape(16.dp), shape = RoundedCornerShape(16.dp),
@@ -208,7 +215,8 @@ fun OptionsScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.height(IntrinsicSize.Min) .height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
@@ -217,7 +225,8 @@ fun OptionsScreen(
Modifier Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp) .padding(top = 20.dp)
}) }
)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Column( Column(
@@ -233,7 +242,8 @@ fun OptionsScreen(
stringResource(R.string.set_primary_tunnel), stringResource(R.string.set_primary_tunnel),
enabled = true, enabled = true,
checked = uiState.isDefaultTunnel, checked = uiState.isDefaultTunnel,
modifier = Modifier modifier =
Modifier
.focusRequester(focusRequester), .focusRequester(focusRequester),
padding = screenPadding, padding = screenPadding,
onCheckChanged = { optionsViewModel.onTogglePrimaryTunnel() }, onCheckChanged = { optionsViewModel.onTogglePrimaryTunnel() },
@@ -246,7 +256,8 @@ fun OptionsScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.height(IntrinsicSize.Min) .height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
@@ -255,7 +266,8 @@ fun OptionsScreen(
Modifier Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp) .padding(top = 20.dp)
}) }
)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Column( Column(
@@ -276,7 +288,8 @@ fun OptionsScreen(
) )
Column { Column {
FlowRow( FlowRow(
modifier = Modifier modifier =
Modifier
.padding(screenPadding) .padding(screenPadding)
.fillMaxWidth(), .fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(5.dp), horizontalArrangement = Arrangement.spacedBy(5.dp),
@@ -292,7 +305,6 @@ fun OptionsScreen(
onIconClick = { onIconClick = {
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus() if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus()
optionsViewModel.onDeleteRunSSID(ssid) optionsViewModel.onDeleteRunSSID(ssid)
}, },
text = ssid, text = ssid,
icon = Icons.Filled.Close, icon = Icons.Filled.Close,
@@ -5,5 +5,5 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
data class OptionsUiState( data class OptionsUiState(
val id: String? = null, val id: String? = null,
val tunnel: TunnelConfig? = 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 import javax.inject.Inject
@HiltViewModel @HiltViewModel
class OptionsViewModel @Inject class OptionsViewModel
@Inject
constructor( constructor(
private val appDataRepository: AppDataRepository private val appDataRepository: AppDataRepository,
) : ViewModel() { ) : ViewModel() {
private val _optionState = MutableStateFlow(OptionsUiState()) private val _optionState = MutableStateFlow(OptionsUiState())
val uiState = combine( val uiState =
combine(
appDataRepository.tunnels.getTunnelConfigsFlow(), appDataRepository.tunnels.getTunnelConfigsFlow(),
_optionState, _optionState,
) { tunnels, optionState -> ) { tunnels, optionState ->
@@ -34,7 +35,9 @@ constructor(
val tunnelConfig = tunnels.fastFirstOrNull { it.id.toString() == optionState.id } val tunnelConfig = tunnels.fastFirstOrNull { it.id.toString() == optionState.id }
val isPrimaryTunnel = tunnelConfig?.isPrimaryTunnel == true val isPrimaryTunnel = tunnelConfig?.isPrimaryTunnel == true
OptionsUiState(optionState.id, tunnelConfig, isPrimaryTunnel) OptionsUiState(optionState.id, tunnelConfig, isPrimaryTunnel)
} else OptionsUiState() } else {
OptionsUiState()
}
}.stateIn( }.stateIn(
viewModelScope, viewModelScope,
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT), SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
@@ -52,7 +55,8 @@ constructor(
fun onDeleteRunSSID(ssid: String) = viewModelScope.launch { fun onDeleteRunSSID(ssid: String) = viewModelScope.launch {
uiState.value.tunnel?.let { uiState.value.tunnel?.let {
appDataRepository.tunnels.save( appDataRepository.tunnels.save(
tunnelConfig = it.copy( tunnelConfig =
it.copy(
tunnelNetworks = (uiState.value.tunnel!!.tunnelNetworks - ssid).toMutableList(), tunnelNetworks = (uiState.value.tunnel!!.tunnelNetworks - ssid).toMutableList(),
), ),
) )
@@ -67,11 +71,13 @@ constructor(
suspend fun onSaveRunSSID(ssid: String): Result<Unit> { suspend fun onSaveRunSSID(ssid: String): Result<Unit> {
val trimmed = ssid.trim() val trimmed = ssid.trim()
val tunnelsWithName = withContext(viewModelScope.coroutineContext) { val tunnelsWithName =
withContext(viewModelScope.coroutineContext) {
appDataRepository.tunnels.findByTunnelNetworksName(trimmed) appDataRepository.tunnels.findByTunnelNetworksName(trimmed)
} }
return if (uiState.value.tunnel?.tunnelNetworks?.contains(trimmed) != true && return if (uiState.value.tunnel?.tunnelNetworks?.contains(trimmed) != true &&
tunnelsWithName.isEmpty()) { tunnelsWithName.isEmpty()
) {
uiState.value.tunnel?.tunnelNetworks?.add(trimmed) uiState.value.tunnel?.tunnelNetworks?.add(trimmed)
saveTunnel(uiState.value.tunnel) saveTunnel(uiState.value.tunnel)
Result.success(Unit) Result.success(Unit)
@@ -84,7 +90,9 @@ constructor(
uiState.value.tunnel?.let { uiState.value.tunnel?.let {
if (it.isMobileDataTunnel) { if (it.isMobileDataTunnel) {
appDataRepository.tunnels.updateMobileDataTunnel(null) 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( PinLock(
title = { pinExists -> title = { pinExists ->
Text( 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, id = R.string.create_pin,
), )
},
) )
}, },
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
@@ -35,7 +40,6 @@ fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
navController.navigate(Screen.Main.route) navController.navigate(Screen.Main.route)
} }
} }
}, },
onPinIncorrect = { onPinIncorrect = {
// pin is incorrect, show error // pin is incorrect, show error
@@ -121,7 +121,9 @@ fun SettingsScreen(
} }
val startForResult = val startForResult =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) { if (result.resultCode == Activity.RESULT_OK) {
result.data result.data
// Handle the Intent // Handle the Intent
@@ -131,28 +133,34 @@ fun SettingsScreen(
fun exportAllConfigs() { fun exportAllConfigs() {
try { try {
val wgFiles = uiState.tunnels.map { config -> val wgFiles =
uiState.tunnels.map { config ->
val file = File(context.cacheDir, "${config.name}-wg.conf") val file = File(context.cacheDir, "${config.name}-wg.conf")
file.outputStream().use { file.outputStream().use {
it.write(config.wgQuick.toByteArray()) it.write(config.wgQuick.toByteArray())
} }
file file
} }
val amFiles = uiState.tunnels.mapNotNull { config -> val amFiles =
uiState.tunnels.mapNotNull { config ->
if (config.amQuick != TunnelConfig.AM_QUICK_DEFAULT) { if (config.amQuick != TunnelConfig.AM_QUICK_DEFAULT) {
val file = File(context.cacheDir, "${config.name}-am.conf") val file = File(context.cacheDir, "${config.name}-am.conf")
file.outputStream().use { file.outputStream().use {
it.write(config.amQuick.toByteArray()) it.write(config.amQuick.toByteArray())
} }
file file
} else null } else {
null
}
} }
scope.launch { scope.launch {
viewModel.onExportTunnels(wgFiles + amFiles).onFailure { viewModel.onExportTunnels(wgFiles + amFiles).onFailure {
appViewModel.showSnackbarMessage(it.getMessage(context)) appViewModel.showSnackbarMessage(it.getMessage(context))
}.onSuccess { }.onSuccess {
didExportFiles = true didExportFiles = true
appViewModel.showSnackbarMessage(context.getString(R.string.exported_configs_message)) appViewModel.showSnackbarMessage(
context.getString(R.string.exported_configs_message),
)
} }
} }
} catch (e: Exception) { } catch (e: Exception) {
@@ -260,14 +268,16 @@ fun SettingsScreen(
Column( Column(
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top, verticalArrangement = Arrangement.Top,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.verticalScroll(scrollState), .verticalScroll(scrollState),
) { ) {
Icon( Icon(
Icons.Rounded.LocationOff, Icons.Rounded.LocationOff,
contentDescription = stringResource(id = R.string.map), contentDescription = stringResource(id = R.string.map),
modifier = Modifier modifier =
Modifier
.padding(30.dp) .padding(30.dp)
.size(128.dp), .size(128.dp),
) )
@@ -321,11 +331,15 @@ fun SettingsScreen(
}, },
onError = { _ -> onError = { _ ->
showAuthPrompt = false showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authentication_failed)) appViewModel.showSnackbarMessage(
context.getString(R.string.error_authentication_failed),
)
}, },
onFailure = { onFailure = {
showAuthPrompt = false 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), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.height(IntrinsicSize.Min) .height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
@@ -374,7 +389,8 @@ fun SettingsScreen(
Modifier Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp) .padding(top = 20.dp)
}) }
)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Column( Column(
@@ -389,21 +405,26 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(id = R.string.tunnel_on_wifi), stringResource(id = R.string.tunnel_on_wifi),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isTunnelOnWifiEnabled, checked = uiState.settings.isTunnelOnWifiEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { viewModel.onToggleTunnelOnWifi() }, onCheckChanged = { viewModel.onToggleTunnelOnWifi() },
modifier = modifier =
if (uiState.settings.isAutoTunnelEnabled) Modifier if (uiState.settings.isAutoTunnelEnabled) {
else
Modifier Modifier
.focusRequester(focusRequester), } else {
Modifier
.focusRequester(focusRequester)
},
) )
AnimatedVisibility(visible = uiState.settings.isTunnelOnWifiEnabled) { AnimatedVisibility(visible = uiState.settings.isTunnelOnWifiEnabled) {
Column { Column {
FlowRow( FlowRow(
modifier = Modifier modifier =
Modifier
.padding(screenPadding) .padding(screenPadding)
.fillMaxWidth(), .fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(5.dp), horizontalArrangement = Arrangement.spacedBy(5.dp),
@@ -419,13 +440,14 @@ fun SettingsScreen(
onIconClick = { onIconClick = {
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus() if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus()
viewModel.onDeleteTrustedSSID(ssid) viewModel.onDeleteTrustedSSID(ssid)
}, },
text = ssid, text = ssid,
icon = Icons.Filled.Close, icon = Icons.Filled.Close,
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
) )
} }
if (uiState.settings.trustedNetworkSSIDs.isEmpty()) { if (uiState.settings.trustedNetworkSSIDs.isEmpty()) {
@@ -438,8 +460,10 @@ fun SettingsScreen(
} }
OutlinedTextField( OutlinedTextField(
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
value = currentText, value = currentText,
onValueChange = { currentText = it }, onValueChange = { currentText = it },
label = { Text(stringResource(R.string.add_trusted_ssid)) }, label = { Text(stringResource(R.string.add_trusted_ssid)) },
@@ -487,8 +511,10 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(R.string.tunnel_mobile_data), stringResource(R.string.tunnel_mobile_data),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isTunnelOnMobileDataEnabled, checked = uiState.settings.isTunnelOnMobileDataEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { viewModel.onToggleTunnelOnMobileData() }, onCheckChanged = { viewModel.onToggleTunnelOnMobileData() },
@@ -496,8 +522,10 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(id = R.string.tunnel_on_ethernet), stringResource(id = R.string.tunnel_on_ethernet),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isTunnelOnEthernetEnabled, checked = uiState.settings.isTunnelOnEthernetEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { viewModel.onToggleTunnelOnEthernet() }, onCheckChanged = { viewModel.onToggleTunnelOnEthernet() },
@@ -505,8 +533,10 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(R.string.restart_on_ping), stringResource(R.string.restart_on_ping),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isPingEnabled, checked = uiState.settings.isPingEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { viewModel.onToggleRestartOnPing() }, onCheckChanged = { viewModel.onToggleRestartOnPing() },
@@ -514,11 +544,15 @@ fun SettingsScreen(
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = modifier =
(if (!uiState.settings.isAutoTunnelEnabled) Modifier (
else if (!uiState.settings.isAutoTunnelEnabled) {
Modifier
} else {
Modifier.focusRequester( Modifier.focusRequester(
focusRequester, focusRequester,
)) )
}
)
.fillMaxSize() .fillMaxSize()
.padding(top = 5.dp), .padding(top = 5.dp),
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
@@ -533,12 +567,16 @@ fun SettingsScreen(
when (false) { when (false) {
isBackgroundLocationGranted -> isBackgroundLocationGranted ->
appViewModel.showSnackbarMessage( appViewModel.showSnackbarMessage(
context.getString(R.string.background_location_required), context.getString(
R.string.background_location_required,
),
) )
fineLocationState.status.isGranted -> fineLocationState.status.isGranted ->
appViewModel.showSnackbarMessage( appViewModel.showSnackbarMessage(
context.getString(R.string.precise_location_required), context.getString(
R.string.precise_location_required,
),
) )
viewModel.isLocationEnabled(context) -> viewModel.isLocationEnabled(context) ->
@@ -569,7 +607,8 @@ fun SettingsScreen(
shadowElevation = 2.dp, shadowElevation = 2.dp,
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = Modifier modifier =
Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(vertical = 10.dp), .padding(vertical = 10.dp),
) { ) {
@@ -585,9 +624,11 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(R.string.use_amnezia), stringResource(R.string.use_amnezia),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled || uiState.settings.isAlwaysOnVpnEnabled ||
(uiState.vpnState.status == TunnelState.UP) || uiState.settings.isKernelEnabled), (uiState.vpnState.status == TunnelState.UP) || uiState.settings.isKernelEnabled
),
checked = uiState.settings.isAmneziaEnabled, checked = uiState.settings.isAmneziaEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { onCheckChanged = {
@@ -598,9 +639,11 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(R.string.use_kernel), stringResource(R.string.use_kernel),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled || uiState.settings.isAlwaysOnVpnEnabled ||
(uiState.vpnState.status == TunnelState.UP)), (uiState.vpnState.status == TunnelState.UP)
),
checked = uiState.settings.isKernelEnabled, checked = uiState.settings.isKernelEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { onCheckChanged = {
@@ -676,7 +719,8 @@ fun SettingsScreen(
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) { if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(top = 5.dp), .padding(top = 5.dp),
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
@@ -10,5 +10,5 @@ data class SettingsUiState(
val vpnState: VpnState = VpnState(), val vpnState: VpnState = VpnState(),
val isLocationDisclosureShown: Boolean = true, val isLocationDisclosureShown: Boolean = true,
val isBatteryOptimizeDisableShown: Boolean = false, val isBatteryOptimizeDisableShown: Boolean = false,
val isPinLockEnabled: Boolean = false val isPinLockEnabled: Boolean = false,
) )
@@ -41,9 +41,8 @@ constructor(
private val rootShell: Provider<RootShell>, private val rootShell: Provider<RootShell>,
private val fileUtils: FileUtils, private val fileUtils: FileUtils,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
vpnService: VpnService vpnService: VpnService,
) : ViewModel() { ) : ViewModel() {
private val _kernelSupport = MutableStateFlow(false) private val _kernelSupport = MutableStateFlow(false)
val kernelSupport = _kernelSupport.asStateFlow() val kernelSupport = _kernelSupport.asStateFlow()
@@ -80,13 +79,11 @@ constructor(
} }
} }
fun setLocationDisclosureShown() = fun setLocationDisclosureShown() = viewModelScope.launch {
viewModelScope.launch {
appDataRepository.appState.setLocationDisclosureShown(true) appDataRepository.appState.setLocationDisclosureShown(true)
} }
fun setBatteryOptimizeDisableShown() = fun setBatteryOptimizeDisableShown() = viewModelScope.launch {
viewModelScope.launch {
appDataRepository.appState.setBatteryOptimizationDisableShown(true) appDataRepository.appState.setBatteryOptimizationDisableShown(true)
} }
@@ -111,8 +108,7 @@ constructor(
return fileUtils.saveFilesToZip(files) return fileUtils.saveFilesToZip(files)
} }
fun onToggleAutoTunnel(context: Context) = fun onToggleAutoTunnel(context: Context) = viewModelScope.launch {
viewModelScope.launch {
val isAutoTunnelEnabled = uiState.value.settings.isAutoTunnelEnabled val isAutoTunnelEnabled = uiState.value.settings.isAutoTunnelEnabled
var isAutoTunnelPaused = uiState.value.settings.isAutoTunnelPaused var isAutoTunnelPaused = uiState.value.settings.isAutoTunnelPaused
@@ -131,8 +127,7 @@ constructor(
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate() WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
} }
fun onToggleAlwaysOnVPN() = fun onToggleAlwaysOnVPN() = viewModelScope.launch {
viewModelScope.launch {
saveSettings( saveSettings(
uiState.value.settings.copy( uiState.value.settings.copy(
isAlwaysOnVpnEnabled = !uiState.value.settings.isAlwaysOnVpnEnabled, isAlwaysOnVpnEnabled = !uiState.value.settings.isAlwaysOnVpnEnabled,
@@ -140,8 +135,7 @@ constructor(
) )
} }
private fun saveSettings(settings: Settings) = private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
viewModelScope.launch { appDataRepository.settings.save(settings) }
fun onToggleTunnelOnEthernet() { fun onToggleTunnelOnEthernet() {
saveSettings( saveSettings(
@@ -152,7 +146,10 @@ constructor(
} }
fun isLocationEnabled(context: Context): Boolean { 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) return LocationManagerCompat.isLocationEnabled(locationManager)
} }
@@ -207,7 +204,6 @@ constructor(
isAmneziaEnabled = false, isAmneziaEnabled = false,
), ),
) )
} catch (e: RootShell.RootShellException) { } catch (e: RootShell.RootShellException) {
Timber.e(e) Timber.e(e)
saveKernelMode(on = false) saveKernelMode(on = false)
@@ -229,7 +225,8 @@ constructor(
} }
fun checkKernelSupport() = viewModelScope.launch { fun checkKernelSupport() = viewModelScope.launch {
val kernelSupport = withContext(ioDispatcher) { val kernelSupport =
withContext(ioDispatcher) {
WgQuickBackend.hasKernelSupport() WgQuickBackend.hasKernelSupport()
} }
_kernelSupport.update { _kernelSupport.update {
@@ -250,8 +247,8 @@ constructor(
fun onToggleRestartAtBoot() = viewModelScope.launch { fun onToggleRestartAtBoot() = viewModelScope.launch {
saveSettings( saveSettings(
uiState.value.settings.copy( uiState.value.settings.copy(
isRestoreOnBootEnabled = !uiState.value.settings.isRestoreOnBootEnabled isRestoreOnBootEnabled = !uiState.value.settings.isRestoreOnBootEnabled,
) ),
) )
} }
} }
@@ -57,7 +57,7 @@ fun SupportScreen(
viewModel: SupportViewModel = hiltViewModel(), viewModel: SupportViewModel = hiltViewModel(),
appViewModel: AppViewModel, appViewModel: AppViewModel,
navController: NavController, navController: NavController,
focusRequester: FocusRequester focusRequester: FocusRequester,
) { ) {
val context = LocalContext.current val context = LocalContext.current
val fillMaxWidth = .85f val fillMaxWidth = .85f
@@ -79,7 +79,8 @@ fun SupportScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.height(IntrinsicSize.Min) .height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
@@ -88,7 +89,8 @@ fun SupportScreen(
Modifier Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp) .padding(top = 20.dp)
}) }
)
.padding(bottom = 25.dp), .padding(bottom = 25.dp),
) { ) {
Column(modifier = Modifier.padding(20.dp)) { Column(modifier = Modifier.padding(20.dp)) {
@@ -113,7 +115,8 @@ fun SupportScreen(
context, context,
) )
}, },
modifier = Modifier modifier =
Modifier
.padding(vertical = 5.dp) .padding(vertical = 5.dp)
.focusRequester(focusRequester), .focusRequester(focusRequester),
) { ) {
@@ -128,7 +131,8 @@ fun SupportScreen(
Text( Text(
stringResource(id = R.string.docs_description), stringResource(id = R.string.docs_description),
textAlign = TextAlign.Justify, textAlign = TextAlign.Justify,
modifier = Modifier modifier =
Modifier
.padding(start = 10.dp) .padding(start = 10.dp)
.weight( .weight(
weight = 1.0f, weight = 1.0f,
@@ -295,12 +299,14 @@ fun SupportScreen(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(25.dp), modifier = Modifier.padding(25.dp),
) { ) {
val version = buildAnnotatedString { val version =
buildAnnotatedString {
append(stringResource(id = R.string.version)) append(stringResource(id = R.string.version))
append(": ") append(": ")
append(BuildConfig.VERSION_NAME) append(BuildConfig.VERSION_NAME)
} }
val mode = buildAnnotatedString { val mode =
buildAnnotatedString {
append(stringResource(R.string.mode)) append(stringResource(R.string.mode))
append(": ") append(": ")
when (uiState.settings.isKernelEnabled) { when (uiState.settings.isKernelEnabled) {
@@ -11,9 +11,10 @@ import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject import javax.inject.Inject
@HiltViewModel @HiltViewModel
class SupportViewModel @Inject constructor(settingsRepository: SettingsRepository) : class SupportViewModel
@Inject
constructor(settingsRepository: SettingsRepository) :
ViewModel() { ViewModel() {
val uiState = val uiState =
settingsRepository settingsRepository
.getSettingsFlow() .getSettingsFlow()
@@ -42,7 +42,6 @@ import kotlinx.coroutines.launch
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable @Composable
fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) { fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
val logs = viewModel.logs val logs = viewModel.logs
val context = LocalContext.current val context = LocalContext.current
@@ -87,7 +86,8 @@ fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.Top), verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.Top),
state = lazyColumnListState, state = lazyColumnListState,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(horizontal = 24.dp), .padding(horizontal = 24.dp),
) { ) {
@@ -99,13 +99,16 @@ fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
Row( Row(
horizontalArrangement = Arrangement.spacedBy(5.dp, Alignment.Start), horizontalArrangement = Arrangement.spacedBy(5.dp, Alignment.Start),
verticalAlignment = Alignment.Top, verticalAlignment = Alignment.Top,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.clickable( .clickable(
interactionSource = remember { MutableInteractionSource() }, interactionSource = remember { MutableInteractionSource() },
indication = null, indication = null,
onClick = { onClick = {
clipboardManager.setText(annotatedString = AnnotatedString(it.toString())) clipboardManager.setText(
annotatedString = AnnotatedString(it.toString()),
)
}, },
), ),
) { ) {
@@ -20,13 +20,13 @@ import javax.inject.Inject
@HiltViewModel @HiltViewModel
class LogsViewModel class LogsViewModel
@Inject constructor( @Inject
constructor(
private val localLogCollector: LocalLogCollector, private val localLogCollector: LocalLogCollector,
private val fileUtils: FileUtils, private val fileUtils: FileUtils,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
@MainDispatcher private val mainDispatcher: CoroutineDispatcher @MainDispatcher private val mainDispatcher: CoroutineDispatcher,
) : ViewModel() { ) : ViewModel() {
val logs = mutableStateListOf<LogMessage>() val logs = mutableStateListOf<LogMessage>()
init { init {
@@ -45,7 +45,8 @@ class LogsViewModel
} }
suspend fun saveLogsToFile(): Result<Unit> { suspend fun saveLogsToFile(): Result<Unit> {
val file = localLogCollector.getLogFile().getOrElse { val file =
localLogCollector.getLogFile().getOrElse {
return Result.failure(it) return Result.failure(it)
} }
val fileContent = fileUtils.readBytesFromFile(file) val fileContent = fileUtils.readBytesFromFile(file)
@@ -49,7 +49,7 @@ fun WireguardAutoTunnelTheme(
// Dynamic color is available on Android 12+ // Dynamic color is available on Android 12+
// turning off dynamic color for now // turning off dynamic color for now
dynamicColor: Boolean = false, dynamicColor: Boolean = false,
content: @Composable () -> Unit content: @Composable () -> Unit,
) { ) {
val colorScheme = val colorScheme =
when { when {
@@ -1,7 +1,6 @@
package com.zaneschepke.wireguardautotunnel.util package com.zaneschepke.wireguardautotunnel.util
object Constants { object Constants {
const val BASE_LOG_FILE_NAME = "wg_tunnel_logs" const val BASE_LOG_FILE_NAME = "wg_tunnel_logs"
const val LOG_BUFFER_SIZE = 3_000L const val LOG_BUFFER_SIZE = 3_000L
@@ -32,13 +31,10 @@ object Constants {
const val PING_INTERVAL = 60_000L const val PING_INTERVAL = 60_000L
const val PING_COOLDOWN = PING_INTERVAL * 60 // one hour const val PING_COOLDOWN = PING_INTERVAL * 60 // one hour
const val ALLOWED_DISPLAY_NAME_LENGTH = 20
const val TUNNEL_EXTRA_KEY = "tunnelId" const val TUNNEL_EXTRA_KEY = "tunnelId"
const val UNREADABLE_SSID = "<unknown ssid>" const val UNREADABLE_SSID = "<unknown ssid>"
val amneziaProperties = listOf("Jc", "Jmin", "Jmax", "S1", "S2", "H1", "H2", "H3", "H4") val amneziaProperties = listOf("Jc", "Jmin", "Jmax", "S1", "S2", "H1", "H2", "H3", "H4")
const val QR_CODE_NAME_PROPERTY = "# Name =" 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). * Borrowed from this [Stack Overflow question](https://stackoverflow.com/questions/51022533/kotlin-chunk-sequence-based-on-size-and-time).
*/ */
@OptIn(ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class) @OptIn(ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class)
fun <T> ReceiveChannel<T>.chunked(scope: CoroutineScope, size: Int, time: Duration) = fun <T> ReceiveChannel<T>.chunked(scope: CoroutineScope, size: Int, time: Duration) = scope.produce<List<T>> {
scope.produce<List<T>> {
while (true) { // this loop goes over each chunk while (true) { // this loop goes over each chunk
val chunk = ConcurrentLinkedQueue<T>() // current chunk val chunk = ConcurrentLinkedQueue<T>() // current chunk
val ticker = ticker(time.toMillis()) // time-limit for this 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) channel.send(value)
} }
} }
@@ -21,7 +21,6 @@ class FileUtils(
private val context: Context, private val context: Context,
private val ioDispatcher: CoroutineDispatcher, private val ioDispatcher: CoroutineDispatcher,
) { ) {
suspend fun readBytesFromFile(file: File): ByteArray { suspend fun readBytesFromFile(file: File): ByteArray {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
FileInputStream(file).use { FileInputStream(file).use {
@@ -61,7 +60,9 @@ class FileUtils(
} else { } else {
val target = val target =
File( File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS,
),
fileName, fileName,
) )
FileOutputStream(target).use { output -> FileOutputStream(target).use { output ->
@@ -101,10 +102,7 @@ class FileUtils(
} }
// TODO issue with android 9 // TODO issue with android 9
private fun createDownloadsFileOutputStream( private fun createDownloadsFileOutputStream(fileName: String, mimeType: String = Constants.ALLOWED_FILE_TYPES): OutputStream? {
fileName: String,
mimeType: String = Constants.ALLOWED_FILE_TYPES
): OutputStream? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val resolver = context.contentResolver val resolver = context.contentResolver
val contentValues = val contentValues =
@@ -4,14 +4,13 @@ import android.content.Context
import androidx.annotation.StringRes import androidx.annotation.StringRes
sealed class StringValue { sealed class StringValue {
data class DynamicString(val value: String) : StringValue() data class DynamicString(val value: String) : StringValue()
data object Empty : StringValue() data object Empty : StringValue()
class StringResource( class StringResource(
@StringRes val resId: Int, @StringRes val resId: Int,
vararg val args: Any vararg val args: Any,
) : StringValue() ) : StringValue()
fun asString(context: Context?): String { fun asString(context: Context?): String {
@@ -5,13 +5,19 @@ import com.zaneschepke.wireguardautotunnel.R
sealed class WgTunnelExceptions : Exception() { sealed class WgTunnelExceptions : Exception() {
abstract fun getMessage(context: Context): String abstract fun getMessage(context: Context): String
data class General(private val userMessage: StringValue) : WgTunnelExceptions() { data class General(private val userMessage: StringValue) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) 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() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -19,9 +25,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class ConfigExportFailed( data class ConfigExportFailed(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.export_configs_failed, R.string.export_configs_failed,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -32,18 +39,29 @@ sealed class WgTunnelExceptions : Exception() {
WgTunnelExceptions() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return StringValue.StringResource(R.string.config_parse_error).asString(context) + ( 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() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) 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() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -51,16 +69,22 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class InvalidFileExtension( data class InvalidFileExtension(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_file_extension, R.string.error_file_extension,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) 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() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -68,9 +92,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class AuthenticationFailed( data class AuthenticationFailed(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_authentication_failed, R.string.error_authentication_failed,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -78,9 +103,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class AuthorizationFailed( data class AuthorizationFailed(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_authorization_failed, R.string.error_authorization_failed,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -88,9 +114,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class BackgroundLocationRequired( data class BackgroundLocationRequired(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.background_location_required, R.string.background_location_required,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -98,9 +125,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class LocationServicesRequired( data class LocationServicesRequired(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.location_services_required, R.string.location_services_required,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -108,9 +136,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class PreciseLocationRequired( data class PreciseLocationRequired(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.precise_location_required, R.string.precise_location_required,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -118,13 +147,13 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class FileExplorerRequired( data class FileExplorerRequired(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_no_file_explorer, R.string.error_no_file_explorer,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
} }
} }
} }
+3
View File
@@ -177,4 +177,7 @@
<string name="wireguard" translatable="false">WireGuard</string> <string name="wireguard" translatable="false">WireGuard</string>
<string name="error_file_format">Invalid tunnel config format</string> <string name="error_file_format">Invalid tunnel config format</string>
<string name="restart_at_boot">Restart on boot</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> </resources>
+16
View File
@@ -6,4 +6,20 @@ plugins {
alias(libs.plugins.ksp) apply false alias(libs.plugins.ksp) apply false
alias(libs.plugins.androidLibrary) apply false alias(libs.plugins.androidLibrary) apply false
alias(libs.plugins.compose.compiler) 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 RELEASE = "release"
const val NIGHTLY = "nightly" const val NIGHTLY = "nightly"
const val PRERELEASE = "prerelease"
const val DEBUG = "debug" const val DEBUG = "debug"
const val TYPE = "type" const val TYPE = "type"
const val NIGHTLY_CODE = 42 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.io.File
import java.util.Properties import java.util.Properties
private fun getCurrentFlavor(gradle: Gradle): String { fun Project.getCurrentFlavor(): String {
val taskRequestsStr = gradle.startParameter.taskRequests.toString() val taskRequestsStr = gradle.startParameter.taskRequests.toString()
val pattern: java.util.regex.Pattern = val pattern: java.util.regex.Pattern =
if (taskRequestsStr.contains("assemble")) { if (taskRequestsStr.contains(":app:assemble")) {
java.util.regex.Pattern.compile("assemble(\\w+)(Release|Debug)") java.util.regex.Pattern.compile(":app:assemble(\\w+)(Release|Debug)")
} else { } 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) val matcher = pattern.matcher(taskRequestsStr)
@@ -23,8 +23,15 @@ private fun getCurrentFlavor(gradle: Gradle): String {
return flavor 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? { fun getLocalProperty(key: String, file: String = "local.properties"): String? {
val properties = java.util.Properties() val properties = Properties()
val localProperties = File(file) val localProperties = File(file)
if (localProperties.isFile) { if (localProperties.isFile) {
java.io.InputStreamReader(java.io.FileInputStream(localProperties), Charsets.UTF_8) 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) return properties.getProperty(key)
} }
fun Project.isGeneralFlavor(gradle: Gradle): Boolean {
return getCurrentFlavor(gradle) == "general"
}
fun Project.getSigningProperties(): Properties { fun Project.getSigningProperties(): Properties {
return Properties().apply { 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" amneziawgAndroid = "1.2.0"
androidx-junit = "1.2.1" androidx-junit = "1.2.1"
appcompat = "1.7.0" appcompat = "1.7.0"
biometricKtx = "1.4.0-alpha01" biometricKtx = "1.2.0-alpha05"
coreGoogleShortcuts = "1.1.0" coreGoogleShortcuts = "1.1.0"
coreKtx = "1.13.1" coreKtx = "1.13.1"
datastorePreferences = "1.1.1" datastorePreferences = "1.1.1"
@@ -24,7 +24,7 @@ timber = "5.0.1"
tunnel = "1.0.20230706" tunnel = "1.0.20230706"
androidGradlePlugin = "8.5.1" androidGradlePlugin = "8.5.1"
kotlin = "2.0.0" kotlin = "2.0.0"
ksp = "2.0.0-1.0.23" ksp = "2.0.0-1.0.24"
composeBom = "2024.06.00" composeBom = "2024.06.00"
compose = "1.6.8" compose = "1.6.8"
zxingAndroidEmbedded = "4.3.0" zxingAndroidEmbedded = "4.3.0"
@@ -33,6 +33,7 @@ gradlePlugins-grgit="5.2.2"
#plugins #plugins
material = "1.12.0" material = "1.12.0"
gradlePlugins-ktlint="12.1.1"
[libraries] [libraries]
@@ -101,4 +102,5 @@ ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
kotlinxSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } kotlinxSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
androidLibrary = { id = "com.android.library", version.ref = "androidGradlePlugin" } androidLibrary = { id = "com.android.library", version.ref = "androidGradlePlugin" }
compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } 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" } grgit = { id = "org.ajoberstar.grgit.service", version.ref = "gradlePlugins-grgit" }
+8 -4
View File
@@ -5,10 +5,10 @@ plugins {
android { android {
namespace = "com.zaneschepke.logcatter" namespace = "com.zaneschepke.logcatter"
compileSdk = 34 compileSdk = Constants.TARGET_SDK
defaultConfig { defaultConfig {
minSdk = 26 minSdk = Constants.MIN_SDK
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro") consumerProguardFiles("consumer-rules.pro")
@@ -23,8 +23,12 @@ android {
) )
} }
create("nightly") { create(Constants.PRERELEASE) {
initWith(getByName("release")) initWith(getByName(Constants.RELEASE))
}
create(Constants.NIGHTLY) {
initWith(getByName(Constants.RELEASE))
} }
} }
compileOptions { compileOptions {
@@ -6,8 +6,10 @@ import java.io.File
interface LocalLogCollector { interface LocalLogCollector {
fun start(onLogMessage: ((message: LogMessage) -> Unit)? = null) fun start(onLogMessage: ((message: LogMessage) -> Unit)? = null)
fun stop() fun stop()
suspend fun getLogFile(): Result<File> suspend fun getLogFile(): Result<File>
val bufferedLogs: Flow<LogMessage> 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 { override fun color(): Long {
return 0xFF000000 return 0xFF000000
} }
}; }, ;
abstract fun color(): Long abstract fun color(): Long
+3 -1
View File
@@ -24,7 +24,9 @@ fun getLocalProperty(key: String, file: String = "local.properties"): String? {
.use { reader -> .use { reader ->
properties.load(reader) properties.load(reader)
} }
} else return null } else {
return null
}
return properties.getProperty(key) return properties.getProperty(key)
} }