mirror of
https://github.com/wgtunnel/android.git
synced 2026-07-03 14:07:49 +02:00
Compare commits
108 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 47f619ff07 | |||
| 791b532d85 | |||
| 57d096ebb1 | |||
| cfb4f85ded | |||
| d330fa4c28 | |||
| a362327fa3 | |||
| 9c72390398 | |||
| d1d59aaf5c | |||
| 03fdb82c24 | |||
| 4355e2e9ce | |||
| d7b4fbecb9 | |||
| 7fee0b3768 | |||
| bd76ee5392 | |||
| 911ed140e0 | |||
| a9d7648425 | |||
| 230f505806 | |||
| e58dad00ea | |||
| 8ddf5cf537 | |||
| d86fa782cc | |||
| fe7b9072d6 | |||
| 9895ed1061 | |||
| 34066ea182 | |||
| b99b116fdb | |||
| 9d42e7299b | |||
| b782cdeb35 | |||
| e40515c138 | |||
| d62df80682 | |||
| 71284b5a9c | |||
| 0a730b7a1a | |||
| 753d7eb22a | |||
| 6e961e0994 | |||
| 6bea44269f | |||
| b2a2b9fcf4 | |||
| 543a61efe0 | |||
| 688fad770c | |||
| e87dd8d3ce | |||
| 30851a7d7b | |||
| 3f4673b2a7 | |||
| 528a1f84e4 | |||
| 1af474c449 | |||
| 7e3405f3fd | |||
| ffeb089aa7 | |||
| 3838c32ddf | |||
| 0c1cb40add | |||
| bfb8d59827 | |||
| 19961ca343 | |||
| 6c007a8ca8 | |||
| 8e6a9bb309 | |||
| 594834a908 | |||
| a5e9aa83b8 | |||
| 5a77661fb3 | |||
| ee5d3ea6a9 | |||
| f6da0fe31b | |||
| 80a02382e1 | |||
| b9a8400453 | |||
| 3a17d2855b | |||
| 086b48c79d | |||
| 1f561fbf38 | |||
| 45e63e9910 | |||
| 66e89c83e2 | |||
| 470fa0191b | |||
| 7c15943a81 | |||
| 05adf7539f | |||
| a9a49e3421 | |||
| 4dd8241fa1 | |||
| 431b2f9061 | |||
| f822292584 | |||
| 4ffc5d4069 | |||
| 680fbed28c | |||
| 737524831b | |||
| b8c36ac192 | |||
| 547686069f | |||
| ac18ac8274 | |||
| cb983da990 | |||
| cfe64dcb61 | |||
| 2db521d510 | |||
| ff6c763b7b | |||
| ebf7521fa1 | |||
| 7a2d96fcd7 | |||
| c6c8047982 | |||
| 9cfb7250de | |||
| 79b5b039b0 | |||
| 29616f8325 | |||
| 8bbe81d294 | |||
| 571fb1b12c | |||
| 02f6f97aa1 | |||
| 1d74d0984e | |||
| 6448386f76 | |||
| d09e85ba45 | |||
| a9bc1cc7f0 | |||
| 54d9653f04 | |||
| efc66821a6 | |||
| 3af7adc45b | |||
| 5754f2183c | |||
| f7f7f1bd9d | |||
| 57bb3f5e74 | |||
| 49196e7c7b | |||
| 894b63e668 | |||
| e16d44ff20 | |||
| b8b3f3001b | |||
| d142ecea6e | |||
| b793984ede | |||
| ae2532afe5 | |||
| 2720a3b35e | |||
| 2350364543 | |||
| f4172cb1fc | |||
| 90c482ae4f | |||
| 1eb8ad62e0 |
+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
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
name: Issue Updates Workflow
|
name: on-issue
|
||||||
|
|
||||||
on:
|
on:
|
||||||
issues:
|
issues:
|
||||||
types: [opened, closed, reopened]
|
types: [ opened, closed, reopened ]
|
||||||
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
|
||||||
build:
|
on-issue:
|
||||||
name: Build
|
name: On new issue
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Send Telegram Message
|
- name: Send Telegram Message
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
name: Release Updates Workflow
|
name: on-publish
|
||||||
|
|
||||||
on:
|
on:
|
||||||
release:
|
release:
|
||||||
types: [published]
|
types: [ published ]
|
||||||
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
|
||||||
build:
|
on-publish:
|
||||||
name: Build
|
name: On publish
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Send Telegram Message
|
- name: Send Telegram Message
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
name: Android CI Tag Deployment (Pre-release)
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- '*.*.*-**'
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
name: Build Signed APK
|
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
env:
|
|
||||||
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
|
|
||||||
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
|
|
||||||
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
|
|
||||||
KEY_STORE_FILE: 'android_keystore.jks'
|
|
||||||
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
|
|
||||||
GH_USER: ${{ secrets.GH_USER }}
|
|
||||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
# 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
|
|
||||||
|
|
||||||
# Build and sign APK ("-x test" argument is used to skip tests)
|
|
||||||
# add fdroid flavor for apk upload
|
|
||||||
- name: Build Fdroid Release APK
|
|
||||||
run: ./gradlew :app:assembleFdroidRelease -x test
|
|
||||||
|
|
||||||
# get fdroid flavor release apk path
|
|
||||||
- name: Get apk path
|
|
||||||
id: apk-path
|
|
||||||
run: echo "path=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_OUTPUT
|
|
||||||
- name: Get version code
|
|
||||||
run: |
|
|
||||||
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
|
|
||||||
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
|
|
||||||
# Save the APK after the Build job is complete to publish it as a Github release in the next job
|
|
||||||
- name: Upload APK
|
|
||||||
uses: actions/upload-artifact@v4.3.3
|
|
||||||
with:
|
|
||||||
name: wgtunnel
|
|
||||||
path: ${{ steps.apk-path.outputs.path }}
|
|
||||||
- name: Download APK from build
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: wgtunnel
|
|
||||||
- name: Create Release with Fastlane changelog notes
|
|
||||||
id: create_release
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
with:
|
|
||||||
# fix hardcode changelog file name
|
|
||||||
body_path: ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt
|
|
||||||
tag_name: ${{ github.ref_name }}
|
|
||||||
name: ${{ github.ref_name }}
|
|
||||||
draft: false
|
|
||||||
prerelease: true
|
|
||||||
files: ${{ github.workspace }}/${{ steps.apk-path.outputs.path }}
|
|
||||||
|
|
||||||
- name: Install apksigner
|
|
||||||
run: |
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y apksigner
|
|
||||||
|
|
||||||
- name: Get checksum
|
|
||||||
id: checksum
|
|
||||||
run: echo "checksum=$(apksigner verify -print-certs ${{ steps.apk-path.outputs.path }} | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT
|
|
||||||
|
|
||||||
- name: Append checksum
|
|
||||||
id: append_checksum
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
with:
|
|
||||||
body: |
|
|
||||||
|
|
||||||
SHA256 fingerprint:
|
|
||||||
```${{ steps.checksum.outputs.checksum }}```
|
|
||||||
tag_name: ${{ github.ref_name }}
|
|
||||||
name: ${{ github.ref_name }}
|
|
||||||
draft: false
|
|
||||||
prerelease: true
|
|
||||||
append_body: true
|
|
||||||
|
|
||||||
- name: Deploy with fastlane
|
|
||||||
uses: ruby/setup-ruby@v1
|
|
||||||
with:
|
|
||||||
ruby-version: '3.2' # Not needed with a .ruby-version file
|
|
||||||
bundler-cache: true
|
|
||||||
- name: Distribute app to Beta track 🚀
|
|
||||||
run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane beta)
|
|
||||||
|
|
||||||
+182
-44
@@ -1,19 +1,59 @@
|
|||||||
# name of the workflow
|
name: release-android
|
||||||
name: Android CI Tag Deployment (Release)
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "4 3 * * *"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
push:
|
inputs:
|
||||||
tags:
|
track:
|
||||||
- '*.*.*'
|
type: choice
|
||||||
- '!*.*.*-**'
|
description: "Google play release track"
|
||||||
|
options:
|
||||||
|
- none
|
||||||
|
- internal
|
||||||
|
- alpha
|
||||||
|
- beta
|
||||||
|
- production
|
||||||
|
default: none
|
||||||
|
required: true
|
||||||
|
release_type:
|
||||||
|
type: choice
|
||||||
|
description: "GitHub release type"
|
||||||
|
options:
|
||||||
|
- none
|
||||||
|
- prerelease
|
||||||
|
- nightly
|
||||||
|
- release
|
||||||
|
default: release
|
||||||
|
required: true
|
||||||
|
tag_name:
|
||||||
|
description: "Tag name for release"
|
||||||
|
required: false
|
||||||
|
default: nightly
|
||||||
|
workflow_call:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
check_date:
|
||||||
name: Build Signed APK
|
runs-on: ubuntu-latest
|
||||||
|
name: Check latest commit
|
||||||
|
outputs:
|
||||||
|
should_run: ${{ steps.should_run.outputs.should_run }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: print latest_commit
|
||||||
|
run: echo ${{ github.sha }}
|
||||||
|
- id: should_run
|
||||||
|
continue-on-error: true
|
||||||
|
name: check latest commit is less than a day
|
||||||
|
if: ${{ github.event_name == 'schedule' }}
|
||||||
|
run: test -z $(git rev-list --after="23 hours" ${{ github.sha }}) && echo "::set-output name=should_run::false"
|
||||||
|
build:
|
||||||
|
needs: check_date
|
||||||
|
if: |
|
||||||
|
github.event_name != 'schedule' ||
|
||||||
|
(needs.check_date.outputs.should_run == 'true' && github.event_name == 'schedule')
|
||||||
|
name: Build Signed APK
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
env:
|
env:
|
||||||
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
|
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
|
||||||
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
|
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
|
||||||
@@ -21,7 +61,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
|
||||||
@@ -34,6 +76,10 @@ jobs:
|
|||||||
- name: Grant execute permission for gradlew
|
- name: Grant execute permission for gradlew
|
||||||
run: chmod +x gradlew
|
run: chmod +x gradlew
|
||||||
|
|
||||||
|
- name: Install system dependencies
|
||||||
|
run: |
|
||||||
|
sudo apt update && sudo apt install -y gh apksigner
|
||||||
|
|
||||||
# Here we need to decode keystore.jks from base64 string and place it
|
# Here we need to decode keystore.jks from base64 string and place it
|
||||||
# in the folder specified in the release signing configuration
|
# in the folder specified in the release signing configuration
|
||||||
- name: Decode Keystore
|
- name: Decode Keystore
|
||||||
@@ -57,75 +103,167 @@ 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 == 'release' }}
|
||||||
run: ./gradlew :app:assembleFdroidRelease -x test
|
run: ./gradlew :app:assembleFdroidRelease -x test
|
||||||
|
|
||||||
# get fdroid flavor release apk path
|
- name: Build Fdroid Prerelease APK
|
||||||
- name: Get apk path
|
if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }}
|
||||||
id: apk-path
|
run: ./gradlew :app:assembleFdroidPrerelease -x test
|
||||||
run: echo "path=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_OUTPUT
|
|
||||||
|
- name: Build Fdroid Nightly APK
|
||||||
|
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
|
||||||
|
run: ./gradlew :app:assembleFdroidNightly -x test
|
||||||
|
|
||||||
|
- if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
|
||||||
|
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/nightly/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
|
||||||
|
- if: ${{ inputs.release_type != '' && inputs.release_type == 'release' }}
|
||||||
|
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
|
||||||
|
- if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }}
|
||||||
|
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/prerelease/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Get version code
|
- name: Get version code
|
||||||
|
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
|
||||||
|
|
||||||
|
- name: Commit and push versionCode changes
|
||||||
|
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' || inputs.release_type == 'prerelease' }}
|
||||||
|
run: |
|
||||||
|
git config --global user.name 'GitHub Actions'
|
||||||
|
git config --global user.email 'actions@github.com'
|
||||||
|
git add versionCode.txt
|
||||||
|
git commit -m "Automated build update"
|
||||||
|
|
||||||
|
- name: Push changes
|
||||||
|
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' || inputs.release_type == 'prerelease' }}
|
||||||
|
uses: ad-m/github-push-action@master
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
branch: ${{ github.ref }}
|
||||||
|
|
||||||
# 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.3
|
uses: actions/upload-artifact@v4.4.0
|
||||||
with:
|
with:
|
||||||
name: wgtunnel
|
name: wgtunnel
|
||||||
path: ${{ steps.apk-path.outputs.path }}
|
path: ${{ env.APK_PATH }}
|
||||||
|
|
||||||
- name: Download APK from build
|
- name: Download APK from build
|
||||||
uses: actions/download-artifact@v4
|
uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: wgtunnel
|
name: wgtunnel
|
||||||
|
|
||||||
- name: Repository Dispatch for my F-Droid repo
|
- name: Repository Dispatch for my F-Droid repo
|
||||||
uses: peter-evans/repository-dispatch@v3
|
uses: peter-evans/repository-dispatch@v3
|
||||||
|
if: ${{ inputs.release_type == 'release' }}
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.PAT }}
|
token: ${{ secrets.PAT }}
|
||||||
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
|
||||||
|
if: ${{ inputs.release_type == 'release' }}
|
||||||
|
run: |
|
||||||
|
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
|
||||||
|
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
|
||||||
|
echo "$RELEASE_NOTES" >> $GITHUB_ENV
|
||||||
|
echo "EOF" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: On nightly release notes
|
||||||
|
if: ${{ contains(env.TAG_NAME, 'nightly') }}
|
||||||
|
run: |
|
||||||
|
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
|
||||||
|
gh release delete nightly --yes || true
|
||||||
|
git push origin :nightly || true
|
||||||
|
|
||||||
|
- name: On prerelease release notes
|
||||||
|
if: ${{ inputs.release_type == 'prerelease' }}
|
||||||
|
run: |
|
||||||
|
echo "RELEASE_NOTES=Testing version of app for specific feature." >> $GITHUB_ENV
|
||||||
|
gh release delete ${{ github.event.inputs.tag_name }} --yes || true
|
||||||
|
|
||||||
|
- name: Get checksum
|
||||||
|
id: checksum
|
||||||
|
run: echo "checksum=$(apksigner verify -print-certs ${{ env.APK_PATH }} | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
|
||||||
- name: Create Release with Fastlane changelog notes
|
- name: Create Release with Fastlane changelog notes
|
||||||
id: create_release
|
id: create_release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
with:
|
|
||||||
body_path: ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt
|
|
||||||
tag_name: ${{ github.ref_name }}
|
|
||||||
name: ${{ github.ref_name }}
|
|
||||||
draft: false
|
|
||||||
prerelease: false
|
|
||||||
files: ${{ github.workspace }}/${{ steps.apk-path.outputs.path }}
|
|
||||||
|
|
||||||
- name: Install apksigner
|
|
||||||
run: |
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y apksigner
|
|
||||||
|
|
||||||
- name: Get checksum
|
|
||||||
id: checksum
|
|
||||||
run: echo "checksum=$(apksigner verify -print-certs ${{ steps.apk-path.outputs.path }} | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT
|
|
||||||
|
|
||||||
- name: Append checksum
|
|
||||||
id: append_checksum
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
with:
|
with:
|
||||||
body: |
|
body: |
|
||||||
|
${{ env.RELEASE_NOTES }}
|
||||||
|
|
||||||
SHA256 fingerprint:
|
SHA256 fingerprint:
|
||||||
```${{ steps.checksum.outputs.checksum }}```
|
```${{ steps.checksum.outputs.checksum }}```
|
||||||
tag_name: ${{ github.ref_name }}
|
tag_name: ${{ env.TAG_NAME }}
|
||||||
name: ${{ github.ref_name }}
|
name: ${{ env.TAG_NAME }}
|
||||||
draft: false
|
draft: false
|
||||||
prerelease: false
|
prerelease: ${{ inputs.release_type == 'prerelease' || inputs.release_type == '' || inputs.release_type == 'nightly' }}
|
||||||
append_body: true
|
make_latest: ${{ inputs.release_type == 'release' }}
|
||||||
|
files: ${{ github.workspace }}/${{ env.APK_PATH }}
|
||||||
|
|
||||||
|
publish-play:
|
||||||
|
if: ${{ inputs.track != 'none' && inputs.track != '' }}
|
||||||
|
name: Publish to Google Play
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
env:
|
||||||
|
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
|
||||||
|
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
|
||||||
|
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
|
||||||
|
KEY_STORE_FILE: 'android_keystore.jks'
|
||||||
|
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
|
||||||
|
GH_USER: ${{ secrets.GH_USER }}
|
||||||
|
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# 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:
|
||||||
ruby-version: '3.2' # Not needed with a .ruby-version file
|
ruby-version: '3.2' # Not needed with a .ruby-version file
|
||||||
bundler-cache: true
|
bundler-cache: true
|
||||||
- name: Distribute app to Prod track 🚀
|
|
||||||
run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane production)
|
- name: Distribute app to Prod track 🚀
|
||||||
|
run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane ${{ inputs.track }})
|
||||||
|
|
||||||
|
|||||||
@@ -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/
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ WG Tunnel
|
|||||||
|
|
||||||
<div align="left">
|
<div align="left">
|
||||||
|
|
||||||
This is an alternative Android Application for [WireGuard](https://www.wireguard.com/) and [AmneziaWG](https://docs.amnezia.org/documentation/amnezia-wg/) with added
|
This is an alternative Android Application for [WireGuard](https://www.wireguard.com/)
|
||||||
|
and [AmneziaWG](https://docs.amnezia.org/documentation/amnezia-wg/) with added
|
||||||
features. Built using the [wireguard-android](https://github.com/WireGuard/wireguard-android)
|
features. Built using the [wireguard-android](https://github.com/WireGuard/wireguard-android)
|
||||||
library and [Jetpack Compose](https://developer.android.com/jetpack/compose), this application was
|
library and [Jetpack Compose](https://developer.android.com/jetpack/compose), this application was
|
||||||
inspired by the official [WireGuard Android](https://github.com/WireGuard/wireguard-android) app.
|
inspired by the official [WireGuard Android](https://github.com/WireGuard/wireguard-android) app.
|
||||||
@@ -54,37 +55,38 @@ and on while on different networks. This app was created to offer a free solutio
|
|||||||
* Split tunneling by application with search
|
* Split tunneling by application with search
|
||||||
* WireGuard support for kernel and userspace modes
|
* WireGuard support for kernel and userspace modes
|
||||||
* Amnezia support for userspace mode for DPI/censorship protection
|
* Amnezia support for userspace mode for DPI/censorship protection
|
||||||
|
* Pre/Post Up/Down scripts support for all modes on a rooted device
|
||||||
* Always-On VPN support
|
* Always-On VPN support
|
||||||
* Export Amnezia and WireGuard tunnels to zip
|
* Export Amnezia and WireGuard tunnels to zip
|
||||||
* Quick tile support for tunnel toggling, auto-tunneling
|
* Quick tile support for tunnel toggling, auto-tunneling
|
||||||
* Static shortcuts support for tunnel toggling, auto-tunneling
|
* Static shortcuts support for tunnel toggling, auto-tunneling
|
||||||
* Intent automation support for all tunnels
|
* Intent automation support for all tunnels
|
||||||
* Automatic auto-tunneling service restart after reboot
|
* Automatic auto-tunneling service and/or tunnel restart after reboot or app update
|
||||||
* Automatic tunnel restart after reboot
|
|
||||||
* Battery preservation measures
|
* Battery preservation measures
|
||||||
* Restart tunnel on ping failure (beta)
|
* Restart tunnel on ping failure (beta)
|
||||||
|
|
||||||
|
## Fdroid
|
||||||
|
|
||||||
|
Want updates faster?
|
||||||
|
|
||||||
|
Check out my personal [fdroid repository](https://github.com/zaneschepke/fdroid) to get updates the
|
||||||
|
moment they are released.
|
||||||
|
|
||||||
## Docs
|
## Docs
|
||||||
|
|
||||||
Basic documentation of the feature and behaviors of this app can be
|
Information about features, behaviors, and answers to common questions can be found in the
|
||||||
found [here](https://zaneschepke.com/wgtunnel-docs/overview.html).
|
app [documentation](https://zaneschepke.com/wgtunnel-docs/overview.html).
|
||||||
|
|
||||||
The repository for these docs can be found [here](https://github.com/zaneschepke/wgtunnel-docs).
|
The repository for these docs can be found [here](https://github.com/zaneschepke/wgtunnel-docs).
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
Any contributions in the form of feedback, issues, code, or translations are welcome and much appreciated!
|
|
||||||
|
|
||||||
Please read the [code of conduct](https://github.com/zaneschepke/wgtunnel?tab=coc-ov-file#contributor-code-of-conduct) before contributing.
|
|
||||||
|
|
||||||
## Translation
|
## Translation
|
||||||
|
|
||||||
This app is using [Weblate](https://weblate.org) to assist with translations.
|
This app is using [Weblate](https://weblate.org) to assist with translations.
|
||||||
|
|
||||||
Help translate WG Tunnel into your language at [Hosted Weblate](https://hosted.weblate.org/engage/wg-tunnel/).\
|
Help translate WG Tunnel into your language
|
||||||
|
at [Hosted Weblate](https://hosted.weblate.org/engage/wg-tunnel/).\
|
||||||
[](https://hosted.weblate.org/engage/wg-tunnel/)
|
[](https://hosted.weblate.org/engage/wg-tunnel/)
|
||||||
|
|
||||||
|
|
||||||
## Building
|
## Building
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -98,4 +100,11 @@ And then build the app:
|
|||||||
$ ./gradlew assembleDebug
|
$ ./gradlew assembleDebug
|
||||||
```
|
```
|
||||||
|
|
||||||
</span>
|
## Contributing
|
||||||
|
|
||||||
|
Any contributions in the form of feedback, issues, code, or translations are welcome and much
|
||||||
|
appreciated!
|
||||||
|
|
||||||
|
Please read
|
||||||
|
the [code of conduct](https://github.com/zaneschepke/wgtunnel?tab=coc-ov-file#contributor-code-of-conduct)
|
||||||
|
before contributing.
|
||||||
|
|||||||
+86
-61
@@ -1,11 +1,26 @@
|
|||||||
import java.util.Properties
|
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.android.application)
|
alias(libs.plugins.android.application)
|
||||||
alias(libs.plugins.kotlin.android)
|
alias(libs.plugins.kotlin.android)
|
||||||
alias(libs.plugins.hilt.android)
|
alias(libs.plugins.hilt.android)
|
||||||
alias(libs.plugins.kotlinxSerialization)
|
alias(libs.plugins.kotlinxSerialization)
|
||||||
alias(libs.plugins.ksp)
|
alias(libs.plugins.ksp)
|
||||||
|
alias(libs.plugins.compose.compiler)
|
||||||
|
alias(libs.plugins.grgit)
|
||||||
|
}
|
||||||
|
|
||||||
|
val versionFile = file("$rootDir/versionCode.txt")
|
||||||
|
|
||||||
|
val versionCodeIncrement = with(getBuildTaskName().lowercase()) {
|
||||||
|
when {
|
||||||
|
this.contains(Constants.NIGHTLY) || this.contains(Constants.PRERELEASE) -> {
|
||||||
|
if (versionFile.exists()) {
|
||||||
|
versionFile.readText().toInt() + 1
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
@@ -20,8 +35,8 @@ android {
|
|||||||
applicationId = Constants.APP_ID
|
applicationId = Constants.APP_ID
|
||||||
minSdk = Constants.MIN_SDK
|
minSdk = Constants.MIN_SDK
|
||||||
targetSdk = Constants.TARGET_SDK
|
targetSdk = Constants.TARGET_SDK
|
||||||
versionCode = Constants.VERSION_CODE
|
versionCode = Constants.VERSION_CODE + versionCodeIncrement
|
||||||
versionName = Constants.VERSION_NAME
|
versionName = determineVersionName()
|
||||||
|
|
||||||
ksp { arg("room.schemaLocation", "$projectDir/schemas") }
|
ksp { arg("room.schemaLocation", "$projectDir/schemas") }
|
||||||
|
|
||||||
@@ -35,44 +50,10 @@ android {
|
|||||||
|
|
||||||
signingConfigs {
|
signingConfigs {
|
||||||
create(Constants.RELEASE) {
|
create(Constants.RELEASE) {
|
||||||
val properties =
|
storeFile = getStoreFile()
|
||||||
Properties().apply {
|
storePassword = getSigningProperty(Constants.STORE_PASS_VAR)
|
||||||
// created local file for signing details
|
keyAlias = getSigningProperty(Constants.KEY_ALIAS_VAR)
|
||||||
try {
|
keyPassword = getSigningProperty(Constants.KEY_PASS_VAR)
|
||||||
load(file("signing.properties").reader())
|
|
||||||
} catch (_: Exception) {
|
|
||||||
load(file("signing_template.properties").reader())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// try to get secrets from env first for pipeline build, then properties file for local
|
|
||||||
// build
|
|
||||||
storeFile =
|
|
||||||
file(
|
|
||||||
System.getenv()
|
|
||||||
.getOrDefault(
|
|
||||||
Constants.KEY_STORE_PATH_VAR,
|
|
||||||
properties.getProperty(Constants.KEY_STORE_PATH_VAR),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
storePassword =
|
|
||||||
System.getenv()
|
|
||||||
.getOrDefault(
|
|
||||||
Constants.STORE_PASS_VAR,
|
|
||||||
properties.getProperty(Constants.STORE_PASS_VAR),
|
|
||||||
)
|
|
||||||
keyAlias =
|
|
||||||
System.getenv()
|
|
||||||
.getOrDefault(
|
|
||||||
Constants.KEY_ALIAS_VAR,
|
|
||||||
properties.getProperty(Constants.KEY_ALIAS_VAR),
|
|
||||||
)
|
|
||||||
keyPassword =
|
|
||||||
System.getenv()
|
|
||||||
.getOrDefault(
|
|
||||||
Constants.KEY_PASS_VAR,
|
|
||||||
properties.getProperty(Constants.KEY_PASS_VAR),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,16 +63,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
|
||||||
@@ -102,7 +73,38 @@ android {
|
|||||||
)
|
)
|
||||||
signingConfig = signingConfigs.getByName(Constants.RELEASE)
|
signingConfig = signingConfigs.getByName(Constants.RELEASE)
|
||||||
}
|
}
|
||||||
debug { isDebuggable = true }
|
debug {
|
||||||
|
applicationIdSuffix = ".debug"
|
||||||
|
versionNameSuffix = "-debug"
|
||||||
|
resValue("string", "app_name", "WG Tunnel - Debug")
|
||||||
|
isDebuggable = true
|
||||||
|
}
|
||||||
|
|
||||||
|
create(Constants.PRERELEASE) {
|
||||||
|
initWith(buildTypes.getByName(Constants.RELEASE))
|
||||||
|
applicationIdSuffix = ".prerelease"
|
||||||
|
versionNameSuffix = "-pre"
|
||||||
|
resValue("string", "app_name", "WG Tunnel - Pre")
|
||||||
|
}
|
||||||
|
|
||||||
|
create(Constants.NIGHTLY) {
|
||||||
|
initWith(buildTypes.getByName(Constants.RELEASE))
|
||||||
|
applicationIdSuffix = ".nightly"
|
||||||
|
versionNameSuffix = "-nightly"
|
||||||
|
resValue("string", "app_name", "WG Tunnel - Nightly")
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
productFlavors {
|
productFlavors {
|
||||||
@@ -112,9 +114,6 @@ android {
|
|||||||
}
|
}
|
||||||
create("general") {
|
create("general") {
|
||||||
dimension = Constants.TYPE
|
dimension = Constants.TYPE
|
||||||
if (BuildHelper.isReleaseBuild(gradle) && BuildHelper.isGeneralFlavor(gradle)) {
|
|
||||||
//any plugins general specific
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
compileOptions {
|
compileOptions {
|
||||||
@@ -127,7 +126,6 @@ android {
|
|||||||
compose = true
|
compose = true
|
||||||
buildConfig = true
|
buildConfig = true
|
||||||
}
|
}
|
||||||
composeOptions { kotlinCompilerExtensionVersion = Constants.COMPOSE_COMPILER_EXTENSION_VERSION }
|
|
||||||
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
|
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,6 +160,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)
|
||||||
@@ -169,13 +168,10 @@ 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)
|
||||||
|
|
||||||
implementation(libs.zaneschepke.multifab)
|
|
||||||
|
|
||||||
// hilt
|
// hilt
|
||||||
implementation(libs.hilt.android)
|
implementation(libs.hilt.android)
|
||||||
ksp(libs.hilt.android.compiler)
|
ksp(libs.hilt.android.compiler)
|
||||||
@@ -203,7 +199,6 @@ dependencies {
|
|||||||
|
|
||||||
// barcode scanning
|
// barcode scanning
|
||||||
implementation(libs.zxing.android.embedded)
|
implementation(libs.zxing.android.embedded)
|
||||||
implementation(libs.zxing.core)
|
|
||||||
|
|
||||||
// bio
|
// bio
|
||||||
implementation(libs.androidx.biometric.ktx)
|
implementation(libs.androidx.biometric.ktx)
|
||||||
@@ -212,4 +207,34 @@ dependencies {
|
|||||||
// shortcuts
|
// shortcuts
|
||||||
implementation(libs.androidx.core)
|
implementation(libs.androidx.core)
|
||||||
implementation(libs.androidx.core.google.shortcuts)
|
implementation(libs.androidx.core.google.shortcuts)
|
||||||
|
|
||||||
|
// splash
|
||||||
|
implementation(libs.androidx.core.splashscreen)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun determineVersionName(): String {
|
||||||
|
return with(getBuildTaskName().lowercase()) {
|
||||||
|
when {
|
||||||
|
contains(Constants.NIGHTLY) || contains(Constants.PRERELEASE) ->
|
||||||
|
Constants.VERSION_NAME +
|
||||||
|
"-${grgitService.service.get().grgit.head().abbreviatedId}"
|
||||||
|
else -> Constants.VERSION_NAME
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val incrementVersionCode by tasks.registering {
|
||||||
|
doLast {
|
||||||
|
val versionFile = file("$rootDir/versionCode.txt")
|
||||||
|
if (versionFile.exists()) {
|
||||||
|
versionFile.writeText(versionCodeIncrement.toString())
|
||||||
|
println("Incremented versionCode to $versionCodeIncrement")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.whenTaskAdded {
|
||||||
|
if (name.startsWith("assemble") && !name.lowercase().contains("debug")) {
|
||||||
|
dependsOn(incrementVersionCode)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
-2
@@ -22,5 +22,3 @@
|
|||||||
-keepclassmembers class * extends androidx.datastore.preferences.protobuf.GeneratedMessageLite {
|
-keepclassmembers class * extends androidx.datastore.preferences.protobuf.GeneratedMessageLite {
|
||||||
<fields>;
|
<fields>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,225 @@
|
|||||||
|
{
|
||||||
|
"formatVersion": 1,
|
||||||
|
"database": {
|
||||||
|
"version": 10,
|
||||||
|
"identityHash": "c8621055524f90b4d1972f6171f59e80",
|
||||||
|
"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, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `ping_interval` INTEGER DEFAULT null, `ping_cooldown` INTEGER DEFAULT null, `ping_ip` TEXT DEFAULT null)",
|
||||||
|
"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"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isPingEnabled",
|
||||||
|
"columnName": "is_ping_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "pingInterval",
|
||||||
|
"columnName": "ping_interval",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": false,
|
||||||
|
"defaultValue": "null"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "pingCooldown",
|
||||||
|
"columnName": "ping_cooldown",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": false,
|
||||||
|
"defaultValue": "null"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "pingIp",
|
||||||
|
"columnName": "ping_ip",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": false,
|
||||||
|
"defaultValue": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"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, 'c8621055524f90b4d1972f6171f59e80')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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" />
|
||||||
@@ -51,7 +57,7 @@
|
|||||||
</queries>
|
</queries>
|
||||||
<application
|
<application
|
||||||
android:name=".WireGuardAutoTunnel"
|
android:name=".WireGuardAutoTunnel"
|
||||||
android:allowBackup="true"
|
android:allowBackup="false"
|
||||||
android:banner="@drawable/ic_banner"
|
android:banner="@drawable/ic_banner"
|
||||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
android:enableOnBackInvokedCallback="true"
|
android:enableOnBackInvokedCallback="true"
|
||||||
@@ -60,18 +66,17 @@
|
|||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
android:supportsRtl="true"
|
android:supportsRtl="true"
|
||||||
android:theme="@style/Theme.WireguardAutoTunnel"
|
android:theme="@style/Theme.AppSplashScreen"
|
||||||
tools:targetApi="tiramisu">
|
tools:targetApi="tiramisu">
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.MainActivity"
|
android:name=".ui.SplashActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:theme="@style/Theme.WireguardAutoTunnel">
|
android:theme="@style/Theme.AppSplashScreen">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
|
||||||
<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" />
|
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
<meta-data
|
<meta-data
|
||||||
@@ -79,25 +84,25 @@
|
|||||||
android:resource="@xml/shortcuts" />
|
android:resource="@xml/shortcuts" />
|
||||||
</activity>
|
</activity>
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.CaptureActivityPortrait"
|
android:name=".ui.MainActivity"
|
||||||
android:screenOrientation="fullSensor"
|
android:exported="true"
|
||||||
android:stateNotNeeded="true"
|
android:theme="@style/Theme.WireguardAutoTunnel">
|
||||||
android:theme="@style/zxing_CaptureTheme"
|
</activity>
|
||||||
android:windowSoftInputMode="stateAlwaysHidden"
|
<activity
|
||||||
tools:ignore="DiscouragedApi" />
|
android:name="com.journeyapps.barcodescanner.CaptureActivity"
|
||||||
|
android:screenOrientation="portrait"
|
||||||
|
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
|
|
||||||
android:name=".service.foreground.ForegroundService"
|
|
||||||
android:enabled="true"
|
|
||||||
android:exported="false"
|
|
||||||
android:foregroundServiceType="systemExempted"
|
|
||||||
tools:node="merge" />
|
|
||||||
<service
|
<service
|
||||||
android:name=".service.tile.TunnelControlTile"
|
android:name=".service.tile.TunnelControlTile"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
@@ -133,7 +138,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"
|
||||||
@@ -148,7 +153,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"
|
||||||
@@ -156,6 +161,16 @@
|
|||||||
android:stopWithTask="false"
|
android:stopWithTask="false"
|
||||||
tools:node="merge" />
|
tools:node="merge" />
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".service.foreground.TunnelBackgroundService"
|
||||||
|
android:exported="false"
|
||||||
|
android:foregroundServiceType="systemExempted"
|
||||||
|
android:permission="android.permission.BIND_VPN_SERVICE">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.net.VpnService" />
|
||||||
|
</intent-filter>
|
||||||
|
</service>
|
||||||
|
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".receiver.BootReceiver"
|
android:name=".receiver.BootReceiver"
|
||||||
android:enabled="true"
|
android:enabled="true"
|
||||||
@@ -170,7 +185,23 @@
|
|||||||
</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.AppUpdateReceiver"
|
||||||
|
android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
<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,56 +1,59 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel
|
package com.zaneschepke.wireguardautotunnel
|
||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
import android.content.ComponentName
|
import android.os.StrictMode
|
||||||
import android.content.pm.PackageManager
|
import android.os.StrictMode.ThreadPolicy
|
||||||
import android.service.quicksettings.TileService
|
import com.zaneschepke.logcatter.LocalLogCollector
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tile.AutoTunnelControlTile
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tile.TunnelControlTile
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
|
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
import dagger.hilt.android.HiltAndroidApp
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
import kotlinx.coroutines.MainScope
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.cancel
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
import javax.inject.Inject
|
||||||
|
|
||||||
@HiltAndroidApp
|
@HiltAndroidApp
|
||||||
class WireGuardAutoTunnel : Application() {
|
class WireGuardAutoTunnel : Application() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var localLogCollector: LocalLogCollector
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@IoDispatcher
|
||||||
|
lateinit var ioDispatcher: CoroutineDispatcher
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
instance = this
|
instance = this
|
||||||
if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree()) else Timber.plant(ReleaseTree())
|
if (BuildConfig.DEBUG) {
|
||||||
PinManager.initialize(this)
|
Timber.plant(Timber.DebugTree())
|
||||||
|
StrictMode.setThreadPolicy(
|
||||||
|
ThreadPolicy.Builder()
|
||||||
|
.detectDiskReads()
|
||||||
|
.detectDiskWrites()
|
||||||
|
.detectNetwork()
|
||||||
|
.penaltyLog()
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Timber.plant(ReleaseTree())
|
||||||
|
}
|
||||||
|
if (!isRunningOnTv()) {
|
||||||
|
applicationScope.launch(ioDispatcher) {
|
||||||
|
localLogCollector.start()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onLowMemory() {
|
|
||||||
super.onLowMemory()
|
|
||||||
applicationScope.cancel("onLowMemory() called by system")
|
|
||||||
applicationScope = MainScope()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|
||||||
var applicationScope = MainScope()
|
|
||||||
|
|
||||||
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 = 10,
|
||||||
autoMigrations =
|
autoMigrations =
|
||||||
[
|
[
|
||||||
AutoMigration(from = 1, to = 2),
|
AutoMigration(from = 1, to = 2),
|
||||||
@@ -33,7 +33,9 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|||||||
to = 7,
|
to = 7,
|
||||||
spec = RemoveLegacySettingColumnsMigration::class,
|
spec = RemoveLegacySettingColumnsMigration::class,
|
||||||
),
|
),
|
||||||
AutoMigration(7, 8)
|
AutoMigration(7, 8),
|
||||||
|
AutoMigration(8, 9),
|
||||||
|
AutoMigration(9, 10),
|
||||||
],
|
],
|
||||||
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
|
||||||
@@ -21,7 +21,10 @@ interface TunnelConfigDao {
|
|||||||
suspend fun getById(id: Long): TunnelConfig?
|
suspend fun getById(id: Long): TunnelConfig?
|
||||||
|
|
||||||
@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
|
||||||
@@ -36,10 +39,10 @@ interface TunnelConfigDao {
|
|||||||
suspend fun findByTunnelNetworkName(name: String): TunnelConfigs
|
suspend fun findByTunnelNetworkName(name: String): TunnelConfigs
|
||||||
|
|
||||||
@Query("UPDATE TunnelConfig SET is_primary_tunnel = 0 WHERE is_primary_tunnel =1")
|
@Query("UPDATE TunnelConfig SET is_primary_tunnel = 0 WHERE is_primary_tunnel =1")
|
||||||
fun resetPrimaryTunnel()
|
suspend fun resetPrimaryTunnel()
|
||||||
|
|
||||||
@Query("UPDATE TunnelConfig SET is_mobile_data_tunnel = 0 WHERE is_mobile_data_tunnel =1")
|
@Query("UPDATE TunnelConfig SET is_mobile_data_tunnel = 0 WHERE is_mobile_data_tunnel =1")
|
||||||
fun resetMobileDataTunnel()
|
suspend fun resetMobileDataTunnel()
|
||||||
|
|
||||||
@Query("SELECT * FROM TUNNELCONFIG WHERE is_primary_tunnel=1")
|
@Query("SELECT * FROM TUNNELCONFIG WHERE is_primary_tunnel=1")
|
||||||
suspend fun findByPrimary(): TunnelConfigs
|
suspend fun findByPrimary(): TunnelConfigs
|
||||||
|
|||||||
+26
-7
@@ -4,24 +4,27 @@ import android.content.Context
|
|||||||
import androidx.datastore.preferences.core.Preferences
|
import androidx.datastore.preferences.core.Preferences
|
||||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||||
import androidx.datastore.preferences.core.edit
|
import androidx.datastore.preferences.core.edit
|
||||||
import androidx.datastore.preferences.core.intPreferencesKey
|
|
||||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||||
import androidx.datastore.preferences.preferencesDataStore
|
import androidx.datastore.preferences.preferencesDataStore
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
|
|
||||||
class DataStoreManager(private val context: Context) {
|
class DataStoreManager(
|
||||||
|
private val context: Context,
|
||||||
|
@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 =
|
|
||||||
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")
|
||||||
}
|
}
|
||||||
|
|
||||||
// preferences
|
// preferences
|
||||||
@@ -32,14 +35,17 @@ class DataStoreManager(private val context: Context) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
suspend fun init() {
|
suspend fun init() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
try {
|
try {
|
||||||
context.dataStore.data.first()
|
context.dataStore.data.first()
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun <T> saveToDataStore(key: Preferences.Key<T>, value: T) {
|
suspend fun <T> saveToDataStore(key: Preferences.Key<T>, value: T) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
try {
|
try {
|
||||||
context.dataStore.edit { it[key] = value }
|
context.dataStore.edit { it[key] = value }
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
@@ -48,19 +54,32 @@ class DataStoreManager(private val context: Context) {
|
|||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun <T> removeFromDataStore(key: Preferences.Key<T>) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
try {
|
||||||
|
context.dataStore.edit { it.remove(key) }
|
||||||
|
} catch (e: IOException) {
|
||||||
|
Timber.e(e)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Timber.e(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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? {
|
||||||
return try {
|
return withContext(ioDispatcher) {
|
||||||
|
try {
|
||||||
context.dataStore.data.map { it[key] }.first()
|
context.dataStore.data.map { it[key] }.first()
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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()
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.data.domain
|
package com.zaneschepke.wireguardautotunnel.data.domain
|
||||||
|
|
||||||
data class GeneralState(
|
data class GeneralState(
|
||||||
val locationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
||||||
val batteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
||||||
val tunnelRunningFromManualStart: Boolean = TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
|
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
|
||||||
val activeTunnelId: 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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,20 +32,53 @@ 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,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "is_ping_enabled",
|
||||||
|
defaultValue = "false",
|
||||||
|
)
|
||||||
|
val isPingEnabled: Boolean = false,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "ping_interval",
|
||||||
|
defaultValue = "null",
|
||||||
|
)
|
||||||
|
val pingInterval: Long? = null,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "ping_cooldown",
|
||||||
|
defaultValue = "null",
|
||||||
|
)
|
||||||
|
val pingCooldown: Long? = null,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "ping_ip",
|
||||||
|
defaultValue = "null",
|
||||||
|
)
|
||||||
|
var pingIp: String? = null,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
fun toAmConfig(): org.amnezia.awg.config.Config {
|
||||||
|
return configFromAmQuick(if (amQuick != "") amQuick else wgQuick)
|
||||||
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|
||||||
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 {
|
||||||
Config.parse(it)
|
Config.parse(it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fun configFromAmQuick(amQuick: String) : org.amnezia.awg.config.Config {
|
|
||||||
|
fun configFromAmQuick(amQuick: String): org.amnezia.awg.config.Config {
|
||||||
val inputStream: InputStream = amQuick.byteInputStream()
|
val inputStream: InputStream = amQuick.byteInputStream()
|
||||||
return inputStream.bufferedReader(Charsets.UTF_8).use {
|
return inputStream.bufferedReader(Charsets.UTF_8).use {
|
||||||
org.amnezia.awg.config.Config.parse(it)
|
org.amnezia.awg.config.Config.parse(it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const val AM_QUICK_DEFAULT = ""
|
const val AM_QUICK_DEFAULT = ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+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
|
||||||
|
|||||||
+7
-18
@@ -3,32 +3,21 @@ 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()) {
|
tunnels.getActive().let {
|
||||||
appState.getActiveTunnelId()?.let {
|
if (it.isNotEmpty()) return it.first()
|
||||||
tunnels.getById(it)
|
return 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,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-8
@@ -5,22 +5,20 @@ 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 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 setTunnelRunningFromManualStart(id: Int)
|
|
||||||
|
|
||||||
suspend fun setManualStop()
|
|
||||||
|
|
||||||
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>
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-31
@@ -6,7 +6,9 @@ import kotlinx.coroutines.flow.Flow
|
|||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
|
||||||
class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager) :
|
class DataStoreAppStateRepository(
|
||||||
|
private val dataStoreManager: DataStoreManager,
|
||||||
|
) :
|
||||||
AppStateRepository {
|
AppStateRepository {
|
||||||
override suspend fun isLocationDisclosureShown(): Boolean {
|
override suspend fun isLocationDisclosureShown(): Boolean {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN)
|
return dataStoreManager.getFromStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN)
|
||||||
@@ -17,6 +19,15 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
|
|||||||
dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown)
|
dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun isPinLockEnabled(): Boolean {
|
||||||
|
return dataStoreManager.getFromStore(DataStoreManager.IS_PIN_LOCK_ENABLED)
|
||||||
|
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun setPinLockEnabled(enabled: Boolean) {
|
||||||
|
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 dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN)
|
||||||
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
|
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
|
||||||
@@ -26,32 +37,6 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
|
|||||||
dataStoreManager.saveToDataStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN, shown)
|
dataStoreManager.saveToDataStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN, shown)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun isTunnelRunningFromManualStart(): Boolean {
|
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START)
|
|
||||||
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT
|
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun setTunnelRunningFromManualStart(id: Int) {
|
|
||||||
setTunnelRunningFromManualStart(true)
|
|
||||||
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 dataStoreManager.getFromStore(DataStoreManager.CURRENT_SSID)
|
||||||
}
|
}
|
||||||
@@ -65,12 +50,15 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
|
|||||||
prefs?.let { pref ->
|
prefs?.let { pref ->
|
||||||
try {
|
try {
|
||||||
GeneralState(
|
GeneralState(
|
||||||
locationDisclosureShown = pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
|
isLocationDisclosureShown =
|
||||||
|
pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
|
||||||
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
||||||
batteryOptimizationDisableShown = 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,
|
||||||
tunnelRunningFromManualStart = pref[DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START]
|
isPinLockEnabled =
|
||||||
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
|
pref[DataStoreManager.IS_PIN_LOCK_ENABLED]
|
||||||
|
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT,
|
||||||
)
|
)
|
||||||
} 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() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-3
@@ -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,9 +19,11 @@ 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?
|
||||||
|
|
||||||
suspend fun findByTunnelNetworksName(name: String): TunnelConfigs
|
suspend fun findByTunnelNetworksName(name: String): TunnelConfigs
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.module
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.zaneschepke.logcatter.LocalLogCollector
|
||||||
|
import com.zaneschepke.logcatter.LogcatUtil
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
class AppModule {
|
||||||
|
@Singleton
|
||||||
|
@ApplicationScope
|
||||||
|
@Provides
|
||||||
|
fun providesApplicationScope(@DefaultDispatcher defaultDispatcher: CoroutineDispatcher): CoroutineScope =
|
||||||
|
CoroutineScope(SupervisorJob() + defaultDispatcher)
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector {
|
||||||
|
return LogcatUtil.init(context = context)
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
@@ -2,6 +2,10 @@ package com.zaneschepke.wireguardautotunnel.module
|
|||||||
|
|
||||||
import javax.inject.Qualifier
|
import javax.inject.Qualifier
|
||||||
|
|
||||||
|
@Qualifier
|
||||||
|
@Retention(AnnotationRetention.BINARY)
|
||||||
|
annotation class Kernel
|
||||||
|
|
||||||
@Qualifier
|
@Qualifier
|
||||||
@Retention(AnnotationRetention.BINARY)
|
@Retention(AnnotationRetention.BINARY)
|
||||||
annotation class Userspace
|
annotation class Userspace
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.module
|
||||||
|
|
||||||
|
import javax.inject.Qualifier
|
||||||
|
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@Qualifier
|
||||||
|
annotation class DefaultDispatcher
|
||||||
|
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@Qualifier
|
||||||
|
annotation class IoDispatcher
|
||||||
|
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@Qualifier
|
||||||
|
annotation class MainDispatcher
|
||||||
|
|
||||||
|
@Retention(AnnotationRetention.BINARY)
|
||||||
|
@Qualifier
|
||||||
|
annotation class MainImmediateDispatcher
|
||||||
|
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@Qualifier
|
||||||
|
annotation class ApplicationScope
|
||||||
|
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@Qualifier
|
||||||
|
annotation class ServiceScope
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.module
|
||||||
|
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
object CoroutinesDispatchersModule {
|
||||||
|
@DefaultDispatcher
|
||||||
|
@Provides
|
||||||
|
fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
|
||||||
|
|
||||||
|
@IoDispatcher
|
||||||
|
@Provides
|
||||||
|
fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
|
||||||
|
|
||||||
|
@MainDispatcher
|
||||||
|
@Provides
|
||||||
|
fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main
|
||||||
|
|
||||||
|
@MainImmediateDispatcher
|
||||||
|
@Provides
|
||||||
|
fun providesMainImmediateDispatcher(): CoroutineDispatcher = Dispatchers.Main.immediate
|
||||||
|
}
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.module
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import androidx.room.Room
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.AppDatabase
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.DatabaseCallback
|
|
||||||
import dagger.Module
|
|
||||||
import dagger.Provides
|
|
||||||
import dagger.hilt.InstallIn
|
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
|
||||||
import dagger.hilt.components.SingletonComponent
|
|
||||||
import javax.inject.Singleton
|
|
||||||
|
|
||||||
@Module
|
|
||||||
@InstallIn(SingletonComponent::class)
|
|
||||||
class DatabaseModule {
|
|
||||||
@Provides
|
|
||||||
@Singleton
|
|
||||||
fun provideDatabase(@ApplicationContext context: Context): AppDatabase {
|
|
||||||
return Room.databaseBuilder(
|
|
||||||
context,
|
|
||||||
AppDatabase::class.java,
|
|
||||||
context.getString(R.string.db_name),
|
|
||||||
)
|
|
||||||
.fallbackToDestructiveMigration()
|
|
||||||
.addCallback(DatabaseCallback())
|
|
||||||
.build()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.module
|
|
||||||
|
|
||||||
import javax.inject.Qualifier
|
|
||||||
|
|
||||||
@Qualifier
|
|
||||||
@Retention(AnnotationRetention.BINARY)
|
|
||||||
annotation class Kernel
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.module
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.navigation.NavHostController
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.NavigationService
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.components.ActivityRetainedComponent
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import dagger.hilt.android.scopes.ActivityRetainedScoped
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(ActivityRetainedComponent::class)
|
||||||
|
object NavigationModule {
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@ActivityRetainedScoped
|
||||||
|
fun provideNestedNavController(@ApplicationContext context: Context): NavHostController {
|
||||||
|
return NavigationService(context).navController
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.module
|
package com.zaneschepke.wireguardautotunnel.module
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import androidx.room.Room
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
import com.zaneschepke.wireguardautotunnel.data.AppDatabase
|
import com.zaneschepke.wireguardautotunnel.data.AppDatabase
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.DatabaseCallback
|
||||||
import com.zaneschepke.wireguardautotunnel.data.SettingsDao
|
import com.zaneschepke.wireguardautotunnel.data.SettingsDao
|
||||||
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
|
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
|
||||||
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
|
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
|
||||||
@@ -18,11 +21,25 @@ import dagger.Provides
|
|||||||
import dagger.hilt.InstallIn
|
import dagger.hilt.InstallIn
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import dagger.hilt.components.SingletonComponent
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@Module
|
@Module
|
||||||
@InstallIn(SingletonComponent::class)
|
@InstallIn(SingletonComponent::class)
|
||||||
class RepositoryModule {
|
class RepositoryModule {
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideDatabase(@ApplicationContext context: Context): AppDatabase {
|
||||||
|
return Room.databaseBuilder(
|
||||||
|
context,
|
||||||
|
AppDatabase::class.java,
|
||||||
|
context.getString(R.string.db_name),
|
||||||
|
)
|
||||||
|
.fallbackToDestructiveMigration()
|
||||||
|
.addCallback(DatabaseCallback())
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun provideSettingsDoa(appDatabase: AppDatabase): SettingsDao {
|
fun provideSettingsDoa(appDatabase: AppDatabase): SettingsDao {
|
||||||
@@ -37,20 +54,20 @@ 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(@ApplicationContext context: Context): DataStoreManager {
|
fun providePreferencesDataStore(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): DataStoreManager {
|
||||||
return DataStoreManager(context)
|
return DataStoreManager(context, ioDispatcher)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@@ -64,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,18 +3,22 @@ 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.data.repository.TunnelConfigRepository
|
||||||
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
|
||||||
import dagger.hilt.InstallIn
|
import dagger.hilt.InstallIn
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import dagger.hilt.components.SingletonComponent
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import javax.inject.Provider
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@Module
|
@Module
|
||||||
@@ -26,40 +30,49 @@ 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
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideVpnService(
|
fun provideVpnService(
|
||||||
amneziaBackend: org.amnezia.awg.backend.Backend,
|
amneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
||||||
@Userspace userspaceBackend: Backend,
|
@Kernel kernelBackend: Provider<Backend>,
|
||||||
@Kernel kernelBackend: Backend,
|
appDataRepository: AppDataRepository,
|
||||||
appDataRepository: AppDataRepository
|
tunnelConfigRepository: TunnelConfigRepository,
|
||||||
): VpnService {
|
@ApplicationScope applicationScope: CoroutineScope,
|
||||||
return WireGuardTunnel(amneziaBackend,userspaceBackend, kernelBackend, appDataRepository)
|
@IoDispatcher ioDispatcher: CoroutineDispatcher,
|
||||||
}
|
): TunnelService {
|
||||||
|
return WireGuardTunnel(
|
||||||
@Provides
|
amneziaBackend,
|
||||||
@Singleton
|
tunnelConfigRepository,
|
||||||
fun provideServiceManager(appDataRepository: AppDataRepository): ServiceManager {
|
kernelBackend,
|
||||||
return ServiceManager(appDataRepository)
|
appDataRepository,
|
||||||
|
applicationScope,
|
||||||
|
ioDispatcher,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.module
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.FileUtils
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.components.ViewModelComponent
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import dagger.hilt.android.scopes.ViewModelScoped
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(ViewModelComponent::class)
|
||||||
|
class ViewModelModule {
|
||||||
|
@ViewModelScoped
|
||||||
|
@Provides
|
||||||
|
fun provideFileUtils(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): FileUtils {
|
||||||
|
return FileUtils(context, ioDispatcher)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.receiver
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import timber.log.Timber
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class AppUpdateReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: TunnelService
|
||||||
|
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
if (intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
|
||||||
|
applicationScope.launch {
|
||||||
|
val settings = appDataRepository.settings.getSettings()
|
||||||
|
if (settings.isAutoTunnelEnabled) {
|
||||||
|
Timber.i("Restarting services after upgrade")
|
||||||
|
ServiceManager.startWatcherServiceForeground(context)
|
||||||
|
}
|
||||||
|
if (!settings.isAutoTunnelEnabled || settings.isAutoTunnelPaused) {
|
||||||
|
val tunnels = appDataRepository.tunnels.getAll().filter { it.isActive }
|
||||||
|
if (tunnels.isNotEmpty()) context.startTunnelBackground(tunnels.first().id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
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.foreground.ServiceManager
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import timber.log.Timber
|
||||||
|
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 -> {
|
||||||
|
Timber.d("Connect actions")
|
||||||
|
applicationScope.launch {
|
||||||
|
val tunnel = tunnelConfigRepository.getById(id)
|
||||||
|
tunnel?.let {
|
||||||
|
ServiceManager.startTunnelBackgroundService(context)
|
||||||
|
tunnelService.get().startTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ACTION_DISCONNECT -> {
|
||||||
|
applicationScope.launch {
|
||||||
|
val tunnel = tunnelConfigRepository.getById(id)
|
||||||
|
tunnel?.let {
|
||||||
|
ServiceManager.stopTunnelBackgroundService(context)
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,41 +4,46 @@ import android.content.BroadcastReceiver
|
|||||||
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.data.repository.AppDataRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
import com.zaneschepke.wireguardautotunnel.util.goAsync
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
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
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
override fun onReceive(context: Context?, intent: Intent?) = goAsync {
|
@Inject
|
||||||
if (Intent.ACTION_BOOT_COMPLETED != intent?.action) return@goAsync
|
@ApplicationScope
|
||||||
context?.run {
|
lateinit var applicationScope: CoroutineScope
|
||||||
val settings = appDataRepository.settings.getSettings()
|
|
||||||
if (settings.isAutoTunnelEnabled) {
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
if (Intent.ACTION_BOOT_COMPLETED != intent.action) return
|
||||||
|
applicationScope.launch {
|
||||||
|
with(appDataRepository.settings.getSettings()) {
|
||||||
|
if (isRestoreOnBootEnabled) {
|
||||||
|
val activeTunnels = appDataRepository.tunnels.getActive()
|
||||||
|
val tunState = tunnelService.get().vpnState.value.status
|
||||||
|
if (activeTunnels.isNotEmpty() && tunState != TunnelState.UP) {
|
||||||
|
Timber.i("Starting previously active tunnel")
|
||||||
|
context.startTunnelBackground(activeTunnels.first().id)
|
||||||
|
}
|
||||||
|
if (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,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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"
|
||||||
|
}
|
||||||
|
}
|
||||||
-36
@@ -1,36 +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.service.foreground.ServiceManager
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.goAsync
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import timber.log.Timber
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class NotificationActionReceiver : BroadcastReceiver() {
|
|
||||||
@Inject
|
|
||||||
lateinit var settingsRepository: SettingsRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var serviceManager: ServiceManager
|
|
||||||
|
|
||||||
override fun onReceive(context: Context, intent: Intent?) = goAsync {
|
|
||||||
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,
|
||||||
}
|
}
|
||||||
|
|||||||
+577
@@ -0,0 +1,577 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.os.PowerManager
|
||||||
|
import androidx.core.app.ServiceCompat
|
||||||
|
import androidx.lifecycle.LifecycleService
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
|
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 com.zaneschepke.wireguardautotunnel.util.extensions.cancelWithMessage
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isReachable
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.onNotRunning
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
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.combine
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
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 : LifecycleService() {
|
||||||
|
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 autoTunnelStateFlow = MutableStateFlow(AutoTunnelState())
|
||||||
|
|
||||||
|
private var wakeLock: PowerManager.WakeLock? = null
|
||||||
|
|
||||||
|
private var wifiJob: Job? = null
|
||||||
|
private var mobileDataJob: Job? = null
|
||||||
|
private var ethernetJob: Job? = null
|
||||||
|
private var pingJob: Job? = null
|
||||||
|
private var networkEventJob: Job? = null
|
||||||
|
|
||||||
|
@get:Synchronized @set:Synchronized
|
||||||
|
private var running: Boolean = false
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||||
|
kotlin.runCatching {
|
||||||
|
launchNotification()
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
Timber.d("onStartCommand executed with startId: $startId")
|
||||||
|
if (intent != null) {
|
||||||
|
val action = intent.action
|
||||||
|
when (action) {
|
||||||
|
Action.START.name,
|
||||||
|
Action.START_FOREGROUND.name,
|
||||||
|
-> startService()
|
||||||
|
Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return super.onStartCommand(intent, flags, startId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun launchNotification() {
|
||||||
|
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
|
||||||
|
launchWatcherPausedNotification()
|
||||||
|
} else {
|
||||||
|
launchWatcherNotification()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startService() {
|
||||||
|
if (running) return
|
||||||
|
running = true
|
||||||
|
kotlin.runCatching {
|
||||||
|
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||||
|
launchNotification()
|
||||||
|
initWakeLock()
|
||||||
|
}
|
||||||
|
startSettingsJob()
|
||||||
|
startVpnStateJob()
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopService() {
|
||||||
|
wakeLock?.let {
|
||||||
|
if (it.isHeld) {
|
||||||
|
it.release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
cancelAndResetNetworkJobs()
|
||||||
|
cancelAndResetPingJob()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
val tag = this.javaClass.name
|
||||||
|
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 startSettingsJob() = lifecycleScope.launch {
|
||||||
|
watchForSettingsChanges()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startVpnStateJob() = lifecycleScope.launch {
|
||||||
|
watchForVpnStateChanges()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startWifiJob() = lifecycleScope.launch {
|
||||||
|
watchForWifiConnectivityChanges()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startMobileDataJob() = lifecycleScope.launch {
|
||||||
|
watchForMobileDataConnectivityChanges()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startEthernetJob() = lifecycleScope.launch {
|
||||||
|
watchForEthernetConnectivityChanges()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startPingJob() = lifecycleScope.launch {
|
||||||
|
watchForPingFailure()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startNetworkEventJob() = lifecycleScope.launch {
|
||||||
|
handleNetworkEventChanges()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForMobileDataConnectivityChanges() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
Timber.i("Starting mobile data watcher")
|
||||||
|
mobileDataService.networkStatus.collect { status ->
|
||||||
|
when (status) {
|
||||||
|
is NetworkStatus.Available -> {
|
||||||
|
Timber.i("Gained Mobile data connection")
|
||||||
|
autoTunnelStateFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isMobileDataConnected = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.CapabilitiesChanged -> {
|
||||||
|
autoTunnelStateFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isMobileDataConnected = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Timber.i("Mobile data capabilities changed")
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.Unavailable -> {
|
||||||
|
autoTunnelStateFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isMobileDataConnected = false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Timber.i("Lost mobile data connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForPingFailure() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
Timber.i("Starting ping watcher")
|
||||||
|
runCatching {
|
||||||
|
do {
|
||||||
|
val vpnState = tunnelService.get().vpnState.value
|
||||||
|
val settings = appDataRepository.settings.getSettings()
|
||||||
|
if (vpnState.status == TunnelState.UP && !settings.isAutoTunnelPaused) {
|
||||||
|
if (vpnState.tunnelConfig != null) {
|
||||||
|
val config = TunnelConfig.configFromWgQuick(vpnState.tunnelConfig.wgQuick)
|
||||||
|
val results = if (vpnState.tunnelConfig.pingIp != null) {
|
||||||
|
Timber.d("Pinging custom ip : ${vpnState.tunnelConfig.pingIp}")
|
||||||
|
listOf(InetAddress.getByName(vpnState.tunnelConfig.pingIp).isReachable(Constants.PING_TIMEOUT.toInt()))
|
||||||
|
} else {
|
||||||
|
Timber.d("Pinging all peers")
|
||||||
|
config.peers.map { peer ->
|
||||||
|
peer.isReachable()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Timber.i("Ping results reachable: $results")
|
||||||
|
if (results.contains(false)) {
|
||||||
|
Timber.i("Restarting VPN for ping failure")
|
||||||
|
val cooldown = vpnState.tunnelConfig.pingCooldown
|
||||||
|
tunnelService.get().bounceTunnel(vpnState.tunnelConfig)
|
||||||
|
delay(cooldown ?: Constants.PING_COOLDOWN)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delay(vpnState.tunnelConfig?.pingInterval ?: Constants.PING_INTERVAL)
|
||||||
|
} while (true)
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onAutoTunnelPause(paused: Boolean) {
|
||||||
|
if (autoTunnelStateFlow.value.settings.isAutoTunnelPaused
|
||||||
|
!= paused
|
||||||
|
) {
|
||||||
|
when (paused) {
|
||||||
|
true -> launchWatcherPausedNotification()
|
||||||
|
false -> launchWatcherNotification()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForSettingsChanges() {
|
||||||
|
Timber.i("Starting settings watcher")
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
appDataRepository.settings.getSettingsFlow().combine(
|
||||||
|
// ignore isActive changes to allow manual tunnel overrides
|
||||||
|
appDataRepository.tunnels.getTunnelConfigsFlow().distinctUntilChanged { old, new ->
|
||||||
|
old.map { it.isActive } != new.map { it.isActive }
|
||||||
|
},
|
||||||
|
) { settings, tunnels ->
|
||||||
|
autoTunnelStateFlow.value.copy(
|
||||||
|
settings = settings,
|
||||||
|
tunnels = tunnels,
|
||||||
|
)
|
||||||
|
}.collect {
|
||||||
|
onAutoTunnelPause(it.settings.isAutoTunnelPaused)
|
||||||
|
manageJobsBySettings(it.settings)
|
||||||
|
autoTunnelStateFlow.emit(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForVpnStateChanges() {
|
||||||
|
Timber.i("Starting vpn state watcher")
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
tunnelService.get().vpnState.collect { state ->
|
||||||
|
state.tunnelConfig?.let {
|
||||||
|
val settings = appDataRepository.settings.getSettings()
|
||||||
|
if (it.isPingEnabled && !settings.isPingEnabled) {
|
||||||
|
pingJob.onNotRunning { pingJob = startPingJob() }
|
||||||
|
}
|
||||||
|
if (!it.isPingEnabled && !settings.isPingEnabled) {
|
||||||
|
cancelAndResetPingJob()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun manageJobsBySettings(settings: Settings) {
|
||||||
|
with(settings) {
|
||||||
|
if (isPingEnabled) {
|
||||||
|
pingJob.onNotRunning { pingJob = startPingJob() }
|
||||||
|
} else {
|
||||||
|
cancelAndResetPingJob()
|
||||||
|
}
|
||||||
|
if (isTunnelOnWifiEnabled || isTunnelOnEthernetEnabled || isTunnelOnMobileDataEnabled) {
|
||||||
|
startNetworkJobs()
|
||||||
|
} else {
|
||||||
|
cancelAndResetNetworkJobs()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startNetworkJobs() {
|
||||||
|
wifiJob.onNotRunning {
|
||||||
|
Timber.i("Wifi job starting")
|
||||||
|
wifiJob = startWifiJob()
|
||||||
|
}
|
||||||
|
ethernetJob.onNotRunning {
|
||||||
|
ethernetJob = startEthernetJob()
|
||||||
|
Timber.i("Ethernet job starting")
|
||||||
|
}
|
||||||
|
mobileDataJob.onNotRunning {
|
||||||
|
mobileDataJob = startMobileDataJob()
|
||||||
|
Timber.i("Mobile data job starting")
|
||||||
|
}
|
||||||
|
networkEventJob.onNotRunning {
|
||||||
|
Timber.i("Network event job starting")
|
||||||
|
networkEventJob = startNetworkEventJob()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelAndResetPingJob() {
|
||||||
|
pingJob?.cancelWithMessage("Ping job canceled")
|
||||||
|
pingJob = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelAndResetNetworkJobs() {
|
||||||
|
networkEventJob?.cancelWithMessage("Network event job canceled")
|
||||||
|
wifiJob?.cancelWithMessage("Wifi job canceled")
|
||||||
|
ethernetJob?.cancelWithMessage("Ethernet job canceled")
|
||||||
|
mobileDataJob?.cancelWithMessage("Mobile data job canceled")
|
||||||
|
networkEventJob = null
|
||||||
|
wifiJob = null
|
||||||
|
ethernetJob = null
|
||||||
|
mobileDataJob = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateEthernet(connected: Boolean) {
|
||||||
|
autoTunnelStateFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isEthernetConnected = connected,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForEthernetConnectivityChanges() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
Timber.i("Starting ethernet data watcher")
|
||||||
|
ethernetService.networkStatus.collect { status ->
|
||||||
|
when (status) {
|
||||||
|
is NetworkStatus.Available -> {
|
||||||
|
Timber.i("Gained Ethernet connection")
|
||||||
|
updateEthernet(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.CapabilitiesChanged -> {
|
||||||
|
Timber.i("Ethernet capabilities changed")
|
||||||
|
updateEthernet(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.Unavailable -> {
|
||||||
|
updateEthernet(false)
|
||||||
|
Timber.i("Lost Ethernet connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForWifiConnectivityChanges() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
Timber.i("Starting wifi watcher")
|
||||||
|
wifiService.networkStatus.collect { status ->
|
||||||
|
when (status) {
|
||||||
|
is NetworkStatus.Available -> {
|
||||||
|
Timber.i("Gained Wi-Fi connection")
|
||||||
|
autoTunnelStateFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isWifiConnected = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.CapabilitiesChanged -> {
|
||||||
|
Timber.i("Wifi capabilities changed")
|
||||||
|
autoTunnelStateFlow.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)
|
||||||
|
autoTunnelStateFlow.update {
|
||||||
|
it.copy(
|
||||||
|
currentNetworkSSID = name,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} ?: Timber.w("Failed to read ssid")
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.Unavailable -> {
|
||||||
|
autoTunnelStateFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isWifiConnected = false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Timber.i("Lost Wi-Fi connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun getMobileDataTunnel(): TunnelConfig? {
|
||||||
|
return appDataRepository.tunnels.findByMobileDataTunnel().firstOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isTunnelDown(): Boolean {
|
||||||
|
return tunnelService.get().vpnState.value.status == TunnelState.DOWN
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun handleNetworkEventChanges() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
Timber.i("Starting network event watcher")
|
||||||
|
autoTunnelStateFlow.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() -> {
|
||||||
|
Timber.i("Untrusted wifi condition met")
|
||||||
|
if (activeTunnel?.tunnelNetworks?.isMatchingToWildcardList(watcherState.currentNetworkSSID) == false ||
|
||||||
|
activeTunnel == null || isTunnelDown()
|
||||||
|
) {
|
||||||
|
Timber.i(
|
||||||
|
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met",
|
||||||
|
)
|
||||||
|
watcherState.tunnels.firstOrNull { it.tunnelNetworks.isMatchingToWildcardList(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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||||
|
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList
|
||||||
|
|
||||||
|
data class AutoTunnelState(
|
||||||
|
val isWifiConnected: Boolean = false,
|
||||||
|
val isEthernetConnected: Boolean = false,
|
||||||
|
val isMobileDataConnected: Boolean = false,
|
||||||
|
val currentNetworkSSID: String = "",
|
||||||
|
val settings: Settings = Settings(),
|
||||||
|
val tunnels: TunnelConfigs = emptyList(),
|
||||||
|
) {
|
||||||
|
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.isMatchingToWildcardList(currentNetworkSSID) &&
|
||||||
|
settings.isTunnelOnWifiEnabled
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isTrustedWifiConditionMet(): Boolean {
|
||||||
|
return (
|
||||||
|
!isEthernetConnected &&
|
||||||
|
(
|
||||||
|
isWifiConnected &&
|
||||||
|
settings.trustedNetworkSSIDs.isMatchingToWildcardList(currentNetworkSSID)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isTunnelOffOnWifiConditionMet(): Boolean {
|
||||||
|
return (
|
||||||
|
!isEthernetConnected &&
|
||||||
|
(
|
||||||
|
isWifiConnected &&
|
||||||
|
!settings.isTunnelOnWifiEnabled
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isTunnelOffOnNoConnectivityMet(): Boolean {
|
||||||
|
return (
|
||||||
|
!isEthernetConnected &&
|
||||||
|
!isWifiConnected &&
|
||||||
|
!isMobileDataConnected
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
-55
@@ -1,55 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.os.IBinder
|
|
||||||
import androidx.lifecycle.LifecycleService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import timber.log.Timber
|
|
||||||
|
|
||||||
open class ForegroundService : LifecycleService() {
|
|
||||||
private var isServiceStarted = false
|
|
||||||
|
|
||||||
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 {
|
|
||||||
super.onStartCommand(intent, flags, startId)
|
|
||||||
Timber.d("onStartCommand executed with startId: $startId")
|
|
||||||
if (intent != null) {
|
|
||||||
val action = intent.action
|
|
||||||
when (action) {
|
|
||||||
Action.START.name,
|
|
||||||
Action.START_FOREGROUND.name -> startService(intent.extras)
|
|
||||||
Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService()
|
|
||||||
Constants.ALWAYS_ON_VPN_ACTION -> {
|
|
||||||
Timber.i("Always-on VPN starting service")
|
|
||||||
startService(intent.extras)
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Timber.d("This should never happen. No action in the received intent")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Timber.d(
|
|
||||||
"with a null intent. It has been probably restarted by the system.",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return START_STICKY
|
|
||||||
}
|
|
||||||
|
|
||||||
protected open fun startService(extras: Bundle?) {
|
|
||||||
if (isServiceStarted) return
|
|
||||||
Timber.d("Starting ${this.javaClass.simpleName}")
|
|
||||||
isServiceStarted = true
|
|
||||||
}
|
|
||||||
|
|
||||||
protected open fun stopService() {
|
|
||||||
Timber.d("Stopping ${this.javaClass.simpleName}")
|
|
||||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
|
||||||
stopSelf()
|
|
||||||
isServiceStarted = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+29
-75
@@ -3,18 +3,12 @@ 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 android.net.VpnService
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
|
||||||
class ServiceManager(private val appDataRepository: AppDataRepository) {
|
object ServiceManager {
|
||||||
|
private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) {
|
||||||
private fun <T : Service> actionOnService(
|
if (VpnService.prepare(context) != null) return
|
||||||
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
|
||||||
@@ -23,7 +17,11 @@ class ServiceManager(private val appDataRepository: AppDataRepository) {
|
|||||||
intent.component?.javaClass
|
intent.component?.javaClass
|
||||||
try {
|
try {
|
||||||
when (action) {
|
when (action) {
|
||||||
Action.START_FOREGROUND, Action.STOP_FOREGROUND -> context.startForegroundService(intent)
|
Action.START_FOREGROUND, Action.STOP_FOREGROUND ->
|
||||||
|
context.startForegroundService(
|
||||||
|
intent,
|
||||||
|
)
|
||||||
|
|
||||||
Action.START, Action.STOP -> context.startService(intent)
|
Action.START, Action.STOP -> context.startService(intent)
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -31,71 +29,11 @@ class ServiceManager(private val appDataRepository: AppDataRepository) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
|
||||||
if (isManualStop) onManualStop()
|
|
||||||
Timber.i("Stopping vpn service")
|
|
||||||
actionOnService(
|
|
||||||
Action.STOP_FOREGROUND,
|
|
||||||
context,
|
|
||||||
WireGuardTunnelService::class.java,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun stopVpnService(context: Context, isManualStop: Boolean = false) {
|
|
||||||
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
|
|
||||||
) {
|
|
||||||
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,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,7 +41,7 @@ class ServiceManager(private val appDataRepository: AppDataRepository) {
|
|||||||
actionOnService(
|
actionOnService(
|
||||||
Action.START,
|
Action.START,
|
||||||
context,
|
context,
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
AutoTunnelService::class.java,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +49,23 @@ class ServiceManager(private val appDataRepository: AppDataRepository) {
|
|||||||
actionOnService(
|
actionOnService(
|
||||||
Action.STOP,
|
Action.STOP,
|
||||||
context,
|
context,
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
AutoTunnelService::class.java,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun startTunnelBackgroundService(context: Context) {
|
||||||
|
actionOnService(
|
||||||
|
Action.START_FOREGROUND,
|
||||||
|
context,
|
||||||
|
TunnelBackgroundService::class.java,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopTunnelBackgroundService(context: Context) {
|
||||||
|
actionOnService(
|
||||||
|
Action.STOP,
|
||||||
|
context,
|
||||||
|
TunnelBackgroundService::class.java,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.IBinder
|
||||||
|
import androidx.lifecycle.LifecycleService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class TunnelBackgroundService : LifecycleService() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var notificationService: NotificationService
|
||||||
|
|
||||||
|
private val foregroundId = 123
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
startForeground(foregroundId, createNotification())
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
val action = intent.action
|
||||||
|
when (action) {
|
||||||
|
Action.START.name,
|
||||||
|
Action.START_FOREGROUND.name,
|
||||||
|
-> startService()
|
||||||
|
Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return super.onStartCommand(intent, flags, startId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startService() {
|
||||||
|
startForeground(foregroundId, createNotification())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopService() {
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createNotification(): Notification {
|
||||||
|
return notificationService.createNotification(
|
||||||
|
getString(R.string.vpn_channel_id),
|
||||||
|
getString(R.string.vpn_channel_name),
|
||||||
|
getString(R.string.tunnel_start_text),
|
||||||
|
description = "",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
-63
@@ -1,63 +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 isTunnelOnMobileDataPreferredConditionMet(): 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
-429
@@ -1,429 +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.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.Dispatchers
|
|
||||||
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 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
|
|
||||||
|
|
||||||
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(Dispatchers.Main) {
|
|
||||||
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(Dispatchers.IO) {
|
|
||||||
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() {
|
|
||||||
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() {
|
|
||||||
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(this)
|
|
||||||
delay(Constants.VPN_RESTART_DELAY)
|
|
||||||
serviceManager.startVpnServiceForeground(this, 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() {
|
|
||||||
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() {
|
|
||||||
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() {
|
|
||||||
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(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isMobileDataConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel on on mobile data condition met")
|
|
||||||
if(isTunnelDown()) serviceManager.startVpnServiceForeground(this, getMobileDataTunnel()?.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOnMobileDataPreferredConditionMet() -> {
|
|
||||||
if(tunnelConfig?.isMobileDataTunnel == false) {
|
|
||||||
getMobileDataTunnel()?.let {
|
|
||||||
Timber.i("$autoTunnel - tunnel connected on mobile data is not preferred condition met, switching to preferred")
|
|
||||||
if(isTunnelDown()) serviceManager.startVpnServiceForeground(
|
|
||||||
this,
|
|
||||||
getMobileDataTunnel()?.id,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnMobileDataConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
|
|
||||||
if(!isTunnelDown()) serviceManager.stopVpnServiceForeground(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
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")
|
|
||||||
if(isTunnelDown()) serviceManager.startVpnServiceForeground(this, it.id)
|
|
||||||
} ?: suspend {
|
|
||||||
Timber.i("No tunnel associated with this SSID, using defaults")
|
|
||||||
if (appDataRepository.getPrimaryOrFirstTunnel()?.name != vpnService.name) {
|
|
||||||
if(isTunnelDown()) serviceManager.startVpnServiceForeground(this)
|
|
||||||
}
|
|
||||||
}.invoke()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTrustedWifiConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off")
|
|
||||||
if(!isTunnelDown()) serviceManager.stopVpnServiceForeground(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnWifiConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on wifi condition met, turning vpn off")
|
|
||||||
if(!isTunnelDown()) serviceManager.stopVpnServiceForeground(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnNoConnectivityMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on no connectivity met, turning vpn off")
|
|
||||||
if(!isTunnelDown()) serviceManager.stopVpnServiceForeground(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
Timber.i("$autoTunnel - no condition met")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-188
@@ -1,188 +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.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.Dispatchers
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
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
|
|
||||||
|
|
||||||
private var job: Job? = null
|
|
||||||
|
|
||||||
private var didShowConnected = false
|
|
||||||
|
|
||||||
override fun onCreate() {
|
|
||||||
super.onCreate()
|
|
||||||
lifecycleScope.launch(Dispatchers.Main) {
|
|
||||||
//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(Dispatchers.IO) {
|
|
||||||
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() {
|
|
||||||
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(Dispatchers.IO) {
|
|
||||||
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)
|
||||||
|
|||||||
+7
-3
@@ -9,11 +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 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
|
||||||
@@ -59,7 +63,7 @@ class WireGuardNotification @Inject constructor(@ApplicationContext private val
|
|||||||
}
|
}
|
||||||
notificationManager.createNotificationChannel(channel)
|
notificationManager.createNotificationChannel(channel)
|
||||||
val pendingIntent: PendingIntent =
|
val pendingIntent: PendingIntent =
|
||||||
Intent(context, MainActivity::class.java).let { notificationIntent ->
|
Intent(context, SplashActivity::class.java).let { notificationIntent ->
|
||||||
PendingIntent.getActivity(
|
PendingIntent.getActivity(
|
||||||
context,
|
context,
|
||||||
0,
|
0,
|
||||||
|
|||||||
+32
-26
@@ -2,60 +2,64 @@ package com.zaneschepke.wireguardautotunnel.service.shortcut
|
|||||||
|
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.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 com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.stopTunnelBackground
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.Dispatchers
|
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
|
||||||
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
WireGuardAutoTunnel.applicationScope.launch(Dispatchers.IO) {
|
applicationScope.launch {
|
||||||
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 -> this@ShortcutsActivity.startTunnelBackground(it.id)
|
||||||
this@ShortcutsActivity, tunnelConfig?.id, isManualStart = true,
|
Action.STOP.name -> this@ShortcutsActivity.stopTunnelBackground(it.id)
|
||||||
)
|
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,
|
||||||
),
|
),
|
||||||
@@ -69,6 +73,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"
|
||||||
}
|
}
|
||||||
|
|||||||
+63
-29
@@ -1,38 +1,52 @@
|
|||||||
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.LifecycleOwner
|
||||||
|
import androidx.lifecycle.LifecycleRegistry
|
||||||
|
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.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.flow.collectLatest
|
|
||||||
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() {
|
class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
private val scope = CoroutineScope(Dispatchers.IO)
|
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
|
||||||
|
|
||||||
private var manualStartConfig: TunnelConfig? = null
|
/* This works around an annoying unsolved frameworks bug some people are hitting. */
|
||||||
|
override fun onBind(intent: Intent): IBinder? {
|
||||||
|
var ret: IBinder? = null
|
||||||
|
try {
|
||||||
|
ret = super.onBind(intent)
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
Timber.e("Failed to bind to AutoTunnelTile")
|
||||||
|
}
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
override fun onStartListening() {
|
override fun onCreate() {
|
||||||
super.onStartListening()
|
super.onCreate()
|
||||||
scope.launch {
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||||
appDataRepository.settings.getSettingsFlow().collectLatest {
|
|
||||||
|
applicationScope.launch {
|
||||||
|
appDataRepository.settings.getSettingsFlow().collect {
|
||||||
|
kotlin.runCatching {
|
||||||
when (it.isAutoTunnelEnabled) {
|
when (it.isAutoTunnelEnabled) {
|
||||||
true -> {
|
true -> {
|
||||||
if (it.isAutoTunnelPaused) {
|
if (it.isAutoTunnelPaused) {
|
||||||
@@ -49,57 +63,73 @@ class AutoTunnelControlTile : TileService() {
|
|||||||
setUnavailable()
|
setUnavailable()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onTileAdded() {
|
override fun onStopListening() {
|
||||||
super.onTileAdded()
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
|
||||||
onStartListening()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
scope.cancel()
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onTileRemoved() {
|
override fun onStartListening() {
|
||||||
super.onTileRemoved()
|
super.onStartListening()
|
||||||
scope.cancel()
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onClick() {
|
override fun onClick() {
|
||||||
super.onClick()
|
super.onClick()
|
||||||
unlockAndRun {
|
unlockAndRun {
|
||||||
scope.launch {
|
lifecycleScope.launch {
|
||||||
try {
|
kotlin.runCatching {
|
||||||
appDataRepository.toggleWatcherServicePause()
|
val settings = appDataRepository.settings.getSettings()
|
||||||
} catch (e: Exception) {
|
if (settings.isAutoTunnelPaused) {
|
||||||
Timber.e(e.message)
|
return@launch appDataRepository.settings.save(
|
||||||
} finally {
|
settings.copy(
|
||||||
cancel()
|
isAutoTunnelPaused = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
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
|
||||||
}
|
}
|
||||||
@@ -108,4 +138,8 @@ class AutoTunnelControlTile : TileService() {
|
|||||||
}
|
}
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override val lifecycle: Lifecycle
|
||||||
|
get() = lifecycleRegistry
|
||||||
}
|
}
|
||||||
|
|||||||
+62
-58
@@ -3,117 +3,107 @@ package com.zaneschepke.wireguardautotunnel.service.tile
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
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.LifecycleOwner
|
||||||
|
import androidx.lifecycle.LifecycleRegistry
|
||||||
|
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.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||||
|
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.Dispatchers
|
|
||||||
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() {
|
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 scope = CoroutineScope(Dispatchers.IO)
|
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
|
||||||
|
|
||||||
private var manualStartConfig: TunnelConfig? = null
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
override fun onStartListening() {
|
Timber.d("onCreate for tile service")
|
||||||
super.onStartListening()
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||||
Timber.d("On start listening called")
|
|
||||||
scope.launch {
|
|
||||||
vpnService.vpnState.collect { it ->
|
|
||||||
when (it.status) {
|
|
||||||
TunnelState.UP -> {
|
|
||||||
setActive()
|
|
||||||
it.tunnelConfig?.name?.let { name -> setTileDescription(name) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
TunnelState.DOWN -> {
|
override fun onStopListening() {
|
||||||
setInactive()
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
|
||||||
val config = appDataRepository.getStartTunnelConfig()?.also { config ->
|
|
||||||
manualStartConfig = config
|
|
||||||
} ?: appDataRepository.getPrimaryOrFirstTunnel()
|
|
||||||
config?.let {
|
|
||||||
setTileDescription(it.name)
|
|
||||||
} ?: setUnavailable()
|
|
||||||
}
|
|
||||||
else -> setInactive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
scope.cancel()
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onTileRemoved() {
|
override fun onStartListening() {
|
||||||
super.onTileRemoved()
|
super.onStartListening()
|
||||||
scope.cancel()
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||||
|
lifecycleScope.launch {
|
||||||
|
if (appDataRepository.tunnels.getAll().isEmpty()) return@launch setUnavailable()
|
||||||
|
updateTileState()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
scope.launch {
|
Timber.d("Click")
|
||||||
try {
|
lifecycleScope.launch {
|
||||||
if (vpnService.getState() == TunnelState.UP) {
|
val context = this@TunnelControlTile
|
||||||
serviceManager.stopVpnServiceForeground(
|
val lastActive = appDataRepository.getStartTunnelConfig()
|
||||||
this@TunnelControlTile,
|
lastActive?.let { tunnel ->
|
||||||
isManualStop = true,
|
if (tunnel.isActive) return@launch context.stopTunnelBackground(tunnel.id)
|
||||||
)
|
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
|
||||||
}
|
}
|
||||||
@@ -122,4 +112,18 @@ class TunnelControlTile : TileService() {
|
|||||||
}
|
}
|
||||||
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
|
||||||
|
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,22 @@
|
|||||||
|
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>
|
||||||
|
|
||||||
|
suspend fun bounceTunnel(tunnelConfig: TunnelConfig): Result<TunnelState>
|
||||||
|
|
||||||
|
val vpnState: StateFlow<VpnState>
|
||||||
|
|
||||||
|
suspend fun runningTunnelNames(): Set<String>
|
||||||
|
|
||||||
|
suspend fun getState(): TunnelState
|
||||||
|
|
||||||
|
fun cancelStatsJob()
|
||||||
|
fun startStatsJob()
|
||||||
|
}
|
||||||
+11
-9
@@ -5,18 +5,19 @@ 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) {
|
||||||
UP -> Tunnel.State.UP
|
UP -> Tunnel.State.UP
|
||||||
DOWN -> Tunnel.State.DOWN
|
DOWN -> Tunnel.State.DOWN
|
||||||
TOGGLE -> Tunnel.State.TOGGLE
|
TOGGLE -> Tunnel.State.TOGGLE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun toAmState() : org.amnezia.awg.backend.Tunnel.State {
|
fun toAmState(): org.amnezia.awg.backend.Tunnel.State {
|
||||||
return when(this) {
|
return when (this) {
|
||||||
UP -> org.amnezia.awg.backend.Tunnel.State.UP
|
UP -> org.amnezia.awg.backend.Tunnel.State.UP
|
||||||
DOWN -> org.amnezia.awg.backend.Tunnel.State.DOWN
|
DOWN -> org.amnezia.awg.backend.Tunnel.State.DOWN
|
||||||
TOGGLE -> org.amnezia.awg.backend.Tunnel.State.TOGGLE
|
TOGGLE -> org.amnezia.awg.backend.Tunnel.State.TOGGLE
|
||||||
@@ -24,15 +25,16 @@ enum class TunnelState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
fun from(state: Tunnel.State) : TunnelState {
|
fun from(state: Tunnel.State): TunnelState {
|
||||||
return when(state) {
|
return when (state) {
|
||||||
Tunnel.State.DOWN -> DOWN
|
Tunnel.State.DOWN -> DOWN
|
||||||
Tunnel.State.TOGGLE -> TOGGLE
|
Tunnel.State.TOGGLE -> TOGGLE
|
||||||
Tunnel.State.UP -> UP
|
Tunnel.State.UP -> UP
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fun from(state: org.amnezia.awg.backend.Tunnel.State) : TunnelState {
|
|
||||||
return when(state) {
|
fun from(state: org.amnezia.awg.backend.Tunnel.State): TunnelState {
|
||||||
|
return when (state) {
|
||||||
org.amnezia.awg.backend.Tunnel.State.DOWN -> DOWN
|
org.amnezia.awg.backend.Tunnel.State.DOWN -> DOWN
|
||||||
org.amnezia.awg.backend.Tunnel.State.TOGGLE -> TOGGLE
|
org.amnezia.awg.backend.Tunnel.State.TOGGLE -> TOGGLE
|
||||||
org.amnezia.awg.backend.Tunnel.State.UP -> UP
|
org.amnezia.awg.backend.Tunnel.State.UP -> UP
|
||||||
|
|||||||
@@ -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,
|
||||||
)
|
)
|
||||||
|
|||||||
+167
-115
@@ -1,111 +1,163 @@
|
|||||||
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.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.data.repository.TunnelConfigRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
import com.zaneschepke.wireguardautotunnel.module.Kernel
|
import com.zaneschepke.wireguardautotunnel.module.Kernel
|
||||||
import com.zaneschepke.wireguardautotunnel.module.Userspace
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.AmneziaStatistics
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.AmneziaStatistics
|
||||||
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 kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import org.amnezia.awg.backend.Tunnel
|
import org.amnezia.awg.backend.Tunnel
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
class WireGuardTunnel
|
class WireGuardTunnel
|
||||||
@Inject
|
@Inject
|
||||||
constructor(
|
constructor(
|
||||||
private val userspaceAmneziaBackend : org.amnezia.awg.backend.Backend,
|
private val amneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
||||||
@Userspace private val userspaceBackend: Backend,
|
tunnelConfigRepository: TunnelConfigRepository,
|
||||||
@Kernel private val kernelBackend: Backend,
|
@Kernel private val kernelBackend: Provider<Backend>,
|
||||||
private val appDataRepository: AppDataRepository,
|
private val appDataRepository: AppDataRepository,
|
||||||
) : VpnService {
|
@ApplicationScope private val applicationScope: CoroutineScope,
|
||||||
private val _vpnState = MutableStateFlow(VpnState())
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
|
) : TunnelService {
|
||||||
|
|
||||||
private val scope = CoroutineScope(Dispatchers.IO)
|
private val _vpnState = MutableStateFlow(VpnState())
|
||||||
|
override val vpnState: StateFlow<VpnState> = _vpnState.combine(
|
||||||
|
tunnelConfigRepository.getTunnelConfigsFlow(),
|
||||||
|
) {
|
||||||
|
vpnState, tunnels ->
|
||||||
|
vpnState.copy(
|
||||||
|
tunnelConfig = tunnels.firstOrNull { it.id == vpnState.tunnelConfig?.id },
|
||||||
|
)
|
||||||
|
}.stateIn(applicationScope, SharingStarted.Lazily, VpnState())
|
||||||
|
|
||||||
private var statsJob: Job? = null
|
private var statsJob: Job? = null
|
||||||
|
|
||||||
private var backend: Backend = userspaceBackend
|
private suspend fun backend(): Any {
|
||||||
|
val settings = appDataRepository.settings.getSettings()
|
||||||
private var backendIsWgUserspace = true
|
if (settings.isKernelEnabled) return kernelBackend.get()
|
||||||
|
return amneziaBackend.get()
|
||||||
private var backendIsAmneziaUserspace = false
|
|
||||||
|
|
||||||
init {
|
|
||||||
scope.launch {
|
|
||||||
appDataRepository.settings.getSettingsFlow().collect {
|
|
||||||
if (it.isKernelEnabled && (backendIsWgUserspace || backendIsAmneziaUserspace)) {
|
|
||||||
Timber.d("Setting kernel backend")
|
|
||||||
backend = kernelBackend
|
|
||||||
backendIsWgUserspace = false
|
|
||||||
backendIsAmneziaUserspace = false
|
|
||||||
} else if (!it.isKernelEnabled && !it.isAmneziaEnabled && !backendIsWgUserspace) {
|
|
||||||
Timber.d("Setting WireGuard userspace backend")
|
|
||||||
backend = userspaceBackend
|
|
||||||
backendIsWgUserspace = true
|
|
||||||
backendIsAmneziaUserspace = false
|
|
||||||
} else if (it.isAmneziaEnabled && !backendIsAmneziaUserspace) {
|
|
||||||
Timber.d("Setting Amnezia userspace backend")
|
|
||||||
backendIsAmneziaUserspace = true
|
|
||||||
backendIsWgUserspace = false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 fun setState(tunnelConfig: TunnelConfig?, tunnelState: TunnelState) : TunnelState {
|
private suspend fun setState(tunnelConfig: TunnelConfig, tunnelState: TunnelState): Result<TunnelState> {
|
||||||
return if(backendIsAmneziaUserspace) {
|
return runCatching {
|
||||||
Timber.i("Using Amnezia backend")
|
when (val backend = backend()) {
|
||||||
val config = tunnelConfig?.let {
|
is Backend -> backend.setState(this, tunnelState.toWgState(), TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick)).let { TunnelState.from(it) }
|
||||||
if(it.amQuick != "") TunnelConfig.configFromAmQuick(it.amQuick) else {
|
is org.amnezia.awg.backend.Backend -> {
|
||||||
Timber.w("Using backwards compatible wg config, amnezia specific config not found.")
|
val config = if (tunnelConfig.amQuick.isBlank()) {
|
||||||
TunnelConfig.configFromAmQuick(it.wgQuick)
|
TunnelConfig.configFromAmQuick(
|
||||||
}
|
tunnelConfig.wgQuick,
|
||||||
}
|
|
||||||
val state = userspaceAmneziaBackend.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)
|
} else {
|
||||||
|
TunnelConfig.configFromAmQuick(tunnelConfig.amQuick)
|
||||||
|
}
|
||||||
|
backend.setState(this, tunnelState.toAmState(), config).let {
|
||||||
|
TunnelState.from(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> throw NotImplementedError()
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun startTunnel(tunnelConfig: TunnelConfig?): TunnelState {
|
override suspend fun startTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||||
return try {
|
return withContext(ioDispatcher) {
|
||||||
//TODO we need better error handling here
|
onBeforeStart(tunnelConfig)
|
||||||
val config = tunnelConfig ?: appDataRepository.getPrimaryOrFirstTunnel()
|
setState(tunnelConfig, TunnelState.UP).onSuccess {
|
||||||
if (config != null) {
|
emitTunnelState(it)
|
||||||
emitTunnelConfig(config)
|
}.onFailure {
|
||||||
setState(config, TunnelState.UP)
|
Timber.e(it)
|
||||||
} else throw Exception("No tunnels")
|
onStartFailed()
|
||||||
} catch (e: BackendException) {
|
}
|
||||||
Timber.e("Failed to start tunnel with error: ${e.message}")
|
|
||||||
TunnelState.from(State.DOWN)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun emitTunnelState(state : TunnelState) {
|
override suspend fun stopTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||||
|
return withContext(ioDispatcher) {
|
||||||
|
onBeforeStop(tunnelConfig)
|
||||||
|
setState(tunnelConfig, TunnelState.DOWN).onSuccess {
|
||||||
|
emitTunnelState(it)
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
onStopFailed()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// use this when we just want to bounce tunnel and not change tunnelConfig active state
|
||||||
|
override suspend fun bounceTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||||
|
toggleTunnel(tunnelConfig)
|
||||||
|
delay(VPN_RESTART_DELAY)
|
||||||
|
return toggleTunnel(tunnelConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun toggleTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||||
|
return withContext(ioDispatcher) {
|
||||||
|
setState(tunnelConfig, TunnelState.TOGGLE).onSuccess {
|
||||||
|
emitTunnelState(it)
|
||||||
|
resetBackendStatistics()
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun onStopFailed() {
|
||||||
|
_vpnState.value.tunnelConfig?.let {
|
||||||
|
appDataRepository.tunnels.save(it.copy(isActive = true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun onStartFailed() {
|
||||||
|
_vpnState.value.tunnelConfig?.let {
|
||||||
|
appDataRepository.tunnels.save(it.copy(isActive = false))
|
||||||
|
}
|
||||||
|
cancelStatsJob()
|
||||||
|
resetBackendStatistics()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun onBeforeStart(tunnelConfig: TunnelConfig) {
|
||||||
|
if (_vpnState.value.status == TunnelState.UP) vpnState.value.tunnelConfig?.let { stopTunnel(it) }
|
||||||
|
resetBackendStatistics()
|
||||||
|
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = true))
|
||||||
|
emitVpnStateConfig(tunnelConfig)
|
||||||
|
startStatsJob()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun onBeforeStop(tunnelConfig: TunnelConfig) {
|
||||||
|
cancelStatsJob()
|
||||||
|
resetBackendStatistics()
|
||||||
|
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = false))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun emitTunnelState(state: TunnelState) {
|
||||||
_vpnState.tryEmit(
|
_vpnState.tryEmit(
|
||||||
_vpnState.value.copy(
|
_vpnState.value.copy(
|
||||||
status = state,
|
status = state,
|
||||||
@@ -121,73 +173,73 @@ constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun emitTunnelConfig(tunnelConfig: TunnelConfig?) {
|
private fun emitVpnStateConfig(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() {
|
override suspend fun getState(): TunnelState {
|
||||||
try {
|
return when (val backend = backend()) {
|
||||||
if (getState() == TunnelState.UP) {
|
is Backend -> backend.getState(this).let { TunnelState.from(it) }
|
||||||
val state = setState(null, TunnelState.DOWN)
|
is org.amnezia.awg.backend.Backend -> backend.getState(this).let { TunnelState.from(it) }
|
||||||
resetVpnState()
|
else -> TunnelState.DOWN
|
||||||
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 {
|
override fun cancelStatsJob() {
|
||||||
return if(backendIsAmneziaUserspace) TunnelState.from(userspaceAmneziaBackend.getState(this))
|
statsJob?.cancel()
|
||||||
else TunnelState.from(backend.getState(this))
|
}
|
||||||
|
|
||||||
|
override fun startStatsJob() {
|
||||||
|
statsJob = startTunnelStatisticsJob()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getName(): String {
|
override fun getName(): String {
|
||||||
return _vpnState.value.tunnelConfig?.name ?: ""
|
return _vpnState.value.tunnelConfig?.name ?: ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun startTunnelStatisticsJob() = applicationScope.launch(ioDispatcher) {
|
||||||
|
val backend = backend()
|
||||||
|
delay(STATS_START_DELAY)
|
||||||
|
while (true) {
|
||||||
|
when (backend) {
|
||||||
|
is Backend -> emitBackendStatistics(
|
||||||
|
WireGuardStatistics(backend.getStatistics(this@WireGuardTunnel)),
|
||||||
|
)
|
||||||
|
is org.amnezia.awg.backend.Backend -> {
|
||||||
|
emitBackendStatistics(
|
||||||
|
AmneziaStatistics(
|
||||||
|
backend.getStatistics(this@WireGuardTunnel),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delay(VPN_STATISTIC_CHECK_INTERVAL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onStateChange(newState: Tunnel.State) {
|
override fun onStateChange(newState: Tunnel.State) {
|
||||||
handleStateChange(TunnelState.from(newState))
|
emitTunnelState(TunnelState.from(newState))
|
||||||
}
|
|
||||||
|
|
||||||
private fun handleStateChange(state: TunnelState) {
|
|
||||||
val tunnel = this
|
|
||||||
emitTunnelState(state)
|
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
|
||||||
if (state == TunnelState.UP) {
|
|
||||||
statsJob =
|
|
||||||
scope.launch {
|
|
||||||
while (true) {
|
|
||||||
if(backendIsAmneziaUserspace) {
|
|
||||||
emitBackendStatistics(AmneziaStatistics(userspaceAmneziaBackend.getStatistics(tunnel)))
|
|
||||||
} else {
|
|
||||||
emitBackendStatistics(WireGuardStatistics(backend.getStatistics(tunnel)))
|
|
||||||
}
|
|
||||||
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (state == TunnelState.DOWN) {
|
|
||||||
try {
|
|
||||||
statsJob?.cancel()
|
|
||||||
} catch (e : CancellationException) {
|
|
||||||
Timber.i("Stats job cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onStateChange(state: State) {
|
override fun onStateChange(state: State) {
|
||||||
handleStateChange(TunnelState.from(state))
|
emitTunnelState(TunnelState.from(state))
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val STATS_START_DELAY = 5_000L
|
||||||
|
const val VPN_STATISTIC_CHECK_INTERVAL = 1_000L
|
||||||
|
const val VPN_RESTART_DELAY = 1_000L
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@ class AmneziaStatistics(private val statistics: Statistics) : TunnelStatistics()
|
|||||||
PeerStats(
|
PeerStats(
|
||||||
rxBytes = stats.rxBytes,
|
rxBytes = stats.rxBytes,
|
||||||
txBytes = stats.txBytes,
|
txBytes = stats.txBytes,
|
||||||
latestHandshakeEpochMillis = stats.latestHandshakeEpochMillis
|
latestHandshakeEpochMillis = stats.latestHandshakeEpochMillis,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -8,11 +8,11 @@ abstract class TunnelStatistics {
|
|||||||
|
|
||||||
abstract fun peerStats(peer: Key): PeerStats?
|
abstract fun peerStats(peer: Key): PeerStats?
|
||||||
|
|
||||||
abstract fun isTunnelStale() : Boolean
|
abstract fun isTunnelStale(): Boolean
|
||||||
|
|
||||||
abstract fun getPeers(): Array<Key>
|
abstract fun getPeers(): Array<Key>
|
||||||
|
|
||||||
abstract fun rx() : Long
|
abstract fun rx(): Long
|
||||||
|
|
||||||
abstract fun tx() : Long
|
abstract fun tx(): Long
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@ class WireGuardStatistics(private val statistics: Statistics) : TunnelStatistics
|
|||||||
PeerStats(
|
PeerStats(
|
||||||
txBytes = peerStats.txBytes,
|
txBytes = peerStats.txBytes,
|
||||||
rxBytes = peerStats.rxBytes,
|
rxBytes = peerStats.rxBytes,
|
||||||
latestHandshakeEpochMillis = peerStats.latestHandshakeEpochMillis
|
latestHandshakeEpochMillis = peerStats.latestHandshakeEpochMillis,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui
|
package com.zaneschepke.wireguardautotunnel.ui
|
||||||
|
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||||
|
|
||||||
data class AppUiState(
|
data class AppUiState(
|
||||||
val snackbarMessage: String = "",
|
val settings: Settings = Settings(),
|
||||||
val snackbarMessageConsumed: Boolean = true,
|
val tunnels: List<TunnelConfig> = emptyList(),
|
||||||
val vpnPermissionAccepted: Boolean = false,
|
val vpnState: VpnState = VpnState(),
|
||||||
val notificationPermissionAccepted: Boolean = false,
|
val generalState: GeneralState = GeneralState(),
|
||||||
val requestPermissions: Boolean = false
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,159 +1,70 @@
|
|||||||
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 android.widget.Toast
|
|
||||||
import androidx.compose.runtime.mutableStateListOf
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.wireguard.android.backend.GoBackend
|
import androidx.navigation.NavHostController
|
||||||
import com.zaneschepke.logcatter.Logcatter
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.logcatter.model.LogMessage
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
import com.zaneschepke.wireguardautotunnel.util.FileUtils
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import kotlinx.coroutines.plus
|
||||||
import java.time.Instant
|
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,
|
||||||
|
tunnelService: TunnelService,
|
||||||
|
val navHostController: NavHostController,
|
||||||
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance)
|
private val _appUiState = MutableStateFlow(AppUiState())
|
||||||
|
|
||||||
private val _appUiState = MutableStateFlow(
|
val uiState =
|
||||||
|
combine(
|
||||||
|
appDataRepository.settings.getSettingsFlow(),
|
||||||
|
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
||||||
|
tunnelService.vpnState,
|
||||||
|
appDataRepository.appState.generalStateFlow,
|
||||||
|
) { settings, tunnels, tunnelState, generalState ->
|
||||||
AppUiState(
|
AppUiState(
|
||||||
vpnPermissionAccepted = vpnIntent == null,
|
settings,
|
||||||
|
tunnels,
|
||||||
|
tunnelState,
|
||||||
|
generalState,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.stateIn(
|
||||||
|
viewModelScope + ioDispatcher,
|
||||||
|
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||||
|
_appUiState.value,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun setTunnels(tunnels: TunnelConfigs) = viewModelScope.launch(ioDispatcher) {
|
||||||
|
_appUiState.emit(
|
||||||
|
_appUiState.value.copy(
|
||||||
|
tunnels = tunnels,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
val appUiState = _appUiState.asStateFlow()
|
|
||||||
|
|
||||||
|
|
||||||
fun isRequiredPermissionGranted(): Boolean {
|
|
||||||
val allAccepted =
|
|
||||||
(_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted)
|
|
||||||
if (!allAccepted) requestPermissions()
|
|
||||||
return allAccepted
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun requestPermissions() {
|
fun onPinLockDisabled() = viewModelScope.launch(ioDispatcher) {
|
||||||
_appUiState.update {
|
PinManager.clearPin()
|
||||||
it.copy(
|
appDataRepository.appState.setPinLockEnabled(false)
|
||||||
requestPermissions = true
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun permissionsRequested() {
|
fun onPinLockEnabled() = viewModelScope.launch {
|
||||||
_appUiState.update {
|
appDataRepository.appState.setPinLockEnabled(true)
|
||||||
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) {
|
|
||||||
_appUiState.update {
|
|
||||||
it.copy(
|
|
||||||
snackbarMessage = message,
|
|
||||||
snackbarMessageConsumed = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun snackbarMessageConsumed() {
|
|
||||||
_appUiState.update {
|
|
||||||
it.copy(
|
|
||||||
snackbarMessage = "",
|
|
||||||
snackbarMessageConsumed = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val logs = mutableStateListOf<LogMessage>()
|
|
||||||
|
|
||||||
fun readLogCatOutput() =
|
|
||||||
viewModelScope.launch(viewModelScope.coroutineContext + Dispatchers.IO) {
|
|
||||||
launch {
|
|
||||||
Logcatter.logs(callback = {
|
|
||||||
logs.add(it)
|
|
||||||
if (logs.size > Constants.LOG_BUFFER_SIZE) {
|
|
||||||
logs.removeRange(0, (logs.size - Constants.LOG_BUFFER_SIZE).toInt())
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun clearLogs() {
|
|
||||||
logs.clear()
|
|
||||||
Logcatter.clear()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun saveLogsToFile(context: Context) {
|
|
||||||
val fileName = "${Constants.BASE_LOG_FILE_NAME}-${Instant.now().epochSecond}.txt"
|
|
||||||
val content = logs.joinToString(separator = "\n")
|
|
||||||
FileUtils.saveFileToDownloads(context.applicationContext, content, fileName)
|
|
||||||
Toast.makeText(context, context.getString(R.string.logs_saved), Toast.LENGTH_SHORT)
|
|
||||||
.show()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setNotificationPermissionAccepted(accepted: Boolean) {
|
|
||||||
_appUiState.update {
|
|
||||||
it.copy(
|
|
||||||
notificationPermissionAccepted = accepted,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui
|
|
||||||
|
|
||||||
import com.journeyapps.barcodescanner.CaptureActivity
|
|
||||||
|
|
||||||
class CaptureActivityPortrait : CaptureActivity()
|
|
||||||
@@ -1,24 +1,25 @@
|
|||||||
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.animation.core.tween
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
import androidx.compose.foundation.focusable
|
import androidx.compose.foundation.focusable
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.rounded.Home
|
||||||
|
import androidx.compose.material.icons.rounded.QuestionMark
|
||||||
|
import androidx.compose.material.icons.rounded.Settings
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.SnackbarData
|
import androidx.compose.material3.SnackbarData
|
||||||
import androidx.compose.material3.SnackbarDuration
|
|
||||||
import androidx.compose.material3.SnackbarHost
|
import androidx.compose.material3.SnackbarHost
|
||||||
import androidx.compose.material3.SnackbarHostState
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.SnackbarResult
|
|
||||||
import androidx.compose.material3.surfaceColorAtElevation
|
import androidx.compose.material3.surfaceColorAtElevation
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
@@ -28,28 +29,25 @@ import androidx.compose.ui.focus.FocusRequester
|
|||||||
import androidx.compose.ui.focus.focusProperties
|
import androidx.compose.ui.focus.focusProperties
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.toArgb
|
import androidx.compose.ui.graphics.toArgb
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import androidx.navigation.NavType
|
|
||||||
import androidx.navigation.compose.NavHost
|
import androidx.navigation.compose.NavHost
|
||||||
import androidx.navigation.compose.composable
|
import androidx.navigation.compose.composable
|
||||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
import androidx.navigation.compose.rememberNavController
|
import androidx.navigation.toRoute
|
||||||
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.R
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar
|
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.isCurrentRoute
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar
|
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarControllerProvider
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen
|
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.options.OptionsScreen
|
import com.zaneschepke.wireguardautotunnel.ui.screens.options.OptionsScreen
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.pinlock.PinLockScreen
|
import com.zaneschepke.wireguardautotunnel.ui.screens.pinlock.PinLockScreen
|
||||||
@@ -57,119 +55,52 @@ import com.zaneschepke.wireguardautotunnel.ui.screens.settings.SettingsScreen
|
|||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.support.SupportScreen
|
import com.zaneschepke.wireguardautotunnel.ui.screens.support.SupportScreen
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.support.logs.LogsScreen
|
import com.zaneschepke.wireguardautotunnel.ui.screens.support.logs.LogsScreen
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.theme.WireguardAutoTunnelTheme
|
import com.zaneschepke.wireguardautotunnel.ui.theme.WireguardAutoTunnelTheme
|
||||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class MainActivity : AppCompatActivity() {
|
class MainActivity : AppCompatActivity() {
|
||||||
|
@Inject
|
||||||
|
lateinit var appStateRepository: AppStateRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var dataStoreManager: DataStoreManager
|
lateinit var tunnelService: TunnelService
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var settingsRepository: SettingsRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var serviceManager: ServiceManager
|
|
||||||
|
|
||||||
@OptIn(
|
|
||||||
ExperimentalPermissionsApi::class,
|
|
||||||
)
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb()))
|
val isPinLockEnabled = intent.extras?.getBoolean(SplashActivity.IS_PIN_LOCK_ENABLED_KEY)
|
||||||
|
|
||||||
|
enableEdgeToEdge(
|
||||||
|
navigationBarStyle = SystemBarStyle.auto(
|
||||||
|
lightScrim = Color.Transparent.toArgb(),
|
||||||
|
darkScrim = Color.Transparent.toArgb(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
// load preferences into memory and init data
|
|
||||||
lifecycleScope.launch {
|
|
||||||
dataStoreManager.init()
|
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
|
||||||
val settings = settingsRepository.getSettings()
|
|
||||||
if (settings.isAutoTunnelEnabled) {
|
|
||||||
serviceManager.startWatcherService(application.applicationContext)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setContent {
|
setContent {
|
||||||
val appViewModel = hiltViewModel<AppViewModel>()
|
val appViewModel = hiltViewModel<AppViewModel>()
|
||||||
val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle()
|
val appUiState by appViewModel.uiState.collectAsStateWithLifecycle(lifecycle = this.lifecycle)
|
||||||
val navController = rememberNavController()
|
val navController = appViewModel.navHostController
|
||||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||||
|
|
||||||
val notificationPermissionState =
|
LaunchedEffect(appUiState.vpnState.status) {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
|
val context = this@MainActivity
|
||||||
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS) else null
|
when (appUiState.vpnState.status) {
|
||||||
|
TunnelState.DOWN -> ServiceManager.stopTunnelBackgroundService(context)
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
else -> Unit
|
||||||
|
|
||||||
val vpnActivityResultState =
|
|
||||||
rememberLauncherForActivityResult(
|
|
||||||
ActivityResultContracts.StartActivityForResult(),
|
|
||||||
onResult = {
|
|
||||||
val accepted = (it.resultCode == RESULT_OK)
|
|
||||||
if (accepted) {
|
|
||||||
appViewModel.onVpnPermissionAccepted()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
fun showSnackBarMessage(message: StringValue) {
|
|
||||||
lifecycleScope.launch(Dispatchers.Main) {
|
|
||||||
val result =
|
|
||||||
snackbarHostState.showSnackbar(
|
|
||||||
message = message.asString(this@MainActivity),
|
|
||||||
duration = SnackbarDuration.Short,
|
|
||||||
)
|
|
||||||
when (result) {
|
|
||||||
SnackbarResult.ActionPerformed,
|
|
||||||
SnackbarResult.Dismissed -> {
|
|
||||||
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
|
|
||||||
)
|
|
||||||
}!!
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
context.requestTunnelTileServiceStateUpdate()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
SnackbarControllerProvider { host ->
|
||||||
WireguardAutoTunnelTheme {
|
WireguardAutoTunnelTheme {
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
appViewModel.setNotificationPermissionAccepted(
|
|
||||||
notificationPermissionState?.status?.isGranted ?: true,
|
|
||||||
)
|
|
||||||
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) appViewModel.readLogCatOutput()
|
|
||||||
}
|
|
||||||
|
|
||||||
LaunchedEffect(appUiState.snackbarMessageConsumed) {
|
|
||||||
if (!appUiState.snackbarMessageConsumed) {
|
|
||||||
showSnackBarMessage(StringValue.DynamicString(appUiState.snackbarMessage))
|
|
||||||
appViewModel.snackbarMessageConsumed()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val focusRequester = remember { FocusRequester() }
|
val focusRequester = remember { FocusRequester() }
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
snackbarHost = {
|
snackbarHost = {
|
||||||
SnackbarHost(snackbarHostState) { snackbarData: SnackbarData ->
|
SnackbarHost(host) { snackbarData: SnackbarData ->
|
||||||
CustomSnackBar(
|
CustomSnackBar(
|
||||||
snackbarData.visuals.message,
|
snackbarData.visuals.message,
|
||||||
isRtl = false,
|
isRtl = false,
|
||||||
@@ -180,102 +111,89 @@ class MainActivity : AppCompatActivity() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
//TODO refactor
|
containerColor = MaterialTheme.colorScheme.background,
|
||||||
modifier = Modifier
|
modifier =
|
||||||
|
Modifier
|
||||||
.focusable()
|
.focusable()
|
||||||
.focusProperties {
|
.focusProperties {
|
||||||
when (navBackStackEntry?.destination?.route) {
|
if (navBackStackEntry?.isCurrentRoute(Route.Lock) == true) {
|
||||||
Screen.Lock.route -> Unit
|
Unit
|
||||||
else -> up = focusRequester
|
} else {
|
||||||
|
up = focusRequester
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
bottomBar = {
|
bottomBar = {
|
||||||
BottomNavBar(
|
BottomNavBar(
|
||||||
navController,
|
navController,
|
||||||
listOf(
|
listOf(
|
||||||
Screen.Main.navItem,
|
BottomNavItem(
|
||||||
Screen.Settings.navItem,
|
name = stringResource(R.string.tunnels),
|
||||||
Screen.Support.navItem,
|
route = Route.Main,
|
||||||
|
icon = Icons.Rounded.Home,
|
||||||
|
),
|
||||||
|
BottomNavItem(
|
||||||
|
name = stringResource(R.string.settings),
|
||||||
|
route = Route.Settings,
|
||||||
|
icon = Icons.Rounded.Settings,
|
||||||
|
),
|
||||||
|
BottomNavItem(
|
||||||
|
name = stringResource(R.string.support),
|
||||||
|
route = Route.Support,
|
||||||
|
icon = Icons.Rounded.QuestionMark,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
) { padding ->
|
) { padding ->
|
||||||
|
Surface(modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||||
NavHost(
|
NavHost(
|
||||||
navController,
|
navController,
|
||||||
startDestination =
|
enterTransition = { fadeIn(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||||
(if (PinManager.pinExists()) Screen.Lock.route else Screen.Main.route),
|
exitTransition = { fadeOut(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||||
modifier =
|
startDestination = (if (isPinLockEnabled == true) Route.Lock else Route.Main),
|
||||||
Modifier
|
|
||||||
.padding(padding)
|
|
||||||
.fillMaxSize(),
|
|
||||||
) {
|
|
||||||
composable(
|
|
||||||
Screen.Main.route,
|
|
||||||
) {
|
) {
|
||||||
|
composable<Route.Main> {
|
||||||
MainScreen(
|
MainScreen(
|
||||||
focusRequester = focusRequester,
|
focusRequester = focusRequester,
|
||||||
appViewModel = appViewModel,
|
uiState = appUiState,
|
||||||
navController = navController,
|
navController = navController,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
composable(
|
composable<Route.Settings> {
|
||||||
Screen.Settings.route,
|
|
||||||
) {
|
|
||||||
SettingsScreen(
|
SettingsScreen(
|
||||||
appViewModel = appViewModel,
|
appViewModel = appViewModel,
|
||||||
|
uiState = appUiState,
|
||||||
navController = navController,
|
navController = navController,
|
||||||
focusRequester = focusRequester,
|
focusRequester = focusRequester,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
composable(
|
composable<Route.Support> {
|
||||||
Screen.Support.route,
|
|
||||||
) {
|
|
||||||
SupportScreen(
|
SupportScreen(
|
||||||
focusRequester = focusRequester,
|
focusRequester = focusRequester,
|
||||||
appViewModel = appViewModel,
|
|
||||||
navController = navController,
|
navController = navController,
|
||||||
|
appUiState = appUiState,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
composable(Screen.Support.Logs.route) {
|
composable<Route.Logs> {
|
||||||
LogsScreen(appViewModel)
|
LogsScreen()
|
||||||
}
|
}
|
||||||
//TODO fix navigation for amnezia
|
composable<Route.Config> {
|
||||||
composable("${Screen.Config.route}/{id}?configType={configType}", arguments =
|
val args = it.toRoute<Route.Config>()
|
||||||
listOf(
|
|
||||||
navArgument("id") {
|
|
||||||
type = NavType.StringType
|
|
||||||
defaultValue = "0"
|
|
||||||
},
|
|
||||||
navArgument("configType") {
|
|
||||||
type = NavType.StringType
|
|
||||||
defaultValue = ConfigType.WIREGUARD.name
|
|
||||||
}
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
val id = it.arguments?.getString("id")
|
|
||||||
val configType = ConfigType.valueOf( it.arguments?.getString("configType") ?: ConfigType.WIREGUARD.name)
|
|
||||||
if (!id.isNullOrBlank()) {
|
|
||||||
ConfigScreen(
|
ConfigScreen(
|
||||||
navController = navController,
|
|
||||||
tunnelId = id,
|
|
||||||
appViewModel = appViewModel,
|
|
||||||
focusRequester = focusRequester,
|
focusRequester = focusRequester,
|
||||||
configType = configType
|
tunnelId = args.id,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
composable<Route.Option> {
|
||||||
composable("${Screen.Option.route}/{id}") {
|
val args = it.toRoute<Route.Option>()
|
||||||
val id = it.arguments?.getString("id")
|
|
||||||
if (!id.isNullOrBlank()) {
|
|
||||||
OptionsScreen(
|
OptionsScreen(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
tunnelId = id,
|
tunnelId = args.id,
|
||||||
appViewModel = appViewModel,
|
|
||||||
focusRequester = focusRequester,
|
focusRequester = focusRequester,
|
||||||
|
appUiState = appUiState,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
composable<Route.Lock> {
|
||||||
composable(Screen.Lock.route) {
|
|
||||||
PinLockScreen(
|
PinLockScreen(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
appViewModel = appViewModel,
|
appViewModel = appViewModel,
|
||||||
@@ -286,4 +204,11 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
tunnelService.cancelStatsJob()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
sealed class Route {
|
||||||
|
@Serializable
|
||||||
|
data object Support : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Settings : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Main : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Option(
|
||||||
|
val id: Int,
|
||||||
|
) : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Lock : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Config(
|
||||||
|
val id: Int,
|
||||||
|
) : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Logs : Route()
|
||||||
|
}
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui
|
|
||||||
|
|
||||||
import androidx.compose.material.icons.Icons
|
|
||||||
import androidx.compose.material.icons.rounded.Home
|
|
||||||
import androidx.compose.material.icons.rounded.QuestionMark
|
|
||||||
import androidx.compose.material.icons.rounded.Settings
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem
|
|
||||||
|
|
||||||
sealed class Screen(val route: String) {
|
|
||||||
data object Main : Screen("main") {
|
|
||||||
val navItem =
|
|
||||||
BottomNavItem(
|
|
||||||
name = WireGuardAutoTunnel.instance.getString(R.string.tunnels),
|
|
||||||
route = route,
|
|
||||||
icon = Icons.Rounded.Home,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
data object Settings : Screen("settings") {
|
|
||||||
val navItem =
|
|
||||||
BottomNavItem(
|
|
||||||
name = WireGuardAutoTunnel.instance.getString(R.string.settings),
|
|
||||||
route = route,
|
|
||||||
icon = Icons.Rounded.Settings,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
data object Support : Screen("support") {
|
|
||||||
val navItem =
|
|
||||||
BottomNavItem(
|
|
||||||
name = WireGuardAutoTunnel.instance.getString(R.string.support),
|
|
||||||
route = route,
|
|
||||||
icon = Icons.Rounded.QuestionMark,
|
|
||||||
)
|
|
||||||
|
|
||||||
data object Logs : Screen("support/logs")
|
|
||||||
}
|
|
||||||
|
|
||||||
data object Config : Screen("config")
|
|
||||||
data object Lock : Screen("lock")
|
|
||||||
|
|
||||||
data object Option : Screen("option")
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.viewModels
|
||||||
|
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
|
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||||
|
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.requestAutoTunnelTileServiceUpdate
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
|
@SuppressLint("CustomSplashScreen")
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class SplashActivity : ComponentActivity() {
|
||||||
|
@Inject
|
||||||
|
lateinit var appStateRepository: AppStateRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
|
private val appViewModel: AppViewModel by viewModels()
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||||
|
val splashScreen = installSplashScreen()
|
||||||
|
splashScreen.setKeepOnScreenCondition { true }
|
||||||
|
}
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
|
lifecycleScope.launch {
|
||||||
|
repeatOnLifecycle(Lifecycle.State.CREATED) {
|
||||||
|
val pinLockEnabled = async {
|
||||||
|
appStateRepository.isPinLockEnabled().also {
|
||||||
|
if (it) PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||||
|
}
|
||||||
|
}.await()
|
||||||
|
async {
|
||||||
|
val settings = appDataRepository.settings.getSettings()
|
||||||
|
if (settings.isAutoTunnelEnabled) ServiceManager.startWatcherService(application.applicationContext)
|
||||||
|
if (tunnelService.get().getState() == TunnelState.UP) tunnelService.get().startStatsJob()
|
||||||
|
val activeTunnels = appDataRepository.tunnels.getActive()
|
||||||
|
if (activeTunnels.isNotEmpty() &&
|
||||||
|
tunnelService.get().getState() == TunnelState.DOWN
|
||||||
|
) {
|
||||||
|
tunnelService.get().startTunnel(activeTunnels.first())
|
||||||
|
}
|
||||||
|
}.await()
|
||||||
|
|
||||||
|
async {
|
||||||
|
val tunnels = appDataRepository.tunnels.getAll()
|
||||||
|
appViewModel.setTunnels(tunnels)
|
||||||
|
}.await()
|
||||||
|
|
||||||
|
requestAutoTunnelTileServiceUpdate()
|
||||||
|
|
||||||
|
val intent =
|
||||||
|
Intent(this@SplashActivity, MainActivity::class.java).apply {
|
||||||
|
putExtra(IS_PIN_LOCK_ENABLED_KEY, pinLockEnabled)
|
||||||
|
}
|
||||||
|
startActivity(intent)
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
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 = true) {
|
||||||
onClick: () -> Unit,
|
|
||||||
onIconClick: () -> Unit,
|
|
||||||
text: String,
|
|
||||||
icon: ImageVector,
|
|
||||||
enabled: Boolean
|
|
||||||
) {
|
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = onClick,
|
onClick = onClick,
|
||||||
enabled = enabled,
|
enabled = enabled,
|
||||||
|
|||||||
@@ -15,11 +15,14 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
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
|
||||||
@@ -30,11 +33,13 @@ fun RowListItem(
|
|||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
rowButton: @Composable () -> Unit,
|
rowButton: @Composable () -> Unit,
|
||||||
expanded: Boolean,
|
expanded: Boolean,
|
||||||
statistics: TunnelStatistics?
|
statistics: TunnelStatistics?,
|
||||||
|
focusRequester: FocusRequester,
|
||||||
) {
|
) {
|
||||||
Box(
|
Box(
|
||||||
modifier =
|
modifier =
|
||||||
Modifier
|
Modifier
|
||||||
|
.focusRequester(focusRequester)
|
||||||
.animateContentSize()
|
.animateContentSize()
|
||||||
.clip(RoundedCornerShape(30.dp))
|
.clip(RoundedCornerShape(30.dp))
|
||||||
.combinedClickable(
|
.combinedClickable(
|
||||||
@@ -44,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,
|
||||||
@@ -52,9 +58,10 @@ fun RowListItem(
|
|||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.fillMaxWidth(13 / 20f),
|
||||||
) {
|
) {
|
||||||
icon()
|
icon()
|
||||||
Text(text)
|
Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
}
|
}
|
||||||
rowButton()
|
rowButton()
|
||||||
}
|
}
|
||||||
@@ -68,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
|
||||||
|
|||||||
@@ -44,19 +44,21 @@ fun SearchBar(onQuery: (queryString: String) -> Unit) {
|
|||||||
onQuery(onQueryChanged)
|
onQuery(onQueryChanged)
|
||||||
},
|
},
|
||||||
leadingIcon = {
|
leadingIcon = {
|
||||||
|
val icon = Icons.Rounded.Search
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Rounded.Search,
|
imageVector = icon,
|
||||||
tint = MaterialTheme.colorScheme.onBackground,
|
tint = MaterialTheme.colorScheme.onBackground,
|
||||||
contentDescription = stringResource(id = R.string.search_icon),
|
contentDescription = icon.name,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
trailingIcon = {
|
trailingIcon = {
|
||||||
if (showClearIcon) {
|
if (showClearIcon) {
|
||||||
IconButton(onClick = { query = "" }) {
|
IconButton(onClick = { query = "" }) {
|
||||||
|
val icon = Icons.Rounded.Clear
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Rounded.Clear,
|
imageVector = icon,
|
||||||
tint = MaterialTheme.colorScheme.onBackground,
|
tint = MaterialTheme.colorScheme.onBackground,
|
||||||
contentDescription = stringResource(id = R.string.clear_icon),
|
contentDescription = icon.name,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-7
@@ -1,5 +1,6 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui.common.config
|
package com.zaneschepke.wireguardautotunnel.ui.common.config
|
||||||
|
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
import androidx.compose.foundation.text.KeyboardActions
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
@@ -14,23 +15,29 @@ fun ConfigurationTextBox(
|
|||||||
value: String,
|
value: String,
|
||||||
hint: String,
|
hint: String,
|
||||||
onValueChange: (String) -> Unit,
|
onValueChange: (String) -> Unit,
|
||||||
keyboardActions: KeyboardActions,
|
keyboardActions: KeyboardActions = KeyboardActions(),
|
||||||
label: String,
|
label: String,
|
||||||
modifier: Modifier
|
modifier: Modifier,
|
||||||
|
isError: Boolean = false,
|
||||||
|
keyboardOptions: KeyboardOptions = KeyboardOptions(
|
||||||
|
capitalization = KeyboardCapitalization.None,
|
||||||
|
imeAction = ImeAction.Done,
|
||||||
|
),
|
||||||
|
trailing: @Composable () -> Unit = {},
|
||||||
|
interactionSource: MutableInteractionSource? = null,
|
||||||
) {
|
) {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
|
isError = isError,
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
value = value,
|
value = value,
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
|
interactionSource = interactionSource,
|
||||||
onValueChange = { onValueChange(it) },
|
onValueChange = { onValueChange(it) },
|
||||||
label = { Text(label) },
|
label = { Text(label) },
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
placeholder = { Text(hint) },
|
placeholder = { Text(hint) },
|
||||||
keyboardOptions =
|
keyboardOptions = keyboardOptions,
|
||||||
KeyboardOptions(
|
|
||||||
capitalization = KeyboardCapitalization.None,
|
|
||||||
imeAction = ImeAction.Done,
|
|
||||||
),
|
|
||||||
keyboardActions = keyboardActions,
|
keyboardActions = keyboardActions,
|
||||||
|
trailingIcon = trailing,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-7
@@ -15,30 +15,36 @@ import androidx.compose.ui.unit.Dp
|
|||||||
@Composable
|
@Composable
|
||||||
fun ConfigurationToggle(
|
fun ConfigurationToggle(
|
||||||
label: String,
|
label: String,
|
||||||
enabled: Boolean,
|
enabled: Boolean = true,
|
||||||
checked: Boolean,
|
checked: Boolean,
|
||||||
padding: Dp,
|
padding: Dp,
|
||||||
onCheckChanged: () -> Unit,
|
onCheckChanged: (checked: Boolean) -> Unit,
|
||||||
modifier: Modifier = Modifier
|
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(label, textAlign = TextAlign.Start, modifier = Modifier
|
Text(
|
||||||
|
label,
|
||||||
|
textAlign = TextAlign.Start,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
.weight(
|
.weight(
|
||||||
weight = 1.0f,
|
weight = 1.0f,
|
||||||
fill = false,
|
fill = false,
|
||||||
),
|
),
|
||||||
softWrap = true)
|
softWrap = true,
|
||||||
|
)
|
||||||
Switch(
|
Switch(
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
enabled = enabled,
|
enabled = enabled,
|
||||||
checked = checked,
|
checked = checked,
|
||||||
onCheckedChange = { onCheckChanged() },
|
onCheckedChange = { onCheckChanged(it) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common.config
|
||||||
|
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.outlined.Save
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.platform.LocalFocusManager
|
||||||
|
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
|
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SubmitConfigurationTextBox(
|
||||||
|
value: String?,
|
||||||
|
label: String,
|
||||||
|
hint: String,
|
||||||
|
focusRequester: FocusRequester,
|
||||||
|
isErrorValue: (value: String?) -> Boolean,
|
||||||
|
onSubmit: (value: String) -> Unit,
|
||||||
|
keyboardOptions: KeyboardOptions = KeyboardOptions(
|
||||||
|
capitalization = KeyboardCapitalization.None,
|
||||||
|
imeAction = ImeAction.Done,
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
val focusManager = LocalFocusManager.current
|
||||||
|
val interactionSource = remember { MutableInteractionSource() }
|
||||||
|
val isFocused by interactionSource.collectIsFocusedAsState()
|
||||||
|
val keyboardController = LocalSoftwareKeyboardController.current
|
||||||
|
|
||||||
|
var stateValue by remember { mutableStateOf(value ?: "") }
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
isError = isErrorValue(stateValue),
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.focusRequester(focusRequester),
|
||||||
|
value = stateValue,
|
||||||
|
singleLine = true,
|
||||||
|
interactionSource = interactionSource,
|
||||||
|
onValueChange = { stateValue = it },
|
||||||
|
label = { Text(label) },
|
||||||
|
maxLines = 1,
|
||||||
|
placeholder = { Text(hint) },
|
||||||
|
keyboardOptions = keyboardOptions,
|
||||||
|
keyboardActions = KeyboardActions(
|
||||||
|
onDone = {
|
||||||
|
onSubmit(stateValue)
|
||||||
|
keyboardController?.hide()
|
||||||
|
},
|
||||||
|
),
|
||||||
|
trailingIcon = {
|
||||||
|
if (!isErrorValue(stateValue) && isFocused) {
|
||||||
|
IconButton(onClick = {
|
||||||
|
onSubmit(stateValue)
|
||||||
|
keyboardController?.hide()
|
||||||
|
focusManager.clearFocus()
|
||||||
|
}) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Outlined.Save,
|
||||||
|
contentDescription = stringResource(R.string.save_changes),
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
-14
@@ -10,34 +10,46 @@ import androidx.compose.runtime.getValue
|
|||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
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.NavDestination.Companion.hasRoute
|
||||||
|
import androidx.navigation.NavDestination.Companion.hierarchy
|
||||||
|
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavItem>) {
|
fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavItem>) {
|
||||||
val backStackEntry = navController.currentBackStackEntryAsState()
|
|
||||||
|
|
||||||
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
|
showBottomBar = bottomNavItems.firstOrNull {
|
||||||
showBottomBar = when (navBackStackEntry?.destination?.route) {
|
navBackStackEntry?.destination?.hierarchy?.any { dest ->
|
||||||
Screen.Lock.route -> false
|
bottomNavItems.map { dest.hasRoute(route = it.route::class) }.contains(true)
|
||||||
else -> true
|
} == true
|
||||||
}
|
} != null
|
||||||
|
|
||||||
|
if (showBottomBar) {
|
||||||
NavigationBar(
|
NavigationBar(
|
||||||
containerColor = if (!showBottomBar) Color.Transparent else MaterialTheme.colorScheme.background,
|
containerColor = MaterialTheme.colorScheme.surface,
|
||||||
) {
|
) {
|
||||||
if (showBottomBar) bottomNavItems.forEach { item ->
|
bottomNavItems.forEach { item ->
|
||||||
val selected = item.route == backStackEntry.value?.destination?.route
|
val selected = navBackStackEntry.isCurrentRoute(item.route)
|
||||||
|
|
||||||
NavigationBarItem(
|
NavigationBarItem(
|
||||||
selected = selected,
|
selected = selected,
|
||||||
onClick = { navController.navigate(item.route) },
|
onClick = {
|
||||||
|
if (selected) return@NavigationBarItem
|
||||||
|
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 +65,5 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -1,9 +1,10 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||||
|
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||||
|
|
||||||
data class BottomNavItem(
|
data class BottomNavItem(
|
||||||
val name: String,
|
val name: String,
|
||||||
val route: String,
|
val route: Route,
|
||||||
val icon: ImageVector,
|
val icon: ImageVector,
|
||||||
)
|
)
|
||||||
|
|||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||||
|
|
||||||
|
import androidx.navigation.NavBackStackEntry
|
||||||
|
import androidx.navigation.NavDestination.Companion.hasRoute
|
||||||
|
import androidx.navigation.NavDestination.Companion.hierarchy
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||||
|
|
||||||
|
fun NavBackStackEntry?.isCurrentRoute(route: Route): Boolean {
|
||||||
|
return this?.destination?.hierarchy?.any {
|
||||||
|
it.hasRoute(route = route::class)
|
||||||
|
} == true
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.navigation.NavHostController
|
||||||
|
import androidx.navigation.compose.ComposeNavigator
|
||||||
|
import androidx.navigation.compose.DialogNavigator
|
||||||
|
|
||||||
|
class NavigationService constructor(
|
||||||
|
context: Context,
|
||||||
|
) {
|
||||||
|
val navController = NavHostController(context).apply {
|
||||||
|
navigatorProvider.addNavigator(ComposeNavigator())
|
||||||
|
navigatorProvider.addNavigator(DialogNavigator())
|
||||||
|
}
|
||||||
|
}
|
||||||
+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(),
|
||||||
|
|||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common.snackbar
|
||||||
|
|
||||||
|
import androidx.compose.material3.SnackbarDuration
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.SnackbarResult
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
|
import androidx.compose.runtime.DisposableEffect
|
||||||
|
import androidx.compose.runtime.Immutable
|
||||||
|
import androidx.compose.runtime.ReadOnlyComposable
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.coroutines.EmptyCoroutineContext
|
||||||
|
|
||||||
|
private val LocalSnackbarController = staticCompositionLocalOf {
|
||||||
|
SnackbarController(
|
||||||
|
host = SnackbarHostState(),
|
||||||
|
scope = CoroutineScope(EmptyCoroutineContext),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
private val channel = Channel<SnackbarChannelMessage>(capacity = 1)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SnackbarControllerProvider(content: @Composable (snackbarHost: SnackbarHostState) -> Unit) {
|
||||||
|
val snackHostState = remember { SnackbarHostState() }
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val snackController = remember(scope) { SnackbarController(snackHostState, scope) }
|
||||||
|
val context = LocalContext.current
|
||||||
|
|
||||||
|
DisposableEffect(snackController, scope) {
|
||||||
|
val job = scope.launch {
|
||||||
|
for (payload in channel) {
|
||||||
|
snackController.showMessage(
|
||||||
|
message = payload.message.asString(context),
|
||||||
|
duration = payload.duration,
|
||||||
|
action = payload.action,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onDispose {
|
||||||
|
job.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CompositionLocalProvider(LocalSnackbarController provides snackController) {
|
||||||
|
content(
|
||||||
|
snackHostState,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Immutable
|
||||||
|
class SnackbarController(
|
||||||
|
private val host: SnackbarHostState,
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
val current
|
||||||
|
@Composable
|
||||||
|
@ReadOnlyComposable
|
||||||
|
get() = LocalSnackbarController.current
|
||||||
|
|
||||||
|
fun showMessage(message: StringValue, action: SnackbarAction? = null, duration: SnackbarDuration = SnackbarDuration.Short) {
|
||||||
|
channel.trySend(
|
||||||
|
SnackbarChannelMessage(
|
||||||
|
message = message,
|
||||||
|
duration = duration,
|
||||||
|
action = action,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun showMessage(message: String, action: SnackbarAction? = null, duration: SnackbarDuration = SnackbarDuration.Short) {
|
||||||
|
scope.launch {
|
||||||
|
/**
|
||||||
|
* note: uncomment this line if you want snackbar to be displayed immediately,
|
||||||
|
* rather than being enqueued and waiting [duration] * current_queue_size
|
||||||
|
*/
|
||||||
|
host.currentSnackbarData?.dismiss()
|
||||||
|
val result =
|
||||||
|
host.showSnackbar(
|
||||||
|
message = message,
|
||||||
|
actionLabel = action?.title,
|
||||||
|
duration = duration,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (result == SnackbarResult.ActionPerformed) {
|
||||||
|
action?.onActionPress?.invoke()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class SnackbarChannelMessage(
|
||||||
|
val message: StringValue,
|
||||||
|
val action: SnackbarAction?,
|
||||||
|
val duration: SnackbarDuration = SnackbarDuration.Short,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class SnackbarAction(val title: String, val onActionPress: () -> Unit)
|
||||||
+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),
|
||||||
|
|||||||
+145
-262
@@ -1,36 +1,27 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui.screens.config
|
package com.zaneschepke.wireguardautotunnel.ui.screens.config
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import androidx.compose.foundation.Image
|
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.focusGroup
|
import androidx.compose.foundation.focusGroup
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.IntrinsicSize
|
import androidx.compose.foundation.layout.IntrinsicSize
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
import androidx.compose.foundation.layout.fillMaxHeight
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
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.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
|
||||||
import androidx.compose.foundation.lazy.items
|
|
||||||
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
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.rounded.Android
|
|
||||||
import androidx.compose.material.icons.rounded.ContentCopy
|
import androidx.compose.material.icons.rounded.ContentCopy
|
||||||
import androidx.compose.material.icons.rounded.Delete
|
import androidx.compose.material.icons.rounded.Delete
|
||||||
import androidx.compose.material.icons.rounded.Refresh
|
import androidx.compose.material.icons.rounded.Refresh
|
||||||
import androidx.compose.material.icons.rounded.Save
|
import androidx.compose.material.icons.rounded.Save
|
||||||
import androidx.compose.material3.BasicAlertDialog
|
|
||||||
import androidx.compose.material3.Checkbox
|
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
|
||||||
import androidx.compose.material3.FabPosition
|
import androidx.compose.material3.FabPosition
|
||||||
import androidx.compose.material3.FloatingActionButton
|
import androidx.compose.material3.FloatingActionButton
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
@@ -39,10 +30,8 @@ import androidx.compose.material3.MaterialTheme
|
|||||||
import androidx.compose.material3.OutlinedTextField
|
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.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.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
|
||||||
@@ -53,8 +42,6 @@ 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.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
|
||||||
@@ -68,76 +55,77 @@ import androidx.compose.ui.text.input.VisualTransformation
|
|||||||
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 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.Screen
|
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.SearchBar
|
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationTextBox
|
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationTextBox
|
||||||
|
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.screen.LoadingScreen
|
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.config.components.ApplicationSelectionDialog
|
||||||
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.isRunningOnTv
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||||
@OptIn(
|
|
||||||
ExperimentalMaterial3Api::class,
|
|
||||||
)
|
|
||||||
@Composable
|
@Composable
|
||||||
fun ConfigScreen(
|
fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||||
viewModel: ConfigViewModel = hiltViewModel(),
|
val viewModel = hiltViewModel<ConfigViewModel, ConfigViewModel.ConfigViewModelFactory> { factory ->
|
||||||
focusRequester: FocusRequester,
|
factory.create(tunnelId)
|
||||||
navController: NavController,
|
}
|
||||||
appViewModel: AppViewModel,
|
|
||||||
tunnelId: String,
|
|
||||||
configType: ConfigType
|
|
||||||
) {
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
val snackbar = SnackbarController.current
|
||||||
val clipboardManager: ClipboardManager = LocalClipboardManager.current
|
val clipboardManager: ClipboardManager = LocalClipboardManager.current
|
||||||
val keyboardController = LocalSoftwareKeyboardController.current
|
val keyboardController = LocalSoftwareKeyboardController.current
|
||||||
var showApplicationsDialog by remember { mutableStateOf(false) }
|
var showApplicationsDialog by remember { mutableStateOf(false) }
|
||||||
var showAuthPrompt by remember { mutableStateOf(false) }
|
var showAuthPrompt by remember { mutableStateOf(false) }
|
||||||
var isAuthenticated by remember { mutableStateOf(false) }
|
var isAuthenticated by remember { mutableStateOf(false) }
|
||||||
|
var configType by remember { mutableStateOf(ConfigType.WIREGUARD) }
|
||||||
|
|
||||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
LaunchedEffect(Unit) { viewModel.init(tunnelId) }
|
LaunchedEffect(Unit) {
|
||||||
|
if (!uiState.loading && context.isRunningOnTv()) {
|
||||||
LaunchedEffect(uiState.loading) {
|
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||||
if (!uiState.loading && WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
kotlin.runCatching {
|
||||||
|
focusRequester.requestFocus()
|
||||||
|
}.onFailure {
|
||||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||||
focusRequester.requestFocus()
|
focusRequester.requestFocus()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (uiState.loading) {
|
LaunchedEffect(Unit) {
|
||||||
LoadingScreen()
|
delay(2_000L)
|
||||||
return
|
viewModel.cleanUpUninstalledApps()
|
||||||
}
|
}
|
||||||
|
|
||||||
val keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() })
|
val keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() })
|
||||||
|
|
||||||
val keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done)
|
val keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done)
|
||||||
|
|
||||||
val fillMaxHeight = .85f
|
val fillMaxHeight = .85f
|
||||||
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,191 +137,39 @@ fun ConfigScreen(
|
|||||||
},
|
},
|
||||||
onError = {
|
onError = {
|
||||||
showAuthPrompt = false
|
showAuthPrompt = false
|
||||||
appViewModel.showSnackbarMessage(context.getString(R.string.error_authentication_failed))
|
snackbar.showMessage(
|
||||||
|
context.getString(R.string.error_authentication_failed),
|
||||||
|
)
|
||||||
},
|
},
|
||||||
onFailure = {
|
onFailure = {
|
||||||
showAuthPrompt = false
|
showAuthPrompt = false
|
||||||
appViewModel.showSnackbarMessage(context.getString(R.string.error_authorization_failed))
|
snackbar.showMessage(
|
||||||
|
context.getString(R.string.error_authorization_failed),
|
||||||
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (showApplicationsDialog) {
|
if (showApplicationsDialog) {
|
||||||
val sortedPackages =
|
ApplicationSelectionDialog(viewModel, uiState) {
|
||||||
remember(uiState.packages) {
|
showApplicationsDialog = false
|
||||||
uiState.packages.sortedBy { viewModel.getPackageLabel(it) }
|
|
||||||
}
|
|
||||||
BasicAlertDialog(onDismissRequest = { showApplicationsDialog = false }) {
|
|
||||||
Surface(
|
|
||||||
tonalElevation = 2.dp,
|
|
||||||
shadowElevation = 2.dp,
|
|
||||||
shape = RoundedCornerShape(12.dp),
|
|
||||||
color = MaterialTheme.colorScheme.surface,
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.fillMaxHeight(if (uiState.isAllApplicationsEnabled) 1 / 5f else 4 / 5f),
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth(),
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 20.dp, vertical = 7.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
|
||||||
) {
|
|
||||||
Text(stringResource(id = R.string.tunnel_all))
|
|
||||||
Switch(
|
|
||||||
checked = uiState.isAllApplicationsEnabled,
|
|
||||||
onCheckedChange = { viewModel.onAllApplicationsChange(it) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (!uiState.isAllApplicationsEnabled) {
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 20.dp, vertical = 7.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
|
||||||
) {
|
|
||||||
Text(stringResource(id = R.string.include))
|
|
||||||
Checkbox(
|
|
||||||
checked = uiState.include,
|
|
||||||
onCheckedChange = {
|
|
||||||
viewModel.onIncludeChange(!uiState.include)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
|
||||||
) {
|
|
||||||
Text(stringResource(id = R.string.exclude))
|
|
||||||
Checkbox(
|
|
||||||
checked = !uiState.include,
|
|
||||||
onCheckedChange = {
|
|
||||||
viewModel.onIncludeChange(!uiState.include)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 20.dp, vertical = 7.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
|
||||||
) {
|
|
||||||
SearchBar(viewModel::emitQueriedPackages)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.padding(5.dp))
|
|
||||||
LazyColumn(
|
|
||||||
horizontalAlignment = Alignment.Start,
|
|
||||||
verticalArrangement = Arrangement.Top,
|
|
||||||
modifier = Modifier.fillMaxHeight(4 / 5f),
|
|
||||||
) {
|
|
||||||
items(sortedPackages, key = { it.packageName }) { pack ->
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.padding(5.dp),
|
|
||||||
) {
|
|
||||||
Row(modifier = Modifier.fillMaxWidth(fillMaxWidth)) {
|
|
||||||
val drawable =
|
|
||||||
pack.applicationInfo?.loadIcon(context.packageManager)
|
|
||||||
if (drawable != null) {
|
|
||||||
Image(
|
|
||||||
painter = DrawablePainter(drawable),
|
|
||||||
stringResource(id = R.string.icon),
|
|
||||||
modifier = Modifier.size(50.dp, 50.dp),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
val icon = Icons.Rounded.Android
|
|
||||||
Icon(
|
|
||||||
icon,
|
|
||||||
icon.name,
|
|
||||||
modifier = Modifier.size(50.dp, 50.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Text(
|
|
||||||
viewModel.getPackageLabel(pack),
|
|
||||||
modifier = Modifier.padding(5.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Checkbox(
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
|
||||||
checked =
|
|
||||||
(uiState.checkedPackageNames.contains(
|
|
||||||
pack.packageName,
|
|
||||||
)),
|
|
||||||
onCheckedChange = {
|
|
||||||
if (it) {
|
|
||||||
viewModel.onAddCheckedPackage(pack.packageName)
|
|
||||||
} else {
|
|
||||||
viewModel.onRemoveCheckedPackage(pack.packageName)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.padding(top = 5.dp),
|
|
||||||
horizontalArrangement = Arrangement.Center,
|
|
||||||
) {
|
|
||||||
TextButton(onClick = { showApplicationsDialog = false }) {
|
|
||||||
Text(stringResource(R.string.done))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
floatingActionButtonPosition = FabPosition.End,
|
floatingActionButtonPosition = FabPosition.End,
|
||||||
floatingActionButton = {
|
floatingActionButton = {
|
||||||
val secondaryColor = MaterialTheme.colorScheme.secondary
|
|
||||||
val hoverColor = MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp)
|
|
||||||
var fobColor by remember { mutableStateOf(secondaryColor) }
|
|
||||||
FloatingActionButton(
|
FloatingActionButton(
|
||||||
modifier =
|
|
||||||
Modifier.onFocusChanged {
|
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
|
||||||
fobColor = if (it.isFocused) hoverColor else secondaryColor
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onClick = {
|
onClick = {
|
||||||
viewModel.onSaveAllChanges(configType).onSuccess {
|
viewModel.onSaveAllChanges()
|
||||||
appViewModel.showSnackbarMessage(context.getString(R.string.config_changes_saved))
|
|
||||||
navController.navigate(Screen.Main.route)
|
|
||||||
}.onFailure {
|
|
||||||
appViewModel.showSnackbarMessage(it.getMessage(context))
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
containerColor = fobColor,
|
containerColor = MaterialTheme.colorScheme.primary,
|
||||||
shape = RoundedCornerShape(16.dp),
|
shape = RoundedCornerShape(16.dp),
|
||||||
) {
|
) {
|
||||||
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 +190,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(),
|
||||||
) {
|
) {
|
||||||
@@ -374,26 +213,37 @@ fun ConfigScreen(
|
|||||||
stringResource(R.string.interface_),
|
stringResource(R.string.interface_),
|
||||||
padding = screenPadding,
|
padding = screenPadding,
|
||||||
)
|
)
|
||||||
|
ConfigurationToggle(
|
||||||
|
stringResource(id = R.string.show_amnezia_properties),
|
||||||
|
checked = configType == ConfigType.AMNEZIA,
|
||||||
|
padding = screenPadding,
|
||||||
|
onCheckChanged = { configType = if (it) ConfigType.AMNEZIA else ConfigType.WIREGUARD },
|
||||||
|
modifier = Modifier.focusRequester(focusRequester),
|
||||||
|
)
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.tunnelName,
|
value = uiState.tunnelName,
|
||||||
onValueChange = { value -> viewModel.onTunnelNameChange(value) },
|
onValueChange = viewModel::onTunnelNameChange,
|
||||||
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.toInt()) || isAuthenticated) {
|
||||||
VisualTransformation.None
|
VisualTransformation.None
|
||||||
else PasswordVisualTransformation(),
|
} else {
|
||||||
enabled = (tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated,
|
PasswordVisualTransformation()
|
||||||
|
},
|
||||||
|
enabled = (tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID.toInt()) || isAuthenticated,
|
||||||
onValueChange = { value -> viewModel.onPrivateKeyChange(value) },
|
onValueChange = { value -> viewModel.onPrivateKeyChange(value) },
|
||||||
trailingIcon = {
|
trailingIcon = {
|
||||||
IconButton(
|
IconButton(
|
||||||
@@ -403,7 +253,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 +283,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,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -443,141 +293,172 @@ fun ConfigScreen(
|
|||||||
keyboardOptions = keyboardOptions,
|
keyboardOptions = keyboardOptions,
|
||||||
keyboardActions = keyboardActions,
|
keyboardActions = keyboardActions,
|
||||||
)
|
)
|
||||||
Row(modifier = Modifier.fillMaxWidth()) {
|
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.addresses,
|
value = uiState.interfaceProxy.addresses,
|
||||||
onValueChange = { value -> viewModel.onAddressesChanged(value) },
|
onValueChange = viewModel::onAddressesChanged,
|
||||||
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 =
|
||||||
.fillMaxWidth(3 / 5f)
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
.padding(end = 5.dp),
|
.padding(end = 5.dp),
|
||||||
)
|
)
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.listenPort,
|
value = uiState.interfaceProxy.listenPort,
|
||||||
onValueChange = { value -> viewModel.onListenPortChanged(value) },
|
onValueChange = viewModel::onListenPortChanged,
|
||||||
keyboardActions = keyboardActions,
|
keyboardActions = keyboardActions,
|
||||||
label = stringResource(R.string.listen_port),
|
label = stringResource(R.string.listen_port),
|
||||||
hint = stringResource(R.string.random),
|
hint = stringResource(R.string.random),
|
||||||
modifier = Modifier.width(IntrinsicSize.Min),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
)
|
)
|
||||||
}
|
|
||||||
Row(modifier = Modifier.fillMaxWidth()) {
|
Row(modifier = Modifier.fillMaxWidth()) {
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.dnsServers,
|
value = uiState.interfaceProxy.dnsServers,
|
||||||
onValueChange = { value -> viewModel.onDnsServersChanged(value) },
|
onValueChange = viewModel::onDnsServersChanged,
|
||||||
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),
|
||||||
)
|
)
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.mtu,
|
value = uiState.interfaceProxy.mtu,
|
||||||
onValueChange = { value -> viewModel.onMtuChanged(value) },
|
onValueChange = viewModel::onMtuChanged,
|
||||||
keyboardActions = keyboardActions,
|
keyboardActions = keyboardActions,
|
||||||
label = stringResource(R.string.mtu),
|
label = stringResource(R.string.mtu),
|
||||||
hint = stringResource(R.string.auto),
|
hint = stringResource(R.string.auto),
|
||||||
modifier = Modifier.width(IntrinsicSize.Min),
|
modifier = Modifier.width(IntrinsicSize.Min),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if(configType == ConfigType.AMNEZIA) {
|
if (configType == ConfigType.AMNEZIA) {
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.junkPacketCount,
|
value = uiState.interfaceProxy.junkPacketCount,
|
||||||
onValueChange = { value -> viewModel.onJunkPacketCountChanged(value) },
|
onValueChange = viewModel::onJunkPacketCountChanged,
|
||||||
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),
|
||||||
)
|
)
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.junkPacketMinSize,
|
value = uiState.interfaceProxy.junkPacketMinSize,
|
||||||
onValueChange = { value -> viewModel.onJunkPacketMinSizeChanged(value) },
|
onValueChange = viewModel::onJunkPacketMinSizeChanged,
|
||||||
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),
|
||||||
)
|
)
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.junkPacketMaxSize,
|
value = uiState.interfaceProxy.junkPacketMaxSize,
|
||||||
onValueChange = { value -> viewModel.onJunkPacketMaxSizeChanged(value) },
|
onValueChange = viewModel::onJunkPacketMaxSizeChanged,
|
||||||
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),
|
||||||
)
|
)
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.initPacketJunkSize,
|
value = uiState.interfaceProxy.initPacketJunkSize,
|
||||||
onValueChange = { value -> viewModel.onInitPacketJunkSizeChanged(value) },
|
onValueChange = viewModel::onInitPacketJunkSizeChanged,
|
||||||
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 = viewModel::onResponsePacketJunkSize,
|
||||||
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 = viewModel::onInitPacketMagicHeader,
|
||||||
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),
|
||||||
)
|
)
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.responsePacketMagicHeader,
|
value = uiState.interfaceProxy.responsePacketMagicHeader,
|
||||||
onValueChange = { value -> viewModel.onResponsePacketMagicHeader(value) },
|
onValueChange = viewModel::onResponsePacketMagicHeader,
|
||||||
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),
|
||||||
)
|
)
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.underloadPacketMagicHeader,
|
value = uiState.interfaceProxy.underloadPacketMagicHeader,
|
||||||
onValueChange = { value -> viewModel.onUnderloadPacketMagicHeader(value) },
|
onValueChange = viewModel::onUnderloadPacketMagicHeader,
|
||||||
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),
|
||||||
)
|
)
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.transportPacketMagicHeader,
|
value = uiState.interfaceProxy.transportPacketMagicHeader,
|
||||||
onValueChange = { value -> viewModel.onTransportPacketMagicHeader(value) },
|
onValueChange = viewModel::onTransportPacketMagicHeader,
|
||||||
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,
|
||||||
@@ -595,26 +476,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),
|
||||||
) {
|
) {
|
||||||
@@ -700,7 +585,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),
|
||||||
) {
|
) {
|
||||||
@@ -714,9 +600,6 @@ fun ConfigScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
|
||||||
Spacer(modifier = Modifier.weight(.17f))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-6
@@ -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()),
|
||||||
@@ -15,11 +15,11 @@ data class ConfigUiState(
|
|||||||
val isAllApplicationsEnabled: Boolean = false,
|
val isAllApplicationsEnabled: Boolean = false,
|
||||||
val loading: Boolean = true,
|
val loading: Boolean = true,
|
||||||
val tunnel: TunnelConfig? = null,
|
val tunnel: TunnelConfig? = null,
|
||||||
val tunnelName: String = "",
|
var tunnelName: String = "",
|
||||||
val isAmneziaEnabled: Boolean = false
|
val isAmneziaEnabled: Boolean = false,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun from(config : Config) : ConfigUiState {
|
fun from(config: Config): ConfigUiState {
|
||||||
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
|
||||||
@@ -43,8 +43,8 @@ data class ConfigUiState(
|
|||||||
isAllApplicationsEnabled,
|
isAllApplicationsEnabled,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
fun from(config: org.amnezia.awg.config.Config) : ConfigUiState {
|
|
||||||
//TODO update with new values
|
fun from(config: org.amnezia.awg.config.Config): ConfigUiState {
|
||||||
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
|
||||||
@@ -68,5 +68,13 @@ data class ConfigUiState(
|
|||||||
isAllApplicationsEnabled,
|
isAllApplicationsEnabled,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun from(tunnel: TunnelConfig): ConfigUiState {
|
||||||
|
val config = tunnel.toAmConfig()
|
||||||
|
return from(config).copy(
|
||||||
|
tunnelName = tunnel.name,
|
||||||
|
tunnel = tunnel,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+227
-138
@@ -6,6 +6,7 @@ import android.content.pm.PackageManager
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import androidx.navigation.NavHostController
|
||||||
import com.wireguard.config.Config
|
import com.wireguard.config.Config
|
||||||
import com.wireguard.config.Interface
|
import com.wireguard.config.Interface
|
||||||
import com.wireguard.config.Peer
|
import com.wireguard.config.Peer
|
||||||
@@ -15,100 +16,123 @@ import com.zaneschepke.wireguardautotunnel.R
|
|||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
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.data.repository.SettingsRepository
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.PeerProxy
|
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.PeerProxy
|
||||||
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.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.extensions.removeAt
|
||||||
import com.zaneschepke.wireguardautotunnel.util.removeAt
|
import com.zaneschepke.wireguardautotunnel.util.extensions.update
|
||||||
import com.zaneschepke.wireguardautotunnel.util.update
|
import dagger.assisted.Assisted
|
||||||
|
import dagger.assisted.AssistedFactory
|
||||||
|
import dagger.assisted.AssistedInject
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.onStart
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.plus
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel(assistedFactory = ConfigViewModel.ConfigViewModelFactory::class)
|
||||||
class ConfigViewModel
|
class ConfigViewModel
|
||||||
@Inject
|
@AssistedInject
|
||||||
constructor(
|
constructor(
|
||||||
private val settingsRepository: SettingsRepository,
|
private val appDataRepository: AppDataRepository,
|
||||||
private val appDataRepository: AppDataRepository
|
private val navController: NavHostController,
|
||||||
|
@Assisted val id: Int,
|
||||||
|
@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.onStart {
|
||||||
|
appDataRepository.tunnels.getById(id)?.let {
|
||||||
fun init(tunnelId: String) =
|
val packages = getQueriedPackages()
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
_uiState.value = ConfigUiState.from(it).copy(
|
||||||
val packages = getQueriedPackages("")
|
|
||||||
val state =
|
|
||||||
if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) {
|
|
||||||
val tunnelConfig =
|
|
||||||
appDataRepository.tunnels.getAll()
|
|
||||||
.firstOrNull { it.id.toString() == tunnelId }
|
|
||||||
val isAmneziaEnabled = settingsRepository.getSettings().isAmneziaEnabled
|
|
||||||
if (tunnelConfig != null) {
|
|
||||||
(if(isAmneziaEnabled) {
|
|
||||||
val amConfig = if(tunnelConfig.amQuick == "") tunnelConfig.wgQuick else tunnelConfig.amQuick
|
|
||||||
ConfigUiState.from(TunnelConfig.configFromAmQuick(amConfig))
|
|
||||||
} else ConfigUiState.from(TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick))).copy(
|
|
||||||
packages = packages,
|
packages = packages,
|
||||||
loading = false,
|
|
||||||
tunnel = tunnelConfig,
|
|
||||||
tunnelName = tunnelConfig.name,
|
|
||||||
isAmneziaEnabled = isAmneziaEnabled
|
|
||||||
)
|
)
|
||||||
} else {
|
|
||||||
ConfigUiState(loading = false, packages = packages)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ConfigUiState(loading = false, packages = packages)
|
|
||||||
}
|
|
||||||
_uiState.value = state
|
|
||||||
}
|
}
|
||||||
|
}.stateIn(
|
||||||
|
viewModelScope + ioDispatcher,
|
||||||
|
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||||
|
ConfigUiState(),
|
||||||
|
)
|
||||||
|
|
||||||
fun onTunnelNameChange(name: String) {
|
fun onTunnelNameChange(name: String) {
|
||||||
_uiState.value = _uiState.value.copy(tunnelName = name)
|
_uiState.update {
|
||||||
|
it.copy(tunnelName = name)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onIncludeChange(include: Boolean) {
|
fun onIncludeChange(include: Boolean) {
|
||||||
_uiState.value = _uiState.value.copy(include = include)
|
_uiState.update {
|
||||||
|
it.copy(include = include)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cleanUpUninstalledApps() = viewModelScope.launch(ioDispatcher) {
|
||||||
|
uiState.value.tunnel?.let {
|
||||||
|
val config = it.toAmConfig()
|
||||||
|
val packages = getQueriedPackages()
|
||||||
|
val packageSet = packages.map { pack -> pack.packageName }.toSet()
|
||||||
|
val includedApps = config.`interface`.includedApplications.toMutableList()
|
||||||
|
val excludedApps = config.`interface`.excludedApplications.toMutableList()
|
||||||
|
if (includedApps.isEmpty() && excludedApps.isEmpty()) return@launch
|
||||||
|
if (includedApps.retainAll(packageSet) || excludedApps.retainAll(packageSet)) {
|
||||||
|
Timber.i("Removing split tunnel package name that no longer exists on the device")
|
||||||
|
_uiState.update { state ->
|
||||||
|
state.copy(
|
||||||
|
checkedPackageNames = if (_uiState.value.include) includedApps else excludedApps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val wgQuick = buildConfig().toWgQuickString(true)
|
||||||
|
val amQuick = buildAmConfig().toAwgQuickString(true)
|
||||||
|
saveConfig(
|
||||||
|
it.copy(
|
||||||
|
amQuick = amQuick,
|
||||||
|
wgQuick = wgQuick,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onAddCheckedPackage(packageName: String) {
|
fun onAddCheckedPackage(packageName: String) {
|
||||||
_uiState.value =
|
_uiState.update {
|
||||||
_uiState.value.copy(
|
it.copy(
|
||||||
checkedPackageNames = _uiState.value.checkedPackageNames + packageName,
|
checkedPackageNames = it.checkedPackageNames + packageName,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun onAllApplicationsChange(isAllApplicationsEnabled: Boolean) {
|
fun onAllApplicationsChange(isAllApplicationsEnabled: Boolean) {
|
||||||
_uiState.value = _uiState.value.copy(isAllApplicationsEnabled = isAllApplicationsEnabled)
|
_uiState.update {
|
||||||
|
it.copy(isAllApplicationsEnabled = isAllApplicationsEnabled)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onRemoveCheckedPackage(packageName: String) {
|
fun onRemoveCheckedPackage(packageName: String) {
|
||||||
_uiState.value =
|
_uiState.update {
|
||||||
_uiState.value.copy(
|
it.copy(
|
||||||
checkedPackageNames = _uiState.value.checkedPackageNames - packageName,
|
checkedPackageNames = it.checkedPackageNames - packageName,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun getQueriedPackages(query: String): List<PackageInfo> {
|
private fun getQueriedPackages(query: String = ""): List<PackageInfo> {
|
||||||
return getAllInternetCapablePackages().filter {
|
return getAllInternetCapablePackages().filter {
|
||||||
getPackageLabel(it).lowercase().contains(query.lowercase())
|
getPackageLabel(it).lowercase().contains(query.lowercase())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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> {
|
||||||
@@ -130,14 +154,13 @@ constructor(
|
|||||||
return _uiState.value.isAllApplicationsEnabled
|
return _uiState.value.isAllApplicationsEnabled
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun saveConfig(tunnelConfig: TunnelConfig) =
|
private fun saveConfig(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||||
viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) }
|
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()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,111 +193,158 @@ constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun emptyCheckedPackagesList() {
|
private fun emptyCheckedPackagesList() {
|
||||||
_uiState.value = _uiState.value.copy(checkedPackageNames = emptyList())
|
_uiState.update {
|
||||||
|
it.copy(checkedPackageNames = emptyList())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun buildInterfaceListFromProxyInterface(): Interface {
|
private fun buildInterfaceListFromProxyInterface(): Interface {
|
||||||
val builder = Interface.Builder()
|
val builder = Interface.Builder()
|
||||||
builder.parsePrivateKey(_uiState.value.interfaceProxy.privateKey.trim())
|
with(_uiState.value.interfaceProxy) {
|
||||||
builder.parseAddresses(_uiState.value.interfaceProxy.addresses.trim())
|
builder.parsePrivateKey(this.privateKey.trim())
|
||||||
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) {
|
builder.parseAddresses(this.addresses.trim())
|
||||||
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim())
|
if (this.dnsServers.isNotEmpty()) {
|
||||||
|
builder.parseDnsServers(this.dnsServers.trim())
|
||||||
}
|
}
|
||||||
if (_uiState.value.interfaceProxy.mtu.isNotEmpty())
|
if (this.mtu.isNotEmpty()) {
|
||||||
builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim())
|
builder.parseMtu(this.mtu.trim())
|
||||||
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
|
}
|
||||||
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
|
if (this.listenPort.isNotEmpty()) {
|
||||||
|
builder.parseListenPort(this.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()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun buildAmInterfaceListFromProxyInterface(): org.amnezia.awg.config.Interface {
|
private fun buildAmInterfaceListFromProxyInterface(): org.amnezia.awg.config.Interface {
|
||||||
val builder = org.amnezia.awg.config.Interface.Builder()
|
val builder = org.amnezia.awg.config.Interface.Builder()
|
||||||
builder.parsePrivateKey(_uiState.value.interfaceProxy.privateKey.trim())
|
with(_uiState.value.interfaceProxy) {
|
||||||
builder.parseAddresses(_uiState.value.interfaceProxy.addresses.trim())
|
builder.parsePrivateKey(this.privateKey.trim())
|
||||||
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) {
|
builder.parseAddresses(this.addresses.trim())
|
||||||
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim())
|
if (this.dnsServers.isNotEmpty()) {
|
||||||
|
builder.parseDnsServers(this.dnsServers.trim())
|
||||||
}
|
}
|
||||||
if (_uiState.value.interfaceProxy.mtu.isNotEmpty())
|
if (this.mtu.isNotEmpty()) {
|
||||||
builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim())
|
builder.parseMtu(this.mtu.trim())
|
||||||
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
|
}
|
||||||
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
|
if (this.listenPort.isNotEmpty()) {
|
||||||
|
builder.parseListenPort(this.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(
|
||||||
if(_uiState.value.interfaceProxy.junkPacketCount.isNotEmpty()) {
|
_uiState.value.checkedPackageNames,
|
||||||
builder.setJunkPacketCount(_uiState.value.interfaceProxy.junkPacketCount.trim().toInt())
|
)
|
||||||
}
|
}
|
||||||
if(_uiState.value.interfaceProxy.junkPacketMinSize.isNotEmpty()) {
|
if (!_uiState.value.include) {
|
||||||
builder.setJunkPacketMinSize(_uiState.value.interfaceProxy.junkPacketMinSize.trim().toInt())
|
builder.excludeApplications(
|
||||||
|
_uiState.value.checkedPackageNames,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if(_uiState.value.interfaceProxy.junkPacketMaxSize.isNotEmpty()) {
|
if (this.junkPacketCount.isNotEmpty()) {
|
||||||
builder.setJunkPacketMaxSize(_uiState.value.interfaceProxy.junkPacketMaxSize.trim().toInt())
|
builder.setJunkPacketCount(
|
||||||
|
this.junkPacketCount.trim().toInt(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if(_uiState.value.interfaceProxy.initPacketJunkSize.isNotEmpty()) {
|
if (this.junkPacketMinSize.isNotEmpty()) {
|
||||||
builder.setInitPacketJunkSize(_uiState.value.interfaceProxy.initPacketJunkSize.trim().toInt())
|
builder.setJunkPacketMinSize(
|
||||||
|
this.junkPacketMinSize.trim().toInt(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if(_uiState.value.interfaceProxy.responsePacketJunkSize.isNotEmpty()) {
|
if (this.junkPacketMaxSize.isNotEmpty()) {
|
||||||
builder.setResponsePacketJunkSize(_uiState.value.interfaceProxy.responsePacketJunkSize.trim().toInt())
|
builder.setJunkPacketMaxSize(
|
||||||
|
this.junkPacketMaxSize.trim().toInt(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if(_uiState.value.interfaceProxy.initPacketMagicHeader.isNotEmpty()) {
|
if (this.initPacketJunkSize.isNotEmpty()) {
|
||||||
builder.setInitPacketMagicHeader(_uiState.value.interfaceProxy.initPacketMagicHeader.trim().toLong())
|
builder.setInitPacketJunkSize(
|
||||||
|
this.initPacketJunkSize.trim().toInt(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if(_uiState.value.interfaceProxy.responsePacketMagicHeader.isNotEmpty()) {
|
if (this.responsePacketJunkSize.isNotEmpty()) {
|
||||||
builder.setResponsePacketMagicHeader(_uiState.value.interfaceProxy.responsePacketMagicHeader.trim().toLong())
|
builder.setResponsePacketJunkSize(
|
||||||
|
this.responsePacketJunkSize.trim().toInt(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if(_uiState.value.interfaceProxy.transportPacketMagicHeader.isNotEmpty()) {
|
if (this.initPacketMagicHeader.isNotEmpty()) {
|
||||||
builder.setTransportPacketMagicHeader(_uiState.value.interfaceProxy.transportPacketMagicHeader.trim().toLong())
|
builder.setInitPacketMagicHeader(
|
||||||
|
this.initPacketMagicHeader.trim().toLong(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if(_uiState.value.interfaceProxy.underloadPacketMagicHeader.isNotEmpty()) {
|
if (this.responsePacketMagicHeader.isNotEmpty()) {
|
||||||
builder.setUnderloadPacketMagicHeader(_uiState.value.interfaceProxy.underloadPacketMagicHeader.trim().toLong())
|
builder.setResponsePacketMagicHeader(
|
||||||
|
this.responsePacketMagicHeader.trim().toLong(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
if (this.transportPacketMagicHeader.isNotEmpty()) {
|
||||||
|
builder.setTransportPacketMagicHeader(
|
||||||
|
this.transportPacketMagicHeader.trim().toLong(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (this.underloadPacketMagicHeader.isNotEmpty()) {
|
||||||
|
builder.setUnderloadPacketMagicHeader(
|
||||||
|
this.underloadPacketMagicHeader.trim().toLong(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return builder.build()
|
return builder.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun buildConfig() : Config {
|
private fun buildConfig(): Config {
|
||||||
val peerList = buildPeerListFromProxyPeers()
|
val peerList = buildPeerListFromProxyPeers()
|
||||||
val wgInterface = buildInterfaceListFromProxyInterface()
|
val wgInterface = buildInterfaceListFromProxyInterface()
|
||||||
return Config.Builder().addPeers(peerList).setInterface(wgInterface).build()
|
return Config.Builder().addPeers(peerList).setInterface(wgInterface).build()
|
||||||
}
|
}
|
||||||
|
|
||||||
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).build()
|
return org.amnezia.awg.config.Config.Builder().addPeers(
|
||||||
|
peerList,
|
||||||
|
).setInterface(amInterface)
|
||||||
|
.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onSaveAllChanges(configType: ConfigType): Result<Unit> {
|
fun onSaveAllChanges() = viewModelScope.launch {
|
||||||
return try {
|
kotlin.runCatching {
|
||||||
val wgQuick = buildConfig().toWgQuickString()
|
val wgQuick = buildConfig().toWgQuickString(true)
|
||||||
val amQuick = if(configType == ConfigType.AMNEZIA) {
|
val amQuick = buildAmConfig().toAwgQuickString(true)
|
||||||
buildAmConfig().toAwgQuickString()
|
val tunnelConfig = uiState.value.tunnel?.copy(
|
||||||
} else TunnelConfig.AM_QUICK_DEFAULT
|
name = _uiState.value.tunnelName,
|
||||||
val tunnelConfig = when (uiState.value.tunnel) {
|
amQuick = amQuick,
|
||||||
null -> TunnelConfig(
|
wgQuick = wgQuick,
|
||||||
|
) ?: TunnelConfig(
|
||||||
name = _uiState.value.tunnelName,
|
name = _uiState.value.tunnelName,
|
||||||
wgQuick = wgQuick,
|
wgQuick = wgQuick,
|
||||||
amQuick = amQuick
|
amQuick = amQuick,
|
||||||
)
|
)
|
||||||
else -> uiState.value.tunnel!!.copy(
|
|
||||||
name = _uiState.value.tunnelName,
|
|
||||||
wgQuick = wgQuick,
|
|
||||||
amQuick = amQuick
|
|
||||||
)
|
|
||||||
}
|
|
||||||
updateTunnelConfig(tunnelConfig)
|
updateTunnelConfig(tunnelConfig)
|
||||||
Result.success(Unit)
|
SnackbarController.showMessage(
|
||||||
} catch (e: Exception) {
|
StringValue.StringResource(R.string.config_changes_saved),
|
||||||
Timber.e(e)
|
)
|
||||||
val message = e.message?.substringAfter(":", missingDelimiterValue = "")
|
navController.navigate(Route.Main)
|
||||||
val stringValue = message?.let {
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
val message = it.message?.substringAfter(":", missingDelimiterValue = "")
|
||||||
|
val stringValue = if (message.isNullOrBlank()) {
|
||||||
|
StringValue.StringResource(R.string.unknown_error)
|
||||||
|
} else {
|
||||||
StringValue.DynamicString(message)
|
StringValue.DynamicString(message)
|
||||||
} ?: StringValue.StringResource(R.string.unknown_error)
|
}
|
||||||
Result.failure(WgTunnelExceptions.ConfigParseError(stringValue))
|
SnackbarController.showMessage(stringValue)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -357,7 +427,7 @@ constructor(
|
|||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy =
|
interfaceProxy =
|
||||||
_uiState.value.interfaceProxy.copy(
|
it.interfaceProxy.copy(
|
||||||
privateKey = keyPair.privateKey.toBase64(),
|
privateKey = keyPair.privateKey.toBase64(),
|
||||||
publicKey = keyPair.publicKey.toBase64(),
|
publicKey = keyPair.publicKey.toBase64(),
|
||||||
),
|
),
|
||||||
@@ -368,16 +438,15 @@ constructor(
|
|||||||
fun onAddressesChanged(value: String) {
|
fun onAddressesChanged(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy = _uiState.value.interfaceProxy.copy(addresses = value),
|
interfaceProxy = it.interfaceProxy.copy(addresses = value),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onListenPortChanged(value: String) {
|
fun onListenPortChanged(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy = _uiState.value.interfaceProxy.copy(listenPort = value),
|
interfaceProxy = it.interfaceProxy.copy(listenPort = value),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -385,30 +454,29 @@ constructor(
|
|||||||
fun onDnsServersChanged(value: String) {
|
fun onDnsServersChanged(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy = _uiState.value.interfaceProxy.copy(dnsServers = value),
|
interfaceProxy = it.interfaceProxy.copy(dnsServers = value),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMtuChanged(value: String) {
|
fun onMtuChanged(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(interfaceProxy = _uiState.value.interfaceProxy.copy(mtu = value))
|
it.copy(interfaceProxy = it.interfaceProxy.copy(mtu = value))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onInterfacePublicKeyChange(value: String) {
|
private fun onInterfacePublicKeyChange(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy = _uiState.value.interfaceProxy.copy(publicKey = value),
|
interfaceProxy = it.interfaceProxy.copy(publicKey = value),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onPrivateKeyChange(value: String) {
|
fun onPrivateKeyChange(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy = _uiState.value.interfaceProxy.copy(privateKey = value),
|
interfaceProxy = it.interfaceProxy.copy(privateKey = value),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (NumberUtils.isValidKey(value)) {
|
if (NumberUtils.isValidKey(value)) {
|
||||||
@@ -430,14 +498,15 @@ constructor(
|
|||||||
fun onJunkPacketCountChanged(value: String) {
|
fun onJunkPacketCountChanged(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy = _uiState.value.interfaceProxy.copy(junkPacketCount = value)
|
interfaceProxy = it.interfaceProxy.copy(junkPacketCount = value),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onJunkPacketMinSizeChanged(value: String) {
|
fun onJunkPacketMinSizeChanged(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy = _uiState.value.interfaceProxy.copy(junkPacketMinSize = value)
|
interfaceProxy = it.interfaceProxy.copy(junkPacketMinSize = value),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -445,7 +514,7 @@ constructor(
|
|||||||
fun onJunkPacketMaxSizeChanged(value: String) {
|
fun onJunkPacketMaxSizeChanged(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy = _uiState.value.interfaceProxy.copy(junkPacketMaxSize = value)
|
interfaceProxy = it.interfaceProxy.copy(junkPacketMaxSize = value),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -453,7 +522,7 @@ constructor(
|
|||||||
fun onInitPacketJunkSizeChanged(value: String) {
|
fun onInitPacketJunkSizeChanged(value: String) {
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
interfaceProxy = _uiState.value.interfaceProxy.copy(initPacketJunkSize = value)
|
interfaceProxy = it.interfaceProxy.copy(initPacketJunkSize = value),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -461,7 +530,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 =
|
||||||
|
it.interfaceProxy.copy(
|
||||||
|
responsePacketJunkSize = value,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -469,7 +541,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 =
|
||||||
|
it.interfaceProxy.copy(
|
||||||
|
initPacketMagicHeader = value,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -477,7 +552,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 =
|
||||||
|
it.interfaceProxy.copy(
|
||||||
|
responsePacketMagicHeader = value,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -485,7 +563,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 =
|
||||||
|
it.interfaceProxy.copy(
|
||||||
|
transportPacketMagicHeader = value,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -493,8 +574,16 @@ 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 =
|
||||||
|
it.interfaceProxy.copy(
|
||||||
|
underloadPacketMagicHeader = value,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@AssistedFactory
|
||||||
|
interface ConfigViewModelFactory {
|
||||||
|
fun create(id: Int): ConfigViewModel
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+199
@@ -0,0 +1,199 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.config.components
|
||||||
|
|
||||||
|
import android.content.pm.PackageInfo
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
|
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.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.rounded.Android
|
||||||
|
import androidx.compose.material3.BasicAlertDialog
|
||||||
|
import androidx.compose.material3.Checkbox
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Switch
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
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.google.accompanist.drawablepainter.DrawablePainter
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.SearchBar
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigUiState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigViewModel
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ApplicationSelectionDialog(viewModel: ConfigViewModel, uiState: ConfigUiState, onDismiss: () -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val licenseComparator = compareBy<PackageInfo> { viewModel.getPackageLabel(it) }
|
||||||
|
|
||||||
|
val sortedPackages = remember(uiState.packages, licenseComparator) {
|
||||||
|
uiState.packages.sortedWith(licenseComparator)
|
||||||
|
}
|
||||||
|
BasicAlertDialog(
|
||||||
|
onDismissRequest = { onDismiss() },
|
||||||
|
) {
|
||||||
|
Surface(
|
||||||
|
tonalElevation = 2.dp,
|
||||||
|
shadowElevation = 2.dp,
|
||||||
|
shape = RoundedCornerShape(12.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surface,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.fillMaxHeight(if (uiState.isAllApplicationsEnabled) 1 / 5f else 4 / 5f),
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 20.dp, vertical = 7.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
) {
|
||||||
|
Text(stringResource(id = R.string.tunnel_all))
|
||||||
|
Switch(
|
||||||
|
checked = uiState.isAllApplicationsEnabled,
|
||||||
|
onCheckedChange = viewModel::onAllApplicationsChange,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!uiState.isAllApplicationsEnabled) {
|
||||||
|
Row(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 20.dp, vertical = 7.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
) {
|
||||||
|
Text(stringResource(id = R.string.include))
|
||||||
|
Checkbox(
|
||||||
|
checked = uiState.include,
|
||||||
|
onCheckedChange = {
|
||||||
|
viewModel.onIncludeChange(!uiState.include)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
) {
|
||||||
|
Text(stringResource(id = R.string.exclude))
|
||||||
|
Checkbox(
|
||||||
|
checked = !uiState.include,
|
||||||
|
onCheckedChange = {
|
||||||
|
viewModel.onIncludeChange(!uiState.include)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Row(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 20.dp, vertical = 7.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
) {
|
||||||
|
SearchBar(viewModel::emitQueriedPackages)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.padding(5.dp))
|
||||||
|
LazyColumn(
|
||||||
|
horizontalAlignment = Alignment.Start,
|
||||||
|
verticalArrangement = Arrangement.Top,
|
||||||
|
modifier = Modifier.fillMaxHeight(19 / 22f),
|
||||||
|
) {
|
||||||
|
items(sortedPackages, key = { it.packageName }) { pack ->
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(5.dp).padding(end = 25.dp),
|
||||||
|
) {
|
||||||
|
Row(modifier = Modifier.fillMaxWidth().padding(start = 5.dp)) {
|
||||||
|
val drawable =
|
||||||
|
pack.applicationInfo?.loadIcon(context.packageManager)
|
||||||
|
val iconSize = 35.dp
|
||||||
|
if (drawable != null) {
|
||||||
|
Image(
|
||||||
|
painter = DrawablePainter(drawable),
|
||||||
|
stringResource(id = R.string.icon),
|
||||||
|
modifier = Modifier.size(iconSize),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
val icon = Icons.Rounded.Android
|
||||||
|
Icon(
|
||||||
|
icon,
|
||||||
|
icon.name,
|
||||||
|
modifier = Modifier.size(iconSize),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
viewModel.getPackageLabel(pack),
|
||||||
|
modifier = Modifier.padding(5.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Checkbox(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
checked =
|
||||||
|
(
|
||||||
|
uiState.checkedPackageNames.contains(
|
||||||
|
pack.packageName,
|
||||||
|
)
|
||||||
|
),
|
||||||
|
onCheckedChange = {
|
||||||
|
if (it) {
|
||||||
|
viewModel.onAddCheckedPackage(pack.packageName)
|
||||||
|
} else {
|
||||||
|
viewModel.onRemoveCheckedPackage(pack.packageName)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(top = 5.dp),
|
||||||
|
horizontalArrangement = Arrangement.Center,
|
||||||
|
) {
|
||||||
|
TextButton(onClick = { onDismiss() }) {
|
||||||
|
Text(stringResource(R.string.done))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+69
-11
@@ -25,7 +25,10 @@ data class InterfaceProxy(
|
|||||||
publicKey = i.keyPair.publicKey.toBase64().trim(),
|
publicKey = i.keyPair.publicKey.toBase64().trim(),
|
||||||
privateKey = i.keyPair.privateKey.toBase64().trim(),
|
privateKey = i.keyPair.privateKey.toBase64().trim(),
|
||||||
addresses = i.addresses.joinToString(", ").trim(),
|
addresses = i.addresses.joinToString(", ").trim(),
|
||||||
dnsServers = i.dnsServers.joinToString(", ").replace("/", "").trim(),
|
dnsServers = listOf(
|
||||||
|
i.dnsServers.joinToString(", ").replace("/", "").trim(),
|
||||||
|
i.dnsSearchDomains.joinToString(", ").trim(),
|
||||||
|
).filter { it.length > 0 }.joinToString(", "),
|
||||||
listenPort =
|
listenPort =
|
||||||
if (i.listenPort.isPresent) {
|
if (i.listenPort.isPresent) {
|
||||||
i.listenPort.get().toString().trim()
|
i.listenPort.get().toString().trim()
|
||||||
@@ -35,7 +38,8 @@ 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 "",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
fun from(i: org.amnezia.awg.config.Interface) : InterfaceProxy {
|
|
||||||
|
fun from(i: org.amnezia.awg.config.Interface): InterfaceProxy {
|
||||||
return InterfaceProxy(
|
return InterfaceProxy(
|
||||||
publicKey = i.keyPair.publicKey.toBase64().trim(),
|
publicKey = i.keyPair.publicKey.toBase64().trim(),
|
||||||
privateKey = i.keyPair.privateKey.toBase64().trim(),
|
privateKey = i.keyPair.privateKey.toBase64().trim(),
|
||||||
@@ -48,15 +52,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().toString() else "",
|
junkPacketCount =
|
||||||
junkPacketMinSize = if(i.junkPacketMinSize.isPresent) i.junkPacketMinSize.get().toString() else "",
|
if (i.junkPacketCount.isPresent) {
|
||||||
junkPacketMaxSize = if(i.junkPacketMaxSize.isPresent) i.junkPacketMaxSize.get().toString() else "",
|
i.junkPacketCount.get()
|
||||||
initPacketJunkSize = if(i.initPacketJunkSize.isPresent) i.initPacketJunkSize.get().toString() else "",
|
.toString()
|
||||||
responsePacketJunkSize = if(i.responsePacketJunkSize.isPresent) i.responsePacketJunkSize.get().toString() else "",
|
} 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 "",
|
junkPacketMinSize =
|
||||||
underloadPacketMagicHeader = if(i.underloadPacketMagicHeader.isPresent) i.underloadPacketMagicHeader.get().toString() else "",
|
if (i.junkPacketMinSize.isPresent) {
|
||||||
|
i.junkPacketMinSize.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
junkPacketMaxSize =
|
||||||
|
if (i.junkPacketMaxSize.isPresent) {
|
||||||
|
i.junkPacketMaxSize.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
initPacketJunkSize =
|
||||||
|
if (i.initPacketJunkSize.isPresent) {
|
||||||
|
i.initPacketJunkSize.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
responsePacketJunkSize =
|
||||||
|
if (i.responsePacketJunkSize.isPresent) {
|
||||||
|
i.responsePacketJunkSize.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
initPacketMagicHeader =
|
||||||
|
if (i.initPacketMagicHeader.isPresent) {
|
||||||
|
i.initPacketMagicHeader.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
responsePacketMagicHeader =
|
||||||
|
if (i.responsePacketMagicHeader.isPresent) {
|
||||||
|
i.responsePacketMagicHeader.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
transportPacketMagicHeader =
|
||||||
|
if (i.transportPacketMagicHeader.isPresent) {
|
||||||
|
i.transportPacketMagicHeader.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
underloadPacketMagicHeader =
|
||||||
|
if (i.underloadPacketMagicHeader.isPresent) {
|
||||||
|
i.underloadPacketMagicHeader.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -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 {
|
||||||
@@ -35,7 +35,7 @@ data class PeerProxy(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun from(peer: org.amnezia.awg.config.Peer) : PeerProxy {
|
fun from(peer: org.amnezia.awg.config.Peer): PeerProxy {
|
||||||
return PeerProxy(
|
return PeerProxy(
|
||||||
publicKey = peer.publicKey.toBase64(),
|
publicKey = peer.publicKey.toBase64(),
|
||||||
preSharedKey =
|
preSharedKey =
|
||||||
|
|||||||
@@ -2,5 +2,5 @@ package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
|||||||
|
|
||||||
enum class ConfigType {
|
enum class ConfigType {
|
||||||
AMNEZIA,
|
AMNEZIA,
|
||||||
WIREGUARD
|
WIREGUARD,
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user