mirror of
https://github.com/wgtunnel/android.git
synced 2026-07-03 14:07:49 +02:00
Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 03c9831e88 | |||
| ffeb089aa7 | |||
| 3838c32ddf | |||
| 0c1cb40add | |||
| bfb8d59827 | |||
| 19961ca343 | |||
| 6c007a8ca8 | |||
| 8e6a9bb309 | |||
| 594834a908 | |||
| a5e9aa83b8 | |||
| 5a77661fb3 | |||
| ee5d3ea6a9 | |||
| f6da0fe31b | |||
| 80a02382e1 | |||
| b9a8400453 | |||
| 3a17d2855b | |||
| 086b48c79d | |||
| 1f561fbf38 | |||
| 45e63e9910 | |||
| 66e89c83e2 | |||
| 470fa0191b | |||
| 7c15943a81 | |||
| 05adf7539f | |||
| a9a49e3421 | |||
| 4dd8241fa1 |
+22
-10
@@ -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
|
||||||
@@ -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,7 +44,9 @@ jobs:
|
|||||||
KEY_STORE_FILE: 'android_keystore.jks'
|
KEY_STORE_FILE: 'android_keystore.jks'
|
||||||
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
|
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
|
||||||
GH_USER: ${{ secrets.GH_USER }}
|
GH_USER: ${{ secrets.GH_USER }}
|
||||||
|
# GH needed for gh cli
|
||||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||||
|
GH_REPO: ${{ github.repository }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
@@ -84,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' }}
|
||||||
@@ -94,18 +99,20 @@ 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
|
||||||
|
|
||||||
# Save the APK after the Build job is complete to publish it as a Github release in the next job
|
# Save the APK after the Build job is complete to publish it as a Github release in the next job
|
||||||
- name: Upload APK
|
- name: Upload APK
|
||||||
uses: actions/upload-artifact@v4.3.4
|
uses: actions/upload-artifact@v4.3.6
|
||||||
with:
|
with:
|
||||||
name: wgtunnel
|
name: wgtunnel
|
||||||
path: ${{ env.APK_PATH }}
|
path: ${{ env.APK_PATH }}
|
||||||
@@ -123,31 +130,31 @@ jobs:
|
|||||||
repository: zaneschepke/fdroid
|
repository: zaneschepke/fdroid
|
||||||
event-type: fdroid-update
|
event-type: fdroid-update
|
||||||
|
|
||||||
|
# Setup TAG_NAME, which is used as a general "name"
|
||||||
|
- if: github.event_name == 'workflow_dispatch'
|
||||||
|
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
|
||||||
|
- if: github.event_name == 'schedule'
|
||||||
|
run: echo "TAG_NAME=nightly" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Set version release notes
|
- name: Set version release notes
|
||||||
if: ${{ inputs.release_type == 'release' || inputs.release_type == 'prerelease' }}
|
if: ${{ inputs.release_type == 'release' }}
|
||||||
run: |
|
run: |
|
||||||
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
|
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
|
||||||
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
|
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
|
||||||
echo "$RELEASE_NOTES" >> $GITHUB_ENV
|
echo "$RELEASE_NOTES" >> $GITHUB_ENV
|
||||||
echo "EOF" >> $GITHUB_ENV
|
echo "EOF" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: On nightly release
|
- name: On nightly release notes
|
||||||
if: ${{ contains(env.TAG_NAME, 'nightly') }}
|
if: ${{ contains(env.TAG_NAME, 'nightly') }}
|
||||||
run: |
|
run: |
|
||||||
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $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
|
||||||
|
|
||||||
# Setup TAG_NAME, which is used as a general "name"
|
- name: On prerelease release notes
|
||||||
- if: github.event_name == 'workflow_dispatch'
|
if: ${{ inputs.release_type == 'prerelease' }}
|
||||||
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
|
|
||||||
- if: github.event_name == 'schedule'
|
|
||||||
run: echo "TAG_NAME=nightly-android" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: On nightly release
|
|
||||||
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=Testing version of app for specific feature." >> $GITHUB_ENV
|
||||||
gh release delete nightly-android --yes || true
|
gh release delete ${{ github.event.inputs.tag_name }} --yes || true
|
||||||
|
|
||||||
- name: Get checksum
|
- name: Get checksum
|
||||||
id: checksum
|
id: checksum
|
||||||
@@ -198,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:
|
||||||
|
|||||||
@@ -71,3 +71,4 @@ app/release/output.json
|
|||||||
.idea/codeStyles/
|
.idea/codeStyles/
|
||||||
# where we keep our signing secrets locally
|
# where we keep our signing secrets locally
|
||||||
app/signing.properties
|
app/signing.properties
|
||||||
|
/.kotlin/
|
||||||
|
|||||||
+39
-21
@@ -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 = versionCode()
|
versionCode = determineVersionCode()
|
||||||
versionName = versionName()
|
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
|
||||||
@@ -67,12 +56,28 @@ android {
|
|||||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
"proguard-rules.pro",
|
"proguard-rules.pro",
|
||||||
)
|
)
|
||||||
signingConfig = signingConfigs.getByName(signingConfigName())
|
signingConfig = signingConfigs.getByName(Constants.RELEASE)
|
||||||
}
|
}
|
||||||
debug { isDebuggable = true }
|
debug { isDebuggable = true }
|
||||||
|
|
||||||
create("nightly") {
|
create(Constants.PRERELEASE) {
|
||||||
initWith(getByName("release"))
|
initWith(buildTypes.getByName(Constants.RELEASE))
|
||||||
|
}
|
||||||
|
|
||||||
|
create(Constants.NIGHTLY) {
|
||||||
|
initWith(buildTypes.getByName(Constants.RELEASE))
|
||||||
|
}
|
||||||
|
|
||||||
|
applicationVariants.all {
|
||||||
|
val variant = this
|
||||||
|
variant.outputs
|
||||||
|
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
|
||||||
|
.forEach { output ->
|
||||||
|
val outputFileName =
|
||||||
|
"${Constants.APP_NAME}-${variant.flavorName}-" +
|
||||||
|
"${variant.buildType.name}-${variant.versionName}.apk"
|
||||||
|
output.outputFileName = outputFileName
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
flavorDimensions.add(Constants.TYPE)
|
flavorDimensions.add(Constants.TYPE)
|
||||||
@@ -129,6 +134,7 @@ dependencies {
|
|||||||
debugImplementation(libs.androidx.compose.manifest)
|
debugImplementation(libs.androidx.compose.manifest)
|
||||||
|
|
||||||
// get tunnel lib from github packages or mavenLocal
|
// get tunnel lib from github packages or mavenLocal
|
||||||
|
// implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.aar"))))
|
||||||
implementation(libs.tunnel)
|
implementation(libs.tunnel)
|
||||||
implementation(libs.amneziawg.android)
|
implementation(libs.amneziawg.android)
|
||||||
coreLibraryDesugaring(libs.desugar.jdk.libs)
|
coreLibraryDesugaring(libs.desugar.jdk.libs)
|
||||||
@@ -136,7 +142,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)
|
||||||
@@ -183,10 +188,23 @@ dependencies {
|
|||||||
implementation(libs.androidx.core.splashscreen)
|
implementation(libs.androidx.core.splashscreen)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun versionCode() : Int {
|
fun determineVersionCode(): Int {
|
||||||
return if(!isNightlyBuild()) Constants.VERSION_CODE else 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 versionName() : String {
|
fun determineVersionName(): String {
|
||||||
return if(!isNightlyBuild()) Constants.VERSION_NAME else 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
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
{
|
||||||
|
"formatVersion": 1,
|
||||||
|
"database": {
|
||||||
|
"version": 9,
|
||||||
|
"identityHash": "e2c91dbf1885a9da592d3f54f1e08302",
|
||||||
|
"entities": [
|
||||||
|
{
|
||||||
|
"tableName": "Settings",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_auto_tunnel_paused` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false)",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isAutoTunnelEnabled",
|
||||||
|
"columnName": "is_tunnel_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isTunnelOnMobileDataEnabled",
|
||||||
|
"columnName": "is_tunnel_on_mobile_data_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "trustedNetworkSSIDs",
|
||||||
|
"columnName": "trusted_network_ssids",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isAlwaysOnVpnEnabled",
|
||||||
|
"columnName": "is_always_on_vpn_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isTunnelOnEthernetEnabled",
|
||||||
|
"columnName": "is_tunnel_on_ethernet_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isShortcutsEnabled",
|
||||||
|
"columnName": "is_shortcuts_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isTunnelOnWifiEnabled",
|
||||||
|
"columnName": "is_tunnel_on_wifi_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isKernelEnabled",
|
||||||
|
"columnName": "is_kernel_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isRestoreOnBootEnabled",
|
||||||
|
"columnName": "is_restore_on_boot_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isMultiTunnelEnabled",
|
||||||
|
"columnName": "is_multi_tunnel_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isAutoTunnelPaused",
|
||||||
|
"columnName": "is_auto_tunnel_paused",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isPingEnabled",
|
||||||
|
"columnName": "is_ping_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isAmneziaEnabled",
|
||||||
|
"columnName": "is_amnezia_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": true,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [],
|
||||||
|
"foreignKeys": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "TunnelConfig",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '', `is_Active` INTEGER NOT NULL DEFAULT false)",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "name",
|
||||||
|
"columnName": "name",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "wgQuick",
|
||||||
|
"columnName": "wg_quick",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "tunnelNetworks",
|
||||||
|
"columnName": "tunnel_networks",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "''"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isMobileDataTunnel",
|
||||||
|
"columnName": "is_mobile_data_tunnel",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isPrimaryTunnel",
|
||||||
|
"columnName": "is_primary_tunnel",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "amQuick",
|
||||||
|
"columnName": "am_quick",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "''"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isActive",
|
||||||
|
"columnName": "is_Active",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": true,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_TunnelConfig_name",
|
||||||
|
"unique": true,
|
||||||
|
"columnNames": [
|
||||||
|
"name"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"foreignKeys": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"views": [],
|
||||||
|
"setupQueries": [
|
||||||
|
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||||
|
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'e2c91dbf1885a9da592d3f54f1e08302')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,6 +31,12 @@
|
|||||||
<!--start service on boot permission-->
|
<!--start service on boot permission-->
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
<!--android tv support-->
|
<!--android tv support-->
|
||||||
|
|
||||||
|
<permission
|
||||||
|
android:name="${applicationId}.permission.CONTROL_TUNNELS"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:protectionLevel="dangerous" />
|
||||||
|
|
||||||
<uses-feature
|
<uses-feature
|
||||||
android:name="android.software.leanback"
|
android:name="android.software.leanback"
|
||||||
android:required="false" />
|
android:required="false" />
|
||||||
@@ -71,7 +77,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 +87,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
|
||||||
@@ -137,7 +144,7 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</service>
|
</service>
|
||||||
<service
|
<service
|
||||||
android:name=".service.foreground.WireGuardTunnelService"
|
android:name=".service.tunnel.AlwaysOnVpnService"
|
||||||
android:enabled="true"
|
android:enabled="true"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:foregroundServiceType="systemExempted"
|
android:foregroundServiceType="systemExempted"
|
||||||
@@ -152,7 +159,7 @@
|
|||||||
android:value="true" />
|
android:value="true" />
|
||||||
</service>
|
</service>
|
||||||
<service
|
<service
|
||||||
android:name=".service.foreground.WireGuardConnectivityWatcherService"
|
android:name=".service.foreground.AutoTunnelService"
|
||||||
android:enabled="true"
|
android:enabled="true"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:foregroundServiceType="systemExempted"
|
android:foregroundServiceType="systemExempted"
|
||||||
@@ -174,7 +181,16 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".receiver.NotificationActionReceiver"
|
android:name=".receiver.BackgroundActionReceiver"
|
||||||
android:exported="false" />
|
android:enabled="true"
|
||||||
|
android:exported="false"/>
|
||||||
|
<receiver
|
||||||
|
android:name=".receiver.KernelReceiver"
|
||||||
|
android:exported="false"
|
||||||
|
android:permission="${applicationId}.permission.CONTROL_TUNNELS">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.wireguard.android.action.REFRESH_TUNNEL_STATES" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
</application>
|
</application>
|
||||||
</manifest>
|
</manifest>
|
||||||
@@ -1,20 +1,22 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel
|
package com.zaneschepke.wireguardautotunnel
|
||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
import android.content.ComponentName
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.StrictMode
|
import android.os.StrictMode
|
||||||
import android.os.StrictMode.ThreadPolicy
|
import android.os.StrictMode.ThreadPolicy
|
||||||
import android.service.quicksettings.TileService
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tile.AutoTunnelControlTile
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tile.TunnelControlTile
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
|
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
|
||||||
import dagger.hilt.android.HiltAndroidApp
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
@HiltAndroidApp
|
@HiltAndroidApp
|
||||||
class WireGuardAutoTunnel : Application() {
|
class WireGuardAutoTunnel : Application() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
instance = this
|
instance = this
|
||||||
@@ -28,30 +30,13 @@ 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
|
||||||
|
|
||||||
fun isRunningOnAndroidTv(): Boolean {
|
|
||||||
return instance.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun requestTunnelTileServiceStateUpdate() {
|
|
||||||
TileService.requestListeningState(
|
|
||||||
instance,
|
|
||||||
ComponentName(instance, TunnelControlTile::class.java),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun requestAutoTunnelTileServiceUpdate() {
|
|
||||||
TileService.requestListeningState(
|
|
||||||
instance,
|
|
||||||
ComponentName(instance, AutoTunnelControlTile::class.java),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|||||||
|
|
||||||
@Database(
|
@Database(
|
||||||
entities = [Settings::class, TunnelConfig::class],
|
entities = [Settings::class, TunnelConfig::class],
|
||||||
version = 8,
|
version = 9,
|
||||||
autoMigrations =
|
autoMigrations =
|
||||||
[
|
[
|
||||||
AutoMigration(from = 1, to = 2),
|
AutoMigration(from = 1, to = 2),
|
||||||
@@ -34,6 +34,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|||||||
spec = RemoveLegacySettingColumnsMigration::class,
|
spec = RemoveLegacySettingColumnsMigration::class,
|
||||||
),
|
),
|
||||||
AutoMigration(7, 8),
|
AutoMigration(7, 8),
|
||||||
|
AutoMigration(8, 9),
|
||||||
],
|
],
|
||||||
exportSchema = true,
|
exportSchema = true,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import androidx.room.Insert
|
|||||||
import androidx.room.OnConflictStrategy
|
import androidx.room.OnConflictStrategy
|
||||||
import androidx.room.Query
|
import androidx.room.Query
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
@Dao
|
@Dao
|
||||||
@@ -23,6 +23,9 @@ interface TunnelConfigDao {
|
|||||||
@Query("SELECT * FROM TunnelConfig WHERE name=:name")
|
@Query("SELECT * FROM TunnelConfig WHERE name=:name")
|
||||||
suspend fun getByName(name: String): TunnelConfig?
|
suspend fun getByName(name: String): TunnelConfig?
|
||||||
|
|
||||||
|
@Query("SELECT * FROM TunnelConfig WHERE is_Active=1")
|
||||||
|
suspend fun getActive(): TunnelConfigs
|
||||||
|
|
||||||
@Query("SELECT * FROM TunnelConfig")
|
@Query("SELECT * FROM TunnelConfig")
|
||||||
suspend fun getAll(): TunnelConfigs
|
suspend fun getAll(): TunnelConfigs
|
||||||
|
|
||||||
|
|||||||
+2
-6
@@ -19,14 +19,12 @@ 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")
|
||||||
val BATTERY_OPTIMIZE_DISABLE_SHOWN = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
val BATTERY_OPTIMIZE_DISABLE_SHOWN = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
||||||
val TUNNEL_RUNNING_FROM_MANUAL_START =
|
val LAST_ACTIVE_TUNNEL = intPreferencesKey("LAST_ACTIVE_TUNNEL")
|
||||||
booleanPreferencesKey("TUNNEL_RUNNING_FROM_MANUAL_START")
|
|
||||||
val ACTIVE_TUNNEL = intPreferencesKey("ACTIVE_TUNNEL")
|
|
||||||
val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
|
val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
|
||||||
val IS_PIN_LOCK_ENABLED = booleanPreferencesKey("PIN_LOCK_ENABLED")
|
val IS_PIN_LOCK_ENABLED = booleanPreferencesKey("PIN_LOCK_ENABLED")
|
||||||
}
|
}
|
||||||
@@ -60,7 +58,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 +71,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()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,12 @@ package com.zaneschepke.wireguardautotunnel.data.domain
|
|||||||
data class GeneralState(
|
data class GeneralState(
|
||||||
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
||||||
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 isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
|
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
|
||||||
val activeTunnelId: Int? = null
|
val lastActiveTunnelId: Int? = null,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
|
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
|
||||||
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
|
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
|
||||||
const val TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT = false
|
|
||||||
const val PIN_LOCK_ENABLED_DEFAULT = false
|
const val PIN_LOCK_ENABLED_DEFAULT = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,8 +32,17 @@ data class TunnelConfig(
|
|||||||
defaultValue = "",
|
defaultValue = "",
|
||||||
)
|
)
|
||||||
val amQuick: String = AM_QUICK_DEFAULT,
|
val amQuick: String = AM_QUICK_DEFAULT,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "is_Active",
|
||||||
|
defaultValue = "false",
|
||||||
|
)
|
||||||
|
val isActive: Boolean = false,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
|
fun findDefault(tunnels: List<TunnelConfig>): TunnelConfig? {
|
||||||
|
return tunnels.find { it.isPrimaryTunnel } ?: tunnels.firstOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
fun configFromWgQuick(wgQuick: String): Config {
|
fun configFromWgQuick(wgQuick: String): Config {
|
||||||
val inputStream: InputStream = wgQuick.byteInputStream()
|
val inputStream: InputStream = wgQuick.byteInputStream()
|
||||||
return inputStream.bufferedReader(Charsets.UTF_8).use {
|
return inputStream.bufferedReader(Charsets.UTF_8).use {
|
||||||
|
|||||||
+1
-2
@@ -4,9 +4,8 @@ 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 toggleWatcherServicePause()
|
suspend fun getStartTunnelConfig(): TunnelConfig?
|
||||||
|
|
||||||
val settings: SettingsRepository
|
val settings: SettingsRepository
|
||||||
val tunnels: TunnelConfigRepository
|
val tunnels: TunnelConfigRepository
|
||||||
|
|||||||
+6
-18
@@ -3,32 +3,20 @@ 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()
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getStartTunnelConfig(): TunnelConfig? {
|
override suspend fun getStartTunnelConfig(): TunnelConfig? {
|
||||||
return if (appState.isTunnelRunningFromManualStart()) {
|
return appState.getLastActiveTunnelId()?.let {
|
||||||
appState.getActiveTunnelId()?.let {
|
|
||||||
tunnels.getById(it)
|
tunnels.getById(it)
|
||||||
}
|
} ?: getPrimaryOrFirstTunnel()
|
||||||
} else null
|
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun toggleWatcherServicePause() {
|
|
||||||
val settings = settings.getSettings()
|
|
||||||
if (settings.isAutoTunnelEnabled) {
|
|
||||||
val pauseAutoTunnel = !settings.isAutoTunnelPaused
|
|
||||||
this.settings.save(
|
|
||||||
settings.copy(
|
|
||||||
isAutoTunnelPaused = pauseAutoTunnel,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-6
@@ -5,25 +5,24 @@ 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 getLastActiveTunnelId(): Int?
|
||||||
suspend fun setTunnelRunningFromManualStart(id: Int)
|
|
||||||
|
|
||||||
suspend fun setManualStop()
|
suspend fun setLastActiveTunnelId(id: Int)
|
||||||
|
|
||||||
suspend fun getActiveTunnelId(): Int?
|
|
||||||
|
|
||||||
suspend fun getCurrentSsid(): String?
|
suspend fun getCurrentSsid(): String?
|
||||||
|
|
||||||
suspend fun setCurrentSsid(ssid: String)
|
suspend fun setCurrentSsid(ssid: String)
|
||||||
|
|
||||||
val generalStateFlow: Flow<GeneralState>
|
val generalStateFlow: Flow<GeneralState>
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-37
@@ -2,71 +2,65 @@ package com.zaneschepke.wireguardautotunnel.data.repository
|
|||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
|
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
|
||||||
class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager) :
|
class DataStoreAppStateRepository(
|
||||||
|
private val dataStoreManager: DataStoreManager,
|
||||||
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
|
) :
|
||||||
AppStateRepository {
|
AppStateRepository {
|
||||||
override suspend fun isLocationDisclosureShown(): Boolean {
|
override suspend fun isLocationDisclosureShown(): Boolean {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN)
|
return withContext(ioDispatcher) {
|
||||||
|
dataStoreManager.getFromStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN)
|
||||||
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT
|
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun setLocationDisclosureShown(shown: Boolean) {
|
override suspend fun setLocationDisclosureShown(shown: Boolean) {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown)
|
withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun isPinLockEnabled(): Boolean {
|
override suspend fun isPinLockEnabled(): Boolean {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.IS_PIN_LOCK_ENABLED)
|
return withContext(ioDispatcher) {
|
||||||
|
dataStoreManager.getFromStore(DataStoreManager.IS_PIN_LOCK_ENABLED)
|
||||||
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT
|
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun setPinLockEnabled(enabled: Boolean) {
|
override suspend fun setPinLockEnabled(enabled: Boolean) {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.IS_PIN_LOCK_ENABLED, enabled)
|
withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.IS_PIN_LOCK_ENABLED, enabled) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun isBatteryOptimizationDisableShown(): Boolean {
|
override suspend fun isBatteryOptimizationDisableShown(): Boolean {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN)
|
return withContext(ioDispatcher) {
|
||||||
|
dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN)
|
||||||
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
|
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun setBatteryOptimizationDisableShown(shown: Boolean) {
|
override suspend fun setBatteryOptimizationDisableShown(shown: Boolean) {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN, shown)
|
withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN, shown) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun isTunnelRunningFromManualStart(): Boolean {
|
override suspend fun getLastActiveTunnelId(): Int? {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START)
|
return withContext(ioDispatcher) { dataStoreManager.getFromStore(DataStoreManager.LAST_ACTIVE_TUNNEL) }
|
||||||
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun setTunnelRunningFromManualStart(id: Int) {
|
override suspend fun setLastActiveTunnelId(id: Int) {
|
||||||
setTunnelRunningFromManualStart(true)
|
return withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.LAST_ACTIVE_TUNNEL, id) }
|
||||||
setActiveTunnelId(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun setManualStop() {
|
|
||||||
setTunnelRunningFromManualStart(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun setTunnelRunningFromManualStart(running: Boolean) {
|
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START, running)
|
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun getActiveTunnelId(): Int? {
|
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.ACTIVE_TUNNEL)
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun setActiveTunnelId(id: Int) {
|
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.ACTIVE_TUNNEL, id)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getCurrentSsid(): String? {
|
override suspend fun getCurrentSsid(): String? {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.CURRENT_SSID)
|
return withContext(ioDispatcher) { dataStoreManager.getFromStore(DataStoreManager.CURRENT_SSID) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun setCurrentSsid(ssid: String) {
|
override suspend fun setCurrentSsid(ssid: String) {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.CURRENT_SSID, ssid)
|
withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.CURRENT_SSID, ssid) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override val generalStateFlow: Flow<GeneralState> =
|
override val generalStateFlow: Flow<GeneralState> =
|
||||||
@@ -74,14 +68,16 @@ 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]
|
isPinLockEnabled =
|
||||||
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
|
pref[DataStoreManager.IS_PIN_LOCK_ENABLED]
|
||||||
isPinLockEnabled = pref[DataStoreManager.IS_PIN_LOCK_ENABLED]
|
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT,
|
||||||
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
|
lastActiveTunnelId = pref[DataStoreManager.LAST_ACTIVE_TUNNEL],
|
||||||
)
|
)
|
||||||
} catch (e: IllegalArgumentException) {
|
} catch (e: IllegalArgumentException) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
|
|||||||
+10
-4
@@ -2,23 +2,29 @@ package com.zaneschepke.wireguardautotunnel.data.repository
|
|||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.SettingsDao
|
import com.zaneschepke.wireguardautotunnel.data.SettingsDao
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
class RoomSettingsRepository(private val settingsDoa: SettingsDao) : SettingsRepository {
|
class RoomSettingsRepository(private val settingsDoa: SettingsDao, @IoDispatcher private val ioDispatcher: CoroutineDispatcher) : SettingsRepository {
|
||||||
|
|
||||||
override suspend fun save(settings: Settings) {
|
override suspend fun save(settings: Settings) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
settingsDoa.save(settings)
|
settingsDoa.save(settings)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun getSettingsFlow(): Flow<Settings> {
|
override fun getSettingsFlow(): Flow<Settings> {
|
||||||
return settingsDoa.getSettingsFlow()
|
return settingsDoa.getSettingsFlow()
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getSettings(): Settings {
|
override suspend fun getSettings(): Settings {
|
||||||
return settingsDoa.getAll().firstOrNull() ?: Settings()
|
return withContext(ioDispatcher) {
|
||||||
|
settingsDoa.getAll().firstOrNull() ?: Settings()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getAll(): List<Settings> {
|
override suspend fun getAll(): List<Settings> {
|
||||||
return settingsDoa.getAll()
|
return withContext(ioDispatcher) { settingsDoa.getAll() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-10
@@ -1,25 +1,38 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.data.repository
|
package com.zaneschepke.wireguardautotunnel.data.repository
|
||||||
|
|
||||||
|
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||||
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
|
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
|
class RoomTunnelConfigRepository(
|
||||||
|
private val tunnelConfigDao: TunnelConfigDao,
|
||||||
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
|
) :
|
||||||
TunnelConfigRepository {
|
TunnelConfigRepository {
|
||||||
override fun getTunnelConfigsFlow(): Flow<TunnelConfigs> {
|
override fun getTunnelConfigsFlow(): Flow<TunnelConfigs> {
|
||||||
return tunnelConfigDao.getAllFlow()
|
return tunnelConfigDao.getAllFlow()
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getAll(): TunnelConfigs {
|
override suspend fun getAll(): TunnelConfigs {
|
||||||
return tunnelConfigDao.getAll()
|
return withContext(ioDispatcher) { tunnelConfigDao.getAll() }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun save(tunnelConfig: TunnelConfig) {
|
override suspend fun save(tunnelConfig: TunnelConfig) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
tunnelConfigDao.save(tunnelConfig)
|
tunnelConfigDao.save(tunnelConfig)
|
||||||
|
}.also {
|
||||||
|
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?) {
|
override suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
tunnelConfigDao.resetPrimaryTunnel()
|
tunnelConfigDao.resetPrimaryTunnel()
|
||||||
tunnelConfig?.let {
|
tunnelConfig?.let {
|
||||||
save(
|
save(
|
||||||
@@ -28,10 +41,11 @@ class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
|
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
tunnelConfigDao.resetMobileDataTunnel()
|
tunnelConfigDao.resetMobileDataTunnel()
|
||||||
tunnelConfig?.let {
|
tunnelConfig?.let {
|
||||||
save(
|
save(
|
||||||
@@ -41,32 +55,43 @@ class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun delete(tunnelConfig: TunnelConfig) {
|
override suspend fun delete(tunnelConfig: TunnelConfig) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
tunnelConfigDao.delete(tunnelConfig)
|
tunnelConfigDao.delete(tunnelConfig)
|
||||||
|
}.also {
|
||||||
|
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getById(id: Int): TunnelConfig? {
|
override suspend fun getById(id: Int): TunnelConfig? {
|
||||||
return tunnelConfigDao.getById(id.toLong())
|
return withContext(ioDispatcher) { tunnelConfigDao.getById(id.toLong()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getActive(): TunnelConfigs {
|
||||||
|
return withContext(ioDispatcher) {
|
||||||
|
tunnelConfigDao.getActive()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun count(): Int {
|
override suspend fun count(): Int {
|
||||||
return tunnelConfigDao.count().toInt()
|
return withContext(ioDispatcher) { tunnelConfigDao.count().toInt() }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findByTunnelName(name: String): TunnelConfig? {
|
override suspend fun findByTunnelName(name: String): TunnelConfig? {
|
||||||
return tunnelConfigDao.getByName(name)
|
return withContext(ioDispatcher) { tunnelConfigDao.getByName(name) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findByTunnelNetworksName(name: String): TunnelConfigs {
|
override suspend fun findByTunnelNetworksName(name: String): TunnelConfigs {
|
||||||
return tunnelConfigDao.findByTunnelNetworkName(name)
|
return withContext(ioDispatcher) { tunnelConfigDao.findByTunnelNetworkName(name) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findByMobileDataTunnel(): TunnelConfigs {
|
override suspend fun findByMobileDataTunnel(): TunnelConfigs {
|
||||||
return tunnelConfigDao.findByMobileDataTunnel()
|
return withContext(ioDispatcher) { tunnelConfigDao.findByMobileDataTunnel() }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findPrimary(): TunnelConfigs {
|
override suspend fun findPrimary(): TunnelConfigs {
|
||||||
return tunnelConfigDao.findByPrimary()
|
return withContext(ioDispatcher) { tunnelConfigDao.findByPrimary() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-2
@@ -1,11 +1,10 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.data.repository
|
package com.zaneschepke.wireguardautotunnel.data.repository
|
||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
|
import com.zaneschepke.wireguardautotunnel.util.extensions.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
|
||||||
@@ -20,6 +19,8 @@ interface TunnelConfigRepository {
|
|||||||
|
|
||||||
suspend fun getById(id: Int): TunnelConfig?
|
suspend fun getById(id: Int): TunnelConfig?
|
||||||
|
|
||||||
|
suspend fun getActive(): TunnelConfigs
|
||||||
|
|
||||||
suspend fun count(): Int
|
suspend fun count(): Int
|
||||||
|
|
||||||
suspend fun findByTunnelName(name: String): TunnelConfig?
|
suspend fun findByTunnelName(name: String): TunnelConfig?
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,29 +54,26 @@ class RepositoryModule {
|
|||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun provideTunnelConfigRepository(tunnelConfigDao: TunnelConfigDao): TunnelConfigRepository {
|
fun provideTunnelConfigRepository(tunnelConfigDao: TunnelConfigDao, @IoDispatcher ioDispatcher: CoroutineDispatcher): TunnelConfigRepository {
|
||||||
return RoomTunnelConfigRepository(tunnelConfigDao)
|
return RoomTunnelConfigRepository(tunnelConfigDao, ioDispatcher)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun provideSettingsRepository(settingsDao: SettingsDao): SettingsRepository {
|
fun provideSettingsRepository(settingsDao: SettingsDao, @IoDispatcher ioDispatcher: CoroutineDispatcher): SettingsRepository {
|
||||||
return RoomSettingsRepository(settingsDao)
|
return RoomSettingsRepository(settingsDao, ioDispatcher)
|
||||||
}
|
}
|
||||||
|
|
||||||
@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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideGeneralStateRepository(dataStoreManager: DataStoreManager): AppStateRepository {
|
fun provideGeneralStateRepository(dataStoreManager: DataStoreManager, @IoDispatcher ioDispatcher: CoroutineDispatcher): AppStateRepository {
|
||||||
return DataStoreAppStateRepository(dataStoreManager)
|
return DataStoreAppStateRepository(dataStoreManager, ioDispatcher)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@@ -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>
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,13 @@ package com.zaneschepke.wireguardautotunnel.module
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.wireguard.android.backend.Backend
|
import com.wireguard.android.backend.Backend
|
||||||
import com.wireguard.android.backend.GoBackend
|
import com.wireguard.android.backend.GoBackend
|
||||||
|
import com.wireguard.android.backend.RootTunnelActionHandler
|
||||||
import com.wireguard.android.backend.WgQuickBackend
|
import com.wireguard.android.backend.WgQuickBackend
|
||||||
import com.wireguard.android.util.RootShell
|
import com.wireguard.android.util.RootShell
|
||||||
import com.wireguard.android.util.ToolsInstaller
|
import com.wireguard.android.util.ToolsInstaller
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.WireGuardTunnel
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.WireGuardTunnel
|
||||||
import dagger.Module
|
import dagger.Module
|
||||||
import dagger.Provides
|
import dagger.Provides
|
||||||
@@ -29,24 +30,30 @@ class TunnelModule {
|
|||||||
return RootShell(context)
|
return RootShell(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideRootShellAm(@ApplicationContext context: Context): org.amnezia.awg.util.RootShell {
|
||||||
|
return org.amnezia.awg.util.RootShell(context)
|
||||||
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
@Userspace
|
@Userspace
|
||||||
fun provideUserspaceBackend(@ApplicationContext context: Context): Backend {
|
fun provideUserspaceBackend(@ApplicationContext context: Context, rootShell: RootShell): Backend {
|
||||||
return GoBackend(context)
|
return GoBackend(context, RootTunnelActionHandler(rootShell))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
@Kernel
|
@Kernel
|
||||||
fun provideKernelBackend(@ApplicationContext context: Context, rootShell: RootShell): Backend {
|
fun provideKernelBackend(@ApplicationContext context: Context, rootShell: RootShell): Backend {
|
||||||
return WgQuickBackend(context, rootShell, ToolsInstaller(context, rootShell))
|
return WgQuickBackend(context, rootShell, ToolsInstaller(context, rootShell), RootTunnelActionHandler(rootShell))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideAmneziaBackend(@ApplicationContext context: Context): org.amnezia.awg.backend.Backend {
|
fun provideAmneziaBackend(@ApplicationContext context: Context, rootShell: org.amnezia.awg.util.RootShell): org.amnezia.awg.backend.Backend {
|
||||||
return org.amnezia.awg.backend.GoBackend(context)
|
return org.amnezia.awg.backend.GoBackend(context, org.amnezia.awg.backend.RootTunnelActionHandler(rootShell))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@@ -57,8 +64,8 @@ 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 {
|
): TunnelService {
|
||||||
return WireGuardTunnel(
|
return WireGuardTunnel(
|
||||||
amneziaBackend,
|
amneziaBackend,
|
||||||
userspaceBackend,
|
userspaceBackend,
|
||||||
@@ -71,10 +78,7 @@ class TunnelModule {
|
|||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideServiceManager(
|
fun provideServiceManager(): ServiceManager {
|
||||||
appDataRepository: AppDataRepository,
|
return ServiceManager()
|
||||||
@IoDispatcher ioDispatcher: CoroutineDispatcher
|
|
||||||
): ServiceManager {
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.receiver
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.TunnelConfigRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class BackgroundActionReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelConfigRepository: TunnelConfigRepository
|
||||||
|
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
val id = intent.getIntExtra(TUNNEL_ID_EXTRA_KEY, 0)
|
||||||
|
if (id == 0) return
|
||||||
|
when (intent.action) {
|
||||||
|
ACTION_CONNECT -> {
|
||||||
|
applicationScope.launch {
|
||||||
|
val tunnel = tunnelConfigRepository.getById(id)
|
||||||
|
tunnel?.let {
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ACTION_DISCONNECT -> {
|
||||||
|
applicationScope.launch {
|
||||||
|
val tunnel = tunnelConfigRepository.getById(id)
|
||||||
|
tunnel?.let {
|
||||||
|
tunnelService.get().stopTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val ACTION_CONNECT = "ACTION_CONNECT"
|
||||||
|
const val ACTION_DISCONNECT = "ACTION_DISCONNECT"
|
||||||
|
const val TUNNEL_ID_EXTRA_KEY = "tunnelId"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,18 +6,22 @@ import android.content.Intent
|
|||||||
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.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class BootReceiver : BroadcastReceiver() {
|
class BootReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
@@ -25,32 +29,19 @@ class BootReceiver : BroadcastReceiver() {
|
|||||||
@ApplicationScope
|
@ApplicationScope
|
||||||
lateinit var applicationScope: CoroutineScope
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
override fun onReceive(context: Context?, intent: Intent?) {
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
if (Intent.ACTION_BOOT_COMPLETED != intent?.action) return
|
if (Intent.ACTION_BOOT_COMPLETED != intent.action) return
|
||||||
context?.run {
|
|
||||||
applicationScope.launch {
|
applicationScope.launch {
|
||||||
val settings = appDataRepository.settings.getSettings()
|
val settings = appDataRepository.settings.getSettings()
|
||||||
if(settings.isRestoreOnBootEnabled) {
|
if (settings.isRestoreOnBootEnabled) {
|
||||||
|
appDataRepository.getStartTunnelConfig()?.let {
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
if (settings.isAutoTunnelEnabled) {
|
if (settings.isAutoTunnelEnabled) {
|
||||||
Timber.i("Starting watcher service from boot")
|
Timber.i("Starting watcher service from boot")
|
||||||
serviceManager.startWatcherServiceForeground(context)
|
serviceManager.startWatcherServiceForeground(context)
|
||||||
}
|
}
|
||||||
if (appDataRepository.appState.isTunnelRunningFromManualStart()) {
|
|
||||||
appDataRepository.appState.getActiveTunnelId()?.let {
|
|
||||||
Timber.i("Starting tunnel that was active before reboot")
|
|
||||||
serviceManager.startVpnServiceForeground(
|
|
||||||
context,
|
|
||||||
appDataRepository.tunnels.getById(it)?.id,
|
|
||||||
)
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (settings.isAlwaysOnVpnEnabled) {
|
|
||||||
Timber.i("Starting vpn service from boot AOVPN")
|
|
||||||
serviceManager.startVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.receiver
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.TunnelConfigRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class KernelReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelConfigRepository: TunnelConfigRepository
|
||||||
|
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
val action = intent.action ?: return
|
||||||
|
applicationScope.launch {
|
||||||
|
if (action == REFRESH_TUNNELS_ACTION) {
|
||||||
|
tunnelService.get().runningTunnelNames().forEach { name ->
|
||||||
|
// TODO can optimize later
|
||||||
|
val tunnel = tunnelConfigRepository.findByTunnelName(name)
|
||||||
|
tunnel?.let {
|
||||||
|
tunnelConfigRepository.save(it.copy(isActive = true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
context.requestTunnelTileServiceStateUpdate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val REFRESH_TUNNELS_ACTION = "com.wireguard.android.action.REFRESH_TUNNEL_STATES"
|
||||||
|
}
|
||||||
|
}
|
||||||
-44
@@ -1,44 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.receiver
|
|
||||||
|
|
||||||
import android.content.BroadcastReceiver
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import timber.log.Timber
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class NotificationActionReceiver : BroadcastReceiver() {
|
|
||||||
@Inject
|
|
||||||
lateinit var settingsRepository: SettingsRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var serviceManager: ServiceManager
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@ApplicationScope
|
|
||||||
lateinit var applicationScope: CoroutineScope
|
|
||||||
|
|
||||||
override fun onReceive(context: Context, intent: Intent?) {
|
|
||||||
applicationScope.launch {
|
|
||||||
try {
|
|
||||||
//TODO fix for manual start changes when enabled
|
|
||||||
serviceManager.stopVpnServiceForeground(context)
|
|
||||||
delay(Constants.TOGGLE_TUNNEL_DELAY)
|
|
||||||
serviceManager.startVpnServiceForeground(context)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e(e)
|
|
||||||
} finally {
|
|
||||||
cancel()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,5 +4,5 @@ enum class Action {
|
|||||||
START,
|
START,
|
||||||
START_FOREGROUND,
|
START_FOREGROUND,
|
||||||
STOP,
|
STOP,
|
||||||
STOP_FOREGROUND
|
STOP_FOREGROUND,
|
||||||
}
|
}
|
||||||
|
|||||||
+467
@@ -0,0 +1,467 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.PowerManager
|
||||||
|
import androidx.core.app.ServiceCompat
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.network.EthernetService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.network.MobileDataService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.network.NetworkService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.network.NetworkStatus
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.network.WifiService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.collectLatest
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import timber.log.Timber
|
||||||
|
import java.net.InetAddress
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class AutoTunnelService : ForegroundService() {
|
||||||
|
private val foregroundId = 122
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var wifiService: NetworkService<WifiService>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var mobileDataService: NetworkService<MobileDataService>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var ethernetService: NetworkService<EthernetService>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var notificationService: NotificationService
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@IoDispatcher
|
||||||
|
lateinit var ioDispatcher: CoroutineDispatcher
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@MainImmediateDispatcher
|
||||||
|
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
||||||
|
|
||||||
|
private val networkEventsFlow = MutableStateFlow(AutoTunnelState())
|
||||||
|
|
||||||
|
private var wakeLock: PowerManager.WakeLock? = null
|
||||||
|
private val tag = this.javaClass.name
|
||||||
|
|
||||||
|
private var running: Boolean = false
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||||
|
kotlin.runCatching {
|
||||||
|
launchNotification()
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun launchNotification() {
|
||||||
|
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
|
||||||
|
launchWatcherPausedNotification()
|
||||||
|
} else {
|
||||||
|
launchWatcherNotification()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun startService(extras: Bundle?) {
|
||||||
|
super.startService(extras)
|
||||||
|
if (running) return
|
||||||
|
kotlin.runCatching {
|
||||||
|
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||||
|
launchNotification()
|
||||||
|
initWakeLock()
|
||||||
|
}
|
||||||
|
startWatcherJob()
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun stopService() {
|
||||||
|
super.stopService()
|
||||||
|
wakeLock?.let {
|
||||||
|
if (it.isHeld) {
|
||||||
|
it.release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun launchWatcherNotification(description: String = getString(R.string.watcher_notification_text_active)) {
|
||||||
|
val notification =
|
||||||
|
notificationService.createNotification(
|
||||||
|
channelId = getString(R.string.watcher_channel_id),
|
||||||
|
channelName = getString(R.string.watcher_channel_name),
|
||||||
|
title = getString(R.string.auto_tunnel_title),
|
||||||
|
description = description,
|
||||||
|
)
|
||||||
|
ServiceCompat.startForeground(
|
||||||
|
this,
|
||||||
|
foregroundId,
|
||||||
|
notification,
|
||||||
|
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun launchWatcherPausedNotification() {
|
||||||
|
launchWatcherNotification(getString(R.string.watcher_notification_text_paused))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initWakeLock() {
|
||||||
|
wakeLock =
|
||||||
|
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
|
||||||
|
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply {
|
||||||
|
try {
|
||||||
|
Timber.i("Initiating wakelock with 10 min timeout")
|
||||||
|
acquire(Constants.BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT)
|
||||||
|
} finally {
|
||||||
|
release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startWatcherJob() = lifecycleScope.launch {
|
||||||
|
val setting = appDataRepository.settings.getSettings()
|
||||||
|
launch {
|
||||||
|
Timber.i("Starting wifi watcher")
|
||||||
|
watchForWifiConnectivityChanges()
|
||||||
|
}
|
||||||
|
if (setting.isTunnelOnMobileDataEnabled) {
|
||||||
|
launch {
|
||||||
|
Timber.i("Starting mobile data watcher")
|
||||||
|
watchForMobileDataConnectivityChanges()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (setting.isTunnelOnEthernetEnabled) {
|
||||||
|
launch {
|
||||||
|
Timber.i("Starting ethernet data watcher")
|
||||||
|
watchForEthernetConnectivityChanges()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
Timber.i("Starting settings watcher")
|
||||||
|
watchForSettingsChanges()
|
||||||
|
}
|
||||||
|
if (setting.isPingEnabled) {
|
||||||
|
launch {
|
||||||
|
Timber.i("Starting ping watcher")
|
||||||
|
watchForPingFailure()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
Timber.i("Starting management watcher")
|
||||||
|
manageVpn()
|
||||||
|
}
|
||||||
|
running = true
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForMobileDataConnectivityChanges() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
mobileDataService.networkStatus.collect { status ->
|
||||||
|
when (status) {
|
||||||
|
is NetworkStatus.Available -> {
|
||||||
|
Timber.i("Gained Mobile data connection")
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isMobileDataConnected = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.CapabilitiesChanged -> {
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isMobileDataConnected = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Timber.i("Mobile data capabilities changed")
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.Unavailable -> {
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isMobileDataConnected = false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Timber.i("Lost mobile data connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForPingFailure() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
if (tunnelService.get().vpnState.value.status == TunnelState.UP) {
|
||||||
|
val tunnelConfig = tunnelService.get().vpnState.value.tunnelConfig
|
||||||
|
tunnelConfig?.let {
|
||||||
|
val config = TunnelConfig.configFromWgQuick(it.wgQuick)
|
||||||
|
val results =
|
||||||
|
config.peers.map { peer ->
|
||||||
|
val host =
|
||||||
|
if (peer.endpoint.isPresent &&
|
||||||
|
peer.endpoint.get().resolved.isPresent
|
||||||
|
) {
|
||||||
|
peer.endpoint.get().resolved.get().host
|
||||||
|
} else {
|
||||||
|
Constants.DEFAULT_PING_IP
|
||||||
|
}
|
||||||
|
Timber.i("Checking reachability of: $host")
|
||||||
|
val reachable =
|
||||||
|
InetAddress.getByName(host)
|
||||||
|
.isReachable(Constants.PING_TIMEOUT.toInt())
|
||||||
|
Timber.i("Result: reachable - $reachable")
|
||||||
|
reachable
|
||||||
|
}
|
||||||
|
if (results.contains(false)) {
|
||||||
|
Timber.i("Restarting VPN for ping failure")
|
||||||
|
tunnelService.get().stopTunnel(it)
|
||||||
|
delay(Constants.VPN_RESTART_DELAY)
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
delay(Constants.PING_COOLDOWN)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delay(Constants.PING_INTERVAL)
|
||||||
|
} while (true)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Timber.e(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForSettingsChanges() {
|
||||||
|
appDataRepository.settings.getSettingsFlow().collect { settings ->
|
||||||
|
if (networkEventsFlow.value.settings.isAutoTunnelPaused
|
||||||
|
!= settings.isAutoTunnelPaused
|
||||||
|
) {
|
||||||
|
when (settings.isAutoTunnelPaused) {
|
||||||
|
true -> launchWatcherPausedNotification()
|
||||||
|
false -> launchWatcherNotification()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
settings = settings,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForEthernetConnectivityChanges() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
ethernetService.networkStatus.collect { status ->
|
||||||
|
when (status) {
|
||||||
|
is NetworkStatus.Available -> {
|
||||||
|
Timber.i("Gained Ethernet connection")
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isEthernetConnected = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.CapabilitiesChanged -> {
|
||||||
|
Timber.i("Ethernet capabilities changed")
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isEthernetConnected = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.Unavailable -> {
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isEthernetConnected = false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Timber.i("Lost Ethernet connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForWifiConnectivityChanges() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
wifiService.networkStatus.collect { status ->
|
||||||
|
when (status) {
|
||||||
|
is NetworkStatus.Available -> {
|
||||||
|
Timber.i("Gained Wi-Fi connection")
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isWifiConnected = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.CapabilitiesChanged -> {
|
||||||
|
Timber.i("Wifi capabilities changed")
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isWifiConnected = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val ssid = wifiService.getNetworkName(status.networkCapabilities)
|
||||||
|
ssid?.let { name ->
|
||||||
|
if (name.contains(Constants.UNREADABLE_SSID)) {
|
||||||
|
Timber.w("SSID unreadable: missing permissions")
|
||||||
|
} else {
|
||||||
|
Timber.i("Detected valid SSID")
|
||||||
|
}
|
||||||
|
appDataRepository.appState.setCurrentSsid(name)
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
currentNetworkSSID = name,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} ?: Timber.w("Failed to read ssid")
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.Unavailable -> {
|
||||||
|
networkEventsFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isWifiConnected = false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Timber.i("Lost Wi-Fi connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun getMobileDataTunnel(): TunnelConfig? {
|
||||||
|
return appDataRepository.tunnels.findByMobileDataTunnel().firstOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun getSsidTunnel(ssid: String): TunnelConfig? {
|
||||||
|
return appDataRepository.tunnels.findByTunnelNetworksName(ssid).firstOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isTunnelDown(): Boolean {
|
||||||
|
return tunnelService.get().vpnState.value.status == TunnelState.DOWN
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun manageVpn() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
networkEventsFlow.collectLatest { watcherState ->
|
||||||
|
val autoTunnel = "Auto-tunnel watcher"
|
||||||
|
if (!watcherState.settings.isAutoTunnelPaused) {
|
||||||
|
// delay for rapid network state changes and then collect latest
|
||||||
|
delay(Constants.WATCHER_COLLECTION_DELAY)
|
||||||
|
val activeTunnel = tunnelService.get().vpnState.value.tunnelConfig
|
||||||
|
val defaultTunnel = appDataRepository.getPrimaryOrFirstTunnel()
|
||||||
|
when {
|
||||||
|
watcherState.isEthernetConditionMet() -> {
|
||||||
|
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
|
||||||
|
if (isTunnelDown()) {
|
||||||
|
defaultTunnel?.let {
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watcherState.isMobileDataConditionMet() -> {
|
||||||
|
Timber.i("$autoTunnel - tunnel on mobile data condition met")
|
||||||
|
val mobileDataTunnel = getMobileDataTunnel()
|
||||||
|
val tunnel =
|
||||||
|
mobileDataTunnel ?: defaultTunnel
|
||||||
|
if (isTunnelDown() || activeTunnel?.isMobileDataTunnel == false) {
|
||||||
|
tunnel?.let {
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watcherState.isTunnelOffOnMobileDataConditionMet() -> {
|
||||||
|
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
|
||||||
|
if (!isTunnelDown()) {
|
||||||
|
activeTunnel?.let {
|
||||||
|
tunnelService.get().stopTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watcherState.isUntrustedWifiConditionMet() -> {
|
||||||
|
if (activeTunnel?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false ||
|
||||||
|
activeTunnel == null
|
||||||
|
) {
|
||||||
|
Timber.i(
|
||||||
|
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met",
|
||||||
|
)
|
||||||
|
getSsidTunnel(watcherState.currentNetworkSSID)?.let {
|
||||||
|
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}")
|
||||||
|
if (isTunnelDown() || activeTunnel?.id != it.id) {
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
}
|
||||||
|
} ?: suspend {
|
||||||
|
Timber.i("No tunnel associated with this SSID, using defaults")
|
||||||
|
val default = appDataRepository.getPrimaryOrFirstTunnel()
|
||||||
|
if (default?.name != tunnelService.get().name || isTunnelDown()) {
|
||||||
|
default?.let {
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.invoke()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watcherState.isTrustedWifiConditionMet() -> {
|
||||||
|
Timber.i(
|
||||||
|
"$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off",
|
||||||
|
)
|
||||||
|
if (!isTunnelDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
watcherState.isTunnelOffOnWifiConditionMet() -> {
|
||||||
|
Timber.i(
|
||||||
|
"$autoTunnel - tunnel off on wifi condition met, turning vpn off",
|
||||||
|
)
|
||||||
|
if (!isTunnelDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
watcherState.isTunnelOffOnNoConnectivityMet() -> {
|
||||||
|
Timber.i(
|
||||||
|
"$autoTunnel - tunnel off on no connectivity met, turning vpn off",
|
||||||
|
)
|
||||||
|
if (!isTunnelDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
Timber.i("$autoTunnel - no condition met")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+73
@@ -0,0 +1,73 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||||
|
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
|
|
||||||
|
data class AutoTunnelState(
|
||||||
|
val isWifiConnected: Boolean = false,
|
||||||
|
val isEthernetConnected: Boolean = false,
|
||||||
|
val isMobileDataConnected: Boolean = false,
|
||||||
|
val currentNetworkSSID: String = "",
|
||||||
|
val settings: Settings = Settings(),
|
||||||
|
) {
|
||||||
|
fun isEthernetConditionMet(): Boolean {
|
||||||
|
return (
|
||||||
|
isEthernetConnected &&
|
||||||
|
settings.isTunnelOnEthernetEnabled
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isMobileDataConditionMet(): Boolean {
|
||||||
|
return (
|
||||||
|
!isEthernetConnected &&
|
||||||
|
settings.isTunnelOnMobileDataEnabled &&
|
||||||
|
!isWifiConnected &&
|
||||||
|
isMobileDataConnected
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isTunnelOffOnMobileDataConditionMet(): Boolean {
|
||||||
|
return (
|
||||||
|
!isEthernetConnected &&
|
||||||
|
!settings.isTunnelOnMobileDataEnabled &&
|
||||||
|
isMobileDataConnected &&
|
||||||
|
!isWifiConnected
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isUntrustedWifiConditionMet(): Boolean {
|
||||||
|
return (
|
||||||
|
!isEthernetConnected &&
|
||||||
|
isWifiConnected &&
|
||||||
|
!settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
|
||||||
|
settings.isTunnelOnWifiEnabled
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isTrustedWifiConditionMet(): Boolean {
|
||||||
|
return (
|
||||||
|
!isEthernetConnected &&
|
||||||
|
(
|
||||||
|
isWifiConnected &&
|
||||||
|
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isTunnelOffOnWifiConditionMet(): Boolean {
|
||||||
|
return (
|
||||||
|
!isEthernetConnected &&
|
||||||
|
(
|
||||||
|
isWifiConnected &&
|
||||||
|
!settings.isTunnelOnWifiEnabled
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isTunnelOffOnNoConnectivityMet(): Boolean {
|
||||||
|
return (
|
||||||
|
!isEthernetConnected &&
|
||||||
|
!isWifiConnected &&
|
||||||
|
!isMobileDataConnected
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -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 -> {
|
||||||
|
|||||||
+8
-87
@@ -3,24 +3,10 @@ package com.zaneschepke.wireguardautotunnel.service.foreground
|
|||||||
import android.app.Service
|
import android.app.Service
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
|
||||||
class ServiceManager(
|
class ServiceManager {
|
||||||
private val appDataRepository: AppDataRepository,
|
private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) {
|
||||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
|
||||||
) {
|
|
||||||
|
|
||||||
private fun <T : Service> actionOnService(
|
|
||||||
action: Action,
|
|
||||||
context: Context,
|
|
||||||
cls: Class<T>,
|
|
||||||
extras: Map<String, Int>? = null
|
|
||||||
) {
|
|
||||||
val intent =
|
val intent =
|
||||||
Intent(context, cls).also {
|
Intent(context, cls).also {
|
||||||
it.action = action.name
|
it.action = action.name
|
||||||
@@ -29,7 +15,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,77 +27,11 @@ class ServiceManager(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun startVpnService(
|
fun startWatcherServiceForeground(context: Context) {
|
||||||
context: Context,
|
|
||||||
tunnelId: Int? = null,
|
|
||||||
isManualStart: Boolean = false
|
|
||||||
) {
|
|
||||||
if (isManualStart) onManualStart(tunnelId)
|
|
||||||
actionOnService(
|
|
||||||
Action.START,
|
|
||||||
context,
|
|
||||||
WireGuardTunnelService::class.java,
|
|
||||||
tunnelId?.let { mapOf(Constants.TUNNEL_EXTRA_KEY to it) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun stopVpnServiceForeground(context: Context, isManualStop: Boolean = false) {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
if (isManualStop) onManualStop()
|
|
||||||
Timber.i("Stopping vpn service")
|
|
||||||
actionOnService(
|
|
||||||
Action.STOP_FOREGROUND,
|
|
||||||
context,
|
|
||||||
WireGuardTunnelService::class.java,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun stopVpnService(context: Context, isManualStop: Boolean = false) {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
if (isManualStop) onManualStop()
|
|
||||||
Timber.i("Stopping vpn service")
|
|
||||||
actionOnService(
|
|
||||||
Action.STOP,
|
|
||||||
context,
|
|
||||||
WireGuardTunnelService::class.java,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun onManualStop() {
|
|
||||||
appDataRepository.appState.setManualStop()
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun onManualStart(tunnelId: Int?) {
|
|
||||||
tunnelId?.let {
|
|
||||||
appDataRepository.appState.setTunnelRunningFromManualStart(it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun startVpnServiceForeground(
|
|
||||||
context: Context,
|
|
||||||
tunnelId: Int? = null,
|
|
||||||
isManualStart: Boolean = false
|
|
||||||
) {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
if (isManualStart) onManualStart(tunnelId)
|
|
||||||
actionOnService(
|
actionOnService(
|
||||||
Action.START_FOREGROUND,
|
Action.START_FOREGROUND,
|
||||||
context,
|
context,
|
||||||
WireGuardTunnelService::class.java,
|
AutoTunnelService::class.java,
|
||||||
tunnelId?.let { mapOf(Constants.TUNNEL_EXTRA_KEY to it) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun startWatcherServiceForeground(
|
|
||||||
context: Context,
|
|
||||||
) {
|
|
||||||
actionOnService(
|
|
||||||
Action.START_FOREGROUND,
|
|
||||||
context,
|
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +39,7 @@ class ServiceManager(
|
|||||||
actionOnService(
|
actionOnService(
|
||||||
Action.START,
|
Action.START,
|
||||||
context,
|
context,
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
AutoTunnelService::class.java,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,7 +47,7 @@ class ServiceManager(
|
|||||||
actionOnService(
|
actionOnService(
|
||||||
Action.STOP,
|
Action.STOP,
|
||||||
context,
|
context,
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
AutoTunnelService::class.java,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-56
@@ -1,56 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
|
||||||
|
|
||||||
data class WatcherState(
|
|
||||||
val isWifiConnected: Boolean = false,
|
|
||||||
val isEthernetConnected: Boolean = false,
|
|
||||||
val isMobileDataConnected: Boolean = false,
|
|
||||||
val currentNetworkSSID: String = "",
|
|
||||||
val settings: Settings = Settings()
|
|
||||||
) {
|
|
||||||
fun isEthernetConditionMet(): Boolean {
|
|
||||||
return (isEthernetConnected &&
|
|
||||||
settings.isTunnelOnEthernetEnabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isMobileDataConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
settings.isTunnelOnMobileDataEnabled &&
|
|
||||||
!isWifiConnected &&
|
|
||||||
isMobileDataConnected)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTunnelOffOnMobileDataConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
!settings.isTunnelOnMobileDataEnabled &&
|
|
||||||
isMobileDataConnected &&
|
|
||||||
!isWifiConnected)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isUntrustedWifiConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
isWifiConnected &&
|
|
||||||
!settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
|
|
||||||
settings.isTunnelOnWifiEnabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTrustedWifiConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
(isWifiConnected &&
|
|
||||||
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTunnelOffOnWifiConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
(isWifiConnected &&
|
|
||||||
!settings.isTunnelOnWifiEnabled))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTunnelOffOnNoConnectivityMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
!isWifiConnected &&
|
|
||||||
!isMobileDataConnected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
-456
@@ -1,456 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.os.PowerManager
|
|
||||||
import androidx.core.app.ServiceCompat
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.EthernetService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.MobileDataService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.NetworkService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.NetworkStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.WifiService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.collectLatest
|
|
||||||
import kotlinx.coroutines.flow.update
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import timber.log.Timber
|
|
||||||
import java.net.InetAddress
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class WireGuardConnectivityWatcherService : ForegroundService() {
|
|
||||||
private val foregroundId = 122
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var wifiService: NetworkService<WifiService>
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var mobileDataService: NetworkService<MobileDataService>
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var ethernetService: NetworkService<EthernetService>
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var appDataRepository: AppDataRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var notificationService: NotificationService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var vpnService: VpnService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var serviceManager: ServiceManager
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@IoDispatcher
|
|
||||||
lateinit var ioDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@MainImmediateDispatcher
|
|
||||||
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
private val networkEventsFlow = MutableStateFlow(WatcherState())
|
|
||||||
|
|
||||||
private var watcherJob: Job? = null
|
|
||||||
|
|
||||||
private var wakeLock: PowerManager.WakeLock? = null
|
|
||||||
private val tag = this.javaClass.name
|
|
||||||
|
|
||||||
override fun onCreate() {
|
|
||||||
super.onCreate()
|
|
||||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
|
||||||
try {
|
|
||||||
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
|
|
||||||
launchWatcherPausedNotification()
|
|
||||||
} else launchWatcherNotification()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e("Failed to start watcher service, not enough permissions")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun startService(extras: Bundle?) {
|
|
||||||
super.startService(extras)
|
|
||||||
try {
|
|
||||||
// we need this lock so our service gets not affected by Doze Mode
|
|
||||||
lifecycleScope.launch { initWakeLock() }
|
|
||||||
cancelWatcherJob()
|
|
||||||
startWatcherJob()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e("Failed to launch watcher service, no permissions")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun stopService() {
|
|
||||||
super.stopService()
|
|
||||||
wakeLock?.let {
|
|
||||||
if (it.isHeld) {
|
|
||||||
it.release()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cancelWatcherJob()
|
|
||||||
stopSelf()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchWatcherNotification(
|
|
||||||
description: String = getString(R.string.watcher_notification_text_active)
|
|
||||||
) {
|
|
||||||
val notification =
|
|
||||||
notificationService.createNotification(
|
|
||||||
channelId = getString(R.string.watcher_channel_id),
|
|
||||||
channelName = getString(R.string.watcher_channel_name),
|
|
||||||
title = getString(R.string.auto_tunnel_title),
|
|
||||||
description = description,
|
|
||||||
)
|
|
||||||
ServiceCompat.startForeground(
|
|
||||||
this,
|
|
||||||
foregroundId,
|
|
||||||
notification,
|
|
||||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchWatcherPausedNotification() {
|
|
||||||
launchWatcherNotification(getString(R.string.watcher_notification_text_paused))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun initWakeLock() {
|
|
||||||
wakeLock =
|
|
||||||
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
|
|
||||||
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply {
|
|
||||||
try {
|
|
||||||
Timber.i("Initiating wakelock with 10 min timeout")
|
|
||||||
acquire(Constants.BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT)
|
|
||||||
} finally {
|
|
||||||
release()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun cancelWatcherJob() {
|
|
||||||
try {
|
|
||||||
watcherJob?.cancel()
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
Timber.i("Watcher job cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startWatcherJob() {
|
|
||||||
watcherJob =
|
|
||||||
lifecycleScope.launch {
|
|
||||||
val setting = appDataRepository.settings.getSettings()
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting wifi watcher")
|
|
||||||
watchForWifiConnectivityChanges()
|
|
||||||
}
|
|
||||||
if (setting.isTunnelOnMobileDataEnabled) {
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting mobile data watcher")
|
|
||||||
watchForMobileDataConnectivityChanges()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (setting.isTunnelOnEthernetEnabled) {
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting ethernet data watcher")
|
|
||||||
watchForEthernetConnectivityChanges()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting settings watcher")
|
|
||||||
watchForSettingsChanges()
|
|
||||||
}
|
|
||||||
if (setting.isPingEnabled) {
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting ping watcher")
|
|
||||||
watchForPingFailure()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting management watcher")
|
|
||||||
manageVpn()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForMobileDataConnectivityChanges() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
mobileDataService.networkStatus.collect { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Available -> {
|
|
||||||
Timber.i("Gained Mobile data connection")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isMobileDataConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.CapabilitiesChanged -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isMobileDataConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Mobile data capabilities changed")
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.Unavailable -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isMobileDataConnected = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Lost mobile data connection")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForPingFailure() {
|
|
||||||
val context = this
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
try {
|
|
||||||
do {
|
|
||||||
if (vpnService.vpnState.value.status == TunnelState.UP) {
|
|
||||||
val tunnelConfig = vpnService.vpnState.value.tunnelConfig
|
|
||||||
tunnelConfig?.let {
|
|
||||||
val config = TunnelConfig.configFromWgQuick(it.wgQuick)
|
|
||||||
val results = config.peers.map { peer ->
|
|
||||||
val host = if (peer.endpoint.isPresent &&
|
|
||||||
peer.endpoint.get().resolved.isPresent)
|
|
||||||
peer.endpoint.get().resolved.get().host
|
|
||||||
else Constants.DEFAULT_PING_IP
|
|
||||||
Timber.i("Checking reachability of: $host")
|
|
||||||
val reachable = InetAddress.getByName(host)
|
|
||||||
.isReachable(Constants.PING_TIMEOUT.toInt())
|
|
||||||
Timber.i("Result: reachable - $reachable")
|
|
||||||
reachable
|
|
||||||
}
|
|
||||||
if (results.contains(false)) {
|
|
||||||
Timber.i("Restarting VPN for ping failure")
|
|
||||||
serviceManager.stopVpnServiceForeground(context)
|
|
||||||
delay(Constants.VPN_RESTART_DELAY)
|
|
||||||
serviceManager.startVpnServiceForeground(context, it.id)
|
|
||||||
delay(Constants.PING_COOLDOWN)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
delay(Constants.PING_INTERVAL)
|
|
||||||
} while (true)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForSettingsChanges() {
|
|
||||||
appDataRepository.settings.getSettingsFlow().collect { settings ->
|
|
||||||
if (networkEventsFlow.value.settings.isAutoTunnelPaused != settings.isAutoTunnelPaused) {
|
|
||||||
when (settings.isAutoTunnelPaused) {
|
|
||||||
true -> launchWatcherPausedNotification()
|
|
||||||
false -> launchWatcherNotification()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
settings = settings,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForEthernetConnectivityChanges() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
ethernetService.networkStatus.collect { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Available -> {
|
|
||||||
Timber.i("Gained Ethernet connection")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isEthernetConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.CapabilitiesChanged -> {
|
|
||||||
Timber.i("Ethernet capabilities changed")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isEthernetConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.Unavailable -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isEthernetConnected = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Lost Ethernet connection")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForWifiConnectivityChanges() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
wifiService.networkStatus.collect { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Available -> {
|
|
||||||
Timber.i("Gained Wi-Fi connection")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isWifiConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.CapabilitiesChanged -> {
|
|
||||||
Timber.i("Wifi capabilities changed")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isWifiConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
val ssid = wifiService.getNetworkName(status.networkCapabilities)
|
|
||||||
ssid?.let { name ->
|
|
||||||
if (name.contains(Constants.UNREADABLE_SSID)) {
|
|
||||||
Timber.w("SSID unreadable: missing permissions")
|
|
||||||
} else Timber.i("Detected valid SSID")
|
|
||||||
appDataRepository.appState.setCurrentSsid(name)
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
currentNetworkSSID = name,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} ?: Timber.w("Failed to read ssid")
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.Unavailable -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isWifiConnected = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Lost Wi-Fi connection")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun getMobileDataTunnel(): TunnelConfig? {
|
|
||||||
return appDataRepository.tunnels.findByMobileDataTunnel().firstOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun getSsidTunnel(ssid: String): TunnelConfig? {
|
|
||||||
return appDataRepository.tunnels.findByTunnelNetworksName(ssid).firstOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun isTunnelDown(): Boolean {
|
|
||||||
return vpnService.vpnState.value.status == TunnelState.DOWN
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun manageVpn() {
|
|
||||||
val context = this
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
networkEventsFlow.collectLatest { watcherState ->
|
|
||||||
val autoTunnel = "Auto-tunnel watcher"
|
|
||||||
if (!watcherState.settings.isAutoTunnelPaused) {
|
|
||||||
//delay for rapid network state changes and then collect latest
|
|
||||||
delay(Constants.WATCHER_COLLECTION_DELAY)
|
|
||||||
val tunnelConfig = vpnService.vpnState.value.tunnelConfig
|
|
||||||
when {
|
|
||||||
watcherState.isEthernetConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
|
|
||||||
if (isTunnelDown()) serviceManager.startVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isMobileDataConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel on mobile data condition met")
|
|
||||||
val mobileDataTunnel = getMobileDataTunnel()
|
|
||||||
val tunnel =
|
|
||||||
mobileDataTunnel ?: appDataRepository.getPrimaryOrFirstTunnel()
|
|
||||||
if (isTunnelDown() || tunnelConfig?.isMobileDataTunnel == false) {
|
|
||||||
serviceManager.startVpnServiceForeground(
|
|
||||||
context,
|
|
||||||
tunnel?.id,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnMobileDataConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isUntrustedWifiConditionMet() -> {
|
|
||||||
if (tunnelConfig?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false ||
|
|
||||||
tunnelConfig == null) {
|
|
||||||
Timber.i("$autoTunnel - tunnel on ssid not associated with current tunnel condition met")
|
|
||||||
getSsidTunnel(watcherState.currentNetworkSSID)?.let {
|
|
||||||
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}")
|
|
||||||
if (isTunnelDown() || tunnelConfig?.id != it.id) serviceManager.startVpnServiceForeground(
|
|
||||||
context,
|
|
||||||
it.id,
|
|
||||||
)
|
|
||||||
} ?: suspend {
|
|
||||||
Timber.i("No tunnel associated with this SSID, using defaults")
|
|
||||||
val default = appDataRepository.getPrimaryOrFirstTunnel()
|
|
||||||
if (default?.name != vpnService.name) {
|
|
||||||
default?.let {
|
|
||||||
serviceManager.startVpnServiceForeground(context, it.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}.invoke()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTrustedWifiConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnWifiConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on wifi condition met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnNoConnectivityMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on no connectivity met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
Timber.i("$autoTunnel - no condition met")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-201
@@ -1,201 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import android.app.PendingIntent
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.core.app.ServiceCompat
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.receiver.NotificationActionReceiver
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.handshakeStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.mapPeerStats
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import timber.log.Timber
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class WireGuardTunnelService : ForegroundService() {
|
|
||||||
private val foregroundId = 123
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var vpnService: VpnService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var appDataRepository: AppDataRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var notificationService: NotificationService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@MainImmediateDispatcher
|
|
||||||
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@IoDispatcher
|
|
||||||
lateinit var ioDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
private var job: Job? = null
|
|
||||||
|
|
||||||
private var didShowConnected = false
|
|
||||||
|
|
||||||
override fun onCreate() {
|
|
||||||
super.onCreate()
|
|
||||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
|
||||||
//TODO fix this to not launch if AOVPN
|
|
||||||
if (appDataRepository.tunnels.count() != 0) {
|
|
||||||
launchVpnNotification()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun startService(extras: Bundle?) {
|
|
||||||
super.startService(extras)
|
|
||||||
cancelJob()
|
|
||||||
job =
|
|
||||||
lifecycleScope.launch {
|
|
||||||
launch {
|
|
||||||
val tunnelId = extras?.getInt(Constants.TUNNEL_EXTRA_KEY)
|
|
||||||
if (vpnService.getState() == TunnelState.UP) {
|
|
||||||
vpnService.stopTunnel()
|
|
||||||
}
|
|
||||||
vpnService.startTunnel(
|
|
||||||
tunnelId?.let {
|
|
||||||
appDataRepository.tunnels.getById(it)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
launch {
|
|
||||||
handshakeNotifications()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//TODO improve tunnel notifications
|
|
||||||
private suspend fun handshakeNotifications() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
var tunnelName: String? = null
|
|
||||||
vpnService.vpnState.collect { state ->
|
|
||||||
state.statistics
|
|
||||||
?.mapPeerStats()
|
|
||||||
?.map { it.value?.handshakeStatus() }
|
|
||||||
.let { statuses ->
|
|
||||||
when {
|
|
||||||
statuses?.all { it == HandshakeStatus.HEALTHY } == true -> {
|
|
||||||
if (!didShowConnected) {
|
|
||||||
delay(Constants.VPN_CONNECTED_NOTIFICATION_DELAY)
|
|
||||||
tunnelName = state.tunnelConfig?.name
|
|
||||||
launchVpnNotification(
|
|
||||||
getString(R.string.tunnel_start_title),
|
|
||||||
"${getString(R.string.tunnel_start_text)} - $tunnelName",
|
|
||||||
)
|
|
||||||
didShowConnected = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
statuses?.any { it == HandshakeStatus.STALE } == true -> {}
|
|
||||||
statuses?.all { it == HandshakeStatus.NOT_STARTED } ==
|
|
||||||
true -> {
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (state.status == TunnelState.UP && state.tunnelConfig?.name != tunnelName) {
|
|
||||||
tunnelName = state.tunnelConfig?.name
|
|
||||||
launchVpnNotification(
|
|
||||||
getString(R.string.tunnel_start_title),
|
|
||||||
"${getString(R.string.tunnel_start_text)} - $tunnelName",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchAlwaysOnDisabledNotification() {
|
|
||||||
launchVpnNotification(
|
|
||||||
title = this.getString(R.string.vpn_connection_failed),
|
|
||||||
description = this.getString(R.string.always_on_disabled),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun stopService() {
|
|
||||||
super.stopService()
|
|
||||||
lifecycleScope.launch {
|
|
||||||
vpnService.stopTunnel()
|
|
||||||
didShowConnected = false
|
|
||||||
}
|
|
||||||
cancelJob()
|
|
||||||
stopSelf()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchVpnNotification(
|
|
||||||
title: String = getString(R.string.vpn_starting),
|
|
||||||
description: String = getString(R.string.attempt_connection)
|
|
||||||
) {
|
|
||||||
val notification =
|
|
||||||
notificationService.createNotification(
|
|
||||||
channelId = getString(R.string.vpn_channel_id),
|
|
||||||
channelName = getString(R.string.vpn_channel_name),
|
|
||||||
title = title,
|
|
||||||
onGoing = false,
|
|
||||||
vibration = false,
|
|
||||||
showTimestamp = true,
|
|
||||||
description = description,
|
|
||||||
)
|
|
||||||
ServiceCompat.startForeground(
|
|
||||||
this,
|
|
||||||
foregroundId,
|
|
||||||
notification,
|
|
||||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchVpnConnectionFailedNotification(message: String) {
|
|
||||||
val notification =
|
|
||||||
notificationService.createNotification(
|
|
||||||
channelId = getString(R.string.vpn_channel_id),
|
|
||||||
channelName = getString(R.string.vpn_channel_name),
|
|
||||||
action =
|
|
||||||
PendingIntent.getBroadcast(
|
|
||||||
this,
|
|
||||||
0,
|
|
||||||
Intent(this, NotificationActionReceiver::class.java),
|
|
||||||
PendingIntent.FLAG_IMMUTABLE,
|
|
||||||
),
|
|
||||||
actionText = getString(R.string.restart),
|
|
||||||
title = getString(R.string.vpn_connection_failed),
|
|
||||||
onGoing = false,
|
|
||||||
vibration = true,
|
|
||||||
showTimestamp = true,
|
|
||||||
description = message,
|
|
||||||
)
|
|
||||||
ServiceCompat.startForeground(
|
|
||||||
this,
|
|
||||||
foregroundId,
|
|
||||||
notification,
|
|
||||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun cancelJob() {
|
|
||||||
try {
|
|
||||||
job?.cancel()
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
Timber.i("Tunnel job cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+6
-11
@@ -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
-1
@@ -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
-1
@@ -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
-1
@@ -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)
|
||||||
|
|||||||
+5
-2
@@ -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
|
||||||
|
|||||||
+23
-23
@@ -5,22 +5,22 @@ import androidx.activity.ComponentActivity
|
|||||||
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.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.Action
|
import com.zaneschepke.wireguardautotunnel.service.foreground.Action
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.AutoTunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardConnectivityWatcherService
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardTunnelService
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class ShortcutsActivity : ComponentActivity() {
|
class ShortcutsActivity : ComponentActivity() {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
@ApplicationScope
|
@ApplicationScope
|
||||||
@@ -32,34 +32,32 @@ class ShortcutsActivity : ComponentActivity() {
|
|||||||
val settings = appDataRepository.settings.getSettings()
|
val settings = appDataRepository.settings.getSettings()
|
||||||
if (settings.isShortcutsEnabled) {
|
if (settings.isShortcutsEnabled) {
|
||||||
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
|
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
|
||||||
WireGuardTunnelService::class.java.simpleName -> {
|
LEGACY_TUNNEL_SERVICE_NAME, TunnelService::class.java.simpleName -> {
|
||||||
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
|
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
|
||||||
|
Timber.d("Tunnel name extra: $tunnelName")
|
||||||
val tunnelConfig = tunnelName?.let {
|
val tunnelConfig = tunnelName?.let {
|
||||||
appDataRepository.tunnels.getAll().firstOrNull {
|
appDataRepository.tunnels.getAll()
|
||||||
it.name == tunnelName
|
.firstOrNull { it.name == tunnelName }
|
||||||
}
|
} ?: appDataRepository.getStartTunnelConfig()
|
||||||
}
|
Timber.d("Shortcut action on name: ${tunnelConfig?.name}")
|
||||||
|
tunnelConfig?.let {
|
||||||
when (intent.action) {
|
when (intent.action) {
|
||||||
Action.START.name -> serviceManager.startVpnServiceForeground(
|
Action.START.name -> tunnelService.get().startTunnel(it)
|
||||||
this@ShortcutsActivity, tunnelConfig?.id, isManualStart = true,
|
Action.STOP.name -> tunnelService.get().stopTunnel(it)
|
||||||
)
|
else -> Unit
|
||||||
|
|
||||||
Action.STOP.name -> serviceManager.stopVpnServiceForeground(
|
|
||||||
this@ShortcutsActivity,
|
|
||||||
isManualStop = true,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
WireGuardConnectivityWatcherService::class.java.simpleName -> {
|
AutoTunnelService::class.java.simpleName, LEGACY_AUTO_TUNNEL_SERVICE_NAME -> {
|
||||||
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 ->
|
||||||
Action.STOP.name -> appDataRepository.settings.save(
|
appDataRepository.settings.save(
|
||||||
settings.copy(
|
settings.copy(
|
||||||
isAutoTunnelPaused = true,
|
isAutoTunnelPaused = true,
|
||||||
),
|
),
|
||||||
@@ -73,6 +71,8 @@ class ShortcutsActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
const val LEGACY_TUNNEL_SERVICE_NAME = "WireGuardTunnelService"
|
||||||
|
const val LEGACY_AUTO_TUNNEL_SERVICE_NAME = "WireGuardConnectivityWatcherService"
|
||||||
const val TUNNEL_NAME_EXTRA_KEY = "tunnelName"
|
const val TUNNEL_NAME_EXTRA_KEY = "tunnelName"
|
||||||
const val CLASS_NAME_EXTRA_KEY = "className"
|
const val CLASS_NAME_EXTRA_KEY = "className"
|
||||||
}
|
}
|
||||||
|
|||||||
+67
-25
@@ -1,45 +1,59 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.tile
|
package com.zaneschepke.wireguardautotunnel.service.tile
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.os.IBinder
|
||||||
import android.service.quicksettings.Tile
|
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.ServiceLifecycleDispatcher
|
import androidx.lifecycle.LifecycleRegistry
|
||||||
import androidx.lifecycle.lifecycleScope
|
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.repository.AppDataRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
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.CoroutineScope
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
private val dispatcher = ServiceLifecycleDispatcher(this)
|
@Inject
|
||||||
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
private var manualStartConfig: TunnelConfig? = null
|
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
|
||||||
|
|
||||||
override fun onStartListening() {
|
/* This works around an annoying unsolved frameworks bug some people are hitting. */
|
||||||
super.onStartListening()
|
override fun onBind(intent: Intent): IBinder? {
|
||||||
lifecycleScope.launch {
|
var ret: IBinder? = null
|
||||||
val settings = appDataRepository.settings.getSettings()
|
try {
|
||||||
when (settings.isAutoTunnelEnabled) {
|
ret = super.onBind(intent)
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
Timber.e("Failed to bind to AutoTunnelTile")
|
||||||
|
}
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||||
|
|
||||||
|
applicationScope.launch {
|
||||||
|
appDataRepository.settings.getSettingsFlow().collect {
|
||||||
|
kotlin.runCatching {
|
||||||
|
when (it.isAutoTunnelEnabled) {
|
||||||
true -> {
|
true -> {
|
||||||
if (settings.isAutoTunnelPaused) {
|
if (it.isAutoTunnelPaused) {
|
||||||
setInactive()
|
setInactive()
|
||||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.paused))
|
setTileDescription(this@AutoTunnelControlTile.getString(R.string.paused))
|
||||||
} else {
|
} else {
|
||||||
@@ -47,52 +61,79 @@ 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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onTileAdded() {
|
override fun onStopListening() {
|
||||||
super.onTileAdded()
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
|
||||||
onStartListening()
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartListening() {
|
||||||
|
super.onStartListening()
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onClick() {
|
override fun onClick() {
|
||||||
super.onClick()
|
super.onClick()
|
||||||
unlockAndRun {
|
unlockAndRun {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
try {
|
kotlin.runCatching {
|
||||||
appDataRepository.toggleWatcherServicePause()
|
val settings = appDataRepository.settings.getSettings()
|
||||||
onStartListening()
|
if (settings.isAutoTunnelPaused) {
|
||||||
} catch (e: Exception) {
|
return@launch appDataRepository.settings.save(
|
||||||
Timber.e(e.message)
|
settings.copy(
|
||||||
} finally {
|
isAutoTunnelPaused = false,
|
||||||
cancel()
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
appDataRepository.settings.save(
|
||||||
|
settings.copy(
|
||||||
|
isAutoTunnelPaused = true,
|
||||||
|
),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun setActive() {
|
private fun setActive() {
|
||||||
|
kotlin.runCatching {
|
||||||
qsTile.state = Tile.STATE_ACTIVE
|
qsTile.state = Tile.STATE_ACTIVE
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun setInactive() {
|
private fun setInactive() {
|
||||||
|
kotlin.runCatching {
|
||||||
qsTile.state = Tile.STATE_INACTIVE
|
qsTile.state = Tile.STATE_INACTIVE
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun setUnavailable() {
|
private fun setUnavailable() {
|
||||||
manualStartConfig = null
|
kotlin.runCatching {
|
||||||
qsTile.state = Tile.STATE_UNAVAILABLE
|
qsTile.state = Tile.STATE_UNAVAILABLE
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun setTileDescription(description: String) {
|
private fun setTileDescription(description: String) {
|
||||||
|
kotlin.runCatching {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
qsTile.subtitle = description
|
qsTile.subtitle = description
|
||||||
}
|
}
|
||||||
@@ -101,7 +142,8 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
|||||||
}
|
}
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override val lifecycle: Lifecycle
|
override val lifecycle: Lifecycle
|
||||||
get() = dispatcher.lifecycle
|
get() = lifecycleRegistry
|
||||||
}
|
}
|
||||||
|
|||||||
+56
-50
@@ -5,109 +5,104 @@ 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.LifecycleRegistry
|
||||||
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.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
import com.zaneschepke.wireguardautotunnel.util.extensions.stopTunnelBackground
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class TunnelControlTile : TileService(), LifecycleOwner {
|
class TunnelControlTile : TileService(), LifecycleOwner {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var vpnService: VpnService
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
private val dispatcher = ServiceLifecycleDispatcher(this)
|
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
|
||||||
|
|
||||||
private var manualStartConfig: TunnelConfig? = null
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
Timber.d("onCreate for tile service")
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStopListening() {
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onStartListening() {
|
override fun onStartListening() {
|
||||||
super.onStartListening()
|
super.onStartListening()
|
||||||
Timber.d("On start listening called")
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
when (vpnService.getState()) {
|
if (appDataRepository.tunnels.getAll().isEmpty()) return@launch setUnavailable()
|
||||||
TunnelState.UP -> {
|
updateTileState()
|
||||||
setActive()
|
|
||||||
setTileDescription(vpnService.name)
|
|
||||||
}
|
|
||||||
|
|
||||||
TunnelState.DOWN -> {
|
|
||||||
setInactive()
|
|
||||||
val config = appDataRepository.getStartTunnelConfig()?.also { config ->
|
|
||||||
manualStartConfig = config
|
|
||||||
} ?: appDataRepository.getPrimaryOrFirstTunnel()
|
|
||||||
config?.let {
|
|
||||||
setTileDescription(it.name)
|
|
||||||
} ?: setUnavailable()
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> setInactive()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onTileAdded() {
|
private suspend fun updateTileState() {
|
||||||
super.onTileAdded()
|
val lastActive = appDataRepository.getStartTunnelConfig()
|
||||||
onStartListening()
|
lastActive?.let {
|
||||||
|
updateTile(it)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onClick() {
|
override fun onClick() {
|
||||||
super.onClick()
|
super.onClick()
|
||||||
unlockAndRun {
|
unlockAndRun {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
try {
|
val context = this@TunnelControlTile
|
||||||
if (vpnService.getState() == TunnelState.UP) {
|
val lastActive = appDataRepository.getStartTunnelConfig()
|
||||||
serviceManager.stopVpnServiceForeground(
|
lastActive?.let { tunnel ->
|
||||||
this@TunnelControlTile,
|
if (tunnel.isActive) return@launch context.stopTunnelBackground(tunnel.id)
|
||||||
isManualStop = true,
|
context.startTunnelBackground(tunnel.id)
|
||||||
)
|
|
||||||
} else {
|
|
||||||
serviceManager.startVpnServiceForeground(
|
|
||||||
this@TunnelControlTile, manualStartConfig?.id, isManualStart = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e(e.message)
|
|
||||||
} finally {
|
|
||||||
cancel()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun setActive() {
|
private fun setActive() {
|
||||||
|
kotlin.runCatching {
|
||||||
qsTile.state = Tile.STATE_ACTIVE
|
qsTile.state = Tile.STATE_ACTIVE
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun setInactive() {
|
private fun setInactive() {
|
||||||
|
kotlin.runCatching {
|
||||||
qsTile.state = Tile.STATE_INACTIVE
|
qsTile.state = Tile.STATE_INACTIVE
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun setUnavailable() {
|
private fun setUnavailable() {
|
||||||
manualStartConfig = null
|
kotlin.runCatching {
|
||||||
qsTile.state = Tile.STATE_UNAVAILABLE
|
qsTile.state = Tile.STATE_UNAVAILABLE
|
||||||
|
setTileDescription("")
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun setTileDescription(description: String) {
|
private fun setTileDescription(description: String) {
|
||||||
|
kotlin.runCatching {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
qsTile.subtitle = description
|
qsTile.subtitle = description
|
||||||
}
|
}
|
||||||
@@ -116,7 +111,18 @@ class TunnelControlTile : TileService(), LifecycleOwner {
|
|||||||
}
|
}
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateTile(tunnelConfig: TunnelConfig?) {
|
||||||
|
kotlin.runCatching {
|
||||||
|
tunnelConfig?.let {
|
||||||
|
setTileDescription(it.name)
|
||||||
|
if (it.isActive) return setActive()
|
||||||
|
setInactive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override val lifecycle: Lifecycle
|
override val lifecycle: Lifecycle
|
||||||
get() = dispatcher.lifecycle
|
get() = lifecycleRegistry
|
||||||
}
|
}
|
||||||
|
|||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.IBinder
|
||||||
|
import androidx.lifecycle.LifecycleService
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import timber.log.Timber
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class AlwaysOnVpnService : LifecycleService() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent): IBinder? {
|
||||||
|
super.onBind(intent)
|
||||||
|
// We don't provide binding, so return null
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
if (intent == null || intent.component == null || intent.component!!.packageName != packageName) {
|
||||||
|
Timber.i("Always-on VPN requested started")
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val settings = appDataRepository.settings.getSettings()
|
||||||
|
if (settings.isAlwaysOnVpnEnabled) {
|
||||||
|
val tunnel = appDataRepository.getPrimaryOrFirstTunnel()
|
||||||
|
tunnel?.let {
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Timber.w("Always-on VPN is not enabled in app settings")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return super.onStartCommand(intent, flags, startId)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -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
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
||||||
|
|
||||||
|
import com.wireguard.android.backend.Tunnel
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
|
interface TunnelService : Tunnel, org.amnezia.awg.backend.Tunnel {
|
||||||
|
suspend fun startTunnel(tunnelConfig: TunnelConfig): Result<TunnelState>
|
||||||
|
|
||||||
|
suspend fun stopTunnel(tunnelConfig: TunnelConfig): Result<TunnelState>
|
||||||
|
|
||||||
|
val vpnState: StateFlow<VpnState>
|
||||||
|
|
||||||
|
suspend fun runningTunnelNames(): Set<String>
|
||||||
|
|
||||||
|
suspend fun getState(): TunnelState
|
||||||
|
}
|
||||||
@@ -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) {
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
|
||||||
|
|
||||||
import com.wireguard.android.backend.Tunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
|
|
||||||
interface VpnService : Tunnel, org.amnezia.awg.backend.Tunnel {
|
|
||||||
suspend fun startTunnel(tunnelConfig: TunnelConfig? = null): TunnelState
|
|
||||||
|
|
||||||
suspend fun stopTunnel()
|
|
||||||
|
|
||||||
val vpnState: StateFlow<VpnState>
|
|
||||||
|
|
||||||
fun getState(): TunnelState
|
|
||||||
}
|
|
||||||
@@ -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,
|
||||||
)
|
)
|
||||||
|
|||||||
+71
-101
@@ -1,7 +1,6 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
||||||
|
|
||||||
import com.wireguard.android.backend.Backend
|
import com.wireguard.android.backend.Backend
|
||||||
import com.wireguard.android.backend.BackendException
|
|
||||||
import com.wireguard.android.backend.Tunnel.State
|
import com.wireguard.android.backend.Tunnel.State
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
@@ -14,6 +13,7 @@ import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.AmneziaStat
|
|||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.WireGuardStatistics
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.WireGuardStatistics
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
@@ -32,96 +32,74 @@ import javax.inject.Provider
|
|||||||
class WireGuardTunnel
|
class WireGuardTunnel
|
||||||
@Inject
|
@Inject
|
||||||
constructor(
|
constructor(
|
||||||
private val userspaceAmneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
private val amneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
||||||
@Userspace private val userspaceBackend: Provider<Backend>,
|
@Userspace private val userspaceBackend: Provider<Backend>,
|
||||||
@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 {
|
) : TunnelService {
|
||||||
private val _vpnState = MutableStateFlow(VpnState())
|
private val _vpnState = MutableStateFlow(VpnState())
|
||||||
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
|
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
|
||||||
|
|
||||||
|
override suspend fun runningTunnelNames(): Set<String> {
|
||||||
|
return when (val backend = backend()) {
|
||||||
|
is Backend -> backend.runningTunnelNames
|
||||||
|
is org.amnezia.awg.backend.Backend -> backend.runningTunnelNames
|
||||||
|
else -> emptySet()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private var statsJob: Job? = null
|
private var statsJob: Job? = null
|
||||||
|
|
||||||
private var backendIsWgUserspace = true
|
private suspend fun setState(tunnelConfig: TunnelConfig, tunnelState: TunnelState): Result<TunnelState> {
|
||||||
|
return runCatching {
|
||||||
private var backendIsAmneziaUserspace = false
|
when (val backend = backend()) {
|
||||||
|
is Backend -> backend.setState(this, tunnelState.toWgState(), TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick)).let { TunnelState.from(it) }
|
||||||
init {
|
is org.amnezia.awg.backend.Backend -> backend.setState(this, tunnelState.toAmState(), TunnelConfig.configFromAmQuick(tunnelConfig.amQuick)).let {
|
||||||
applicationScope.launch(ioDispatcher) {
|
TunnelState.from(it)
|
||||||
appDataRepository.settings.getSettingsFlow().collect {
|
|
||||||
if (it.isKernelEnabled && (backendIsWgUserspace || backendIsAmneziaUserspace)) {
|
|
||||||
Timber.i("Setting kernel backend")
|
|
||||||
backendIsWgUserspace = false
|
|
||||||
backendIsAmneziaUserspace = false
|
|
||||||
} else if (!it.isKernelEnabled && !it.isAmneziaEnabled && !backendIsWgUserspace) {
|
|
||||||
Timber.i("Setting WireGuard userspace backend")
|
|
||||||
backendIsWgUserspace = true
|
|
||||||
backendIsAmneziaUserspace = false
|
|
||||||
} else if (it.isAmneziaEnabled && !backendIsAmneziaUserspace) {
|
|
||||||
Timber.i("Setting Amnezia userspace backend")
|
|
||||||
backendIsAmneziaUserspace = true
|
|
||||||
backendIsWgUserspace = false
|
|
||||||
}
|
}
|
||||||
|
else -> throw NotImplementedError()
|
||||||
}
|
}
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun setState(tunnelConfig: TunnelConfig?, tunnelState: TunnelState): TunnelState {
|
private suspend fun backend(): Any {
|
||||||
return if (backendIsAmneziaUserspace) {
|
val settings = appDataRepository.settings.getSettings()
|
||||||
Timber.i("Using Amnezia backend")
|
if (settings.isKernelEnabled) return kernelBackend.get()
|
||||||
val config = tunnelConfig?.let {
|
if (settings.isAmneziaEnabled) return amneziaBackend.get()
|
||||||
if (it.amQuick != "") TunnelConfig.configFromAmQuick(it.amQuick) else {
|
return userspaceBackend.get()
|
||||||
Timber.w("Using backwards compatible wg config, amnezia specific config not found.")
|
|
||||||
TunnelConfig.configFromAmQuick(it.wgQuick)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val state =
|
|
||||||
userspaceAmneziaBackend.get().setState(this, tunnelState.toAmState(), config)
|
|
||||||
TunnelState.from(state)
|
|
||||||
} else {
|
|
||||||
Timber.i("Using Wg backend")
|
|
||||||
val wgConfig = tunnelConfig?.let { TunnelConfig.configFromWgQuick(it.wgQuick) }
|
|
||||||
val state = backend().setState(
|
|
||||||
this,
|
|
||||||
tunnelState.toWgState(),
|
|
||||||
wgConfig,
|
|
||||||
)
|
|
||||||
TunnelState.from(state)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun startTunnel(tunnelConfig: TunnelConfig?): TunnelState {
|
override suspend fun startTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||||
return withContext(ioDispatcher) {
|
return withContext(ioDispatcher) {
|
||||||
try {
|
if (_vpnState.value.status == TunnelState.UP) vpnState.value.tunnelConfig?.let { stopTunnel(it) }
|
||||||
//TODO we need better error handling here
|
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = true))
|
||||||
// need to bubble up these errors to the UI
|
appDataRepository.appState.setLastActiveTunnelId(tunnelConfig.id)
|
||||||
val config = tunnelConfig ?: appDataRepository.getPrimaryOrFirstTunnel()
|
emitTunnelConfig(tunnelConfig)
|
||||||
if (config != null) {
|
setState(tunnelConfig, TunnelState.UP).onSuccess {
|
||||||
emitTunnelConfig(config)
|
emitTunnelState(it)
|
||||||
setState(config, TunnelState.UP)
|
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||||
} else throw Exception("No tunnels")
|
}.onFailure {
|
||||||
} catch (e: BackendException) {
|
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = false))
|
||||||
Timber.e("Failed to start tunnel with error: ${e.message}")
|
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||||
TunnelState.from(State.DOWN)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun backend(): Backend {
|
override suspend fun stopTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||||
return when {
|
return withContext(ioDispatcher) {
|
||||||
backendIsWgUserspace -> {
|
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = false))
|
||||||
userspaceBackend.get()
|
setState(tunnelConfig, TunnelState.DOWN).onSuccess {
|
||||||
}
|
emitTunnelState(it)
|
||||||
|
resetBackendStatistics()
|
||||||
!backendIsWgUserspace && !backendIsAmneziaUserspace -> {
|
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||||
kernelBackend.get()
|
}.onFailure {
|
||||||
}
|
Timber.e(it)
|
||||||
|
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = true))
|
||||||
else -> {
|
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||||
userspaceBackend.get()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,53 +120,41 @@ constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun emitTunnelConfig(tunnelConfig: TunnelConfig?) {
|
private fun emitTunnelConfig(tunnelConfig: TunnelConfig?) {
|
||||||
_vpnState.emit(
|
_vpnState.tryEmit(
|
||||||
_vpnState.value.copy(
|
_vpnState.value.copy(
|
||||||
tunnelConfig = tunnelConfig,
|
tunnelConfig = tunnelConfig,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun resetVpnState() {
|
private fun resetBackendStatistics() {
|
||||||
_vpnState.tryEmit(VpnState())
|
_vpnState.tryEmit(
|
||||||
}
|
_vpnState.value.copy(
|
||||||
|
statistics = null,
|
||||||
override suspend fun stopTunnel() {
|
),
|
||||||
withContext(ioDispatcher) {
|
|
||||||
try {
|
|
||||||
if (getState() == TunnelState.UP) {
|
|
||||||
val state = setState(null, TunnelState.DOWN)
|
|
||||||
resetVpnState()
|
|
||||||
emitTunnelState(state)
|
|
||||||
}
|
|
||||||
} catch (e: BackendException) {
|
|
||||||
Timber.e("Failed to stop wireguard tunnel with error: ${e.message}")
|
|
||||||
} catch (e: org.amnezia.awg.backend.BackendException) {
|
|
||||||
Timber.e("Failed to stop amnezia tunnel with error: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun getState(): TunnelState {
|
|
||||||
return if (backendIsAmneziaUserspace) TunnelState.from(
|
|
||||||
userspaceAmneziaBackend.get().getState(this),
|
|
||||||
)
|
)
|
||||||
else TunnelState.from(backend().getState(this))
|
}
|
||||||
|
|
||||||
|
override suspend fun getState(): TunnelState {
|
||||||
|
return when (val backend = backend()) {
|
||||||
|
is Backend -> backend.getState(this).let { TunnelState.from(it) }
|
||||||
|
is org.amnezia.awg.backend.Backend -> backend.getState(this).let { TunnelState.from(it) }
|
||||||
|
else -> TunnelState.DOWN
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleStateChange(state: TunnelState) {
|
private fun handleStateChange(state: TunnelState) {
|
||||||
emitTunnelState(state)
|
emitTunnelState(state)
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||||
if (state == TunnelState.UP) {
|
if (state == TunnelState.UP) {
|
||||||
statsJob = startTunnelStatisticsJob()
|
statsJob = startTunnelStatisticsJob()
|
||||||
}
|
}
|
||||||
@@ -202,15 +168,19 @@ constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun startTunnelStatisticsJob() = applicationScope.launch(ioDispatcher) {
|
private fun startTunnelStatisticsJob() = applicationScope.launch(ioDispatcher) {
|
||||||
|
val backend = backend()
|
||||||
while (true) {
|
while (true) {
|
||||||
if (backendIsAmneziaUserspace) {
|
when (backend) {
|
||||||
|
is Backend -> emitBackendStatistics(
|
||||||
|
WireGuardStatistics(backend.getStatistics(this@WireGuardTunnel)),
|
||||||
|
)
|
||||||
|
is org.amnezia.awg.backend.Backend -> {
|
||||||
emitBackendStatistics(
|
emitBackendStatistics(
|
||||||
AmneziaStatistics(
|
AmneziaStatistics(
|
||||||
userspaceAmneziaBackend.get().getStatistics(this@WireGuardTunnel),
|
backend.getStatistics(this@WireGuardTunnel),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
} else {
|
}
|
||||||
emitBackendStatistics(WireGuardStatistics(backend().getStatistics(this@WireGuardTunnel)))
|
|
||||||
}
|
}
|
||||||
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
|
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package com.zaneschepke.wireguardautotunnel.ui
|
|||||||
data class AppUiState(
|
data class AppUiState(
|
||||||
val snackbarMessage: String = "",
|
val snackbarMessage: String = "",
|
||||||
val snackbarMessageConsumed: Boolean = true,
|
val snackbarMessageConsumed: Boolean = true,
|
||||||
val vpnPermissionAccepted: Boolean = false,
|
|
||||||
val notificationPermissionAccepted: Boolean = false,
|
val notificationPermissionAccepted: Boolean = false,
|
||||||
val requestPermissions: Boolean = false
|
val requestPermissions: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,100 +1,29 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui
|
package com.zaneschepke.wireguardautotunnel.ui
|
||||||
|
|
||||||
import android.content.ActivityNotFoundException
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.net.Uri
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import com.wireguard.android.backend.GoBackend
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import timber.log.Timber
|
import kotlinx.coroutines.launch
|
||||||
|
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class AppViewModel
|
class AppViewModel
|
||||||
@Inject
|
@Inject
|
||||||
constructor() : ViewModel() {
|
constructor(
|
||||||
|
private val appDataRepository: AppDataRepository,
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance)
|
private val _appUiState =
|
||||||
|
MutableStateFlow(
|
||||||
private val _appUiState = MutableStateFlow(
|
AppUiState(),
|
||||||
AppUiState(
|
|
||||||
vpnPermissionAccepted = vpnIntent == null,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
val appUiState = _appUiState.asStateFlow()
|
val appUiState = _appUiState.asStateFlow()
|
||||||
|
|
||||||
|
|
||||||
fun isRequiredPermissionGranted(): Boolean {
|
|
||||||
val allAccepted =
|
|
||||||
(_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted)
|
|
||||||
if (!allAccepted) requestPermissions()
|
|
||||||
return allAccepted
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun requestPermissions() {
|
|
||||||
_appUiState.update {
|
|
||||||
it.copy(
|
|
||||||
requestPermissions = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun permissionsRequested() {
|
|
||||||
_appUiState.update {
|
|
||||||
it.copy(
|
|
||||||
requestPermissions = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun openWebPage(url: String, context: Context) {
|
|
||||||
try {
|
|
||||||
val webpage: Uri = Uri.parse(url)
|
|
||||||
val intent = Intent(Intent.ACTION_VIEW, webpage).apply {
|
|
||||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
||||||
}
|
|
||||||
context.startActivity(intent)
|
|
||||||
} catch (e: ActivityNotFoundException) {
|
|
||||||
Timber.e(e)
|
|
||||||
showSnackbarMessage(context.getString(R.string.no_browser_detected))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onVpnPermissionAccepted() {
|
|
||||||
_appUiState.update {
|
|
||||||
it.copy(
|
|
||||||
vpnPermissionAccepted = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun launchEmail(context: Context) {
|
|
||||||
try {
|
|
||||||
val intent =
|
|
||||||
Intent(Intent.ACTION_SENDTO).apply {
|
|
||||||
type = Constants.EMAIL_MIME_TYPE
|
|
||||||
putExtra(Intent.EXTRA_EMAIL, arrayOf(context.getString(R.string.my_email)))
|
|
||||||
putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.email_subject))
|
|
||||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
||||||
}
|
|
||||||
context.startActivity(
|
|
||||||
Intent.createChooser(intent, context.getString(R.string.email_chooser)).apply {
|
|
||||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
} catch (e: ActivityNotFoundException) {
|
|
||||||
Timber.e(e)
|
|
||||||
showSnackbarMessage(context.getString(R.string.no_email_detected))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun showSnackbarMessage(message: String) {
|
fun showSnackbarMessage(message: String) {
|
||||||
_appUiState.update {
|
_appUiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
@@ -113,11 +42,12 @@ constructor() : ViewModel() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setNotificationPermissionAccepted(accepted: Boolean) {
|
fun onPinLockDisabled() = viewModelScope.launch {
|
||||||
_appUiState.update {
|
PinManager.clearPin()
|
||||||
it.copy(
|
appDataRepository.appState.setPinLockEnabled(false)
|
||||||
notificationPermissionAccepted = accepted,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun onPinLockEnabled() = viewModelScope.launch {
|
||||||
|
appDataRepository.appState.setPinLockEnabled(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,9 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui
|
package com.zaneschepke.wireguardautotunnel.ui
|
||||||
|
|
||||||
import android.Manifest
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.SystemBarStyle
|
import androidx.activity.SystemBarStyle
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
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.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
@@ -38,11 +34,6 @@ import androidx.navigation.compose.composable
|
|||||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
import androidx.navigation.compose.rememberNavController
|
import androidx.navigation.compose.rememberNavController
|
||||||
import androidx.navigation.navArgument
|
import androidx.navigation.navArgument
|
||||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
|
||||||
import com.google.accompanist.permissions.isGranted
|
|
||||||
import com.google.accompanist.permissions.rememberPermissionState
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
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
|
||||||
@@ -65,7 +56,6 @@ import javax.inject.Inject
|
|||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class MainActivity : AppCompatActivity() {
|
class MainActivity : AppCompatActivity() {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appStateRepository: AppStateRepository
|
lateinit var appStateRepository: AppStateRepository
|
||||||
|
|
||||||
@@ -75,9 +65,6 @@ class MainActivity : AppCompatActivity() {
|
|||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
@OptIn(
|
|
||||||
ExperimentalPermissionsApi::class,
|
|
||||||
)
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
@@ -86,7 +73,6 @@ class MainActivity : AppCompatActivity() {
|
|||||||
enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb()))
|
enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb()))
|
||||||
|
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
|
||||||
val settings = settingsRepository.getSettings()
|
val settings = settingsRepository.getSettings()
|
||||||
if (settings.isAutoTunnelEnabled) {
|
if (settings.isAutoTunnelEnabled) {
|
||||||
serviceManager.startWatcherService(application.applicationContext)
|
serviceManager.startWatcherService(application.applicationContext)
|
||||||
@@ -99,23 +85,8 @@ class MainActivity : AppCompatActivity() {
|
|||||||
val navController = rememberNavController()
|
val navController = rememberNavController()
|
||||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||||
|
|
||||||
val notificationPermissionState =
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
|
|
||||||
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS) else null
|
|
||||||
|
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
|
|
||||||
val vpnActivityResultState =
|
|
||||||
rememberLauncherForActivityResult(
|
|
||||||
ActivityResultContracts.StartActivityForResult(),
|
|
||||||
onResult = {
|
|
||||||
val accepted = (it.resultCode == RESULT_OK)
|
|
||||||
if (accepted) {
|
|
||||||
appViewModel.onVpnPermissionAccepted()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
fun showSnackBarMessage(message: StringValue) {
|
fun showSnackBarMessage(message: StringValue) {
|
||||||
lifecycleScope.launch(Dispatchers.Main) {
|
lifecycleScope.launch(Dispatchers.Main) {
|
||||||
val result =
|
val result =
|
||||||
@@ -125,38 +96,15 @@ class MainActivity : AppCompatActivity() {
|
|||||||
)
|
)
|
||||||
when (result) {
|
when (result) {
|
||||||
SnackbarResult.ActionPerformed,
|
SnackbarResult.ActionPerformed,
|
||||||
SnackbarResult.Dismissed -> {
|
SnackbarResult.Dismissed,
|
||||||
|
-> {
|
||||||
snackbarHostState.currentSnackbarData?.dismiss()
|
snackbarHostState.currentSnackbarData?.dismiss()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(appUiState.requestPermissions) {
|
|
||||||
if (appUiState.requestPermissions) {
|
|
||||||
appViewModel.permissionsRequested()
|
|
||||||
if (notificationPermissionState != null && !notificationPermissionState.status.isGranted
|
|
||||||
) {
|
|
||||||
showSnackBarMessage(StringValue.StringResource(R.string.notification_permission_required))
|
|
||||||
return@LaunchedEffect notificationPermissionState.launchPermissionRequest()
|
|
||||||
}
|
|
||||||
if (!appUiState.vpnPermissionAccepted) {
|
|
||||||
return@LaunchedEffect appViewModel.vpnIntent?.let {
|
|
||||||
vpnActivityResultState.launch(
|
|
||||||
it,
|
|
||||||
)
|
|
||||||
}!!
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
WireguardAutoTunnelTheme {
|
WireguardAutoTunnelTheme {
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
appViewModel.setNotificationPermissionAccepted(
|
|
||||||
notificationPermissionState?.status?.isGranted ?: true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
LaunchedEffect(appUiState.snackbarMessageConsumed) {
|
LaunchedEffect(appUiState.snackbarMessageConsumed) {
|
||||||
if (!appUiState.snackbarMessageConsumed) {
|
if (!appUiState.snackbarMessageConsumed) {
|
||||||
showSnackBarMessage(StringValue.DynamicString(appUiState.snackbarMessage))
|
showSnackBarMessage(StringValue.DynamicString(appUiState.snackbarMessage))
|
||||||
@@ -179,8 +127,9 @@ 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 +151,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(),
|
||||||
) {
|
) {
|
||||||
@@ -229,7 +179,6 @@ class MainActivity : AppCompatActivity() {
|
|||||||
) {
|
) {
|
||||||
SupportScreen(
|
SupportScreen(
|
||||||
focusRequester = focusRequester,
|
focusRequester = focusRequester,
|
||||||
appViewModel = appViewModel,
|
|
||||||
navController = navController,
|
navController = navController,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -251,7 +200,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")
|
||||||
|
|||||||
@@ -11,22 +11,35 @@ import androidx.lifecycle.lifecycleScope
|
|||||||
import androidx.lifecycle.repeatOnLifecycle
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
import com.zaneschepke.logcatter.LocalLogCollector
|
import com.zaneschepke.logcatter.LocalLogCollector
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel.Companion.isRunningOnAndroidTv
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import timber.log.Timber
|
||||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
@SuppressLint("CustomSplashScreen")
|
@SuppressLint("CustomSplashScreen")
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class SplashActivity : ComponentActivity() {
|
class SplashActivity : ComponentActivity() {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appStateRepository: AppStateRepository
|
lateinit var appStateRepository: AppStateRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var localLogCollector: LocalLogCollector
|
lateinit var localLogCollector: LocalLogCollector
|
||||||
|
|
||||||
@@ -42,7 +55,7 @@ class SplashActivity : ComponentActivity() {
|
|||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
applicationScope.launch {
|
applicationScope.launch {
|
||||||
if (!isRunningOnAndroidTv()) localLogCollector.start()
|
if (!this@SplashActivity.isRunningOnTv()) localLogCollector.start()
|
||||||
}
|
}
|
||||||
|
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
@@ -51,8 +64,24 @@ class SplashActivity : ComponentActivity() {
|
|||||||
if (pinLockEnabled) {
|
if (pinLockEnabled) {
|
||||||
PinManager.initialize(WireGuardAutoTunnel.instance)
|
PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||||
}
|
}
|
||||||
|
// TODO eventually make this support multi-tunnel
|
||||||
|
Timber.d("Check for active tunnels")
|
||||||
|
val settings = appDataRepository.settings.getSettings()
|
||||||
|
if (settings.isKernelEnabled) {
|
||||||
|
// delay in case state change is underway while app is opened
|
||||||
|
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||||
|
val activeTunnels = appDataRepository.tunnels.getActive()
|
||||||
|
Timber.d("Kernel mode enabled, seeing if we need to start a tunnel")
|
||||||
|
activeTunnels.firstOrNull()?.let {
|
||||||
|
Timber.d("Trying to start active kernel tunnel: ${it.name}")
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
requestTunnelTileServiceStateUpdate()
|
||||||
|
requestAutoTunnelTileServiceUpdate()
|
||||||
|
|
||||||
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 +94,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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-7
@@ -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,
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ import androidx.compose.ui.unit.dp
|
|||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
||||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||||
import com.zaneschepke.wireguardautotunnel.util.toThreeDecimalPlaceString
|
import com.zaneschepke.wireguardautotunnel.util.extensions.toThreeDecimalPlaceString
|
||||||
|
|
||||||
@OptIn(ExperimentalFoundationApi::class)
|
@OptIn(ExperimentalFoundationApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -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,
|
||||||
@@ -73,7 +75,7 @@ fun RowListItem(
|
|||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||||
) {
|
) {
|
||||||
//TODO change these to string resources
|
// TODO change these to string resources
|
||||||
val handshakeEpoch = statistics.peerStats(it)!!.latestHandshakeEpochMillis
|
val handshakeEpoch = statistics.peerStats(it)!!.latestHandshakeEpochMillis
|
||||||
val peerTx = statistics.peerStats(it)!!.txBytes
|
val peerTx = statistics.peerStats(it)!!.txBytes
|
||||||
val peerRx = statistics.peerStats(it)!!.rxBytes
|
val peerRx = statistics.peerStats(it)!!.rxBytes
|
||||||
|
|||||||
+1
-1
@@ -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,
|
||||||
|
|||||||
+7
-11
@@ -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() },
|
||||||
|
)
|
||||||
|
}
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common.functions
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.activity.compose.ManagedActivityResultLauncher
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun rememberFileImportLauncherForResult(onNoFileExplorer: () -> Unit, onData: (data: Uri) -> Unit): ManagedActivityResultLauncher<String, Uri?> {
|
||||||
|
return rememberLauncherForActivityResult(
|
||||||
|
object : ActivityResultContracts.GetContent() {
|
||||||
|
override fun createIntent(context: Context, input: String): Intent {
|
||||||
|
val intent = super.createIntent(context, input)
|
||||||
|
|
||||||
|
/* AndroidTV now comes with stubs that do nothing but display a Toast less helpful than
|
||||||
|
* what we can do, so detect this and throw an exception that we can catch later. */
|
||||||
|
val activitiesToResolveIntent =
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
context.packageManager.queryIntentActivities(
|
||||||
|
intent,
|
||||||
|
PackageManager.ResolveInfoFlags.of(
|
||||||
|
PackageManager.MATCH_DEFAULT_ONLY.toLong(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
context.packageManager.queryIntentActivities(
|
||||||
|
intent,
|
||||||
|
PackageManager.MATCH_DEFAULT_ONLY,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
activitiesToResolveIntent.all {
|
||||||
|
val name = it.activityInfo.packageName
|
||||||
|
name.startsWith(Constants.GOOGLE_TV_EXPLORER_STUB) ||
|
||||||
|
name.startsWith(Constants.ANDROID_TV_EXPLORER_STUB)
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
onNoFileExplorer()
|
||||||
|
}
|
||||||
|
return intent
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) { data ->
|
||||||
|
if (data == null) return@rememberLauncherForActivityResult
|
||||||
|
onData(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
-4
@@ -13,6 +13,7 @@ import androidx.compose.runtime.setValue
|
|||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
|
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
||||||
|
|
||||||
@@ -23,8 +24,9 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
|
|||||||
var showBottomBar by rememberSaveable { mutableStateOf(true) }
|
var showBottomBar by rememberSaveable { mutableStateOf(true) }
|
||||||
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,12 +34,25 @@ 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(
|
||||||
selected = selected,
|
selected = selected,
|
||||||
onClick = { navController.navigate(item.route) },
|
onClick = {
|
||||||
|
navController.navigate(item.route) {
|
||||||
|
// Pop up to the start destination of the graph to
|
||||||
|
// avoid building up a large stack of destinations
|
||||||
|
// on the back stack as users select items
|
||||||
|
popUpTo(navController.graph.findStartDestination().id) {
|
||||||
|
saveState = true
|
||||||
|
}
|
||||||
|
// Avoid multiple copies of the same destination when
|
||||||
|
// reselecting the same item
|
||||||
|
launchSingleTop = true
|
||||||
|
}
|
||||||
|
},
|
||||||
label = {
|
label = {
|
||||||
Text(
|
Text(
|
||||||
text = item.name,
|
text = item.name,
|
||||||
@@ -53,4 +68,5 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-4
@@ -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()
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-10
@@ -19,23 +19,21 @@ import androidx.compose.runtime.CompositionLocalProvider
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.LocalLayoutDirection
|
import androidx.compose.ui.platform.LocalLayoutDirection
|
||||||
import androidx.compose.ui.unit.LayoutDirection
|
import androidx.compose.ui.unit.LayoutDirection
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun CustomSnackBar(
|
fun CustomSnackBar(message: String, isRtl: Boolean = true, containerColor: Color = MaterialTheme.colorScheme.surface) {
|
||||||
message: String,
|
val context = LocalContext.current
|
||||||
isRtl: Boolean = true,
|
|
||||||
containerColor: Color = MaterialTheme.colorScheme.surface
|
|
||||||
) {
|
|
||||||
Snackbar(
|
Snackbar(
|
||||||
containerColor = containerColor,
|
containerColor = containerColor,
|
||||||
modifier =
|
modifier =
|
||||||
Modifier
|
Modifier
|
||||||
.fillMaxWidth(
|
.fillMaxWidth(
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) 1 / 3f else 2 / 3f,
|
if (context.isRunningOnTv()) 1 / 3f else 2 / 3f,
|
||||||
)
|
)
|
||||||
.padding(bottom = 100.dp),
|
.padding(bottom = 100.dp),
|
||||||
shape = RoundedCornerShape(16.dp),
|
shape = RoundedCornerShape(16.dp),
|
||||||
@@ -44,7 +42,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,
|
||||||
@@ -54,10 +53,10 @@ fun CustomSnackBar(
|
|||||||
Icon(
|
Icon(
|
||||||
icon,
|
icon,
|
||||||
contentDescription = icon.name,
|
contentDescription = icon.name,
|
||||||
tint = Color.White,
|
tint = MaterialTheme.colorScheme.onSurface,
|
||||||
modifier = Modifier.padding(end = 10.dp),
|
modifier = Modifier.padding(end = 10.dp),
|
||||||
)
|
)
|
||||||
Text(message, color = Color.White, modifier = Modifier.padding(end = 5.dp))
|
Text(message, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.padding(end = 5.dp))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -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(),
|
||||||
|
|||||||
+2
-1
@@ -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),
|
||||||
|
|||||||
+126
-55
@@ -54,7 +54,6 @@ import androidx.compose.ui.Modifier
|
|||||||
import androidx.compose.ui.focus.FocusRequester
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
import androidx.compose.ui.focus.focusRequester
|
import androidx.compose.ui.focus.focusRequester
|
||||||
import androidx.compose.ui.focus.onFocusChanged
|
import androidx.compose.ui.focus.onFocusChanged
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.platform.ClipboardManager
|
import androidx.compose.ui.platform.ClipboardManager
|
||||||
import androidx.compose.ui.platform.LocalClipboardManager
|
import androidx.compose.ui.platform.LocalClipboardManager
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
@@ -71,7 +70,6 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
import com.google.accompanist.drawablepainter.DrawablePainter
|
import com.google.accompanist.drawablepainter.DrawablePainter
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
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.SearchBar
|
import com.zaneschepke.wireguardautotunnel.ui.common.SearchBar
|
||||||
@@ -81,7 +79,8 @@ import com.zaneschepke.wireguardautotunnel.ui.common.screen.LoadingScreen
|
|||||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
import com.zaneschepke.wireguardautotunnel.util.getMessage
|
import com.zaneschepke.wireguardautotunnel.util.extensions.getMessage
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||||
@@ -95,7 +94,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
|
||||||
@@ -109,7 +108,7 @@ fun ConfigScreen(
|
|||||||
LaunchedEffect(Unit) { viewModel.init(tunnelId) }
|
LaunchedEffect(Unit) { viewModel.init(tunnelId) }
|
||||||
|
|
||||||
LaunchedEffect(uiState.loading) {
|
LaunchedEffect(uiState.loading) {
|
||||||
if (!uiState.loading && WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (!uiState.loading && context.isRunningOnTv()) {
|
||||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||||
focusRequester.requestFocus()
|
focusRequester.requestFocus()
|
||||||
}
|
}
|
||||||
@@ -128,16 +127,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 +155,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 +185,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 +257,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 +287,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 +306,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,
|
||||||
@@ -315,13 +330,15 @@ fun ConfigScreen(
|
|||||||
FloatingActionButton(
|
FloatingActionButton(
|
||||||
modifier =
|
modifier =
|
||||||
Modifier.onFocusChanged {
|
Modifier.onFocusChanged {
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
fobColor = if (it.isFocused) hoverColor else secondaryColor
|
fobColor = if (it.isFocused) hoverColor else secondaryColor
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
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))
|
||||||
@@ -333,7 +350,7 @@ fun ConfigScreen(
|
|||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Rounded.Save,
|
imageVector = Icons.Rounded.Save,
|
||||||
contentDescription = stringResource(id = R.string.save_changes),
|
contentDescription = stringResource(id = R.string.save_changes),
|
||||||
tint = Color.DarkGray,
|
tint = MaterialTheme.colorScheme.background,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -354,19 +371,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 (context.isRunningOnTv()) {
|
||||||
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 +400,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 = {
|
||||||
@@ -403,7 +427,7 @@ fun ConfigScreen(
|
|||||||
Icon(
|
Icon(
|
||||||
Icons.Rounded.Refresh,
|
Icons.Rounded.Refresh,
|
||||||
stringResource(R.string.rotate_keys),
|
stringResource(R.string.rotate_keys),
|
||||||
tint = Color.White,
|
tint = MaterialTheme.colorScheme.onSurface,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -433,7 +457,7 @@ fun ConfigScreen(
|
|||||||
Icon(
|
Icon(
|
||||||
Icons.Rounded.ContentCopy,
|
Icons.Rounded.ContentCopy,
|
||||||
stringResource(R.string.copy_public_key),
|
stringResource(R.string.copy_public_key),
|
||||||
tint = Color.White,
|
tint = MaterialTheme.colorScheme.onSurface,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -450,7 +474,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 +495,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 +512,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 +533,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 +551,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 +570,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 +618,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 +636,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 +654,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 +685,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 (context.isRunningOnTv()) {
|
||||||
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 +794,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),
|
||||||
) {
|
) {
|
||||||
@@ -738,7 +809,7 @@ fun ConfigScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
Spacer(modifier = Modifier.weight(.17f))
|
Spacer(modifier = Modifier.weight(.17f))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -4,7 +4,7 @@ import com.wireguard.config.Config
|
|||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.InterfaceProxy
|
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.InterfaceProxy
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.PeerProxy
|
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.PeerProxy
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Packages
|
import com.zaneschepke.wireguardautotunnel.util.extensions.Packages
|
||||||
|
|
||||||
data class ConfigUiState(
|
data class ConfigUiState(
|
||||||
val proxyPeers: List<PeerProxy> = arrayListOf(PeerProxy()),
|
val proxyPeers: List<PeerProxy> = arrayListOf(PeerProxy()),
|
||||||
@@ -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 {
|
||||||
@@ -45,7 +45,7 @@ data class ConfigUiState(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun from(config: org.amnezia.awg.config.Config): ConfigUiState {
|
fun from(config: org.amnezia.awg.config.Config): ConfigUiState {
|
||||||
//TODO update with new values
|
// TODO update with new values
|
||||||
val proxyPeers = config.peers.map { PeerProxy.from(it) }
|
val proxyPeers = config.peers.map { PeerProxy.from(it) }
|
||||||
val proxyInterface = InterfaceProxy.from(config.`interface`)
|
val proxyInterface = InterfaceProxy.from(config.`interface`)
|
||||||
var include = true
|
var include = true
|
||||||
|
|||||||
+79
-36
@@ -23,8 +23,8 @@ import com.zaneschepke.wireguardautotunnel.util.Constants
|
|||||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||||
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
||||||
import com.zaneschepke.wireguardautotunnel.util.removeAt
|
import com.zaneschepke.wireguardautotunnel.util.extensions.removeAt
|
||||||
import com.zaneschepke.wireguardautotunnel.util.update
|
import com.zaneschepke.wireguardautotunnel.util.extensions.update
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
@@ -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,14 +137,11 @@ 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()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,14 +184,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 +211,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 +285,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(true)
|
||||||
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 +321,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 +422,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 +452,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 +511,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 +522,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 +533,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 +544,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 +555,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,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+63
-18
@@ -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 {
|
||||||
|
""
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -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,
|
||||||
}
|
}
|
||||||
|
|||||||
+113
-318
@@ -1,40 +1,26 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.Build
|
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.animation.fadeIn
|
import androidx.compose.animation.fadeIn
|
||||||
import androidx.compose.animation.fadeOut
|
import androidx.compose.animation.fadeOut
|
||||||
import androidx.compose.animation.slideInVertically
|
|
||||||
import androidx.compose.animation.slideOutVertically
|
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.focusGroup
|
|
||||||
import androidx.compose.foundation.focusable
|
import androidx.compose.foundation.focusable
|
||||||
import androidx.compose.foundation.gestures.ScrollableDefaults
|
import androidx.compose.foundation.gestures.ScrollableDefaults
|
||||||
import androidx.compose.foundation.gestures.detectTapGestures
|
import androidx.compose.foundation.gestures.detectTapGestures
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.overscroll
|
import androidx.compose.foundation.overscroll
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.foundation.text.ClickableText
|
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Create
|
|
||||||
import androidx.compose.material.icons.filled.FileOpen
|
|
||||||
import androidx.compose.material.icons.filled.QrCode
|
|
||||||
import androidx.compose.material.icons.rounded.Bolt
|
import androidx.compose.material.icons.rounded.Bolt
|
||||||
import androidx.compose.material.icons.rounded.Circle
|
import androidx.compose.material.icons.rounded.Circle
|
||||||
import androidx.compose.material.icons.rounded.CopyAll
|
import androidx.compose.material.icons.rounded.CopyAll
|
||||||
@@ -43,23 +29,15 @@ 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.FabPosition
|
import androidx.compose.material3.FabPosition
|
||||||
import androidx.compose.material3.HorizontalDivider
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.ModalBottomSheet
|
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Switch
|
import androidx.compose.material3.Switch
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.rememberModalBottomSheetState
|
|
||||||
import androidx.compose.material3.surfaceColorAtElevation
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.derivedStateOf
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
@@ -80,59 +58,64 @@ import androidx.compose.ui.input.pointer.pointerInput
|
|||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.SpanStyle
|
|
||||||
import androidx.compose.ui.text.buildAnnotatedString
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
import androidx.compose.ui.text.font.FontStyle
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.text.withStyle
|
|
||||||
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
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
import com.iamageo.multifablibrary.FabIcon
|
|
||||||
import com.iamageo.multifablibrary.FabOption
|
|
||||||
import com.iamageo.multifablibrary.MultiFabItem
|
|
||||||
import com.iamageo.multifablibrary.MultiFloatingActionButton
|
|
||||||
import com.journeyapps.barcodescanner.ScanContract
|
import com.journeyapps.barcodescanner.ScanContract
|
||||||
import com.journeyapps.barcodescanner.ScanOptions
|
import com.journeyapps.barcodescanner.ScanOptions
|
||||||
|
import com.wireguard.android.backend.GoBackend
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
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.functions.rememberFileImportLauncherForResult
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.screen.LoadingScreen
|
import com.zaneschepke.wireguardautotunnel.ui.common.screen.LoadingScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.GettingStartedLabel
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.ScrollDismissMultiFab
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.TunnelImportSheet
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.VpnDeniedDialog
|
||||||
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
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
import com.zaneschepke.wireguardautotunnel.util.getMessage
|
import com.zaneschepke.wireguardautotunnel.util.extensions.getMessage
|
||||||
import com.zaneschepke.wireguardautotunnel.util.handshakeStatus
|
import com.zaneschepke.wireguardautotunnel.util.extensions.handshakeStatus
|
||||||
import com.zaneschepke.wireguardautotunnel.util.mapPeerStats
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.mapPeerStats
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.openWebUrl
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import timber.log.Timber
|
||||||
|
|
||||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
|
@OptIn(ExperimentalFoundationApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun MainScreen(
|
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
|
||||||
val isVisible = rememberSaveable { mutableStateOf(true) }
|
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
val sheetState = rememberModalBottomSheetState()
|
|
||||||
var showBottomSheet by remember { mutableStateOf(false) }
|
var showBottomSheet by remember { mutableStateOf(false) }
|
||||||
var configType by remember { mutableStateOf(ConfigType.WIREGUARD) }
|
var configType by remember { mutableStateOf(ConfigType.WIREGUARD) }
|
||||||
|
var showVpnPermissionDialog by remember { mutableStateOf(false) }
|
||||||
|
val isVisible = rememberSaveable { mutableStateOf(true) }
|
||||||
|
var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) }
|
||||||
|
var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) }
|
||||||
|
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
// Nested scroll for control FAB
|
val nestedScrollConnection =
|
||||||
val nestedScrollConnection = remember {
|
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
|
||||||
@@ -143,66 +126,43 @@ fun MainScreen(
|
|||||||
if (available.y > 1) {
|
if (available.y > 1) {
|
||||||
isVisible.value = true
|
isVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
return Offset.Zero
|
return Offset.Zero
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val vpnActivityResultState =
|
||||||
var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) }
|
rememberLauncherForActivityResult(
|
||||||
var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) }
|
ActivityResultContracts.StartActivityForResult(),
|
||||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
onResult = {
|
||||||
|
val accepted = (it.resultCode == RESULT_OK)
|
||||||
|
if (accepted) {
|
||||||
|
Timber.d("VPN permission granted")
|
||||||
|
} else {
|
||||||
|
showVpnPermissionDialog = true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||||
focusRequester.requestFocus()
|
focusRequester.requestFocus()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val tunnelFileImportResultLauncher =
|
val tunnelFileImportResultLauncher = rememberFileImportLauncherForResult(onNoFileExplorer = {
|
||||||
rememberLauncherForActivityResult(
|
appViewModel.showSnackbarMessage(
|
||||||
object : ActivityResultContracts.GetContent() {
|
context.getString(R.string.error_no_file_explorer),
|
||||||
override fun createIntent(context: Context, input: String): Intent {
|
|
||||||
val intent = super.createIntent(context, input)
|
|
||||||
|
|
||||||
/* AndroidTV now comes with stubs that do nothing but display a Toast less helpful than
|
|
||||||
* what we can do, so detect this and throw an exception that we can catch later. */
|
|
||||||
val activitiesToResolveIntent =
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
||||||
context.packageManager.queryIntentActivities(
|
|
||||||
intent,
|
|
||||||
PackageManager.ResolveInfoFlags.of(
|
|
||||||
PackageManager.MATCH_DEFAULT_ONLY.toLong(),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
} else {
|
}, onData = { data ->
|
||||||
context.packageManager.queryIntentActivities(
|
|
||||||
intent,
|
|
||||||
PackageManager.MATCH_DEFAULT_ONLY,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
activitiesToResolveIntent.all {
|
|
||||||
val name = it.activityInfo.packageName
|
|
||||||
name.startsWith(Constants.GOOGLE_TV_EXPLORER_STUB) ||
|
|
||||||
name.startsWith(Constants.ANDROID_TV_EXPLORER_STUB)
|
|
||||||
}
|
|
||||||
) {
|
|
||||||
appViewModel.showSnackbarMessage(context.getString(R.string.error_no_file_explorer))
|
|
||||||
}
|
|
||||||
return intent
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) { data ->
|
|
||||||
if (data == null) return@rememberLauncherForActivityResult
|
|
||||||
scope.launch {
|
scope.launch {
|
||||||
viewModel.onTunnelFileSelected(data, configType, context).onFailure {
|
viewModel.onTunnelFileSelected(data, configType, context).onFailure {
|
||||||
appViewModel.showSnackbarMessage(it.getMessage(context))
|
appViewModel.showSnackbarMessage(it.getMessage(context))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
|
|
||||||
val scanLauncher =
|
val scanLauncher =
|
||||||
rememberLauncherForActivityResult(
|
rememberLauncherForActivityResult(
|
||||||
contract = ScanContract(),
|
contract = ScanContract(),
|
||||||
@@ -217,34 +177,32 @@ fun MainScreen(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
AnimatedVisibility(showDeleteTunnelAlertDialog) {
|
VpnDeniedDialog(showVpnPermissionDialog, onDismiss = { showVpnPermissionDialog = false })
|
||||||
AlertDialog(
|
|
||||||
onDismissRequest = { showDeleteTunnelAlertDialog = false },
|
if (showDeleteTunnelAlertDialog) {
|
||||||
confirmButton = {
|
InfoDialog(
|
||||||
TextButton(
|
onDismiss = { showDeleteTunnelAlertDialog = false },
|
||||||
onClick = {
|
onAttest = {
|
||||||
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 (checked) {
|
||||||
if (checked) viewModel.onTunnelStart(tunnel, context) else viewModel.onTunnelStop(
|
if (uiState.settings.isKernelEnabled) {
|
||||||
context,
|
context.startTunnelBackground(tunnel.id)
|
||||||
|
} else {
|
||||||
|
viewModel.onTunnelStart(tunnel)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
viewModel.onTunnelStop(
|
||||||
|
tunnel,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -274,159 +232,26 @@ fun MainScreen(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
},
|
},
|
||||||
floatingActionButtonPosition = FabPosition.End,
|
floatingActionButtonPosition = FabPosition.End,
|
||||||
floatingActionButton = {
|
floatingActionButton = {
|
||||||
AnimatedVisibility(
|
ScrollDismissMultiFab(R.drawable.add, focusRequester, isVisible = isVisible.value, onFabItemClicked = {
|
||||||
visible = isVisible.value,
|
|
||||||
enter = slideInVertically(initialOffsetY = { it * 2 }),
|
|
||||||
exit = slideOutVertically(targetOffsetY = { it * 2 }),
|
|
||||||
modifier = Modifier
|
|
||||||
.focusRequester(focusRequester)
|
|
||||||
.focusGroup(),
|
|
||||||
) {
|
|
||||||
val secondaryColor = MaterialTheme.colorScheme.secondary
|
|
||||||
val tvFobColor = MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp)
|
|
||||||
val fobColor =
|
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) tvFobColor else secondaryColor
|
|
||||||
val fobIconColor =
|
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) Color.White else MaterialTheme.colorScheme.background
|
|
||||||
MultiFloatingActionButton(
|
|
||||||
fabIcon = FabIcon(
|
|
||||||
iconRes = R.drawable.add,
|
|
||||||
iconResAfterRotate = R.drawable.close,
|
|
||||||
iconRotate = 180f,
|
|
||||||
),
|
|
||||||
fabOption = FabOption(
|
|
||||||
iconTint = fobIconColor,
|
|
||||||
backgroundTint = fobColor,
|
|
||||||
),
|
|
||||||
itemsMultiFab = listOf(
|
|
||||||
MultiFabItem(
|
|
||||||
label = {
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.amnezia),
|
|
||||||
color = Color.White,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(end = 10.dp),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
modifier = Modifier
|
|
||||||
.size(40.dp),
|
|
||||||
icon = R.drawable.add,
|
|
||||||
value = ConfigType.AMNEZIA.name,
|
|
||||||
miniFabOption = FabOption(
|
|
||||||
backgroundTint = fobColor,
|
|
||||||
fobIconColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
MultiFabItem(
|
|
||||||
label = {
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.wireguard),
|
|
||||||
color = Color.White,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(end = 10.dp),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
icon = R.drawable.add,
|
|
||||||
value = ConfigType.WIREGUARD.name,
|
|
||||||
miniFabOption = FabOption(
|
|
||||||
backgroundTint = fobColor,
|
|
||||||
fobIconColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
onFabItemClicked = {
|
|
||||||
showBottomSheet = true
|
showBottomSheet = true
|
||||||
configType = ConfigType.valueOf(it.value)
|
configType = ConfigType.valueOf(it.value)
|
||||||
},
|
})
|
||||||
shape = RoundedCornerShape(16.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
if (showBottomSheet) {
|
TunnelImportSheet(
|
||||||
ModalBottomSheet(
|
showBottomSheet,
|
||||||
onDismissRequest = {
|
onDismiss = { showBottomSheet = false },
|
||||||
showBottomSheet = false
|
onFileClick = { tunnelFileImportResultLauncher.launch(Constants.ALLOWED_FILE_TYPES) },
|
||||||
|
onQrClick = { launchQrScanner() },
|
||||||
},
|
onManualImportClick = {
|
||||||
sheetState = sheetState,
|
|
||||||
) {
|
|
||||||
// Sheet content
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.clickable {
|
|
||||||
showBottomSheet = false
|
|
||||||
tunnelFileImportResultLauncher.launch(Constants.ALLOWED_FILE_TYPES)
|
|
||||||
}
|
|
||||||
.padding(10.dp),
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
Icons.Filled.FileOpen,
|
|
||||||
contentDescription = stringResource(id = R.string.open_file),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.add_tunnels_text),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
|
||||||
HorizontalDivider()
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.clickable {
|
|
||||||
scope.launch {
|
|
||||||
showBottomSheet = false
|
|
||||||
launchQrScanner()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding(10.dp),
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
Icons.Filled.QrCode,
|
|
||||||
contentDescription = stringResource(id = R.string.qr_scan),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.add_from_qr),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
HorizontalDivider()
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.clickable {
|
|
||||||
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),
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
Icons.Filled.Create,
|
|
||||||
contentDescription = stringResource(id = R.string.create_import),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
)
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.create_import),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
horizontalAlignment = Alignment.Start,
|
horizontalAlignment = Alignment.Start,
|
||||||
verticalArrangement = Arrangement.Top,
|
verticalArrangement = Arrangement.Top,
|
||||||
@@ -442,75 +267,46 @@ fun MainScreen(
|
|||||||
) {
|
) {
|
||||||
item {
|
item {
|
||||||
AnimatedVisibility(
|
AnimatedVisibility(
|
||||||
uiState.tunnels.isEmpty(), exit = fadeOut(), enter = fadeIn(),
|
uiState.tunnels.isEmpty(),
|
||||||
|
exit = fadeOut(),
|
||||||
|
enter = fadeIn(),
|
||||||
) {
|
) {
|
||||||
Column(
|
GettingStartedLabel(onClick = { context.openWebUrl(it) })
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
verticalArrangement = Arrangement.Center,
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(top = 100.dp)
|
|
||||||
.fillMaxSize(),
|
|
||||||
) {
|
|
||||||
val gettingStarted = buildAnnotatedString {
|
|
||||||
append(stringResource(id = R.string.see_the))
|
|
||||||
append(" ")
|
|
||||||
pushStringAnnotation(
|
|
||||||
tag = "gettingStarted",
|
|
||||||
annotation = stringResource(id = R.string.getting_started_url),
|
|
||||||
)
|
|
||||||
withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.primary)) {
|
|
||||||
append(stringResource(id = R.string.getting_started_guide))
|
|
||||||
}
|
|
||||||
pop()
|
|
||||||
append(" ")
|
|
||||||
append(stringResource(R.string.unsure_how))
|
|
||||||
append(".")
|
|
||||||
}
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.no_tunnels),
|
|
||||||
fontStyle = FontStyle.Italic,
|
|
||||||
)
|
|
||||||
ClickableText(
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(vertical = 10.dp, horizontal = 24.dp),
|
|
||||||
text = gettingStarted,
|
|
||||||
style = MaterialTheme.typography.bodyMedium.copy(
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
),
|
|
||||||
) {
|
|
||||||
gettingStarted.getStringAnnotations(tag = "gettingStarted", it, it)
|
|
||||||
.firstOrNull()?.let { annotation ->
|
|
||||||
appViewModel.openWebPage(annotation.item, context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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,
|
||||||
@@ -532,14 +328,14 @@ fun MainScreen(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
onClick = {
|
onClick = {
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
itemFocusRequester.requestFocus()
|
itemFocusRequester.requestFocus()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onHold = {},
|
onHold = {},
|
||||||
expanded = false,
|
expanded = false,
|
||||||
statistics = null,
|
statistics = null,
|
||||||
focusRequester = focusRequester
|
focusRequester = focusRequester,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -547,10 +343,11 @@ fun MainScreen(
|
|||||||
uiState.tunnels,
|
uiState.tunnels,
|
||||||
key = { tunnel -> tunnel.id },
|
key = { tunnel -> tunnel.id },
|
||||||
) { tunnel ->
|
) { tunnel ->
|
||||||
|
val isActive = uiState.tunnels.any { it.id == tunnel.id && it.isActive }
|
||||||
val leadingIconColor =
|
val leadingIconColor =
|
||||||
(if (
|
(
|
||||||
uiState.vpnState.tunnelConfig?.name == tunnel.name &&
|
if (
|
||||||
uiState.vpnState.status == TunnelState.UP
|
isActive
|
||||||
) {
|
) {
|
||||||
uiState.vpnState.statistics
|
uiState.vpnState.statistics
|
||||||
?.mapPeerStats()
|
?.mapPeerStats()
|
||||||
@@ -569,13 +366,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 +385,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,17 +400,18 @@ 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)
|
||||||
selectedTunnel = tunnel
|
selectedTunnel = tunnel
|
||||||
},
|
},
|
||||||
onClick = {
|
onClick = {
|
||||||
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (!context.isRunningOnTv()) {
|
||||||
if (
|
if (
|
||||||
uiState.vpnState.status == TunnelState.UP &&
|
isActive
|
||||||
(uiState.vpnState.tunnelConfig?.name == tunnel.name)
|
|
||||||
) {
|
) {
|
||||||
expanded.value = !expanded.value
|
expanded.value = !expanded.value
|
||||||
}
|
}
|
||||||
@@ -625,7 +426,7 @@ fun MainScreen(
|
|||||||
rowButton = {
|
rowButton = {
|
||||||
if (
|
if (
|
||||||
tunnel.id == selectedTunnel?.id &&
|
tunnel.id == selectedTunnel?.id &&
|
||||||
!WireGuardAutoTunnel.isRunningOnAndroidTv()
|
!context.isRunningOnTv()
|
||||||
) {
|
) {
|
||||||
Row {
|
Row {
|
||||||
IconButton(
|
IconButton(
|
||||||
@@ -666,25 +467,19 @@ fun MainScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
val checked by remember {
|
if (!isActive) expanded.value = false
|
||||||
derivedStateOf {
|
|
||||||
(uiState.vpnState.status == TunnelState.UP &&
|
|
||||||
tunnel.name == uiState.vpnState.tunnelConfig?.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!checked) expanded.value = false
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun TunnelSwitch() =
|
fun TunnelSwitch() = Switch(
|
||||||
Switch(
|
|
||||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||||
checked = checked,
|
checked = isActive,
|
||||||
onCheckedChange = { checked ->
|
onCheckedChange = { checked ->
|
||||||
if (!checked) expanded.value = false
|
if (!checked) expanded.value = false
|
||||||
|
val intent = if (uiState.settings.isKernelEnabled) null else GoBackend.VpnService.prepare(context)
|
||||||
|
if (intent != null) return@Switch vpnActivityResultState.launch(intent)
|
||||||
onTunnelToggle(checked, tunnel)
|
onTunnelToggle(checked, tunnel)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
Row {
|
Row {
|
||||||
IconButton(
|
IconButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
|
|||||||
+2
-2
@@ -2,11 +2,11 @@ package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
|||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||||
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
|
|
||||||
data class MainUiState(
|
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,
|
||||||
)
|
)
|
||||||
|
|||||||
+55
-67
@@ -7,17 +7,16 @@ import android.provider.OpenableColumns
|
|||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.wireguard.config.Config
|
import com.wireguard.config.Config
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
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.IoDispatcher
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||||
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
||||||
import com.zaneschepke.wireguardautotunnel.util.toWgQuickString
|
import com.zaneschepke.wireguardautotunnel.util.extensions.toWgQuickString
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
@@ -36,15 +35,14 @@ class MainViewModel
|
|||||||
constructor(
|
constructor(
|
||||||
private val appDataRepository: AppDataRepository,
|
private val appDataRepository: AppDataRepository,
|
||||||
private val serviceManager: ServiceManager,
|
private val serviceManager: ServiceManager,
|
||||||
val vpnService: VpnService,
|
val tunnelService: TunnelService,
|
||||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
val uiState =
|
val uiState =
|
||||||
combine(
|
combine(
|
||||||
appDataRepository.settings.getSettingsFlow(),
|
appDataRepository.settings.getSettingsFlow(),
|
||||||
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
||||||
vpnService.vpnState,
|
tunnelService.vpnState,
|
||||||
) { settings, tunnels, vpnState ->
|
) { settings, tunnels, vpnState ->
|
||||||
MainUiState(settings, tunnels, vpnState, false)
|
MainUiState(settings, tunnels, vpnState, false)
|
||||||
}
|
}
|
||||||
@@ -67,7 +65,6 @@ constructor(
|
|||||||
resetTunnelSetting(settings)
|
resetTunnelSetting(settings)
|
||||||
}
|
}
|
||||||
appDataRepository.tunnels.delete(tunnel)
|
appDataRepository.tunnels.delete(tunnel)
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,21 +77,14 @@ constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onTunnelStart(tunnelConfig: TunnelConfig, context: Context) =
|
fun onTunnelStart(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||||
viewModelScope.launch {
|
Timber.i("Starting tunnel ${tunnelConfig.name}")
|
||||||
Timber.d("On start called!")
|
tunnelService.startTunnel(tunnelConfig)
|
||||||
serviceManager.startVpnService(
|
|
||||||
context,
|
|
||||||
tunnelConfig.id,
|
|
||||||
isManualStart = true,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun onTunnelStop(tunnel: TunnelConfig) = viewModelScope.launch {
|
||||||
fun onTunnelStop(context: Context) =
|
|
||||||
viewModelScope.launch {
|
|
||||||
Timber.i("Stopping active tunnel")
|
Timber.i("Stopping active tunnel")
|
||||||
serviceManager.stopVpnService(context, isManualStop = true)
|
tunnelService.stopTunnel(tunnel)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun validateConfigString(config: String, configType: ConfigType) {
|
private fun validateConfigString(config: String, configType: ConfigType) {
|
||||||
@@ -139,16 +129,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 +165,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)
|
||||||
@@ -187,7 +184,7 @@ constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
ConfigType.WIREGUARD -> {
|
ConfigType.WIREGUARD -> {
|
||||||
Config.parse(it).toWgQuickString()
|
Config.parse(it).toWgQuickString(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -207,11 +204,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 +213,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 +232,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,13 +248,16 @@ 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()
|
||||||
}
|
}
|
||||||
|
|
||||||
ConfigType.WIREGUARD -> {
|
ConfigType.WIREGUARD -> {
|
||||||
Config.parse(zip).toWgQuickString()
|
Config.parse(zip).toWgQuickString(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
addTunnel(
|
addTunnel(
|
||||||
@@ -285,12 +278,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) {
|
||||||
@@ -307,21 +295,19 @@ constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun addTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
private fun addTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||||
val firstTunnel = appDataRepository.tunnels.count() == 0
|
|
||||||
saveTunnel(tunnelConfig)
|
saveTunnel(tunnelConfig)
|
||||||
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()
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
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()
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun saveTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
private fun saveTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||||
@@ -349,8 +335,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 +364,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 {
|
||||||
|
|||||||
+71
@@ -0,0 +1,71 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.text.ClickableText
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.SpanStyle
|
||||||
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
|
import androidx.compose.ui.text.font.FontStyle
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.text.withStyle
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun GettingStartedLabel(onClick: (url: String) -> Unit) {
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.padding(top = 100.dp)
|
||||||
|
.fillMaxSize(),
|
||||||
|
) {
|
||||||
|
val gettingStarted =
|
||||||
|
buildAnnotatedString {
|
||||||
|
append(stringResource(id = R.string.see_the))
|
||||||
|
append(" ")
|
||||||
|
pushStringAnnotation(
|
||||||
|
tag = "gettingStarted",
|
||||||
|
annotation = stringResource(id = R.string.getting_started_url),
|
||||||
|
)
|
||||||
|
withStyle(
|
||||||
|
style = SpanStyle(color = MaterialTheme.colorScheme.primary),
|
||||||
|
) {
|
||||||
|
append(stringResource(id = R.string.getting_started_guide))
|
||||||
|
}
|
||||||
|
pop()
|
||||||
|
append(" ")
|
||||||
|
append(stringResource(R.string.unsure_how))
|
||||||
|
append(".")
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.no_tunnels),
|
||||||
|
fontStyle = FontStyle.Italic,
|
||||||
|
)
|
||||||
|
ClickableText(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.padding(vertical = 10.dp, horizontal = 24.dp),
|
||||||
|
text = gettingStarted,
|
||||||
|
style =
|
||||||
|
MaterialTheme.typography.bodyMedium.copy(
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
gettingStarted.getStringAnnotations(tag = "gettingStarted", it, it)
|
||||||
|
.firstOrNull()?.let { annotation ->
|
||||||
|
onClick(annotation.item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||||
|
|
||||||
|
import androidx.annotation.DrawableRes
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.slideInVertically
|
||||||
|
import androidx.compose.animation.slideOutVertically
|
||||||
|
import androidx.compose.foundation.focusGroup
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.iamageo.multifablibrary.FabIcon
|
||||||
|
import com.iamageo.multifablibrary.FabOption
|
||||||
|
import com.iamageo.multifablibrary.MultiFabItem
|
||||||
|
import com.iamageo.multifablibrary.MultiFloatingActionButton
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ScrollDismissMultiFab(
|
||||||
|
@DrawableRes res: Int,
|
||||||
|
focusRequester: FocusRequester,
|
||||||
|
isVisible: Boolean,
|
||||||
|
onFabItemClicked: (fabItem: MultiFabItem) -> Unit,
|
||||||
|
) {
|
||||||
|
// Nested scroll for control FAB
|
||||||
|
|
||||||
|
val context = LocalContext.current
|
||||||
|
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = isVisible,
|
||||||
|
enter = slideInVertically(initialOffsetY = { it * 2 }),
|
||||||
|
exit = slideOutVertically(targetOffsetY = { it * 2 }),
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.focusRequester(focusRequester)
|
||||||
|
.focusGroup(),
|
||||||
|
) {
|
||||||
|
val fobColor = MaterialTheme.colorScheme.secondary
|
||||||
|
val fobIconColor = MaterialTheme.colorScheme.background
|
||||||
|
MultiFloatingActionButton(
|
||||||
|
fabIcon =
|
||||||
|
FabIcon(
|
||||||
|
iconRes = res,
|
||||||
|
iconResAfterRotate = R.drawable.close,
|
||||||
|
iconRotate = 180f,
|
||||||
|
),
|
||||||
|
fabOption =
|
||||||
|
FabOption(
|
||||||
|
iconTint = fobIconColor,
|
||||||
|
backgroundTint = fobColor,
|
||||||
|
),
|
||||||
|
itemsMultiFab =
|
||||||
|
listOf(
|
||||||
|
MultiFabItem(
|
||||||
|
label = {
|
||||||
|
Text(
|
||||||
|
stringResource(id = R.string.amnezia),
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
modifier = Modifier.padding(end = 10.dp),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.size(40.dp),
|
||||||
|
icon = res,
|
||||||
|
value = ConfigType.AMNEZIA.name,
|
||||||
|
miniFabOption =
|
||||||
|
FabOption(
|
||||||
|
backgroundTint = fobColor,
|
||||||
|
fobIconColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
MultiFabItem(
|
||||||
|
label = {
|
||||||
|
Text(
|
||||||
|
stringResource(id = R.string.wireguard),
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
modifier = Modifier.padding(end = 10.dp),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
icon = res,
|
||||||
|
value = ConfigType.WIREGUARD.name,
|
||||||
|
miniFabOption =
|
||||||
|
FabOption(
|
||||||
|
backgroundTint = fobColor,
|
||||||
|
fobIconColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
onFabItemClicked = {
|
||||||
|
onFabItemClicked(it)
|
||||||
|
},
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+104
@@ -0,0 +1,104 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Create
|
||||||
|
import androidx.compose.material.icons.filled.FileOpen
|
||||||
|
import androidx.compose.material.icons.filled.QrCode
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.ModalBottomSheet
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.rememberModalBottomSheetState
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun TunnelImportSheet(show: Boolean, onDismiss: () -> Unit, onFileClick: () -> Unit, onQrClick: () -> Unit, onManualImportClick: () -> Unit) {
|
||||||
|
val sheetState = rememberModalBottomSheetState()
|
||||||
|
|
||||||
|
val context = LocalContext.current
|
||||||
|
if (show) {
|
||||||
|
ModalBottomSheet(
|
||||||
|
onDismissRequest = {
|
||||||
|
onDismiss()
|
||||||
|
},
|
||||||
|
sheetState = sheetState,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable {
|
||||||
|
onDismiss()
|
||||||
|
onFileClick()
|
||||||
|
}
|
||||||
|
.padding(10.dp),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.FileOpen,
|
||||||
|
contentDescription = stringResource(id = R.string.open_file),
|
||||||
|
modifier = Modifier.padding(10.dp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(id = R.string.add_tunnels_text),
|
||||||
|
modifier = Modifier.padding(10.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!context.isRunningOnTv()) {
|
||||||
|
HorizontalDivider()
|
||||||
|
Row(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable {
|
||||||
|
onDismiss()
|
||||||
|
onQrClick()
|
||||||
|
}
|
||||||
|
.padding(10.dp),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.QrCode,
|
||||||
|
contentDescription = stringResource(id = R.string.qr_scan),
|
||||||
|
modifier = Modifier.padding(10.dp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(id = R.string.add_from_qr),
|
||||||
|
modifier = Modifier.padding(10.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
Row(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable {
|
||||||
|
onDismiss()
|
||||||
|
onManualImportClick()
|
||||||
|
}
|
||||||
|
.padding(10.dp),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Create,
|
||||||
|
contentDescription = stringResource(id = R.string.create_import),
|
||||||
|
modifier = Modifier.padding(10.dp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(id = R.string.create_import),
|
||||||
|
modifier = Modifier.padding(10.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.text.ClickableText
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.SpanStyle
|
||||||
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
|
import androidx.compose.ui.text.withStyle
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.InfoDialog
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.launchVpnSettings
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun VpnDeniedDialog(show: Boolean, onDismiss: () -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
if (show) {
|
||||||
|
val alwaysOnDescription = buildAnnotatedString {
|
||||||
|
append(stringResource(R.string.always_on_message))
|
||||||
|
append(" ")
|
||||||
|
pushStringAnnotation(tag = "vpnSettings", annotation = "")
|
||||||
|
withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.primary)) {
|
||||||
|
append(stringResource(id = R.string.vpn_settings))
|
||||||
|
}
|
||||||
|
pop()
|
||||||
|
append(" ")
|
||||||
|
append(stringResource(R.string.always_on_message2))
|
||||||
|
append(".")
|
||||||
|
}
|
||||||
|
InfoDialog(
|
||||||
|
onDismiss = { onDismiss() },
|
||||||
|
onAttest = { onDismiss() },
|
||||||
|
title = { Text(text = stringResource(R.string.vpn_denied_dialog_title)) },
|
||||||
|
body = {
|
||||||
|
ClickableText(
|
||||||
|
text = alwaysOnDescription,
|
||||||
|
style = MaterialTheme.typography.bodyMedium.copy(color = MaterialTheme.colorScheme.outline),
|
||||||
|
) {
|
||||||
|
alwaysOnDescription.getStringAnnotations(tag = "vpnSettings", it, it).firstOrNull()?.let {
|
||||||
|
context.launchVpnSettings()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmText = { Text(text = stringResource(R.string.okay)) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
-92
@@ -1,11 +1,7 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui.screens.options
|
package com.zaneschepke.wireguardautotunnel.ui.screens.options
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
|
||||||
import androidx.compose.animation.slideInVertically
|
|
||||||
import androidx.compose.animation.slideOutVertically
|
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.focusGroup
|
|
||||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
@@ -16,7 +12,6 @@ import androidx.compose.foundation.layout.fillMaxSize
|
|||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.text.KeyboardActions
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
@@ -32,7 +27,6 @@ import androidx.compose.material3.OutlinedTextField
|
|||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.surfaceColorAtElevation
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
@@ -44,32 +38,27 @@ import androidx.compose.ui.Alignment
|
|||||||
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.focusRequester
|
import androidx.compose.ui.focus.focusRequester
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.LocalFocusManager
|
import androidx.compose.ui.platform.LocalFocusManager
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.font.FontStyle
|
import androidx.compose.ui.text.font.FontStyle
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
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
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
import com.iamageo.multifablibrary.FabIcon
|
|
||||||
import com.iamageo.multifablibrary.FabOption
|
|
||||||
import com.iamageo.multifablibrary.MultiFabItem
|
|
||||||
import com.iamageo.multifablibrary.MultiFloatingActionButton
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
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.ClickableIconButton
|
import com.zaneschepke.wireguardautotunnel.ui.common.ClickableIconButton
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.ScrollDismissMultiFab
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
import com.zaneschepke.wireguardautotunnel.util.getMessage
|
import com.zaneschepke.wireguardautotunnel.util.extensions.getMessage
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
@@ -81,7 +70,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()
|
||||||
@@ -97,7 +86,7 @@ fun OptionsScreen(
|
|||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
optionsViewModel.init(tunnelId)
|
optionsViewModel.init(tunnelId)
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||||
focusRequester.requestFocus()
|
focusRequester.requestFocus()
|
||||||
}
|
}
|
||||||
@@ -117,75 +106,12 @@ fun OptionsScreen(
|
|||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
floatingActionButton = {
|
floatingActionButton = {
|
||||||
val secondaryColor = MaterialTheme.colorScheme.secondary
|
ScrollDismissMultiFab(R.drawable.edit, focusRequester, isVisible = true, onFabItemClicked = {
|
||||||
val tvFobColor = MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp)
|
|
||||||
val fobColor =
|
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) tvFobColor else secondaryColor
|
|
||||||
val fobIconColor =
|
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) Color.White else MaterialTheme.colorScheme.background
|
|
||||||
AnimatedVisibility(
|
|
||||||
visible = true,
|
|
||||||
enter = slideInVertically(initialOffsetY = { it * 2 }),
|
|
||||||
exit = slideOutVertically(targetOffsetY = { it * 2 }),
|
|
||||||
modifier = Modifier
|
|
||||||
.focusRequester(focusRequester)
|
|
||||||
.focusGroup(),
|
|
||||||
) {
|
|
||||||
MultiFloatingActionButton(
|
|
||||||
fabIcon = FabIcon(
|
|
||||||
iconRes = R.drawable.edit,
|
|
||||||
iconResAfterRotate = R.drawable.close,
|
|
||||||
iconRotate = 180f,
|
|
||||||
),
|
|
||||||
fabOption = FabOption(
|
|
||||||
iconTint = fobIconColor,
|
|
||||||
backgroundTint = fobColor,
|
|
||||||
),
|
|
||||||
itemsMultiFab = listOf(
|
|
||||||
MultiFabItem(
|
|
||||||
label = {
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.amnezia),
|
|
||||||
color = Color.White,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(end = 10.dp),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
modifier = Modifier
|
|
||||||
.size(40.dp),
|
|
||||||
icon = R.drawable.edit,
|
|
||||||
value = ConfigType.AMNEZIA.name,
|
|
||||||
miniFabOption = FabOption(
|
|
||||||
backgroundTint = fobColor,
|
|
||||||
fobIconColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
MultiFabItem(
|
|
||||||
label = {
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.wireguard),
|
|
||||||
color = Color.White,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(end = 10.dp),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
icon = R.drawable.edit,
|
|
||||||
value = ConfigType.WIREGUARD.name,
|
|
||||||
miniFabOption = FabOption(
|
|
||||||
backgroundTint = fobColor,
|
|
||||||
fobIconColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
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),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
@@ -208,7 +134,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 (context.isRunningOnTv()) {
|
||||||
Modifier
|
Modifier
|
||||||
.height(IntrinsicSize.Min)
|
.height(IntrinsicSize.Min)
|
||||||
.fillMaxWidth(fillMaxWidth)
|
.fillMaxWidth(fillMaxWidth)
|
||||||
@@ -217,7 +144,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 +161,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 +175,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 (context.isRunningOnTv()) {
|
||||||
Modifier
|
Modifier
|
||||||
.height(IntrinsicSize.Min)
|
.height(IntrinsicSize.Min)
|
||||||
.fillMaxWidth(fillMaxWidth)
|
.fillMaxWidth(fillMaxWidth)
|
||||||
@@ -255,7 +185,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 +207,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),
|
||||||
@@ -284,15 +216,14 @@ fun OptionsScreen(
|
|||||||
uiState.tunnel?.tunnelNetworks?.forEach { ssid ->
|
uiState.tunnel?.tunnelNetworks?.forEach { ssid ->
|
||||||
ClickableIconButton(
|
ClickableIconButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
focusRequester.requestFocus()
|
focusRequester.requestFocus()
|
||||||
optionsViewModel.onDeleteRunSSID(ssid)
|
optionsViewModel.onDeleteRunSSID(ssid)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onIconClick = {
|
onIconClick = {
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus()
|
if (context.isRunningOnTv()) focusRequester.requestFocus()
|
||||||
optionsViewModel.onDeleteRunSSID(ssid)
|
optionsViewModel.onDeleteRunSSID(ssid)
|
||||||
|
|
||||||
},
|
},
|
||||||
text = ssid,
|
text = ssid,
|
||||||
icon = Icons.Filled.Close,
|
icon = Icons.Filled.Close,
|
||||||
@@ -303,7 +234,7 @@ fun OptionsScreen(
|
|||||||
Text(
|
Text(
|
||||||
stringResource(R.string.no_wifi_names_configured),
|
stringResource(R.string.no_wifi_names_configured),
|
||||||
fontStyle = FontStyle.Italic,
|
fontStyle = FontStyle.Italic,
|
||||||
color = Color.Gray,
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -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,
|
||||||
)
|
)
|
||||||
|
|||||||
+17
-11
@@ -3,7 +3,6 @@ package com.zaneschepke.wireguardautotunnel.ui.screens.options
|
|||||||
import androidx.compose.ui.util.fastFirstOrNull
|
import androidx.compose.ui.util.fastFirstOrNull
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
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.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
@@ -19,14 +18,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 +34,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 +54,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 +70,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 +89,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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,7 +103,6 @@ constructor(
|
|||||||
false -> uiState.value.tunnel
|
false -> uiState.value.tunnel
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-5
@@ -7,10 +7,10 @@ import androidx.compose.ui.platform.LocalContext
|
|||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
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.util.StringValue
|
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
import xyz.teamgravity.pin_lock_compose.PinLock
|
import xyz.teamgravity.pin_lock_compose.PinLock
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
@@ -19,15 +19,20 @@ 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,
|
||||||
onPinCorrect = {
|
onPinCorrect = {
|
||||||
// pin is correct, navigate or hide pin lock
|
// pin is correct, navigate or hide pin lock
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
navController.navigate(Screen.Main.route)
|
navController.navigate(Screen.Main.route)
|
||||||
} else {
|
} else {
|
||||||
val isPopped = navController.popBackStack()
|
val isPopped = navController.popBackStack()
|
||||||
@@ -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
|
||||||
@@ -48,6 +52,7 @@ fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
|
|||||||
appViewModel.showSnackbarMessage(
|
appViewModel.showSnackbarMessage(
|
||||||
StringValue.StringResource(R.string.pin_created).asString(context),
|
StringValue.StringResource(R.string.pin_created).asString(context),
|
||||||
)
|
)
|
||||||
|
appViewModel.onPinLockEnabled()
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+177
-167
@@ -8,10 +8,10 @@ import android.net.Uri
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.PowerManager
|
import android.os.PowerManager
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
|
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.ActivityResult
|
import androidx.activity.result.ActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
@@ -25,7 +25,6 @@ import androidx.compose.foundation.layout.fillMaxSize
|
|||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.text.KeyboardActions
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
@@ -34,8 +33,6 @@ import androidx.compose.foundation.verticalScroll
|
|||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Close
|
import androidx.compose.material.icons.filled.Close
|
||||||
import androidx.compose.material.icons.outlined.Add
|
import androidx.compose.material.icons.outlined.Add
|
||||||
import androidx.compose.material.icons.rounded.LocationOff
|
|
||||||
import androidx.compose.material3.AlertDialog
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
@@ -55,16 +52,13 @@ import androidx.compose.ui.Alignment
|
|||||||
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.focusRequester
|
import androidx.compose.ui.focus.focusRequester
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.LocalFocusManager
|
import androidx.compose.ui.platform.LocalFocusManager
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.font.FontStyle
|
import androidx.compose.ui.text.font.FontStyle
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
@@ -81,9 +75,17 @@ import com.zaneschepke.wireguardautotunnel.ui.common.ClickableIconButton
|
|||||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.AuthorizationPrompt
|
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.AuthorizationPrompt
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||||
import com.zaneschepke.wireguardautotunnel.util.getMessage
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.VpnDeniedDialog
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.BackgroundLocationDialog
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.BackgroundLocationDisclosure
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.LocationServicesDialog
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.getMessage
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.launchAppSettings
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.showToast
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
@OptIn(
|
@OptIn(
|
||||||
@@ -109,9 +111,11 @@ fun SettingsScreen(
|
|||||||
val fineLocationState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION)
|
val fineLocationState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||||
var currentText by remember { mutableStateOf("") }
|
var currentText by remember { mutableStateOf("") }
|
||||||
var isBackgroundLocationGranted by remember { mutableStateOf(true) }
|
var isBackgroundLocationGranted by remember { mutableStateOf(true) }
|
||||||
|
var showVpnPermissionDialog by remember { mutableStateOf(false) }
|
||||||
var showLocationServicesAlertDialog by remember { mutableStateOf(false) }
|
var showLocationServicesAlertDialog by remember { mutableStateOf(false) }
|
||||||
var didExportFiles by remember { mutableStateOf(false) }
|
var didExportFiles by remember { mutableStateOf(false) }
|
||||||
var showAuthPrompt by remember { mutableStateOf(false) }
|
var showAuthPrompt by remember { mutableStateOf(false) }
|
||||||
|
var showLocationDialog by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
val screenPadding = 5.dp
|
val screenPadding = 5.dp
|
||||||
val fillMaxWidth = .85f
|
val fillMaxWidth = .85f
|
||||||
@@ -120,8 +124,17 @@ fun SettingsScreen(
|
|||||||
viewModel.checkKernelSupport()
|
viewModel.checkKernelSupport()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val notificationPermissionState =
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
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
|
||||||
@@ -129,30 +142,49 @@ fun SettingsScreen(
|
|||||||
viewModel.setBatteryOptimizeDisableShown()
|
viewModel.setBatteryOptimizeDisableShown()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val vpnActivityResultState =
|
||||||
|
rememberLauncherForActivityResult(
|
||||||
|
ActivityResultContracts.StartActivityForResult(),
|
||||||
|
onResult = {
|
||||||
|
val accepted = (it.resultCode == RESULT_OK)
|
||||||
|
if (accepted) {
|
||||||
|
viewModel.onToggleAutoTunnel(context)
|
||||||
|
} else {
|
||||||
|
showVpnPermissionDialog = true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
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) {
|
||||||
@@ -175,13 +207,20 @@ fun SettingsScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun handleAutoTunnelToggle() {
|
fun handleAutoTunnelToggle() {
|
||||||
if (uiState.isBatteryOptimizeDisableShown || isBatteryOptimizationsDisabled()) {
|
if (!uiState.isBatteryOptimizeDisableShown || !isBatteryOptimizationsDisabled()) return requestBatteryOptimizationsDisabled()
|
||||||
if (appViewModel.isRequiredPermissionGranted()) {
|
if (notificationPermissionState != null && !notificationPermissionState.status.isGranted) {
|
||||||
viewModel.onToggleAutoTunnel(context)
|
appViewModel.showSnackbarMessage(
|
||||||
|
context.getString(R.string.notification_permission_required),
|
||||||
|
)
|
||||||
|
return notificationPermissionState.launchPermissionRequest()
|
||||||
}
|
}
|
||||||
|
val intent = if (!uiState.settings.isKernelEnabled) {
|
||||||
|
com.wireguard.android.backend.GoBackend.VpnService.prepare(context)
|
||||||
} else {
|
} else {
|
||||||
requestBatteryOptimizationsDisabled()
|
null
|
||||||
}
|
}
|
||||||
|
if (intent != null) return vpnActivityResultState.launch(intent)
|
||||||
|
viewModel.onToggleAutoTunnel(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun saveTrustedSSID() {
|
fun saveTrustedSSID() {
|
||||||
@@ -194,12 +233,6 @@ fun SettingsScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun openSettings() {
|
|
||||||
val intentSettings = Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
|
|
||||||
intentSettings.data = Uri.fromParts("package", context.packageName, null)
|
|
||||||
context.startActivity(intentSettings)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun checkFineLocationGranted() {
|
fun checkFineLocationGranted() {
|
||||||
isBackgroundLocationGranted =
|
isBackgroundLocationGranted =
|
||||||
if (!fineLocationState.status.isGranted) {
|
if (!fineLocationState.status.isGranted) {
|
||||||
@@ -210,9 +243,13 @@ fun SettingsScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun onRootDenied() = appViewModel.showSnackbarMessage(context.getString(R.string.error_root_denied))
|
||||||
|
|
||||||
|
fun onRootAccepted() = appViewModel.showSnackbarMessage(context.getString(R.string.root_accepted))
|
||||||
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
if (
|
if (
|
||||||
WireGuardAutoTunnel.isRunningOnAndroidTv() &&
|
context.isRunningOnTv() &&
|
||||||
Build.VERSION.SDK_INT == Build.VERSION_CODES.Q
|
Build.VERSION.SDK_INT == Build.VERSION_CODES.Q
|
||||||
) {
|
) {
|
||||||
checkFineLocationGranted()
|
checkFineLocationGranted()
|
||||||
@@ -233,85 +270,30 @@ fun SettingsScreen(
|
|||||||
checkFineLocationGranted()
|
checkFineLocationGranted()
|
||||||
}
|
}
|
||||||
|
|
||||||
AnimatedVisibility(showLocationServicesAlertDialog) {
|
BackgroundLocationDisclosure(
|
||||||
AlertDialog(
|
!uiState.isLocationDisclosureShown,
|
||||||
onDismissRequest = { showLocationServicesAlertDialog = false },
|
onDismiss = { viewModel.setLocationDisclosureShown() },
|
||||||
confirmButton = {
|
onAttest = {
|
||||||
TextButton(
|
context.launchAppSettings()
|
||||||
onClick = {
|
|
||||||
showLocationServicesAlertDialog = false
|
|
||||||
handleAutoTunnelToggle()
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
Text(text = stringResource(R.string.okay))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
dismissButton = {
|
|
||||||
TextButton(onClick = { showLocationServicesAlertDialog = false }) {
|
|
||||||
Text(text = stringResource(R.string.cancel))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
title = { Text(text = stringResource(R.string.location_services_not_detected)) },
|
|
||||||
text = { Text(text = stringResource(R.string.location_services_missing_message)) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!uiState.isLocationDisclosureShown) {
|
|
||||||
Column(
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
verticalArrangement = Arrangement.Top,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.verticalScroll(scrollState),
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
Icons.Rounded.LocationOff,
|
|
||||||
contentDescription = stringResource(id = R.string.map),
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(30.dp)
|
|
||||||
.size(128.dp),
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.prominent_background_location_title),
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(30.dp),
|
|
||||||
fontSize = 20.sp,
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.prominent_background_location_message),
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(30.dp),
|
|
||||||
fontSize = 15.sp,
|
|
||||||
)
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(10.dp)
|
|
||||||
} else {
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(30.dp)
|
|
||||||
},
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
|
||||||
) {
|
|
||||||
TextButton(onClick = { viewModel.setLocationDisclosureShown() }) {
|
|
||||||
Text(stringResource(id = R.string.no_thanks))
|
|
||||||
}
|
|
||||||
TextButton(
|
|
||||||
modifier = Modifier.focusRequester(focusRequester),
|
|
||||||
onClick = {
|
|
||||||
openSettings()
|
|
||||||
viewModel.setLocationDisclosureShown()
|
viewModel.setLocationDisclosureShown()
|
||||||
},
|
},
|
||||||
) {
|
scrollState,
|
||||||
Text(stringResource(id = R.string.turn_on))
|
focusRequester,
|
||||||
}
|
)
|
||||||
}
|
|
||||||
}
|
BackgroundLocationDialog(
|
||||||
}
|
showLocationDialog,
|
||||||
|
onDismiss = { showLocationDialog = false },
|
||||||
|
onAttest = { showLocationDialog = false },
|
||||||
|
)
|
||||||
|
|
||||||
|
LocationServicesDialog(
|
||||||
|
showLocationServicesAlertDialog,
|
||||||
|
onDismiss = { showVpnPermissionDialog = false },
|
||||||
|
onAttest = { handleAutoTunnelToggle() },
|
||||||
|
)
|
||||||
|
|
||||||
|
VpnDeniedDialog(showVpnPermissionDialog, onDismiss = { showVpnPermissionDialog = false })
|
||||||
|
|
||||||
if (showAuthPrompt) {
|
if (showAuthPrompt) {
|
||||||
AuthorizationPrompt(
|
AuthorizationPrompt(
|
||||||
@@ -321,30 +303,20 @@ 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),
|
||||||
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (uiState.tunnels.isEmpty() && uiState.isLocationDisclosureShown) {
|
if (uiState.isLocationDisclosureShown) {
|
||||||
Column(
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
verticalArrangement = Arrangement.Center,
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.one_tunnel_required),
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(15.dp),
|
|
||||||
fontStyle = FontStyle.Italic,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (uiState.isLocationDisclosureShown && uiState.tunnels.isNotEmpty()) {
|
|
||||||
Column(
|
Column(
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
verticalArrangement = Arrangement.Top,
|
verticalArrangement = Arrangement.Top,
|
||||||
@@ -365,7 +337,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 (context.isRunningOnTv()) {
|
||||||
Modifier
|
Modifier
|
||||||
.height(IntrinsicSize.Min)
|
.height(IntrinsicSize.Min)
|
||||||
.fillMaxWidth(fillMaxWidth)
|
.fillMaxWidth(fillMaxWidth)
|
||||||
@@ -374,7 +347,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 +363,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),
|
||||||
@@ -411,35 +390,39 @@ fun SettingsScreen(
|
|||||||
uiState.settings.trustedNetworkSSIDs.forEach { ssid ->
|
uiState.settings.trustedNetworkSSIDs.forEach { ssid ->
|
||||||
ClickableIconButton(
|
ClickableIconButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
focusRequester.requestFocus()
|
focusRequester.requestFocus()
|
||||||
viewModel.onDeleteTrustedSSID(ssid)
|
viewModel.onDeleteTrustedSSID(ssid)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onIconClick = {
|
onIconClick = {
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus()
|
if (context.isRunningOnTv()) 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()) {
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.none),
|
stringResource(R.string.none),
|
||||||
fontStyle = FontStyle.Italic,
|
fontStyle = FontStyle.Italic,
|
||||||
color = Color.Gray,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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 +470,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 +481,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 +492,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 +503,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,
|
||||||
@@ -526,21 +519,14 @@ fun SettingsScreen(
|
|||||||
TextButton(
|
TextButton(
|
||||||
enabled = !uiState.settings.isAlwaysOnVpnEnabled,
|
enabled = !uiState.settings.isAlwaysOnVpnEnabled,
|
||||||
onClick = {
|
onClick = {
|
||||||
|
if (uiState.tunnels.isEmpty()) return@TextButton context.showToast(R.string.tunnel_required)
|
||||||
if (
|
if (
|
||||||
uiState.settings.isTunnelOnWifiEnabled &&
|
uiState.settings.isTunnelOnWifiEnabled &&
|
||||||
!uiState.settings.isAutoTunnelEnabled
|
!uiState.settings.isAutoTunnelEnabled
|
||||||
) {
|
) {
|
||||||
when (false) {
|
when (false) {
|
||||||
isBackgroundLocationGranted ->
|
isBackgroundLocationGranted -> showLocationDialog = true
|
||||||
appViewModel.showSnackbarMessage(
|
fineLocationState.status.isGranted -> showLocationDialog = true
|
||||||
context.getString(R.string.background_location_required),
|
|
||||||
)
|
|
||||||
|
|
||||||
fineLocationState.status.isGranted ->
|
|
||||||
appViewModel.showSnackbarMessage(
|
|
||||||
context.getString(R.string.precise_location_required),
|
|
||||||
)
|
|
||||||
|
|
||||||
viewModel.isLocationEnabled(context) ->
|
viewModel.isLocationEnabled(context) ->
|
||||||
showLocationServicesAlertDialog = true
|
showLocationServicesAlertDialog = true
|
||||||
|
|
||||||
@@ -569,7 +555,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 +572,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,19 +587,35 @@ 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 = {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
viewModel.onToggleKernelMode().onFailure {
|
viewModel.onToggleKernelMode({ onRootAccepted() }, { onRootDenied() })
|
||||||
appViewModel.showSnackbarMessage(it.getMessage(context))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(top = 5.dp),
|
||||||
|
horizontalArrangement = Arrangement.Center,
|
||||||
|
) {
|
||||||
|
TextButton(
|
||||||
|
onClick = {
|
||||||
|
viewModel.requestRoot({ onRootAccepted() }, { onRootDenied() })
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.request_root))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -634,7 +639,7 @@ fun SettingsScreen(
|
|||||||
title = stringResource(id = R.string.other),
|
title = stringResource(id = R.string.other),
|
||||||
padding = screenPadding,
|
padding = screenPadding,
|
||||||
)
|
)
|
||||||
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (!context.isRunningOnTv()) {
|
||||||
ConfigurationToggle(
|
ConfigurationToggle(
|
||||||
stringResource(R.string.always_on_vpn_support),
|
stringResource(R.string.always_on_vpn_support),
|
||||||
enabled = !uiState.settings.isAutoTunnelEnabled,
|
enabled = !uiState.settings.isAutoTunnelEnabled,
|
||||||
@@ -666,24 +671,29 @@ fun SettingsScreen(
|
|||||||
padding = screenPadding,
|
padding = screenPadding,
|
||||||
onCheckChanged = {
|
onCheckChanged = {
|
||||||
if (uiState.isPinLockEnabled) {
|
if (uiState.isPinLockEnabled) {
|
||||||
viewModel.onPinLockDisabled()
|
appViewModel.onPinLockDisabled()
|
||||||
} else {
|
} else {
|
||||||
viewModel.onPinLockEnabled()
|
// TODO may want to show a dialog before proceeding in the future
|
||||||
|
PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||||
navController.navigate(Screen.Lock.route)
|
navController.navigate(Screen.Lock.route)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (!context.isRunningOnTv()) {
|
||||||
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,
|
||||||
) {
|
) {
|
||||||
TextButton(
|
TextButton(
|
||||||
enabled = !didExportFiles,
|
enabled = !didExportFiles,
|
||||||
onClick = { showAuthPrompt = true },
|
onClick = {
|
||||||
|
if (uiState.tunnels.isEmpty()) return@TextButton context.showToast(R.string.tunnel_required)
|
||||||
|
showAuthPrompt = true
|
||||||
|
},
|
||||||
) {
|
) {
|
||||||
Text(stringResource(R.string.export_configs))
|
Text(stringResource(R.string.export_configs))
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -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
-47
@@ -7,12 +7,11 @@ import androidx.lifecycle.ViewModel
|
|||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.wireguard.android.backend.WgQuickBackend
|
import com.wireguard.android.backend.WgQuickBackend
|
||||||
import com.wireguard.android.util.RootShell
|
import com.wireguard.android.util.RootShell
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
import com.zaneschepke.wireguardautotunnel.util.FileUtils
|
import com.zaneschepke.wireguardautotunnel.util.FileUtils
|
||||||
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
||||||
@@ -27,7 +26,6 @@ import kotlinx.coroutines.flow.update
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Provider
|
import javax.inject.Provider
|
||||||
@@ -41,9 +39,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
|
tunnelService: TunnelService,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val _kernelSupport = MutableStateFlow(false)
|
private val _kernelSupport = MutableStateFlow(false)
|
||||||
val kernelSupport = _kernelSupport.asStateFlow()
|
val kernelSupport = _kernelSupport.asStateFlow()
|
||||||
|
|
||||||
@@ -51,7 +48,7 @@ constructor(
|
|||||||
combine(
|
combine(
|
||||||
appDataRepository.settings.getSettingsFlow(),
|
appDataRepository.settings.getSettingsFlow(),
|
||||||
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
||||||
vpnService.vpnState,
|
tunnelService.vpnState,
|
||||||
appDataRepository.appState.generalStateFlow,
|
appDataRepository.appState.generalStateFlow,
|
||||||
) { settings, tunnels, tunnelState, generalState ->
|
) { settings, tunnels, tunnelState, generalState ->
|
||||||
SettingsUiState(
|
SettingsUiState(
|
||||||
@@ -80,13 +77,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 +106,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
|
||||||
|
|
||||||
@@ -128,11 +122,9 @@ constructor(
|
|||||||
isAutoTunnelPaused = isAutoTunnelPaused,
|
isAutoTunnelPaused = isAutoTunnelPaused,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
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 +132,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 +143,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -164,10 +158,10 @@ constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun saveKernelMode(on: Boolean) {
|
private fun saveKernelMode(enabled: Boolean) {
|
||||||
saveSettings(
|
saveSettings(
|
||||||
uiState.value.settings.copy(
|
uiState.value.settings.copy(
|
||||||
isKernelEnabled = on,
|
isKernelEnabled = enabled,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -195,28 +189,25 @@ constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun onToggleKernelMode(): Result<Unit> {
|
fun onToggleKernelMode(onSuccess: () -> Unit, onFailure: () -> Unit) = viewModelScope.launch {
|
||||||
return withContext(ioDispatcher) {
|
|
||||||
if (!uiState.value.settings.isKernelEnabled) {
|
if (!uiState.value.settings.isKernelEnabled) {
|
||||||
try {
|
requestRoot(
|
||||||
rootShell.get().start()
|
{
|
||||||
Timber.i("Root shell accepted!")
|
onSuccess()
|
||||||
saveSettings(
|
saveSettings(
|
||||||
uiState.value.settings.copy(
|
uiState.value.settings.copy(
|
||||||
isKernelEnabled = true,
|
isKernelEnabled = true,
|
||||||
isAmneziaEnabled = false,
|
isAmneziaEnabled = false,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
},
|
||||||
} catch (e: RootShell.RootShellException) {
|
{
|
||||||
Timber.e(e)
|
onFailure()
|
||||||
saveKernelMode(on = false)
|
saveKernelMode(enabled = false)
|
||||||
return@withContext Result.failure(WgTunnelExceptions.RootDenied())
|
},
|
||||||
}
|
)
|
||||||
} else {
|
} else {
|
||||||
saveKernelMode(on = false)
|
saveKernelMode(enabled = false)
|
||||||
}
|
|
||||||
Result.success(Unit)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,7 +220,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 {
|
||||||
@@ -237,21 +229,23 @@ constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onPinLockDisabled() = viewModelScope.launch {
|
|
||||||
PinManager.clearPin()
|
|
||||||
appDataRepository.appState.setPinLockEnabled(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onPinLockEnabled() = viewModelScope.launch {
|
|
||||||
PinManager.initialize(WireGuardAutoTunnel.instance)
|
|
||||||
appDataRepository.appState.setPinLockEnabled(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun requestRoot(onSuccess: () -> Unit, onFailure: () -> Unit) = viewModelScope.launch(ioDispatcher) {
|
||||||
|
kotlin.runCatching {
|
||||||
|
rootShell.get().start()
|
||||||
|
Timber.i("Root shell accepted!")
|
||||||
|
onSuccess()
|
||||||
|
}.onFailure {
|
||||||
|
onFailure()
|
||||||
|
}.onSuccess {
|
||||||
|
onSuccess()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.text.ClickableText
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.SpanStyle
|
||||||
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
|
import androidx.compose.ui.text.withStyle
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.InfoDialog
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.launchAppSettings
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun BackgroundLocationDialog(show: Boolean, onDismiss: () -> Unit, onAttest: () -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
if (show) {
|
||||||
|
val alwaysOnDescription = buildAnnotatedString {
|
||||||
|
append(stringResource(R.string.background_location_message))
|
||||||
|
append(" ")
|
||||||
|
pushStringAnnotation(tag = "appSettings", annotation = "")
|
||||||
|
withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.primary)) {
|
||||||
|
append(stringResource(id = R.string.app_settings))
|
||||||
|
}
|
||||||
|
pop()
|
||||||
|
append(" ")
|
||||||
|
append(stringResource(R.string.background_location_message2))
|
||||||
|
append(".")
|
||||||
|
}
|
||||||
|
InfoDialog(
|
||||||
|
onDismiss = { onDismiss() },
|
||||||
|
onAttest = { onDismiss() },
|
||||||
|
title = { Text(text = stringResource(R.string.vpn_denied_dialog_title)) },
|
||||||
|
body = {
|
||||||
|
ClickableText(
|
||||||
|
text = alwaysOnDescription,
|
||||||
|
style = MaterialTheme.typography.bodyMedium.copy(color = MaterialTheme.colorScheme.outline),
|
||||||
|
) {
|
||||||
|
alwaysOnDescription.getStringAnnotations(tag = "appSettings", it, it).firstOrNull()?.let {
|
||||||
|
context.launchAppSettings()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmText = { Text(text = stringResource(R.string.okay)) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+96
@@ -0,0 +1,96 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.ScrollState
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.rounded.LocationOff
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun BackgroundLocationDisclosure(
|
||||||
|
show: Boolean,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onAttest: () -> Unit,
|
||||||
|
scrollState: ScrollState,
|
||||||
|
focusRequester: FocusRequester,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
if (show) {
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Top,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.verticalScroll(scrollState),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Rounded.LocationOff,
|
||||||
|
contentDescription = stringResource(id = R.string.map),
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.padding(30.dp)
|
||||||
|
.size(128.dp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.prominent_background_location_title),
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
modifier = Modifier.padding(30.dp),
|
||||||
|
fontSize = 20.sp,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.prominent_background_location_message),
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
modifier = Modifier.padding(30.dp),
|
||||||
|
fontSize = 15.sp,
|
||||||
|
)
|
||||||
|
Row(
|
||||||
|
modifier =
|
||||||
|
if (context.isRunningOnTv()) {
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(10.dp)
|
||||||
|
} else {
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(30.dp)
|
||||||
|
},
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||||
|
) {
|
||||||
|
TextButton(onClick = { onDismiss() }) {
|
||||||
|
Text(stringResource(id = R.string.no_thanks))
|
||||||
|
}
|
||||||
|
TextButton(
|
||||||
|
modifier = Modifier.focusRequester(focusRequester),
|
||||||
|
onClick = {
|
||||||
|
onAttest()
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Text(stringResource(id = R.string.turn_on))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.components
|
||||||
|
|
||||||
|
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 LocationServicesDialog(show: Boolean, onDismiss: () -> Unit, onAttest: () -> Unit) {
|
||||||
|
if (show) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { onDismiss() },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(
|
||||||
|
onClick = {
|
||||||
|
onDismiss()
|
||||||
|
onAttest()
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Text(text = stringResource(R.string.okay))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { onDismiss() }) {
|
||||||
|
Text(text = stringResource(R.string.cancel))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
title = { Text(text = stringResource(R.string.location_services_not_detected)) },
|
||||||
|
text = { Text(text = stringResource(R.string.location_services_missing_message)) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
-25
@@ -48,17 +48,13 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
import com.zaneschepke.wireguardautotunnel.BuildConfig
|
import com.zaneschepke.wireguardautotunnel.BuildConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.launchSupportEmail
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.openWebUrl
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun SupportScreen(
|
fun SupportScreen(viewModel: SupportViewModel = hiltViewModel(), navController: NavController, focusRequester: FocusRequester) {
|
||||||
viewModel: SupportViewModel = hiltViewModel(),
|
|
||||||
appViewModel: AppViewModel,
|
|
||||||
navController: NavController,
|
|
||||||
focusRequester: FocusRequester
|
|
||||||
) {
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val fillMaxWidth = .85f
|
val fillMaxWidth = .85f
|
||||||
|
|
||||||
@@ -79,7 +75,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 (context.isRunningOnTv()) {
|
||||||
Modifier
|
Modifier
|
||||||
.height(IntrinsicSize.Min)
|
.height(IntrinsicSize.Min)
|
||||||
.fillMaxWidth(fillMaxWidth)
|
.fillMaxWidth(fillMaxWidth)
|
||||||
@@ -88,7 +85,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)) {
|
||||||
@@ -108,12 +106,12 @@ fun SupportScreen(
|
|||||||
)
|
)
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
appViewModel.openWebPage(
|
context.openWebUrl(
|
||||||
context.resources.getString(R.string.docs_url),
|
context.resources.getString(R.string.docs_url),
|
||||||
context,
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
modifier = Modifier
|
modifier =
|
||||||
|
Modifier
|
||||||
.padding(vertical = 5.dp)
|
.padding(vertical = 5.dp)
|
||||||
.focusRequester(focusRequester),
|
.focusRequester(focusRequester),
|
||||||
) {
|
) {
|
||||||
@@ -128,7 +126,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,
|
||||||
@@ -149,9 +148,8 @@ fun SupportScreen(
|
|||||||
)
|
)
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
appViewModel.openWebPage(
|
context.openWebUrl(
|
||||||
context.resources.getString(R.string.telegram_url),
|
context.resources.getString(R.string.telegram_url),
|
||||||
context,
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
modifier = Modifier.padding(vertical = 5.dp),
|
modifier = Modifier.padding(vertical = 5.dp),
|
||||||
@@ -169,7 +167,7 @@ fun SupportScreen(
|
|||||||
Modifier.size(25.dp),
|
Modifier.size(25.dp),
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
stringResource(id = R.string.discord_description),
|
stringResource(id = R.string.chat_description),
|
||||||
textAlign = TextAlign.Justify,
|
textAlign = TextAlign.Justify,
|
||||||
modifier = Modifier.padding(start = 10.dp),
|
modifier = Modifier.padding(start = 10.dp),
|
||||||
)
|
)
|
||||||
@@ -186,9 +184,8 @@ fun SupportScreen(
|
|||||||
)
|
)
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
appViewModel.openWebPage(
|
context.openWebUrl(
|
||||||
context.resources.getString(R.string.github_url),
|
context.resources.getString(R.string.github_url),
|
||||||
context,
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
modifier = Modifier.padding(vertical = 5.dp),
|
modifier = Modifier.padding(vertical = 5.dp),
|
||||||
@@ -222,7 +219,7 @@ fun SupportScreen(
|
|||||||
color = MaterialTheme.colorScheme.onBackground,
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
)
|
)
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = { appViewModel.launchEmail(context) },
|
onClick = { context.launchSupportEmail() },
|
||||||
modifier = Modifier.padding(vertical = 5.dp),
|
modifier = Modifier.padding(vertical = 5.dp),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
@@ -245,7 +242,7 @@ fun SupportScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (!context.isRunningOnTv()) {
|
||||||
HorizontalDivider(
|
HorizontalDivider(
|
||||||
thickness = 0.5.dp,
|
thickness = 0.5.dp,
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
@@ -284,9 +281,8 @@ fun SupportScreen(
|
|||||||
fontSize = 16.sp,
|
fontSize = 16.sp,
|
||||||
modifier =
|
modifier =
|
||||||
Modifier.clickable {
|
Modifier.clickable {
|
||||||
appViewModel.openWebPage(
|
context.openWebUrl(
|
||||||
context.resources.getString(R.string.privacy_policy_url),
|
context.resources.getString(R.string.privacy_policy_url),
|
||||||
context,
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -295,12 +291,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) {
|
||||||
|
|||||||
+3
-2
@@ -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()
|
||||||
|
|||||||
+7
-4
@@ -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()),
|
||||||
|
)
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
) {
|
) {
|
||||||
|
|||||||
+6
-5
@@ -9,7 +9,7 @@ import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
|||||||
import com.zaneschepke.wireguardautotunnel.module.MainDispatcher
|
import com.zaneschepke.wireguardautotunnel.module.MainDispatcher
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
import com.zaneschepke.wireguardautotunnel.util.FileUtils
|
import com.zaneschepke.wireguardautotunnel.util.FileUtils
|
||||||
import com.zaneschepke.wireguardautotunnel.util.chunked
|
import com.zaneschepke.wireguardautotunnel.util.extensions.chunked
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.zaneschepke.wireguardautotunnel.ui.theme
|
|||||||
|
|
||||||
import android.app.Activity
|
import android.app.Activity
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.darkColorScheme
|
import androidx.compose.material3.darkColorScheme
|
||||||
import androidx.compose.material3.dynamicDarkColorScheme
|
import androidx.compose.material3.dynamicDarkColorScheme
|
||||||
@@ -44,21 +45,19 @@ private val LightColorScheme =
|
|||||||
@Composable
|
@Composable
|
||||||
fun WireguardAutoTunnelTheme(
|
fun WireguardAutoTunnelTheme(
|
||||||
// force dark theme
|
// force dark theme
|
||||||
darkTheme: Boolean = true,
|
useDarkTheme: Boolean = isSystemInDarkTheme(),
|
||||||
// darkTheme: Boolean = isSystemInDarkTheme(),
|
content: @Composable () -> Unit,
|
||||||
// Dynamic color is available on Android 12+
|
|
||||||
// turning off dynamic color for now
|
|
||||||
dynamicColor: Boolean = false,
|
|
||||||
content: @Composable () -> Unit
|
|
||||||
) {
|
) {
|
||||||
val colorScheme =
|
|
||||||
when {
|
|
||||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
val colorScheme = when {
|
||||||
|
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) -> {
|
||||||
|
if (useDarkTheme) {
|
||||||
|
dynamicDarkColorScheme(context)
|
||||||
|
} else {
|
||||||
|
dynamicLightColorScheme(context)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
darkTheme -> DarkColorScheme
|
useDarkTheme -> DarkColorScheme
|
||||||
else -> LightColorScheme
|
else -> LightColorScheme
|
||||||
}
|
}
|
||||||
val view = LocalView.current
|
val view = LocalView.current
|
||||||
@@ -69,7 +68,7 @@ fun WireguardAutoTunnelTheme(
|
|||||||
window.statusBarColor = Color.Transparent.toArgb()
|
window.statusBarColor = Color.Transparent.toArgb()
|
||||||
window.navigationBarColor = Color.Transparent.toArgb()
|
window.navigationBarColor = Color.Transparent.toArgb()
|
||||||
WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightStatusBars =
|
WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightStatusBars =
|
||||||
!darkTheme
|
!useDarkTheme
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,12 @@
|
|||||||
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
|
||||||
|
|
||||||
const val MANUAL_TUNNEL_CONFIG_ID = "0"
|
const val MANUAL_TUNNEL_CONFIG_ID = "0"
|
||||||
const val BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT = 10 * 60 * 1_000L // 10 minutes
|
const val BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT = 10 * 60 * 1_000L // 10 minutes
|
||||||
const val VPN_STATISTIC_CHECK_INTERVAL = 1_000L
|
const val VPN_STATISTIC_CHECK_INTERVAL = 1_000L
|
||||||
const val VPN_CONNECTED_NOTIFICATION_DELAY = 3_000L
|
|
||||||
const val TOGGLE_TUNNEL_DELAY = 300L
|
|
||||||
const val WATCHER_COLLECTION_DELAY = 1_000L
|
const val WATCHER_COLLECTION_DELAY = 1_000L
|
||||||
const val CONF_FILE_EXTENSION = ".conf"
|
const val CONF_FILE_EXTENSION = ".conf"
|
||||||
const val ZIP_FILE_EXTENSION = ".zip"
|
const val ZIP_FILE_EXTENSION = ".zip"
|
||||||
@@ -20,6 +17,7 @@ object Constants {
|
|||||||
const val GOOGLE_TV_EXPLORER_STUB = "com.google.android.tv.frameworkpackagestubs"
|
const val GOOGLE_TV_EXPLORER_STUB = "com.google.android.tv.frameworkpackagestubs"
|
||||||
const val ANDROID_TV_EXPLORER_STUB = "com.android.tv.frameworkpackagestubs"
|
const val ANDROID_TV_EXPLORER_STUB = "com.android.tv.frameworkpackagestubs"
|
||||||
const val ALWAYS_ON_VPN_ACTION = "android.net.VpnService"
|
const val ALWAYS_ON_VPN_ACTION = "android.net.VpnService"
|
||||||
|
const val VPN_SETTINGS_PACKAGE = "android.net.vpn.SETTINGS"
|
||||||
const val EMAIL_MIME_TYPE = "plain/text"
|
const val EMAIL_MIME_TYPE = "plain/text"
|
||||||
const val SYSTEM_EXEMPT_SERVICE_TYPE_ID = 1024
|
const val SYSTEM_EXEMPT_SERVICE_TYPE_ID = 1024
|
||||||
|
|
||||||
@@ -30,15 +28,10 @@ object Constants {
|
|||||||
const val PING_TIMEOUT = 5_000L
|
const val PING_TIMEOUT = 5_000L
|
||||||
const val VPN_RESTART_DELAY = 1_000L
|
const val VPN_RESTART_DELAY = 1_000L
|
||||||
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 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 ="
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,148 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.util
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.pm.PackageInfo
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
|
||||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
|
||||||
import kotlinx.coroutines.ObsoleteCoroutinesApi
|
|
||||||
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
|
||||||
import kotlinx.coroutines.channels.ReceiveChannel
|
|
||||||
import kotlinx.coroutines.channels.produce
|
|
||||||
import kotlinx.coroutines.channels.ticker
|
|
||||||
import kotlinx.coroutines.coroutineScope
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
|
||||||
import kotlinx.coroutines.flow.channelFlow
|
|
||||||
import kotlinx.coroutines.selects.whileSelect
|
|
||||||
import org.amnezia.awg.config.Config
|
|
||||||
import timber.log.Timber
|
|
||||||
import java.math.BigDecimal
|
|
||||||
import java.text.DecimalFormat
|
|
||||||
import java.time.Duration
|
|
||||||
import java.util.concurrent.ConcurrentLinkedQueue
|
|
||||||
import kotlin.coroutines.cancellation.CancellationException
|
|
||||||
|
|
||||||
fun BigDecimal.toThreeDecimalPlaceString(): String {
|
|
||||||
val df = DecimalFormat("#.###")
|
|
||||||
return df.format(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun <T> List<T>.update(index: Int, item: T): List<T> = toMutableList().apply { this[index] = item }
|
|
||||||
|
|
||||||
fun <T> List<T>.removeAt(index: Int): List<T> = toMutableList().apply { this.removeAt(index) }
|
|
||||||
|
|
||||||
typealias TunnelConfigs = List<TunnelConfig>
|
|
||||||
|
|
||||||
typealias Packages = List<PackageInfo>
|
|
||||||
|
|
||||||
fun TunnelStatistics.mapPeerStats(): Map<org.amnezia.awg.crypto.Key, TunnelStatistics.PeerStats?> {
|
|
||||||
return this.getPeers().associateWith { key -> (this.peerStats(key)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun TunnelStatistics.PeerStats.latestHandshakeSeconds(): Long? {
|
|
||||||
return NumberUtils.getSecondsBetweenTimestampAndNow(this.latestHandshakeEpochMillis)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun TunnelStatistics.PeerStats.handshakeStatus(): HandshakeStatus {
|
|
||||||
// TODO add never connected status after duration
|
|
||||||
return this.latestHandshakeSeconds().let {
|
|
||||||
when {
|
|
||||||
it == null -> HandshakeStatus.NOT_STARTED
|
|
||||||
it <= HandshakeStatus.STALE_TIME_LIMIT_SEC -> HandshakeStatus.HEALTHY
|
|
||||||
it > HandshakeStatus.STALE_TIME_LIMIT_SEC -> HandshakeStatus.STALE
|
|
||||||
else -> {
|
|
||||||
HandshakeStatus.UNKNOWN
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun Config.toWgQuickString(): String {
|
|
||||||
val amQuick = toAwgQuickString()
|
|
||||||
val lines = amQuick.lines().toMutableList()
|
|
||||||
val linesIterator = lines.iterator()
|
|
||||||
while (linesIterator.hasNext()) {
|
|
||||||
val next = linesIterator.next()
|
|
||||||
Constants.amneziaProperties.forEach {
|
|
||||||
if (next.startsWith(it, ignoreCase = true)) {
|
|
||||||
linesIterator.remove()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return lines.joinToString(System.lineSeparator())
|
|
||||||
}
|
|
||||||
|
|
||||||
fun Throwable.getMessage(context: Context): String {
|
|
||||||
return when (this) {
|
|
||||||
is WgTunnelExceptions -> this.getMessage(context)
|
|
||||||
else -> this.message ?: StringValue.StringResource(R.string.unknown_error).asString(context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Chunks based on a time or size threshold.
|
|
||||||
*
|
|
||||||
* Borrowed from this [Stack Overflow question](https://stackoverflow.com/questions/51022533/kotlin-chunk-sequence-based-on-size-and-time).
|
|
||||||
*/
|
|
||||||
@OptIn(ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class)
|
|
||||||
fun <T> ReceiveChannel<T>.chunked(scope: CoroutineScope, size: Int, time: Duration) =
|
|
||||||
scope.produce<List<T>> {
|
|
||||||
while (true) { // this loop goes over each chunk
|
|
||||||
val chunk = ConcurrentLinkedQueue<T>() // current chunk
|
|
||||||
val ticker = ticker(time.toMillis()) // time-limit for this chunk
|
|
||||||
try {
|
|
||||||
whileSelect {
|
|
||||||
ticker.onReceive {
|
|
||||||
false // done with chunk when timer ticks, takes priority over received elements
|
|
||||||
}
|
|
||||||
this@chunked.onReceive {
|
|
||||||
chunk += it
|
|
||||||
chunk.size < size // continue whileSelect if chunk is not full
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e: ClosedReceiveChannelException) {
|
|
||||||
Timber.e(e)
|
|
||||||
return@produce
|
|
||||||
} finally {
|
|
||||||
ticker.cancel()
|
|
||||||
if (chunk.isNotEmpty()) {
|
|
||||||
send(chunk.toList())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class)
|
|
||||||
fun <T> Flow<T>.chunked(size: Int, time: Duration) = channelFlow {
|
|
||||||
coroutineScope {
|
|
||||||
val channel = asChannel(this@chunked).chunked(this, size, time)
|
|
||||||
try {
|
|
||||||
while (!channel.isClosedForReceive) {
|
|
||||||
send(channel.receive())
|
|
||||||
}
|
|
||||||
} catch (e: ClosedReceiveChannelException) {
|
|
||||||
// Channel was closed by the flow completing, nothing to do
|
|
||||||
Timber.w(e)
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
channel.cancel(e)
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
|
||||||
channel.cancel(CancellationException("Closing channel due to flow exception", e))
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExperimentalCoroutinesApi
|
|
||||||
fun <T> CoroutineScope.asChannel(flow: Flow<T>): ReceiveChannel<T> = produce {
|
|
||||||
flow.collect { 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 ->
|
||||||
@@ -100,11 +101,8 @@ 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 {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user