mirror of
https://github.com/wgtunnel/android.git
synced 2026-07-03 14:07:49 +02:00
Compare commits
105 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2c0c88baf2 | |||
| 05e7cb7c04 | |||
| bc811f74ef | |||
| 09b669f54b | |||
| f08d73cbb7 | |||
| 7ca23d3ef5 | |||
| 7fdd95ea51 | |||
| e11f0f794a | |||
| fea31437cd | |||
| 1306fdc8b2 | |||
| d2e5d6d3bc | |||
| 960af02beb | |||
| 3f1ff22488 | |||
| d6b032845b | |||
| ffad6b331f | |||
| 1fb953e2fe | |||
| 893a03d3b1 | |||
| 30b577a03d | |||
| 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 |
+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
|
||||||
@@ -15,6 +15,7 @@ A clear and concise description of what the bug is.
|
|||||||
- Device: [e.g. Pixel 4a]
|
- Device: [e.g. Pixel 4a]
|
||||||
- Android Version: [e.g. Android 13]
|
- Android Version: [e.g. Android 13]
|
||||||
- App Version [e.g. 3.3.3]
|
- App Version [e.g. 3.3.3]
|
||||||
|
- Backend: [e.g. Kernel, Userspace]
|
||||||
|
|
||||||
**To Reproduce**
|
**To Reproduce**
|
||||||
Steps to reproduce the behavior:
|
Steps to reproduce the behavior:
|
||||||
|
|||||||
@@ -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,4 +1,4 @@
|
|||||||
name: Issue Updates Workflow
|
name: on-issue
|
||||||
|
|
||||||
on:
|
on:
|
||||||
issues:
|
issues:
|
||||||
@@ -7,8 +7,8 @@ on:
|
|||||||
|
|
||||||
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,4 +1,4 @@
|
|||||||
name: Release Updates Workflow
|
name: on-publish
|
||||||
|
|
||||||
on:
|
on:
|
||||||
release:
|
release:
|
||||||
@@ -7,8 +7,8 @@ on:
|
|||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
+186
-43
@@ -1,19 +1,64 @@
|
|||||||
# 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_commits:
|
||||||
name: Build Signed APK
|
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Check for new commits in the last 23 hours
|
||||||
|
id: check_commits
|
||||||
|
run: |
|
||||||
|
# Get the current time and the time 23 hours ago in ISO 8601 format
|
||||||
|
now=$(date --utc +%Y-%m-%dT%H:%M:%SZ)
|
||||||
|
past=$(date --utc --date='23 hours ago' +%Y-%m-%dT%H:%M:%SZ)
|
||||||
|
|
||||||
|
# Fetch commit history and check for commits in the last 23 hours
|
||||||
|
if git rev-list --since="$past" --count HEAD > /dev/null; then
|
||||||
|
echo "New commits found in the last 23 hours."
|
||||||
|
echo "::set-output name=new_commits::true"
|
||||||
|
else
|
||||||
|
echo "No new commits found in the last 23 hours."
|
||||||
|
echo "::set-output name=new_commits::false"
|
||||||
|
fi
|
||||||
|
build:
|
||||||
|
needs: check_commits
|
||||||
|
if: ${{ needs.check_commits.outputs.new_commits == 'true' || github.event_name != 'schedule'}}
|
||||||
|
name: Build Signed APK
|
||||||
|
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 +66,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 +81,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 +108,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.3
|
||||||
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/
|
||||||
|
|||||||
@@ -55,32 +55,30 @@ 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.
|
||||||
@@ -102,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.
|
||||||
|
|||||||
+90
-62
@@ -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
|
||||||
@@ -101,8 +72,43 @@ android {
|
|||||||
"proguard-rules.pro",
|
"proguard-rules.pro",
|
||||||
)
|
)
|
||||||
signingConfig = signingConfigs.getByName(Constants.RELEASE)
|
signingConfig = signingConfigs.getByName(Constants.RELEASE)
|
||||||
|
resValue("string", "provider", "\"${Constants.APP_NAME}.provider\"")
|
||||||
|
}
|
||||||
|
debug {
|
||||||
|
applicationIdSuffix = ".debug"
|
||||||
|
versionNameSuffix = "-debug"
|
||||||
|
resValue("string", "app_name", "WG Tunnel - Debug")
|
||||||
|
isDebuggable = true
|
||||||
|
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.debug\"")
|
||||||
|
}
|
||||||
|
|
||||||
|
create(Constants.PRERELEASE) {
|
||||||
|
initWith(buildTypes.getByName(Constants.RELEASE))
|
||||||
|
applicationIdSuffix = ".prerelease"
|
||||||
|
versionNameSuffix = "-pre"
|
||||||
|
resValue("string", "app_name", "WG Tunnel - Pre")
|
||||||
|
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.pre\"")
|
||||||
|
}
|
||||||
|
|
||||||
|
create(Constants.NIGHTLY) {
|
||||||
|
initWith(buildTypes.getByName(Constants.RELEASE))
|
||||||
|
applicationIdSuffix = ".nightly"
|
||||||
|
versionNameSuffix = "-nightly"
|
||||||
|
resValue("string", "app_name", "WG Tunnel - Nightly")
|
||||||
|
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
debug { isDebuggable = true }
|
|
||||||
}
|
}
|
||||||
flavorDimensions.add(Constants.TYPE)
|
flavorDimensions.add(Constants.TYPE)
|
||||||
productFlavors {
|
productFlavors {
|
||||||
@@ -112,9 +118,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,12 +130,9 @@ 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}" } }
|
||||||
}
|
}
|
||||||
|
|
||||||
val generalImplementation by configurations
|
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
|
||||||
implementation(project(":logcatter"))
|
implementation(project(":logcatter"))
|
||||||
@@ -162,6 +162,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 +170,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)
|
||||||
@@ -211,4 +209,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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,7 +66,7 @@
|
|||||||
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.App.Start"
|
||||||
tools:targetApi="tiramisu">
|
tools:targetApi="tiramisu">
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.MainActivity"
|
android:name=".ui.MainActivity"
|
||||||
@@ -71,7 +77,6 @@
|
|||||||
|
|
||||||
<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,30 @@
|
|||||||
android:resource="@xml/shortcuts" />
|
android:resource="@xml/shortcuts" />
|
||||||
</activity>
|
</activity>
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.CaptureActivityPortrait"
|
android:name="com.journeyapps.barcodescanner.CaptureActivity"
|
||||||
android:screenOrientation="fullSensor"
|
android:screenOrientation="portrait"
|
||||||
android:stateNotNeeded="true"
|
tools:replace="screenOrientation" />
|
||||||
android:theme="@style/zxing_CaptureTheme"
|
|
||||||
android:windowSoftInputMode="stateAlwaysHidden"
|
|
||||||
tools:ignore="DiscouragedApi" />
|
|
||||||
<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
|
<provider
|
||||||
android:name=".service.foreground.ForegroundService"
|
android:name="androidx.core.content.FileProvider"
|
||||||
android:enabled="true"
|
android:authorities="@string/provider"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:foregroundServiceType="systemExempted"
|
android:grantUriPermissions="true">
|
||||||
tools:node="merge" />
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/file_paths" />
|
||||||
|
</provider>
|
||||||
|
|
||||||
<service
|
<service
|
||||||
android:name=".service.tile.TunnelControlTile"
|
android:name=".service.tile.TunnelControlTile"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
@@ -133,7 +143,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 +158,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 +166,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 +190,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,35 +1,30 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel
|
package com.zaneschepke.wireguardautotunnel
|
||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
import android.content.ComponentName
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.StrictMode
|
import android.os.StrictMode
|
||||||
import android.os.StrictMode.ThreadPolicy
|
import android.os.StrictMode.ThreadPolicy
|
||||||
import android.service.quicksettings.TileService
|
import com.zaneschepke.logcatter.LogReader
|
||||||
import com.zaneschepke.logcatter.LocalLogCollector
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tile.AutoTunnelControlTile
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tile.TunnelControlTile
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
|
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
import dagger.hilt.android.HiltAndroidApp
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@HiltAndroidApp
|
@HiltAndroidApp
|
||||||
class WireGuardAutoTunnel : Application() {
|
class WireGuardAutoTunnel : Application() {
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var localLogCollector: LocalLogCollector
|
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
@ApplicationScope
|
@ApplicationScope
|
||||||
lateinit var applicationScope: CoroutineScope
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var logReader: LogReader
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
@IoDispatcher
|
@IoDispatcher
|
||||||
lateinit var ioDispatcher: CoroutineDispatcher
|
lateinit var ioDispatcher: CoroutineDispatcher
|
||||||
@@ -47,34 +42,18 @@ class WireGuardAutoTunnel : Application() {
|
|||||||
.penaltyLog()
|
.penaltyLog()
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
} else Timber.plant(ReleaseTree())
|
} else {
|
||||||
|
Timber.plant(ReleaseTree())
|
||||||
|
}
|
||||||
|
if (!isRunningOnTv()) {
|
||||||
applicationScope.launch(ioDispatcher) {
|
applicationScope.launch(ioDispatcher) {
|
||||||
PinManager.initialize(this@WireGuardAutoTunnel)
|
logReader.start()
|
||||||
if (!isRunningOnAndroidTv()) localLogCollector.start()
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|
||||||
lateinit var instance: WireGuardAutoTunnel
|
lateinit var instance: WireGuardAutoTunnel
|
||||||
private set
|
private set
|
||||||
|
|
||||||
fun isRunningOnAndroidTv(): Boolean {
|
|
||||||
return instance.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun requestTunnelTileServiceStateUpdate() {
|
|
||||||
TileService.requestListeningState(
|
|
||||||
instance,
|
|
||||||
ComponentName(instance, TunnelControlTile::class.java),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun requestAutoTunnelTileServiceUpdate() {
|
|
||||||
TileService.requestListeningState(
|
|
||||||
instance,
|
|
||||||
ComponentName(instance, AutoTunnelControlTile::class.java),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|||||||
|
|
||||||
@Database(
|
@Database(
|
||||||
entities = [Settings::class, TunnelConfig::class],
|
entities = [Settings::class, TunnelConfig::class],
|
||||||
version = 8,
|
version = 10,
|
||||||
autoMigrations =
|
autoMigrations =
|
||||||
[
|
[
|
||||||
AutoMigration(from = 1, to = 2),
|
AutoMigration(from = 1, to = 2),
|
||||||
@@ -34,6 +34,8 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|||||||
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
|
||||||
@@ -23,6 +23,9 @@ interface TunnelConfigDao {
|
|||||||
@Query("SELECT * FROM TunnelConfig WHERE name=:name")
|
@Query("SELECT * FROM TunnelConfig WHERE name=:name")
|
||||||
suspend fun getByName(name: String): TunnelConfig?
|
suspend fun getByName(name: String): TunnelConfig?
|
||||||
|
|
||||||
|
@Query("SELECT * FROM TunnelConfig WHERE is_Active=1")
|
||||||
|
suspend fun getActive(): TunnelConfigs
|
||||||
|
|
||||||
@Query("SELECT * FROM TunnelConfig")
|
@Query("SELECT * FROM TunnelConfig")
|
||||||
suspend fun getAll(): TunnelConfigs
|
suspend fun getAll(): TunnelConfigs
|
||||||
|
|
||||||
|
|||||||
+14
-6
@@ -4,7 +4,6 @@ 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 com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
@@ -19,15 +18,14 @@ import java.io.IOException
|
|||||||
|
|
||||||
class DataStoreManager(
|
class DataStoreManager(
|
||||||
private val context: Context,
|
private val context: Context,
|
||||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
|
val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
|
||||||
val BATTERY_OPTIMIZE_DISABLE_SHOWN = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
val BATTERY_OPTIMIZE_DISABLE_SHOWN = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
||||||
val TUNNEL_RUNNING_FROM_MANUAL_START =
|
|
||||||
booleanPreferencesKey("TUNNEL_RUNNING_FROM_MANUAL_START")
|
|
||||||
val ACTIVE_TUNNEL = intPreferencesKey("ACTIVE_TUNNEL")
|
|
||||||
val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
|
val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
|
||||||
|
val IS_PIN_LOCK_ENABLED = booleanPreferencesKey("PIN_LOCK_ENABLED")
|
||||||
|
val IS_TUNNEL_STATS_EXPANDED = booleanPreferencesKey("TUNNEL_STATS_EXPANDED")
|
||||||
}
|
}
|
||||||
|
|
||||||
// preferences
|
// preferences
|
||||||
@@ -59,6 +57,17 @@ class DataStoreManager(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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] }
|
||||||
|
|
||||||
@@ -73,7 +82,6 @@ class DataStoreManager(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking {
|
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking {
|
||||||
context.dataStore.data.map { it[key] }.first()
|
context.dataStore.data.map { it[key] }.first()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
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
|
val isTunnelStatsExpanded: Boolean = IS_TUNNEL_STATS_EXPANDED,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
|
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
|
||||||
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
|
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
|
||||||
const val TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT = false
|
const val PIN_LOCK_ENABLED_DEFAULT = false
|
||||||
|
const val IS_TUNNEL_STATS_EXPANDED = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,8 +32,39 @@ 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 {
|
||||||
|
|||||||
+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,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-8
@@ -5,22 +5,24 @@ import kotlinx.coroutines.flow.Flow
|
|||||||
|
|
||||||
interface AppStateRepository {
|
interface AppStateRepository {
|
||||||
suspend fun isLocationDisclosureShown(): Boolean
|
suspend fun isLocationDisclosureShown(): Boolean
|
||||||
|
|
||||||
suspend fun setLocationDisclosureShown(shown: Boolean)
|
suspend fun setLocationDisclosureShown(shown: Boolean)
|
||||||
|
|
||||||
|
suspend fun isPinLockEnabled(): Boolean
|
||||||
|
|
||||||
|
suspend fun 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>
|
suspend fun isTunnelStatsExpanded(): Boolean
|
||||||
|
|
||||||
|
suspend fun setTunnelStatsExpanded(expanded: Boolean)
|
||||||
|
|
||||||
|
val generalStateFlow: Flow<GeneralState>
|
||||||
}
|
}
|
||||||
|
|||||||
+29
-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)
|
||||||
}
|
}
|
||||||
@@ -60,17 +45,30 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
|
|||||||
dataStoreManager.saveToDataStore(DataStoreManager.CURRENT_SSID, ssid)
|
dataStoreManager.saveToDataStore(DataStoreManager.CURRENT_SSID, ssid)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun isTunnelStatsExpanded(): Boolean {
|
||||||
|
return dataStoreManager.getFromStore(DataStoreManager.IS_TUNNEL_STATS_EXPANDED)
|
||||||
|
?: GeneralState.IS_TUNNEL_STATS_EXPANDED
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun setTunnelStatsExpanded(expanded: Boolean) {
|
||||||
|
dataStoreManager.saveToDataStore(DataStoreManager.IS_TUNNEL_STATS_EXPANDED, expanded)
|
||||||
|
}
|
||||||
|
|
||||||
override val generalStateFlow: Flow<GeneralState> =
|
override val generalStateFlow: Flow<GeneralState> =
|
||||||
dataStoreManager.preferencesFlow.map { prefs ->
|
dataStoreManager.preferencesFlow.map { prefs ->
|
||||||
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,
|
||||||
|
isTunnelStatsExpanded = pref[DataStoreManager.IS_TUNNEL_STATS_EXPANDED] ?: GeneralState.IS_TUNNEL_STATS_EXPANDED,
|
||||||
)
|
)
|
||||||
} catch (e: IllegalArgumentException) {
|
} catch (e: IllegalArgumentException) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
|
|||||||
+10
-4
@@ -2,23 +2,29 @@ package com.zaneschepke.wireguardautotunnel.data.repository
|
|||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.SettingsDao
|
import com.zaneschepke.wireguardautotunnel.data.SettingsDao
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
class RoomSettingsRepository(private val settingsDoa: SettingsDao) : SettingsRepository {
|
class RoomSettingsRepository(private val settingsDoa: SettingsDao, @IoDispatcher private val ioDispatcher: CoroutineDispatcher) : SettingsRepository {
|
||||||
|
|
||||||
override suspend fun save(settings: Settings) {
|
override suspend fun save(settings: Settings) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
settingsDoa.save(settings)
|
settingsDoa.save(settings)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun getSettingsFlow(): Flow<Settings> {
|
override fun getSettingsFlow(): Flow<Settings> {
|
||||||
return settingsDoa.getSettingsFlow()
|
return settingsDoa.getSettingsFlow()
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getSettings(): Settings {
|
override suspend fun getSettings(): Settings {
|
||||||
return settingsDoa.getAll().firstOrNull() ?: Settings()
|
return withContext(ioDispatcher) {
|
||||||
|
settingsDoa.getAll().firstOrNull() ?: Settings()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getAll(): List<Settings> {
|
override suspend fun getAll(): List<Settings> {
|
||||||
return settingsDoa.getAll()
|
return withContext(ioDispatcher) { settingsDoa.getAll() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-10
@@ -1,25 +1,38 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.data.repository
|
package com.zaneschepke.wireguardautotunnel.data.repository
|
||||||
|
|
||||||
|
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||||
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
|
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
|
class RoomTunnelConfigRepository(
|
||||||
|
private val tunnelConfigDao: TunnelConfigDao,
|
||||||
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
|
) :
|
||||||
TunnelConfigRepository {
|
TunnelConfigRepository {
|
||||||
override fun getTunnelConfigsFlow(): Flow<TunnelConfigs> {
|
override fun getTunnelConfigsFlow(): Flow<TunnelConfigs> {
|
||||||
return tunnelConfigDao.getAllFlow()
|
return tunnelConfigDao.getAllFlow()
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getAll(): TunnelConfigs {
|
override suspend fun getAll(): TunnelConfigs {
|
||||||
return tunnelConfigDao.getAll()
|
return withContext(ioDispatcher) { tunnelConfigDao.getAll() }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun save(tunnelConfig: TunnelConfig) {
|
override suspend fun save(tunnelConfig: TunnelConfig) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
tunnelConfigDao.save(tunnelConfig)
|
tunnelConfigDao.save(tunnelConfig)
|
||||||
|
}.also {
|
||||||
|
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?) {
|
override suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
tunnelConfigDao.resetPrimaryTunnel()
|
tunnelConfigDao.resetPrimaryTunnel()
|
||||||
tunnelConfig?.let {
|
tunnelConfig?.let {
|
||||||
save(
|
save(
|
||||||
@@ -28,10 +41,11 @@ class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
|
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
tunnelConfigDao.resetMobileDataTunnel()
|
tunnelConfigDao.resetMobileDataTunnel()
|
||||||
tunnelConfig?.let {
|
tunnelConfig?.let {
|
||||||
save(
|
save(
|
||||||
@@ -41,32 +55,43 @@ class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun delete(tunnelConfig: TunnelConfig) {
|
override suspend fun delete(tunnelConfig: TunnelConfig) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
tunnelConfigDao.delete(tunnelConfig)
|
tunnelConfigDao.delete(tunnelConfig)
|
||||||
|
}.also {
|
||||||
|
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getById(id: Int): TunnelConfig? {
|
override suspend fun getById(id: Int): TunnelConfig? {
|
||||||
return tunnelConfigDao.getById(id.toLong())
|
return withContext(ioDispatcher) { tunnelConfigDao.getById(id.toLong()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getActive(): TunnelConfigs {
|
||||||
|
return withContext(ioDispatcher) {
|
||||||
|
tunnelConfigDao.getActive()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun count(): Int {
|
override suspend fun count(): Int {
|
||||||
return tunnelConfigDao.count().toInt()
|
return withContext(ioDispatcher) { tunnelConfigDao.count().toInt() }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findByTunnelName(name: String): TunnelConfig? {
|
override suspend fun findByTunnelName(name: String): TunnelConfig? {
|
||||||
return tunnelConfigDao.getByName(name)
|
return withContext(ioDispatcher) { tunnelConfigDao.getByName(name) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findByTunnelNetworksName(name: String): TunnelConfigs {
|
override suspend fun findByTunnelNetworksName(name: String): TunnelConfigs {
|
||||||
return tunnelConfigDao.findByTunnelNetworkName(name)
|
return withContext(ioDispatcher) { tunnelConfigDao.findByTunnelNetworkName(name) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findByMobileDataTunnel(): TunnelConfigs {
|
override suspend fun findByMobileDataTunnel(): TunnelConfigs {
|
||||||
return tunnelConfigDao.findByMobileDataTunnel()
|
return withContext(ioDispatcher) { tunnelConfigDao.findByMobileDataTunnel() }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findPrimary(): TunnelConfigs {
|
override suspend fun findPrimary(): TunnelConfigs {
|
||||||
return tunnelConfigDao.findByPrimary()
|
return withContext(ioDispatcher) { tunnelConfigDao.findByPrimary() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-2
@@ -1,11 +1,10 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.data.repository
|
package com.zaneschepke.wireguardautotunnel.data.repository
|
||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
interface TunnelConfigRepository {
|
interface TunnelConfigRepository {
|
||||||
|
|
||||||
fun getTunnelConfigsFlow(): Flow<TunnelConfigs>
|
fun getTunnelConfigsFlow(): Flow<TunnelConfigs>
|
||||||
|
|
||||||
suspend fun getAll(): TunnelConfigs
|
suspend fun getAll(): TunnelConfigs
|
||||||
@@ -20,6 +19,8 @@ interface TunnelConfigRepository {
|
|||||||
|
|
||||||
suspend fun getById(id: Int): TunnelConfig?
|
suspend fun getById(id: Int): TunnelConfig?
|
||||||
|
|
||||||
|
suspend fun getActive(): TunnelConfigs
|
||||||
|
|
||||||
suspend fun count(): Int
|
suspend fun count(): Int
|
||||||
|
|
||||||
suspend fun findByTunnelName(name: String): TunnelConfig?
|
suspend fun findByTunnelName(name: String): TunnelConfig?
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.module
|
package com.zaneschepke.wireguardautotunnel.module
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.zaneschepke.logcatter.LocalLogCollector
|
import com.zaneschepke.logcatter.LogReader
|
||||||
import com.zaneschepke.logcatter.LogcatHelper
|
import com.zaneschepke.logcatter.LogcatCollector
|
||||||
import dagger.Module
|
import dagger.Module
|
||||||
import dagger.Provides
|
import dagger.Provides
|
||||||
import dagger.hilt.InstallIn
|
import dagger.hilt.InstallIn
|
||||||
@@ -24,7 +24,7 @@ class AppModule {
|
|||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector {
|
fun provideLogCollect(@ApplicationContext context: Context): LogReader {
|
||||||
return LogcatHelper.init(context = context)
|
return LogcatCollector.init(context = context)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,22 +54,19 @@ class RepositoryModule {
|
|||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun provideTunnelConfigRepository(tunnelConfigDao: TunnelConfigDao): TunnelConfigRepository {
|
fun provideTunnelConfigRepository(tunnelConfigDao: TunnelConfigDao, @IoDispatcher ioDispatcher: CoroutineDispatcher): TunnelConfigRepository {
|
||||||
return RoomTunnelConfigRepository(tunnelConfigDao)
|
return RoomTunnelConfigRepository(tunnelConfigDao, ioDispatcher)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun provideSettingsRepository(settingsDao: SettingsDao): SettingsRepository {
|
fun provideSettingsRepository(settingsDao: SettingsDao, @IoDispatcher ioDispatcher: CoroutineDispatcher): SettingsRepository {
|
||||||
return RoomSettingsRepository(settingsDao)
|
return RoomSettingsRepository(settingsDao, ioDispatcher)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun providePreferencesDataStore(
|
fun providePreferencesDataStore(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): DataStoreManager {
|
||||||
@ApplicationContext context: Context,
|
|
||||||
@IoDispatcher ioDispatcher: CoroutineDispatcher
|
|
||||||
): DataStoreManager {
|
|
||||||
return DataStoreManager(context, ioDispatcher)
|
return DataStoreManager(context, ioDispatcher)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,10 +81,8 @@ class RepositoryModule {
|
|||||||
fun provideAppDataRepository(
|
fun provideAppDataRepository(
|
||||||
settingsRepository: SettingsRepository,
|
settingsRepository: SettingsRepository,
|
||||||
tunnelConfigRepository: TunnelConfigRepository,
|
tunnelConfigRepository: TunnelConfigRepository,
|
||||||
appStateRepository: AppStateRepository
|
appStateRepository: AppStateRepository,
|
||||||
): AppDataRepository {
|
): AppDataRepository {
|
||||||
return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository)
|
return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,9 +17,7 @@ import dagger.hilt.android.scopes.ServiceScoped
|
|||||||
abstract class ServiceModule {
|
abstract class ServiceModule {
|
||||||
@Binds
|
@Binds
|
||||||
@ServiceScoped
|
@ServiceScoped
|
||||||
abstract fun provideNotificationService(
|
abstract fun provideNotificationService(wireGuardNotification: WireGuardNotification): NotificationService
|
||||||
wireGuardNotification: WireGuardNotification
|
|
||||||
): NotificationService
|
|
||||||
|
|
||||||
@Binds
|
@Binds
|
||||||
@ServiceScoped
|
@ServiceScoped
|
||||||
@@ -27,13 +25,9 @@ abstract class ServiceModule {
|
|||||||
|
|
||||||
@Binds
|
@Binds
|
||||||
@ServiceScoped
|
@ServiceScoped
|
||||||
abstract fun provideMobileDataService(
|
abstract fun provideMobileDataService(mobileDataService: MobileDataService): NetworkService<MobileDataService>
|
||||||
mobileDataService: MobileDataService
|
|
||||||
): NetworkService<MobileDataService>
|
|
||||||
|
|
||||||
@Binds
|
@Binds
|
||||||
@ServiceScoped
|
@ServiceScoped
|
||||||
abstract fun provideEthernetService(
|
abstract fun provideEthernetService(ethernetService: EthernetService): NetworkService<EthernetService>
|
||||||
ethernetService: EthernetService
|
|
||||||
): NetworkService<EthernetService>
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,13 @@ package com.zaneschepke.wireguardautotunnel.module
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.wireguard.android.backend.Backend
|
import com.wireguard.android.backend.Backend
|
||||||
import com.wireguard.android.backend.GoBackend
|
import com.wireguard.android.backend.GoBackend
|
||||||
|
import com.wireguard.android.backend.RootTunnelActionHandler
|
||||||
import com.wireguard.android.backend.WgQuickBackend
|
import com.wireguard.android.backend.WgQuickBackend
|
||||||
import com.wireguard.android.util.RootShell
|
import com.wireguard.android.util.RootShell
|
||||||
import com.wireguard.android.util.ToolsInstaller
|
import com.wireguard.android.util.ToolsInstaller
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.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
|
||||||
@@ -17,6 +18,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext
|
|||||||
import dagger.hilt.components.SingletonComponent
|
import dagger.hilt.components.SingletonComponent
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import javax.inject.Provider
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@Module
|
@Module
|
||||||
@@ -28,52 +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,
|
||||||
@ApplicationScope applicationScope: CoroutineScope,
|
@ApplicationScope applicationScope: CoroutineScope,
|
||||||
@IoDispatcher ioDispatcher: CoroutineDispatcher
|
@IoDispatcher ioDispatcher: CoroutineDispatcher,
|
||||||
): VpnService {
|
): TunnelService {
|
||||||
return WireGuardTunnel(
|
return WireGuardTunnel(
|
||||||
amneziaBackend,
|
amneziaBackend,
|
||||||
userspaceBackend,
|
tunnelConfigRepository,
|
||||||
kernelBackend,
|
kernelBackend,
|
||||||
appDataRepository,
|
appDataRepository,
|
||||||
applicationScope,
|
applicationScope,
|
||||||
ioDispatcher,
|
ioDispatcher,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
|
||||||
@Singleton
|
|
||||||
fun provideServiceManager(
|
|
||||||
appDataRepository: AppDataRepository,
|
|
||||||
@IoDispatcher ioDispatcher: CoroutineDispatcher
|
|
||||||
): ServiceManager {
|
|
||||||
return ServiceManager(appDataRepository, ioDispatcher)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,13 +13,9 @@ import kotlinx.coroutines.CoroutineDispatcher
|
|||||||
@Module
|
@Module
|
||||||
@InstallIn(ViewModelComponent::class)
|
@InstallIn(ViewModelComponent::class)
|
||||||
class ViewModelModule {
|
class ViewModelModule {
|
||||||
|
|
||||||
@ViewModelScoped
|
@ViewModelScoped
|
||||||
@Provides
|
@Provides
|
||||||
fun provideFileUtils(
|
fun provideFileUtils(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): FileUtils {
|
||||||
@ApplicationContext context: Context,
|
|
||||||
@IoDispatcher ioDispatcher: CoroutineDispatcher
|
|
||||||
): FileUtils {
|
|
||||||
return FileUtils(context, ioDispatcher)
|
return FileUtils(context, ioDispatcher)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
}
|
}
|
||||||
|
|||||||
+589
@@ -0,0 +1,589 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.os.PowerManager
|
||||||
|
import androidx.core.app.ServiceCompat
|
||||||
|
import androidx.lifecycle.LifecycleService
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import com.wireguard.android.util.RootShell
|
||||||
|
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.getCurrentWifiName
|
||||||
|
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 rootShell: Provider<RootShell>
|
||||||
|
|
||||||
|
@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 fun updateWifi(connected: Boolean) {
|
||||||
|
autoTunnelStateFlow.update {
|
||||||
|
it.copy(
|
||||||
|
isWifiConnected = 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")
|
||||||
|
updateWifi(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkStatus.CapabilitiesChanged -> {
|
||||||
|
Timber.i("Wifi capabilities changed")
|
||||||
|
updateWifi(true)
|
||||||
|
val ssid = getWifiSSID(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 -> {
|
||||||
|
updateWifi(false)
|
||||||
|
Timber.i("Lost Wi-Fi connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun getWifiSSID(networkCapabilities: NetworkCapabilities): String? {
|
||||||
|
return withContext(ioDispatcher) {
|
||||||
|
try {
|
||||||
|
rootShell.get().getCurrentWifiName()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
wifiService.getNetworkName(networkCapabilities)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
-56
@@ -1,56 +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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+26
-87
@@ -3,24 +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.module.IoDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
|
||||||
class ServiceManager(
|
object ServiceManager {
|
||||||
private val appDataRepository: AppDataRepository,
|
private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) {
|
||||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
if (VpnService.prepare(context) != null) return
|
||||||
) {
|
|
||||||
|
|
||||||
private fun <T : Service> actionOnService(
|
|
||||||
action: Action,
|
|
||||||
context: Context,
|
|
||||||
cls: Class<T>,
|
|
||||||
extras: Map<String, Int>? = null
|
|
||||||
) {
|
|
||||||
val intent =
|
val intent =
|
||||||
Intent(context, cls).also {
|
Intent(context, cls).also {
|
||||||
it.action = action.name
|
it.action = action.name
|
||||||
@@ -29,7 +17,8 @@ class ServiceManager(
|
|||||||
intent.component?.javaClass
|
intent.component?.javaClass
|
||||||
try {
|
try {
|
||||||
when (action) {
|
when (action) {
|
||||||
Action.START_FOREGROUND, Action.STOP_FOREGROUND -> context.startForegroundService(
|
Action.START_FOREGROUND, Action.STOP_FOREGROUND ->
|
||||||
|
context.startForegroundService(
|
||||||
intent,
|
intent,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -40,77 +29,11 @@ class ServiceManager(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun startVpnService(
|
fun startWatcherServiceForeground(context: Context) {
|
||||||
context: Context,
|
|
||||||
tunnelId: Int? = null,
|
|
||||||
isManualStart: Boolean = false
|
|
||||||
) {
|
|
||||||
if (isManualStart) onManualStart(tunnelId)
|
|
||||||
actionOnService(
|
|
||||||
Action.START,
|
|
||||||
context,
|
|
||||||
WireGuardTunnelService::class.java,
|
|
||||||
tunnelId?.let { mapOf(Constants.TUNNEL_EXTRA_KEY to it) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun stopVpnServiceForeground(context: Context, isManualStop: Boolean = false) {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
if (isManualStop) onManualStop()
|
|
||||||
Timber.i("Stopping vpn service")
|
|
||||||
actionOnService(
|
|
||||||
Action.STOP_FOREGROUND,
|
|
||||||
context,
|
|
||||||
WireGuardTunnelService::class.java,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun stopVpnService(context: Context, isManualStop: Boolean = false) {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
if (isManualStop) onManualStop()
|
|
||||||
Timber.i("Stopping vpn service")
|
|
||||||
actionOnService(
|
|
||||||
Action.STOP,
|
|
||||||
context,
|
|
||||||
WireGuardTunnelService::class.java,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun onManualStop() {
|
|
||||||
appDataRepository.appState.setManualStop()
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun onManualStart(tunnelId: Int?) {
|
|
||||||
tunnelId?.let {
|
|
||||||
appDataRepository.appState.setTunnelRunningFromManualStart(it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun startVpnServiceForeground(
|
|
||||||
context: Context,
|
|
||||||
tunnelId: Int? = null,
|
|
||||||
isManualStart: Boolean = false
|
|
||||||
) {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
if (isManualStart) onManualStart(tunnelId)
|
|
||||||
actionOnService(
|
actionOnService(
|
||||||
Action.START_FOREGROUND,
|
Action.START_FOREGROUND,
|
||||||
context,
|
context,
|
||||||
WireGuardTunnelService::class.java,
|
AutoTunnelService::class.java,
|
||||||
tunnelId?.let { mapOf(Constants.TUNNEL_EXTRA_KEY to it) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun startWatcherServiceForeground(
|
|
||||||
context: Context,
|
|
||||||
) {
|
|
||||||
actionOnService(
|
|
||||||
Action.START_FOREGROUND,
|
|
||||||
context,
|
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +41,7 @@ class ServiceManager(
|
|||||||
actionOnService(
|
actionOnService(
|
||||||
Action.START,
|
Action.START,
|
||||||
context,
|
context,
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
AutoTunnelService::class.java,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,7 +49,23 @@ class ServiceManager(
|
|||||||
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 = "",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
-56
@@ -1,56 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
|
||||||
|
|
||||||
data class WatcherState(
|
|
||||||
val isWifiConnected: Boolean = false,
|
|
||||||
val isEthernetConnected: Boolean = false,
|
|
||||||
val isMobileDataConnected: Boolean = false,
|
|
||||||
val currentNetworkSSID: String = "",
|
|
||||||
val settings: Settings = Settings()
|
|
||||||
) {
|
|
||||||
fun isEthernetConditionMet(): Boolean {
|
|
||||||
return (isEthernetConnected &&
|
|
||||||
settings.isTunnelOnEthernetEnabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isMobileDataConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
settings.isTunnelOnMobileDataEnabled &&
|
|
||||||
!isWifiConnected &&
|
|
||||||
isMobileDataConnected)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTunnelOffOnMobileDataConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
!settings.isTunnelOnMobileDataEnabled &&
|
|
||||||
isMobileDataConnected &&
|
|
||||||
!isWifiConnected)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isUntrustedWifiConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
isWifiConnected &&
|
|
||||||
!settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
|
|
||||||
settings.isTunnelOnWifiEnabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTrustedWifiConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
(isWifiConnected &&
|
|
||||||
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTunnelOffOnWifiConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
(isWifiConnected &&
|
|
||||||
!settings.isTunnelOnWifiEnabled))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTunnelOffOnNoConnectivityMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
!isWifiConnected &&
|
|
||||||
!isMobileDataConnected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
-461
@@ -1,461 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.os.PowerManager
|
|
||||||
import androidx.core.app.ServiceCompat
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.EthernetService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.MobileDataService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.NetworkService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.NetworkStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.WifiService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.collectLatest
|
|
||||||
import kotlinx.coroutines.flow.update
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import timber.log.Timber
|
|
||||||
import java.net.InetAddress
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class WireGuardConnectivityWatcherService : ForegroundService() {
|
|
||||||
private val foregroundId = 122
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var wifiService: NetworkService<WifiService>
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var mobileDataService: NetworkService<MobileDataService>
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var ethernetService: NetworkService<EthernetService>
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var appDataRepository: AppDataRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var notificationService: NotificationService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var vpnService: VpnService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var serviceManager: ServiceManager
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@IoDispatcher
|
|
||||||
lateinit var ioDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@MainImmediateDispatcher
|
|
||||||
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
private val networkEventsFlow = MutableStateFlow(WatcherState())
|
|
||||||
|
|
||||||
private var watcherJob: Job? = null
|
|
||||||
|
|
||||||
private var wakeLock: PowerManager.WakeLock? = null
|
|
||||||
private val tag = this.javaClass.name
|
|
||||||
|
|
||||||
override fun onCreate() {
|
|
||||||
super.onCreate()
|
|
||||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
|
||||||
try {
|
|
||||||
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
|
|
||||||
launchWatcherPausedNotification()
|
|
||||||
} else launchWatcherNotification()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e("Failed to start watcher service, not enough permissions")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun startService(extras: Bundle?) {
|
|
||||||
super.startService(extras)
|
|
||||||
try {
|
|
||||||
// we need this lock so our service gets not affected by Doze Mode
|
|
||||||
lifecycleScope.launch { initWakeLock() }
|
|
||||||
cancelWatcherJob()
|
|
||||||
startWatcherJob()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e("Failed to launch watcher service, no permissions")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun stopService() {
|
|
||||||
super.stopService()
|
|
||||||
wakeLock?.let {
|
|
||||||
if (it.isHeld) {
|
|
||||||
it.release()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cancelWatcherJob()
|
|
||||||
stopSelf()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchWatcherNotification(
|
|
||||||
description: String = getString(R.string.watcher_notification_text_active)
|
|
||||||
) {
|
|
||||||
val notification =
|
|
||||||
notificationService.createNotification(
|
|
||||||
channelId = getString(R.string.watcher_channel_id),
|
|
||||||
channelName = getString(R.string.watcher_channel_name),
|
|
||||||
title = getString(R.string.auto_tunnel_title),
|
|
||||||
description = description,
|
|
||||||
)
|
|
||||||
ServiceCompat.startForeground(
|
|
||||||
this,
|
|
||||||
foregroundId,
|
|
||||||
notification,
|
|
||||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchWatcherPausedNotification() {
|
|
||||||
launchWatcherNotification(getString(R.string.watcher_notification_text_paused))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun initWakeLock() {
|
|
||||||
wakeLock =
|
|
||||||
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
|
|
||||||
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply {
|
|
||||||
try {
|
|
||||||
Timber.i("Initiating wakelock with 10 min timeout")
|
|
||||||
acquire(Constants.BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT)
|
|
||||||
} finally {
|
|
||||||
release()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun cancelWatcherJob() {
|
|
||||||
try {
|
|
||||||
watcherJob?.cancel()
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
Timber.i("Watcher job cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startWatcherJob() {
|
|
||||||
watcherJob =
|
|
||||||
lifecycleScope.launch {
|
|
||||||
val setting = appDataRepository.settings.getSettings()
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting wifi watcher")
|
|
||||||
watchForWifiConnectivityChanges()
|
|
||||||
}
|
|
||||||
if (setting.isTunnelOnMobileDataEnabled) {
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting mobile data watcher")
|
|
||||||
watchForMobileDataConnectivityChanges()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (setting.isTunnelOnEthernetEnabled) {
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting ethernet data watcher")
|
|
||||||
watchForEthernetConnectivityChanges()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting settings watcher")
|
|
||||||
watchForSettingsChanges()
|
|
||||||
}
|
|
||||||
if (setting.isPingEnabled) {
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting ping watcher")
|
|
||||||
watchForPingFailure()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting management watcher")
|
|
||||||
manageVpn()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForMobileDataConnectivityChanges() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
mobileDataService.networkStatus.collect { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Available -> {
|
|
||||||
Timber.i("Gained Mobile data connection")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isMobileDataConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.CapabilitiesChanged -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isMobileDataConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Mobile data capabilities changed")
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.Unavailable -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isMobileDataConnected = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Lost mobile data connection")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForPingFailure() {
|
|
||||||
val context = this
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
try {
|
|
||||||
do {
|
|
||||||
if (vpnService.vpnState.value.status == TunnelState.UP) {
|
|
||||||
val tunnelConfig = vpnService.vpnState.value.tunnelConfig
|
|
||||||
tunnelConfig?.let {
|
|
||||||
val config = TunnelConfig.configFromWgQuick(it.wgQuick)
|
|
||||||
val results = config.peers.map { peer ->
|
|
||||||
val host = if (peer.endpoint.isPresent &&
|
|
||||||
peer.endpoint.get().resolved.isPresent)
|
|
||||||
peer.endpoint.get().resolved.get().host
|
|
||||||
else Constants.DEFAULT_PING_IP
|
|
||||||
Timber.i("Checking reachability of: $host")
|
|
||||||
val reachable = InetAddress.getByName(host)
|
|
||||||
.isReachable(Constants.PING_TIMEOUT.toInt())
|
|
||||||
Timber.i("Result: reachable - $reachable")
|
|
||||||
reachable
|
|
||||||
}
|
|
||||||
if (results.contains(false)) {
|
|
||||||
Timber.i("Restarting VPN for ping failure")
|
|
||||||
serviceManager.stopVpnServiceForeground(context)
|
|
||||||
delay(Constants.VPN_RESTART_DELAY)
|
|
||||||
serviceManager.startVpnServiceForeground(context, it.id)
|
|
||||||
delay(Constants.PING_COOLDOWN)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
delay(Constants.PING_INTERVAL)
|
|
||||||
} while (true)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForSettingsChanges() {
|
|
||||||
appDataRepository.settings.getSettingsFlow().collect { settings ->
|
|
||||||
if (networkEventsFlow.value.settings.isAutoTunnelPaused != settings.isAutoTunnelPaused) {
|
|
||||||
when (settings.isAutoTunnelPaused) {
|
|
||||||
true -> launchWatcherPausedNotification()
|
|
||||||
false -> launchWatcherNotification()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
settings = settings,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForEthernetConnectivityChanges() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
ethernetService.networkStatus.collect { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Available -> {
|
|
||||||
Timber.i("Gained Ethernet connection")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isEthernetConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.CapabilitiesChanged -> {
|
|
||||||
Timber.i("Ethernet capabilities changed")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isEthernetConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.Unavailable -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isEthernetConnected = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Lost Ethernet connection")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForWifiConnectivityChanges() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
wifiService.networkStatus.collect { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Available -> {
|
|
||||||
Timber.i("Gained Wi-Fi connection")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isWifiConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.CapabilitiesChanged -> {
|
|
||||||
Timber.i("Wifi capabilities changed")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isWifiConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
val ssid = wifiService.getNetworkName(status.networkCapabilities)
|
|
||||||
ssid?.let { name ->
|
|
||||||
if (name.contains(Constants.UNREADABLE_SSID)) {
|
|
||||||
Timber.w("SSID unreadable: missing permissions")
|
|
||||||
} else Timber.i("Detected valid SSID")
|
|
||||||
appDataRepository.appState.setCurrentSsid(name)
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
currentNetworkSSID = name,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} ?: Timber.w("Failed to read ssid")
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.Unavailable -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isWifiConnected = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Lost Wi-Fi connection")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun getMobileDataTunnel(): TunnelConfig? {
|
|
||||||
return appDataRepository.tunnels.findByMobileDataTunnel().firstOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun getSsidTunnel(ssid: String): TunnelConfig? {
|
|
||||||
return appDataRepository.tunnels.findByTunnelNetworksName(ssid).firstOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun isTunnelDown(): Boolean {
|
|
||||||
return vpnService.vpnState.value.status == TunnelState.DOWN
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun manageVpn() {
|
|
||||||
val context = this
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
networkEventsFlow.collectLatest { watcherState ->
|
|
||||||
val autoTunnel = "Auto-tunnel watcher"
|
|
||||||
if (!watcherState.settings.isAutoTunnelPaused) {
|
|
||||||
//delay for rapid network state changes and then collect latest
|
|
||||||
delay(Constants.WATCHER_COLLECTION_DELAY)
|
|
||||||
val tunnelConfig = vpnService.vpnState.value.tunnelConfig
|
|
||||||
when {
|
|
||||||
watcherState.isEthernetConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
|
|
||||||
if (isTunnelDown()) serviceManager.startVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isMobileDataConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel on on mobile data condition met")
|
|
||||||
val mobileDataTunnel = getMobileDataTunnel()
|
|
||||||
val tunnel =
|
|
||||||
mobileDataTunnel ?: appDataRepository.getPrimaryOrFirstTunnel()
|
|
||||||
if (isTunnelDown()) return@collectLatest serviceManager.startVpnServiceForeground(
|
|
||||||
context,
|
|
||||||
tunnel?.id,
|
|
||||||
)
|
|
||||||
if (tunnelConfig?.isMobileDataTunnel == false && mobileDataTunnel != null) {
|
|
||||||
Timber.i("$autoTunnel - tunnel connected on mobile data is not preferred condition met, switching to preferred")
|
|
||||||
serviceManager.startVpnServiceForeground(
|
|
||||||
context,
|
|
||||||
mobileDataTunnel.id,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnMobileDataConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isUntrustedWifiConditionMet() -> {
|
|
||||||
if (tunnelConfig?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false ||
|
|
||||||
tunnelConfig == null) {
|
|
||||||
Timber.i("$autoTunnel - tunnel on ssid not associated with current tunnel condition met")
|
|
||||||
getSsidTunnel(watcherState.currentNetworkSSID)?.let {
|
|
||||||
Timber.i("Found tunnel associated with this SSID, bringing tunnel up")
|
|
||||||
if (isTunnelDown()) serviceManager.startVpnServiceForeground(
|
|
||||||
context,
|
|
||||||
it.id,
|
|
||||||
)
|
|
||||||
} ?: suspend {
|
|
||||||
Timber.i("No tunnel associated with this SSID, using defaults")
|
|
||||||
val default = appDataRepository.getPrimaryOrFirstTunnel()
|
|
||||||
if (default?.name != vpnService.name) {
|
|
||||||
default?.let {
|
|
||||||
serviceManager.startVpnServiceForeground(context, it.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}.invoke()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTrustedWifiConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnWifiConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on wifi condition met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnNoConnectivityMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on no connectivity met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
Timber.i("$autoTunnel - no condition met")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-201
@@ -1,201 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import android.app.PendingIntent
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.core.app.ServiceCompat
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.receiver.NotificationActionReceiver
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.handshakeStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.mapPeerStats
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import timber.log.Timber
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class WireGuardTunnelService : ForegroundService() {
|
|
||||||
private val foregroundId = 123
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var vpnService: VpnService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var appDataRepository: AppDataRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var notificationService: NotificationService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@MainImmediateDispatcher
|
|
||||||
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@IoDispatcher
|
|
||||||
lateinit var ioDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
private var job: Job? = null
|
|
||||||
|
|
||||||
private var didShowConnected = false
|
|
||||||
|
|
||||||
override fun onCreate() {
|
|
||||||
super.onCreate()
|
|
||||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
|
||||||
//TODO fix this to not launch if AOVPN
|
|
||||||
if (appDataRepository.tunnels.count() != 0) {
|
|
||||||
launchVpnNotification()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun startService(extras: Bundle?) {
|
|
||||||
super.startService(extras)
|
|
||||||
cancelJob()
|
|
||||||
job =
|
|
||||||
lifecycleScope.launch {
|
|
||||||
launch {
|
|
||||||
val tunnelId = extras?.getInt(Constants.TUNNEL_EXTRA_KEY)
|
|
||||||
if (vpnService.getState() == TunnelState.UP) {
|
|
||||||
vpnService.stopTunnel()
|
|
||||||
}
|
|
||||||
vpnService.startTunnel(
|
|
||||||
tunnelId?.let {
|
|
||||||
appDataRepository.tunnels.getById(it)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
launch {
|
|
||||||
handshakeNotifications()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//TODO improve tunnel notifications
|
|
||||||
private suspend fun handshakeNotifications() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
var tunnelName: String? = null
|
|
||||||
vpnService.vpnState.collect { state ->
|
|
||||||
state.statistics
|
|
||||||
?.mapPeerStats()
|
|
||||||
?.map { it.value?.handshakeStatus() }
|
|
||||||
.let { statuses ->
|
|
||||||
when {
|
|
||||||
statuses?.all { it == HandshakeStatus.HEALTHY } == true -> {
|
|
||||||
if (!didShowConnected) {
|
|
||||||
delay(Constants.VPN_CONNECTED_NOTIFICATION_DELAY)
|
|
||||||
tunnelName = state.tunnelConfig?.name
|
|
||||||
launchVpnNotification(
|
|
||||||
getString(R.string.tunnel_start_title),
|
|
||||||
"${getString(R.string.tunnel_start_text)} - $tunnelName",
|
|
||||||
)
|
|
||||||
didShowConnected = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
statuses?.any { it == HandshakeStatus.STALE } == true -> {}
|
|
||||||
statuses?.all { it == HandshakeStatus.NOT_STARTED } ==
|
|
||||||
true -> {
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (state.status == TunnelState.UP && state.tunnelConfig?.name != tunnelName) {
|
|
||||||
tunnelName = state.tunnelConfig?.name
|
|
||||||
launchVpnNotification(
|
|
||||||
getString(R.string.tunnel_start_title),
|
|
||||||
"${getString(R.string.tunnel_start_text)} - $tunnelName",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchAlwaysOnDisabledNotification() {
|
|
||||||
launchVpnNotification(
|
|
||||||
title = this.getString(R.string.vpn_connection_failed),
|
|
||||||
description = this.getString(R.string.always_on_disabled),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun stopService() {
|
|
||||||
super.stopService()
|
|
||||||
lifecycleScope.launch {
|
|
||||||
vpnService.stopTunnel()
|
|
||||||
didShowConnected = false
|
|
||||||
}
|
|
||||||
cancelJob()
|
|
||||||
stopSelf()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchVpnNotification(
|
|
||||||
title: String = getString(R.string.vpn_starting),
|
|
||||||
description: String = getString(R.string.attempt_connection)
|
|
||||||
) {
|
|
||||||
val notification =
|
|
||||||
notificationService.createNotification(
|
|
||||||
channelId = getString(R.string.vpn_channel_id),
|
|
||||||
channelName = getString(R.string.vpn_channel_name),
|
|
||||||
title = title,
|
|
||||||
onGoing = false,
|
|
||||||
vibration = false,
|
|
||||||
showTimestamp = true,
|
|
||||||
description = description,
|
|
||||||
)
|
|
||||||
ServiceCompat.startForeground(
|
|
||||||
this,
|
|
||||||
foregroundId,
|
|
||||||
notification,
|
|
||||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchVpnConnectionFailedNotification(message: String) {
|
|
||||||
val notification =
|
|
||||||
notificationService.createNotification(
|
|
||||||
channelId = getString(R.string.vpn_channel_id),
|
|
||||||
channelName = getString(R.string.vpn_channel_name),
|
|
||||||
action =
|
|
||||||
PendingIntent.getBroadcast(
|
|
||||||
this,
|
|
||||||
0,
|
|
||||||
Intent(this, NotificationActionReceiver::class.java),
|
|
||||||
PendingIntent.FLAG_IMMUTABLE,
|
|
||||||
),
|
|
||||||
actionText = getString(R.string.restart),
|
|
||||||
title = getString(R.string.vpn_connection_failed),
|
|
||||||
onGoing = false,
|
|
||||||
vibration = true,
|
|
||||||
showTimestamp = true,
|
|
||||||
description = message,
|
|
||||||
)
|
|
||||||
ServiceCompat.startForeground(
|
|
||||||
this,
|
|
||||||
foregroundId,
|
|
||||||
notification,
|
|
||||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun cancelJob() {
|
|
||||||
try {
|
|
||||||
job?.cancel()
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
Timber.i("Tunnel job cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+7
-38
@@ -5,8 +5,6 @@ import android.net.ConnectivityManager
|
|||||||
import android.net.Network
|
import android.net.Network
|
||||||
import android.net.NetworkCapabilities
|
import android.net.NetworkCapabilities
|
||||||
import android.net.NetworkRequest
|
import android.net.NetworkRequest
|
||||||
import android.net.wifi.SupplicantState
|
|
||||||
import android.net.wifi.WifiInfo
|
|
||||||
import android.net.wifi.WifiManager
|
import android.net.wifi.WifiManager
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import kotlinx.coroutines.channels.awaitClose
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
@@ -16,15 +14,16 @@ 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
|
||||||
|
|
||||||
private val wifiManager =
|
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 +39,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 +60,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,
|
||||||
@@ -88,37 +81,13 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
|
|||||||
|
|
||||||
awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) }
|
awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
|
||||||
var ssid: String? = getWifiNameFromCapabilities(networkCapabilities)
|
|
||||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
|
|
||||||
val info = wifiManager.connectionInfo
|
|
||||||
if (info.supplicantState === SupplicantState.COMPLETED) {
|
|
||||||
ssid = info.ssid
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ssid?.trim('"')
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private fun getWifiNameFromCapabilities(networkCapabilities: NetworkCapabilities): String? {
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
|
||||||
val info: WifiInfo
|
|
||||||
if (networkCapabilities.transportInfo is WifiInfo) {
|
|
||||||
info = networkCapabilities.transportInfo as WifiInfo
|
|
||||||
return info.ssid
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun <Result> Flow<NetworkStatus>.map(
|
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)
|
||||||
|
|||||||
+11
-2
@@ -5,5 +5,14 @@ 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
|
||||||
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET)
|
@Inject
|
||||||
|
constructor(
|
||||||
|
@ApplicationContext context: Context,
|
||||||
|
) :
|
||||||
|
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET) {
|
||||||
|
|
||||||
|
override fun isNetworkSecure(): Boolean {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+10
-2
@@ -5,5 +5,13 @@ 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
|
||||||
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR)
|
@Inject
|
||||||
|
constructor(
|
||||||
|
@ApplicationContext context: Context,
|
||||||
|
) :
|
||||||
|
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR) {
|
||||||
|
override fun isNetworkSecure(): Boolean {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.network
|
||||||
|
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.wifi.WifiInfo
|
||||||
|
import android.os.Build
|
||||||
|
|
||||||
|
fun NetworkCapabilities.getWifiName(): String? {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
val info: WifiInfo
|
||||||
|
if (transportInfo is WifiInfo) {
|
||||||
|
info = transportInfo as WifiInfo
|
||||||
|
return info.ssid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
+5
-1
@@ -4,7 +4,11 @@ import android.net.NetworkCapabilities
|
|||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
interface NetworkService<T> {
|
interface NetworkService<T> {
|
||||||
fun getNetworkName(networkCapabilities: NetworkCapabilities): String?
|
fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isNetworkSecure(): Boolean
|
||||||
|
|
||||||
val networkStatus: Flow<NetworkStatus>
|
val networkStatus: Flow<NetworkStatus>
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-2
@@ -2,8 +2,31 @@ package com.zaneschepke.wireguardautotunnel.service.network
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.net.NetworkCapabilities
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.wifi.SupplicantState
|
||||||
|
import android.os.Build
|
||||||
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
|
||||||
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI)
|
@Inject
|
||||||
|
constructor(
|
||||||
|
@ApplicationContext context: Context,
|
||||||
|
) :
|
||||||
|
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI) {
|
||||||
|
|
||||||
|
override fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
||||||
|
var ssid = networkCapabilities.getWifiName()
|
||||||
|
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
|
||||||
|
val info = wifiManager.connectionInfo
|
||||||
|
if (info.supplicantState === SupplicantState.COMPLETED) {
|
||||||
|
ssid = info.ssid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ssid?.trim('"')
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun isNetworkSecure(): Boolean {
|
||||||
|
// TODO
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+5
-1
@@ -13,7 +13,11 @@ import com.zaneschepke.wireguardautotunnel.ui.MainActivity
|
|||||||
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
|
||||||
|
|||||||
+25
-23
@@ -5,22 +5,24 @@ import androidx.activity.ComponentActivity
|
|||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.Action
|
import com.zaneschepke.wireguardautotunnel.service.foreground.Action
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.AutoTunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardConnectivityWatcherService
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardTunnelService
|
import 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.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class ShortcutsActivity : ComponentActivity() {
|
class ShortcutsActivity : ComponentActivity() {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
@ApplicationScope
|
@ApplicationScope
|
||||||
@@ -32,34 +34,32 @@ class ShortcutsActivity : ComponentActivity() {
|
|||||||
val settings = appDataRepository.settings.getSettings()
|
val settings = appDataRepository.settings.getSettings()
|
||||||
if (settings.isShortcutsEnabled) {
|
if (settings.isShortcutsEnabled) {
|
||||||
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
|
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
|
||||||
WireGuardTunnelService::class.java.simpleName -> {
|
LEGACY_TUNNEL_SERVICE_NAME, TunnelService::class.java.simpleName -> {
|
||||||
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
|
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
|
||||||
|
Timber.d("Tunnel name extra: $tunnelName")
|
||||||
val tunnelConfig = tunnelName?.let {
|
val tunnelConfig = tunnelName?.let {
|
||||||
appDataRepository.tunnels.getAll().firstOrNull {
|
appDataRepository.tunnels.getAll()
|
||||||
it.name == tunnelName
|
.firstOrNull { it.name == tunnelName }
|
||||||
}
|
} ?: appDataRepository.getStartTunnelConfig()
|
||||||
}
|
Timber.d("Shortcut action on name: ${tunnelConfig?.name}")
|
||||||
|
tunnelConfig?.let {
|
||||||
when (intent.action) {
|
when (intent.action) {
|
||||||
Action.START.name -> serviceManager.startVpnServiceForeground(
|
Action.START.name -> 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,
|
||||||
),
|
),
|
||||||
@@ -73,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"
|
||||||
}
|
}
|
||||||
|
|||||||
+69
-25
@@ -1,42 +1,55 @@
|
|||||||
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.module.ApplicationScope
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class AutoTunnelControlTile : TileService() {
|
class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var serviceManager: ServiceManager
|
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
@ApplicationScope
|
@ApplicationScope
|
||||||
lateinit var applicationScope: CoroutineScope
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
private var manualStartConfig: TunnelConfig? = null
|
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
|
||||||
|
|
||||||
|
/* 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 onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||||
|
|
||||||
override fun onStartListening() {
|
|
||||||
super.onStartListening()
|
|
||||||
applicationScope.launch {
|
applicationScope.launch {
|
||||||
val settings = appDataRepository.settings.getSettings()
|
appDataRepository.settings.getSettingsFlow().collect {
|
||||||
when (settings.isAutoTunnelEnabled) {
|
kotlin.runCatching {
|
||||||
|
when (it.isAutoTunnelEnabled) {
|
||||||
true -> {
|
true -> {
|
||||||
if (settings.isAutoTunnelPaused) {
|
if (it.isAutoTunnelPaused) {
|
||||||
setInactive()
|
setInactive()
|
||||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.paused))
|
setTileDescription(this@AutoTunnelControlTile.getString(R.string.paused))
|
||||||
} else {
|
} else {
|
||||||
@@ -50,46 +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() {
|
||||||
|
super.onDestroy()
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartListening() {
|
||||||
|
super.onStartListening()
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onClick() {
|
override fun onClick() {
|
||||||
super.onClick()
|
super.onClick()
|
||||||
unlockAndRun {
|
unlockAndRun {
|
||||||
applicationScope.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
|
||||||
}
|
}
|
||||||
@@ -98,4 +138,8 @@ class AutoTunnelControlTile : TileService() {
|
|||||||
}
|
}
|
||||||
qsTile.updateTile()
|
qsTile.updateTile()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override val lifecycle: Lifecycle
|
||||||
|
get() = lifecycleRegistry
|
||||||
}
|
}
|
||||||
|
|||||||
+63
-56
@@ -3,114 +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.module.ApplicationScope
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
import com.zaneschepke.wireguardautotunnel.util.extensions.stopTunnelBackground
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
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
|
|
||||||
lateinit var serviceManager: ServiceManager
|
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
@ApplicationScope
|
@ApplicationScope
|
||||||
lateinit var applicationScope: CoroutineScope
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
private var manualStartConfig: TunnelConfig? = null
|
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
|
||||||
|
|
||||||
private var job: Job? = null;
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
Timber.d("onCreate for tile service")
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStopListening() {
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onStartListening() {
|
override fun onStartListening() {
|
||||||
super.onStartListening()
|
super.onStartListening()
|
||||||
Timber.d("On start listening called")
|
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||||
//TODO Fix this
|
lifecycleScope.launch {
|
||||||
if (job == null || job?.isCancelled == true) job = applicationScope.launch {
|
if (appDataRepository.tunnels.getAll().isEmpty()) return@launch setUnavailable()
|
||||||
vpnService.vpnState.collect { it ->
|
updateTileState()
|
||||||
when (it.status) {
|
|
||||||
TunnelState.UP -> {
|
|
||||||
setActive()
|
|
||||||
it.tunnelConfig?.name?.let { name -> setTileDescription(name) }
|
|
||||||
}
|
|
||||||
|
|
||||||
TunnelState.DOWN -> {
|
|
||||||
setInactive()
|
|
||||||
val config = appDataRepository.getStartTunnelConfig()?.also { config ->
|
|
||||||
manualStartConfig = config
|
|
||||||
} ?: appDataRepository.getPrimaryOrFirstTunnel()
|
|
||||||
config?.let {
|
|
||||||
setTileDescription(it.name)
|
|
||||||
} ?: setUnavailable()
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> setInactive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onTileAdded() {
|
private suspend fun updateTileState() {
|
||||||
super.onTileAdded()
|
val lastActive = appDataRepository.getStartTunnelConfig()
|
||||||
onStartListening()
|
lastActive?.let {
|
||||||
|
updateTile(it)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onClick() {
|
override fun onClick() {
|
||||||
super.onClick()
|
super.onClick()
|
||||||
unlockAndRun {
|
unlockAndRun {
|
||||||
applicationScope.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
|
||||||
}
|
}
|
||||||
@@ -119,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()
|
||||||
|
}
|
||||||
@@ -5,7 +5,8 @@ import com.wireguard.android.backend.Tunnel
|
|||||||
enum class TunnelState {
|
enum class TunnelState {
|
||||||
UP,
|
UP,
|
||||||
DOWN,
|
DOWN,
|
||||||
TOGGLE;
|
TOGGLE,
|
||||||
|
;
|
||||||
|
|
||||||
fun toWgState(): Tunnel.State {
|
fun toWgState(): Tunnel.State {
|
||||||
return when (this) {
|
return when (this) {
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
|
||||||
|
|
||||||
import com.wireguard.android.backend.Tunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
|
|
||||||
interface VpnService : Tunnel, org.amnezia.awg.backend.Tunnel {
|
|
||||||
suspend fun startTunnel(tunnelConfig: TunnelConfig? = null): TunnelState
|
|
||||||
|
|
||||||
suspend fun stopTunnel()
|
|
||||||
|
|
||||||
val vpnState: StateFlow<VpnState>
|
|
||||||
|
|
||||||
fun getState(): TunnelState
|
|
||||||
}
|
|
||||||
@@ -6,5 +6,5 @@ import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStati
|
|||||||
data class VpnState(
|
data class VpnState(
|
||||||
val status: TunnelState = TunnelState.DOWN,
|
val status: TunnelState = TunnelState.DOWN,
|
||||||
val tunnelConfig: TunnelConfig? = null,
|
val tunnelConfig: TunnelConfig? = null,
|
||||||
val statistics: TunnelStatistics? = null
|
val statistics: TunnelStatistics? = null,
|
||||||
)
|
)
|
||||||
|
|||||||
+159
-115
@@ -1,116 +1,162 @@
|
|||||||
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.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
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.CancellationException
|
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
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 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,
|
||||||
@ApplicationScope private val applicationScope: CoroutineScope,
|
@ApplicationScope private val applicationScope: CoroutineScope,
|
||||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
) : VpnService {
|
) : TunnelService {
|
||||||
private val _vpnState = MutableStateFlow(VpnState())
|
|
||||||
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
|
|
||||||
|
|
||||||
|
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 {
|
|
||||||
applicationScope.launch(ioDispatcher) {
|
|
||||||
appDataRepository.settings.getSettingsFlow().collect {
|
|
||||||
if (it.isKernelEnabled && (backendIsWgUserspace || backendIsAmneziaUserspace)) {
|
|
||||||
Timber.i("Setting kernel backend")
|
|
||||||
backend = kernelBackend
|
|
||||||
backendIsWgUserspace = false
|
|
||||||
backendIsAmneziaUserspace = false
|
|
||||||
} else if (!it.isKernelEnabled && !it.isAmneziaEnabled && !backendIsWgUserspace) {
|
|
||||||
Timber.i("Setting WireGuard userspace backend")
|
|
||||||
backend = userspaceBackend
|
|
||||||
backendIsWgUserspace = true
|
|
||||||
backendIsAmneziaUserspace = false
|
|
||||||
} else if (it.isAmneziaEnabled && !backendIsAmneziaUserspace) {
|
|
||||||
Timber.i("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 withContext(ioDispatcher) {
|
return withContext(ioDispatcher) {
|
||||||
try {
|
onBeforeStart(tunnelConfig)
|
||||||
//TODO we need better error handling here
|
setState(tunnelConfig, TunnelState.UP).onSuccess {
|
||||||
val config = tunnelConfig ?: appDataRepository.getPrimaryOrFirstTunnel()
|
emitTunnelState(it)
|
||||||
if (config != null) {
|
}.onFailure {
|
||||||
emitTunnelConfig(config)
|
Timber.e(it)
|
||||||
setState(config, TunnelState.UP)
|
onStartFailed()
|
||||||
} else throw Exception("No tunnels")
|
|
||||||
} catch (e: BackendException) {
|
|
||||||
Timber.e("Failed to start tunnel with error: ${e.message}")
|
|
||||||
TunnelState.from(State.DOWN)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
private fun emitTunnelState(state: TunnelState) {
|
||||||
_vpnState.tryEmit(
|
_vpnState.tryEmit(
|
||||||
_vpnState.value.copy(
|
_vpnState.value.copy(
|
||||||
@@ -127,75 +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 {
|
||||||
withContext(ioDispatcher) {
|
return when (val backend = backend()) {
|
||||||
try {
|
is Backend -> backend.getState(this).let { TunnelState.from(it) }
|
||||||
if (getState() == TunnelState.UP) {
|
is org.amnezia.awg.backend.Backend -> backend.getState(this).let { TunnelState.from(it) }
|
||||||
val state = setState(null, TunnelState.DOWN)
|
else -> TunnelState.DOWN
|
||||||
resetVpnState()
|
|
||||||
emitTunnelState(state)
|
|
||||||
}
|
|
||||||
} catch (e: BackendException) {
|
|
||||||
Timber.e("Failed to stop wireguard tunnel with error: ${e.message}")
|
|
||||||
} catch (e: org.amnezia.awg.backend.BackendException) {
|
|
||||||
Timber.e("Failed to stop amnezia tunnel with error: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getState(): TunnelState {
|
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) {
|
|
||||||
emitTunnelState(state)
|
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
|
||||||
if (state == TunnelState.UP) {
|
|
||||||
statsJob = startTunnelStatisticsJob()
|
|
||||||
}
|
|
||||||
if (state == TunnelState.DOWN) {
|
|
||||||
try {
|
|
||||||
statsJob?.cancel()
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
Timber.i("Stats job cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startTunnelStatisticsJob() = applicationScope.launch(ioDispatcher) {
|
|
||||||
while (true) {
|
|
||||||
if (backendIsAmneziaUserspace) {
|
|
||||||
emitBackendStatistics(AmneziaStatistics(userspaceAmneziaBackend.getStatistics(this@WireGuardTunnel)))
|
|
||||||
} else {
|
|
||||||
emitBackendStatistics(WireGuardStatistics(backend.getStatistics(this@WireGuardTunnel)))
|
|
||||||
}
|
|
||||||
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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,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,123 +1,115 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui
|
package com.zaneschepke.wireguardautotunnel.ui
|
||||||
|
|
||||||
import android.content.ActivityNotFoundException
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.net.Uri
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import com.wireguard.android.backend.GoBackend
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
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.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.collect
|
||||||
import timber.log.Timber
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.onCompletion
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
|
import kotlinx.coroutines.flow.takeWhile
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.plus
|
||||||
|
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class AppViewModel
|
class AppViewModel
|
||||||
@Inject
|
@Inject
|
||||||
constructor() : ViewModel() {
|
constructor(
|
||||||
|
private val appDataRepository: AppDataRepository,
|
||||||
|
private val tunnelService: Provider<TunnelService>,
|
||||||
|
@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.get().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,
|
||||||
|
)
|
||||||
|
|
||||||
|
private val _isAppReady = MutableStateFlow<Boolean>(false)
|
||||||
|
val isAppReady = _isAppReady.asStateFlow()
|
||||||
|
|
||||||
|
init {
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
initPin()
|
||||||
|
initAutoTunnel()
|
||||||
|
initTunnel()
|
||||||
|
appReadyCheck()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun appReadyCheck() {
|
||||||
|
val tunnelCount = appDataRepository.tunnels.count()
|
||||||
|
uiState.takeWhile { it.tunnels.size != tunnelCount }.onCompletion {
|
||||||
|
_isAppReady.emit(true)
|
||||||
|
}.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun initTunnel() {
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun initPin() {
|
||||||
|
val isPinEnabled = appDataRepository.appState.isPinLockEnabled()
|
||||||
|
if (isPinEnabled) PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun initAutoTunnel() {
|
||||||
|
val settings = appDataRepository.settings.getSettings()
|
||||||
|
if (settings.isAutoTunnelEnabled) ServiceManager.startWatcherService(WireGuardAutoTunnel.instance)
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,25 +1,28 @@
|
|||||||
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.activity.viewModels
|
||||||
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.Box
|
||||||
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.SnackbarResult
|
|
||||||
import androidx.compose.material3.surfaceColorAtElevation
|
import androidx.compose.material3.surfaceColorAtElevation
|
||||||
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
@@ -28,28 +31,27 @@ 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.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||||
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.compose.rememberNavController
|
||||||
import androidx.navigation.navArgument
|
import androidx.navigation.toRoute
|
||||||
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.LocalNavController
|
||||||
|
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,118 +59,64 @@ 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.requestAutoTunnelTileServiceUpdate
|
||||||
|
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
|
private val viewModel by viewModels<AppViewModel>()
|
||||||
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.auto(
|
||||||
|
lightScrim = Color.Transparent.toArgb(),
|
||||||
|
darkScrim = Color.Transparent.toArgb(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb()))
|
installSplashScreen().apply {
|
||||||
|
setKeepOnScreenCondition {
|
||||||
// load preferences into memory and init data
|
!viewModel.isAppReady.value
|
||||||
lifecycleScope.launch {
|
|
||||||
dataStoreManager.init()
|
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
|
||||||
val settings = settingsRepository.getSettings()
|
|
||||||
if (settings.isAutoTunnelEnabled) {
|
|
||||||
serviceManager.startWatcherService(application.applicationContext)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setContent {
|
setContent {
|
||||||
val appViewModel = hiltViewModel<AppViewModel>()
|
val appUiState by viewModel.uiState.collectAsStateWithLifecycle(lifecycle = this.lifecycle)
|
||||||
val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle()
|
|
||||||
val navController = rememberNavController()
|
val navController = rememberNavController()
|
||||||
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 =
|
context.requestTunnelTileServiceStateUpdate()
|
||||||
rememberLauncherForActivityResult(
|
|
||||||
ActivityResultContracts.StartActivityForResult(),
|
|
||||||
onResult = {
|
|
||||||
val accepted = (it.resultCode == RESULT_OK)
|
|
||||||
if (accepted) {
|
|
||||||
appViewModel.onVpnPermissionAccepted()
|
|
||||||
}
|
}
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
fun showSnackBarMessage(message: StringValue) {
|
with(appUiState.settings) {
|
||||||
lifecycleScope.launch(Dispatchers.Main) {
|
LaunchedEffect(isAutoTunnelPaused, isAutoTunnelEnabled) {
|
||||||
val result =
|
this@MainActivity.requestAutoTunnelTileServiceUpdate()
|
||||||
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,
|
|
||||||
)
|
|
||||||
}!!
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
CompositionLocalProvider(LocalNavController provides navController) {
|
||||||
|
SnackbarControllerProvider { host ->
|
||||||
WireguardAutoTunnelTheme {
|
WireguardAutoTunnelTheme {
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
appViewModel.setNotificationPermissionAccepted(
|
|
||||||
notificationPermissionState?.status?.isGranted ?: true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
||||||
@@ -179,108 +127,86 @@ class MainActivity : AppCompatActivity() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
//TODO refactor
|
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 ->
|
||||||
|
Box(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 (appUiState.generalState.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,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
composable(
|
composable<Route.Settings> {
|
||||||
Screen.Settings.route,
|
|
||||||
) {
|
|
||||||
SettingsScreen(
|
SettingsScreen(
|
||||||
appViewModel = appViewModel,
|
appViewModel = viewModel,
|
||||||
navController = navController,
|
uiState = appUiState,
|
||||||
focusRequester = focusRequester,
|
focusRequester = focusRequester,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
composable(
|
composable<Route.Support> {
|
||||||
Screen.Support.route,
|
|
||||||
) {
|
|
||||||
SupportScreen(
|
SupportScreen(
|
||||||
focusRequester = focusRequester,
|
focusRequester = focusRequester,
|
||||||
appViewModel = appViewModel,
|
appUiState = appUiState,
|
||||||
navController = navController,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
composable(Screen.Support.Logs.route) {
|
composable<Route.Logs> {
|
||||||
LogsScreen()
|
LogsScreen()
|
||||||
}
|
}
|
||||||
composable(
|
composable<Route.Config> {
|
||||||
"${Screen.Config.route}/{id}?configType={configType}",
|
val args = it.toRoute<Route.Config>()
|
||||||
arguments =
|
|
||||||
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,
|
tunnelId = args.id,
|
||||||
tunnelId = id,
|
|
||||||
appViewModel = appViewModel,
|
|
||||||
focusRequester = focusRequester,
|
focusRequester = focusRequester,
|
||||||
|
appUiState = appUiState,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
composable<Route.Lock> {
|
||||||
composable(Screen.Lock.route) {
|
|
||||||
PinLockScreen(
|
PinLockScreen(
|
||||||
navController = navController,
|
appViewModel = viewModel,
|
||||||
appViewModel = appViewModel,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -288,4 +214,12 @@ 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")
|
|
||||||
}
|
|
||||||
+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,
|
||||||
|
|||||||
+69
@@ -0,0 +1,69 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||||
|
|
||||||
|
import androidx.compose.animation.animateContentSize
|
||||||
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
|
import androidx.compose.foundation.combinedClickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
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
|
||||||
|
|
||||||
|
@OptIn(ExperimentalFoundationApi::class)
|
||||||
|
@Composable
|
||||||
|
fun ExpandingRowListItem(
|
||||||
|
leading: @Composable () -> Unit,
|
||||||
|
text: String,
|
||||||
|
onHold: () -> Unit = {},
|
||||||
|
onClick: () -> Unit,
|
||||||
|
trailing: @Composable () -> Unit,
|
||||||
|
isExpanded: Boolean,
|
||||||
|
expanded: @Composable () -> Unit = {},
|
||||||
|
focusRequester: FocusRequester,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.focusRequester(focusRequester)
|
||||||
|
.animateContentSize()
|
||||||
|
.clip(RoundedCornerShape(30.dp))
|
||||||
|
.combinedClickable(
|
||||||
|
onClick = { onClick() },
|
||||||
|
onLongClick = { onHold() },
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
Column {
|
||||||
|
Row(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 15.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(15.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth(13 / 20f),
|
||||||
|
) {
|
||||||
|
leading()
|
||||||
|
Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.labelLarge)
|
||||||
|
}
|
||||||
|
trailing()
|
||||||
|
}
|
||||||
|
if (isExpanded) expanded()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||||
|
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
|
||||||
|
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
|
||||||
|
|
||||||
|
class NestedScrollListener(val onUp: () -> Unit, val onDown: () -> Unit) : NestedScrollConnection {
|
||||||
|
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
|
||||||
|
if (available.y < -1) onDown()
|
||||||
|
if (available.y > 1) onUp()
|
||||||
|
return Offset.Zero
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui.common
|
|
||||||
|
|
||||||
import androidx.compose.animation.animateContentSize
|
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
|
||||||
import androidx.compose.foundation.combinedClickable
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.toThreeDecimalPlaceString
|
|
||||||
|
|
||||||
@OptIn(ExperimentalFoundationApi::class)
|
|
||||||
@Composable
|
|
||||||
fun RowListItem(
|
|
||||||
icon: @Composable () -> Unit,
|
|
||||||
text: String,
|
|
||||||
onHold: () -> Unit,
|
|
||||||
onClick: () -> Unit,
|
|
||||||
rowButton: @Composable () -> Unit,
|
|
||||||
expanded: Boolean,
|
|
||||||
statistics: TunnelStatistics?
|
|
||||||
) {
|
|
||||||
Box(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.animateContentSize()
|
|
||||||
.clip(RoundedCornerShape(30.dp))
|
|
||||||
.combinedClickable(
|
|
||||||
onClick = { onClick() },
|
|
||||||
onLongClick = { onHold() },
|
|
||||||
),
|
|
||||||
) {
|
|
||||||
Column {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 15.dp, vertical = 5.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
modifier = Modifier.fillMaxWidth(13 / 20f),
|
|
||||||
) {
|
|
||||||
icon()
|
|
||||||
Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
|
||||||
}
|
|
||||||
rowButton()
|
|
||||||
}
|
|
||||||
if (expanded) {
|
|
||||||
statistics?.getPeers()?.forEach {
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(end = 10.dp, bottom = 10.dp, start = 10.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
|
||||||
) {
|
|
||||||
//TODO change these to string resources
|
|
||||||
val handshakeEpoch = statistics.peerStats(it)!!.latestHandshakeEpochMillis
|
|
||||||
val peerTx = statistics.peerStats(it)!!.txBytes
|
|
||||||
val peerRx = statistics.peerStats(it)!!.rxBytes
|
|
||||||
val peerId = it.toBase64().subSequence(0, 3).toString() + "***"
|
|
||||||
val handshakeSec =
|
|
||||||
NumberUtils.getSecondsBetweenTimestampAndNow(handshakeEpoch)
|
|
||||||
val handshake =
|
|
||||||
if (handshakeSec == null) "never" else "$handshakeSec secs ago"
|
|
||||||
val peerTxMB = NumberUtils.bytesToMB(peerTx).toThreeDecimalPlaceString()
|
|
||||||
val peerRxMB = NumberUtils.bytesToMB(peerRx).toThreeDecimalPlaceString()
|
|
||||||
val fontSize = 9.sp
|
|
||||||
Text("peer: $peerId", fontSize = fontSize)
|
|
||||||
Text("handshake: $handshake", fontSize = fontSize)
|
|
||||||
Text("tx: $peerTxMB MB", fontSize = fontSize)
|
|
||||||
Text("rx: $peerRxMB MB", fontSize = fontSize)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+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,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-7
@@ -4,6 +4,7 @@ import androidx.compose.foundation.layout.Arrangement
|
|||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
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.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Switch
|
import androidx.compose.material3.Switch
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
@@ -15,22 +16,26 @@ 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(
|
Text(
|
||||||
label, textAlign = TextAlign.Start,
|
label,
|
||||||
modifier = Modifier
|
textAlign = TextAlign.Start,
|
||||||
|
style = MaterialTheme.typography.labelLarge,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
.weight(
|
.weight(
|
||||||
weight = 1.0f,
|
weight = 1.0f,
|
||||||
fill = false,
|
fill = false,
|
||||||
@@ -41,7 +46,7 @@ fun ConfigurationToggle(
|
|||||||
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() },
|
||||||
|
)
|
||||||
|
}
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
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
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
|
|
||||||
|
@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).apply {
|
||||||
|
type = if (context.isRunningOnTv()) {
|
||||||
|
Constants.ALLOWED_TV_FILE_TYPES
|
||||||
|
} else {
|
||||||
|
Constants.ALL_FILE_TYPES
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
-15
@@ -10,38 +10,45 @@ 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.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
|
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
|
||||||
|
|
||||||
@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.any {
|
||||||
showBottomBar = when (navBackStackEntry?.destination?.route) {
|
navBackStackEntry?.isCurrentRoute(it.route) == true
|
||||||
Screen.Lock.route -> false
|
|
||||||
else -> true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
fontWeight = FontWeight.SemiBold,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
icon = {
|
icon = {
|
||||||
@@ -53,4 +60,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,
|
||||||
)
|
)
|
||||||
|
|||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import androidx.navigation.NavBackStackEntry
|
||||||
|
import androidx.navigation.NavDestination.Companion.hasRoute
|
||||||
|
import androidx.navigation.NavDestination.Companion.hierarchy
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||||
|
|
||||||
|
@SuppressLint("RestrictedApi")
|
||||||
|
fun NavBackStackEntry?.isCurrentRoute(route: Route): Boolean {
|
||||||
|
return this?.destination?.hierarchy?.any {
|
||||||
|
it.hasRoute(route = route::class)
|
||||||
|
} == true
|
||||||
|
}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||||
|
|
||||||
|
import androidx.compose.runtime.compositionLocalOf
|
||||||
|
import androidx.navigation.NavHostController
|
||||||
|
|
||||||
|
val LocalNavController = compositionLocalOf<NavHostController> {
|
||||||
|
error("NavController was not provided")
|
||||||
|
}
|
||||||
+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),
|
||||||
|
|||||||
+2
-4
@@ -1,22 +1,20 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui.common.text
|
package com.zaneschepke.wireguardautotunnel.ui.common.text
|
||||||
|
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.text.TextStyle
|
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun SectionTitle(title: String, padding: Dp) {
|
fun SectionTitle(title: String, padding: Dp) {
|
||||||
Text(
|
Text(
|
||||||
title,
|
title,
|
||||||
textAlign = TextAlign.Start,
|
textAlign = TextAlign.Start,
|
||||||
style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.ExtraBold),
|
style = MaterialTheme.typography.titleMedium,
|
||||||
modifier = Modifier.padding(padding, bottom = 5.dp, top = 5.dp),
|
modifier = Modifier.padding(padding, bottom = 5.dp, top = 5.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+154
-284
@@ -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,88 @@ 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.Route
|
||||||
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.navigation.LocalNavController
|
||||||
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
|
||||||
|
val navController = LocalNavController.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()
|
||||||
|
val saved by viewModel.saved.collectAsStateWithLifecycle(null)
|
||||||
|
|
||||||
LaunchedEffect(Unit) { viewModel.init(tunnelId) }
|
LaunchedEffect(saved) {
|
||||||
|
if (saved == true) {
|
||||||
|
navController.navigate(Route.Main)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
LaunchedEffect(uiState.loading) {
|
LaunchedEffect(Unit) {
|
||||||
if (!uiState.loading && WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (!uiState.loading && context.isRunningOnTv()) {
|
||||||
|
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||||
|
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 +148,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 +201,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 +224,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 +264,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 +294,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,40 +304,40 @@ 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),
|
||||||
@@ -486,122 +347,129 @@ fun ConfigScreen(
|
|||||||
if (configType == ConfigType.AMNEZIA) {
|
if (configType == ConfigType.AMNEZIA) {
|
||||||
ConfigurationTextBox(
|
ConfigurationTextBox(
|
||||||
value = uiState.interfaceProxy.junkPacketCount,
|
value = uiState.interfaceProxy.junkPacketCount,
|
||||||
onValueChange = { value -> viewModel.onJunkPacketCountChanged(value) },
|
onValueChange = 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 ->
|
onValueChange = viewModel::onJunkPacketMinSizeChanged,
|
||||||
viewModel.onJunkPacketMinSizeChanged(
|
|
||||||
value,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
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 ->
|
onValueChange = viewModel::onJunkPacketMaxSizeChanged,
|
||||||
viewModel.onJunkPacketMaxSizeChanged(
|
|
||||||
value,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
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 ->
|
onValueChange = viewModel::onInitPacketJunkSizeChanged,
|
||||||
viewModel.onInitPacketJunkSizeChanged(
|
|
||||||
value,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
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 ->
|
onValueChange = viewModel::onResponsePacketMagicHeader,
|
||||||
viewModel.onResponsePacketMagicHeader(
|
|
||||||
value,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
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 ->
|
onValueChange = viewModel::onUnderloadPacketMagicHeader,
|
||||||
viewModel.onUnderloadPacketMagicHeader(
|
|
||||||
value,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
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 ->
|
onValueChange = viewModel::onTransportPacketMagicHeader,
|
||||||
viewModel.onTransportPacketMagicHeader(
|
|
||||||
value,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
keyboardActions = keyboardActions,
|
keyboardActions = keyboardActions,
|
||||||
label = stringResource(R.string.transport_packet_magic_header),
|
label = stringResource(R.string.transport_packet_magic_header),
|
||||||
hint = stringResource(R.string.transport_packet_magic_header).lowercase(),
|
hint =
|
||||||
modifier = Modifier
|
stringResource(
|
||||||
|
R.string.transport_packet_magic_header,
|
||||||
|
).lowercase(),
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.focusRequester(focusRequester),
|
.focusRequester(focusRequester),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
modifier = Modifier
|
modifier =
|
||||||
|
Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(top = 5.dp),
|
.padding(top = 5.dp),
|
||||||
horizontalArrangement = Arrangement.Center,
|
horizontalArrangement = Arrangement.Center,
|
||||||
@@ -619,26 +487,30 @@ fun ConfigScreen(
|
|||||||
shape = RoundedCornerShape(12.dp),
|
shape = RoundedCornerShape(12.dp),
|
||||||
color = MaterialTheme.colorScheme.surface,
|
color = MaterialTheme.colorScheme.surface,
|
||||||
modifier =
|
modifier =
|
||||||
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
(
|
||||||
|
if (context.isRunningOnTv()) {
|
||||||
Modifier
|
Modifier
|
||||||
.fillMaxHeight(fillMaxHeight)
|
.fillMaxHeight(fillMaxHeight)
|
||||||
.fillMaxWidth(fillMaxWidth)
|
.fillMaxWidth(fillMaxWidth)
|
||||||
} else {
|
} else {
|
||||||
Modifier.fillMaxWidth(fillMaxWidth)
|
Modifier.fillMaxWidth(fillMaxWidth)
|
||||||
})
|
}
|
||||||
|
)
|
||||||
.padding(top = 10.dp, bottom = 10.dp),
|
.padding(top = 10.dp, bottom = 10.dp),
|
||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
horizontalAlignment = Alignment.Start,
|
horizontalAlignment = Alignment.Start,
|
||||||
verticalArrangement = Arrangement.Top,
|
verticalArrangement = Arrangement.Top,
|
||||||
modifier = Modifier
|
modifier =
|
||||||
|
Modifier
|
||||||
.padding(horizontal = 15.dp)
|
.padding(horizontal = 15.dp)
|
||||||
.padding(bottom = 10.dp),
|
.padding(bottom = 10.dp),
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
modifier = Modifier
|
modifier =
|
||||||
|
Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 5.dp),
|
.padding(horizontal = 5.dp),
|
||||||
) {
|
) {
|
||||||
@@ -724,7 +596,8 @@ fun ConfigScreen(
|
|||||||
Row(
|
Row(
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
modifier = Modifier
|
modifier =
|
||||||
|
Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(bottom = 140.dp),
|
.padding(bottom = 140.dp),
|
||||||
) {
|
) {
|
||||||
@@ -738,9 +611,6 @@ fun ConfigScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
|
||||||
Spacer(modifier = Modifier.weight(.17f))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-4
@@ -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,8 +15,8 @@ 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 {
|
||||||
@@ -45,7 +45,6 @@ data class ConfigUiState(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun from(config: org.amnezia.awg.config.Config): ConfigUiState {
|
fun from(config: org.amnezia.awg.config.Config): ConfigUiState {
|
||||||
//TODO update with new values
|
|
||||||
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
|
||||||
@@ -69,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,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+205
-136
@@ -15,103 +15,126 @@ 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.module.IoDispatcher
|
||||||
|
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.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
|
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,
|
||||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
@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 _saved = MutableSharedFlow<Boolean>()
|
||||||
val uiState = _uiState.asStateFlow()
|
val saved = _saved.asSharedFlow()
|
||||||
|
|
||||||
fun init(tunnelId: String) =
|
private val _uiState = MutableStateFlow(ConfigUiState())
|
||||||
viewModelScope.launch(ioDispatcher) {
|
val uiState = _uiState.onStart {
|
||||||
val packages = getQueriedPackages("")
|
appDataRepository.tunnels.getById(id)?.let {
|
||||||
val state =
|
val packages = getQueriedPackages()
|
||||||
if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) {
|
_uiState.value = ConfigUiState.from(it).copy(
|
||||||
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> {
|
||||||
@@ -133,14 +156,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()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,85 +195,113 @@ 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.excludeApplications(
|
||||||
|
_uiState.value.checkedPackageNames,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (this.junkPacketCount.isNotEmpty()) {
|
||||||
|
builder.setJunkPacketCount(
|
||||||
|
this.junkPacketCount.trim().toInt(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (this.junkPacketMinSize.isNotEmpty()) {
|
||||||
builder.setJunkPacketMinSize(
|
builder.setJunkPacketMinSize(
|
||||||
_uiState.value.interfaceProxy.junkPacketMinSize.trim().toInt(),
|
this.junkPacketMinSize.trim().toInt(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (_uiState.value.interfaceProxy.junkPacketMaxSize.isNotEmpty()) {
|
if (this.junkPacketMaxSize.isNotEmpty()) {
|
||||||
builder.setJunkPacketMaxSize(
|
builder.setJunkPacketMaxSize(
|
||||||
_uiState.value.interfaceProxy.junkPacketMaxSize.trim().toInt(),
|
this.junkPacketMaxSize.trim().toInt(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (_uiState.value.interfaceProxy.initPacketJunkSize.isNotEmpty()) {
|
if (this.initPacketJunkSize.isNotEmpty()) {
|
||||||
builder.setInitPacketJunkSize(
|
builder.setInitPacketJunkSize(
|
||||||
_uiState.value.interfaceProxy.initPacketJunkSize.trim().toInt(),
|
this.initPacketJunkSize.trim().toInt(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (_uiState.value.interfaceProxy.responsePacketJunkSize.isNotEmpty()) {
|
if (this.responsePacketJunkSize.isNotEmpty()) {
|
||||||
builder.setResponsePacketJunkSize(
|
builder.setResponsePacketJunkSize(
|
||||||
_uiState.value.interfaceProxy.responsePacketJunkSize.trim().toInt(),
|
this.responsePacketJunkSize.trim().toInt(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (_uiState.value.interfaceProxy.initPacketMagicHeader.isNotEmpty()) {
|
if (this.initPacketMagicHeader.isNotEmpty()) {
|
||||||
builder.setInitPacketMagicHeader(
|
builder.setInitPacketMagicHeader(
|
||||||
_uiState.value.interfaceProxy.initPacketMagicHeader.trim().toLong(),
|
this.initPacketMagicHeader.trim().toLong(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (_uiState.value.interfaceProxy.responsePacketMagicHeader.isNotEmpty()) {
|
if (this.responsePacketMagicHeader.isNotEmpty()) {
|
||||||
builder.setResponsePacketMagicHeader(
|
builder.setResponsePacketMagicHeader(
|
||||||
_uiState.value.interfaceProxy.responsePacketMagicHeader.trim().toLong(),
|
this.responsePacketMagicHeader.trim().toLong(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (_uiState.value.interfaceProxy.transportPacketMagicHeader.isNotEmpty()) {
|
if (this.transportPacketMagicHeader.isNotEmpty()) {
|
||||||
builder.setTransportPacketMagicHeader(
|
builder.setTransportPacketMagicHeader(
|
||||||
_uiState.value.interfaceProxy.transportPacketMagicHeader.trim().toLong(),
|
this.transportPacketMagicHeader.trim().toLong(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (_uiState.value.interfaceProxy.underloadPacketMagicHeader.isNotEmpty()) {
|
if (this.underloadPacketMagicHeader.isNotEmpty()) {
|
||||||
builder.setUnderloadPacketMagicHeader(
|
builder.setUnderloadPacketMagicHeader(
|
||||||
_uiState.value.interfaceProxy.underloadPacketMagicHeader.trim().toLong(),
|
this.underloadPacketMagicHeader.trim().toLong(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return builder.build()
|
return builder.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,38 +314,39 @@ constructor(
|
|||||||
private fun buildAmConfig(): org.amnezia.awg.config.Config {
|
private fun buildAmConfig(): org.amnezia.awg.config.Config {
|
||||||
val peerList = buildAmPeerListFromProxyPeers()
|
val peerList = buildAmPeerListFromProxyPeers()
|
||||||
val amInterface = buildAmInterfaceListFromProxyInterface()
|
val amInterface = buildAmInterfaceListFromProxyInterface()
|
||||||
return org.amnezia.awg.config.Config.Builder().addPeers(peerList).setInterface(amInterface)
|
return org.amnezia.awg.config.Config.Builder().addPeers(
|
||||||
|
peerList,
|
||||||
|
).setInterface(amInterface)
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onSaveAllChanges(configType: ConfigType): Result<Unit> {
|
fun onSaveAllChanges() = 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 = "")
|
_saved.emit(true)
|
||||||
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -378,7 +429,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(),
|
||||||
),
|
),
|
||||||
@@ -389,16 +440,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),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -406,30 +456,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)) {
|
||||||
@@ -451,7 +500,7 @@ 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),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -459,7 +508,7 @@ constructor(
|
|||||||
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),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -467,7 +516,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),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -475,7 +524,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),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -483,7 +532,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,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -491,7 +543,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,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -499,7 +554,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,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -507,7 +565,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,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -515,8 +576,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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+68
-20
@@ -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()
|
||||||
@@ -41,7 +44,7 @@ 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 = (i.dnsServers + i.dnsSearchDomains).joinToString(", ").replace("/", "").trim(),
|
||||||
listenPort =
|
listenPort =
|
||||||
if (i.listenPort.isPresent) {
|
if (i.listenPort.isPresent) {
|
||||||
i.listenPort.get().toString().trim()
|
i.listenPort.get().toString().trim()
|
||||||
@@ -49,24 +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()
|
junkPacketCount =
|
||||||
.toString() else "",
|
if (i.junkPacketCount.isPresent) {
|
||||||
junkPacketMinSize = if (i.junkPacketMinSize.isPresent) i.junkPacketMinSize.get()
|
i.junkPacketCount.get()
|
||||||
.toString() else "",
|
.toString()
|
||||||
junkPacketMaxSize = if (i.junkPacketMaxSize.isPresent) i.junkPacketMaxSize.get()
|
} else {
|
||||||
.toString() else "",
|
""
|
||||||
initPacketJunkSize = if (i.initPacketJunkSize.isPresent) i.initPacketJunkSize.get()
|
},
|
||||||
.toString() else "",
|
junkPacketMinSize =
|
||||||
responsePacketJunkSize = if (i.responsePacketJunkSize.isPresent) i.responsePacketJunkSize.get()
|
if (i.junkPacketMinSize.isPresent) {
|
||||||
.toString() else "",
|
i.junkPacketMinSize.get()
|
||||||
initPacketMagicHeader = if (i.initPacketMagicHeader.isPresent) i.initPacketMagicHeader.get()
|
.toString()
|
||||||
.toString() else "",
|
} else {
|
||||||
responsePacketMagicHeader = if (i.responsePacketMagicHeader.isPresent) i.responsePacketMagicHeader.get()
|
""
|
||||||
.toString() else "",
|
},
|
||||||
transportPacketMagicHeader = if (i.transportPacketMagicHeader.isPresent) i.transportPacketMagicHeader.get()
|
junkPacketMaxSize =
|
||||||
.toString() else "",
|
if (i.junkPacketMaxSize.isPresent) {
|
||||||
underloadPacketMagicHeader = if (i.underloadPacketMagicHeader.isPresent) i.underloadPacketMagicHeader.get()
|
i.junkPacketMaxSize.get()
|
||||||
.toString() else "",
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
initPacketJunkSize =
|
||||||
|
if (i.initPacketJunkSize.isPresent) {
|
||||||
|
i.initPacketJunkSize.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
responsePacketJunkSize =
|
||||||
|
if (i.responsePacketJunkSize.isPresent) {
|
||||||
|
i.responsePacketJunkSize.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
initPacketMagicHeader =
|
||||||
|
if (i.initPacketMagicHeader.isPresent) {
|
||||||
|
i.initPacketMagicHeader.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
responsePacketMagicHeader =
|
||||||
|
if (i.responsePacketMagicHeader.isPresent) {
|
||||||
|
i.responsePacketMagicHeader.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
transportPacketMagicHeader =
|
||||||
|
if (i.transportPacketMagicHeader.isPresent) {
|
||||||
|
i.transportPacketMagicHeader.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
|
underloadPacketMagicHeader =
|
||||||
|
if (i.underloadPacketMagicHeader.isPresent) {
|
||||||
|
i.underloadPacketMagicHeader.get()
|
||||||
|
.toString()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@ data class PeerProxy(
|
|||||||
val preSharedKey: String = "",
|
val preSharedKey: String = "",
|
||||||
val persistentKeepalive: String = "",
|
val persistentKeepalive: String = "",
|
||||||
val endpoint: String = "",
|
val endpoint: String = "",
|
||||||
val allowedIps: String = IPV4_WILDCARD.joinToString(", ").trim()
|
val allowedIps: String = IPV4_WILDCARD.joinToString(", ").trim(),
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun from(peer: Peer): PeerProxy {
|
fun from(peer: Peer): PeerProxy {
|
||||||
|
|||||||
@@ -2,5 +2,5 @@ package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
|||||||
|
|
||||||
enum class ConfigType {
|
enum class ConfigType {
|
||||||
AMNEZIA,
|
AMNEZIA,
|
||||||
WIREGUARD
|
WIREGUARD,
|
||||||
}
|
}
|
||||||
|
|||||||
+103
-622
@@ -1,259 +1,147 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.content.Context
|
import android.net.VpnService
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.Build
|
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
|
||||||
import androidx.compose.animation.fadeIn
|
|
||||||
import androidx.compose.animation.fadeOut
|
|
||||||
import androidx.compose.animation.slideInVertically
|
|
||||||
import androidx.compose.animation.slideOutVertically
|
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.focusGroup
|
|
||||||
import androidx.compose.foundation.focusable
|
|
||||||
import androidx.compose.foundation.gestures.ScrollableDefaults
|
import androidx.compose.foundation.gestures.ScrollableDefaults
|
||||||
import androidx.compose.foundation.gestures.detectTapGestures
|
import androidx.compose.foundation.gestures.detectTapGestures
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
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.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.overscroll
|
import androidx.compose.foundation.overscroll
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.foundation.text.ClickableText
|
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Create
|
import androidx.compose.material.icons.filled.Add
|
||||||
import androidx.compose.material.icons.filled.FileOpen
|
|
||||||
import androidx.compose.material.icons.filled.QrCode
|
|
||||||
import androidx.compose.material.icons.rounded.Bolt
|
|
||||||
import androidx.compose.material.icons.rounded.Circle
|
|
||||||
import androidx.compose.material.icons.rounded.CopyAll
|
|
||||||
import androidx.compose.material.icons.rounded.Delete
|
|
||||||
import androidx.compose.material.icons.rounded.Info
|
|
||||||
import androidx.compose.material.icons.rounded.Settings
|
|
||||||
import androidx.compose.material.icons.rounded.Smartphone
|
|
||||||
import androidx.compose.material.icons.rounded.Star
|
|
||||||
import androidx.compose.material3.AlertDialog
|
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
|
||||||
import androidx.compose.material3.FabPosition
|
import androidx.compose.material3.FabPosition
|
||||||
import androidx.compose.material3.HorizontalDivider
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.ModalBottomSheet
|
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Switch
|
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
|
||||||
import androidx.compose.material3.rememberModalBottomSheetState
|
|
||||||
import androidx.compose.material3.surfaceColorAtElevation
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.derivedStateOf
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
|
||||||
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.Alignment
|
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.geometry.Offset
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
|
||||||
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
|
|
||||||
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
|
|
||||||
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
||||||
import androidx.compose.ui.input.pointer.pointerInput
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.SpanStyle
|
|
||||||
import androidx.compose.ui.text.buildAnnotatedString
|
|
||||||
import androidx.compose.ui.text.font.FontStyle
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.text.withStyle
|
|
||||||
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.navigation.NavController
|
|
||||||
import com.iamageo.multifablibrary.FabIcon
|
|
||||||
import com.iamageo.multifablibrary.FabOption
|
|
||||||
import com.iamageo.multifablibrary.MultiFabItem
|
|
||||||
import com.iamageo.multifablibrary.MultiFloatingActionButton
|
|
||||||
import com.journeyapps.barcodescanner.ScanContract
|
import com.journeyapps.barcodescanner.ScanContract
|
||||||
import com.journeyapps.barcodescanner.ScanOptions
|
import com.journeyapps.barcodescanner.ScanOptions
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
|
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
import com.zaneschepke.wireguardautotunnel.ui.common.NestedScrollListener
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.CaptureActivityPortrait
|
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.InfoDialog
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
import com.zaneschepke.wireguardautotunnel.ui.common.functions.rememberFileImportLauncherForResult
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.RowListItem
|
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.screen.LoadingScreen
|
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.theme.corn
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.AutoTunnelRowItem
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.theme.mint
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.GettingStartedLabel
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.ScrollDismissFab
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.TunnelImportSheet
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.TunnelRowItem
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.VpnDeniedDialog
|
||||||
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 com.zaneschepke.wireguardautotunnel.util.handshakeStatus
|
import com.zaneschepke.wireguardautotunnel.util.extensions.openWebUrl
|
||||||
import com.zaneschepke.wireguardautotunnel.util.mapPeerStats
|
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
|
|
||||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
|
@OptIn(ExperimentalFoundationApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun MainScreen(
|
fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState, focusRequester: FocusRequester) {
|
||||||
viewModel: MainViewModel = hiltViewModel(),
|
|
||||||
appViewModel: AppViewModel,
|
|
||||||
focusRequester: FocusRequester,
|
|
||||||
navController: NavController
|
|
||||||
) {
|
|
||||||
val haptic = LocalHapticFeedback.current
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val isVisible = rememberSaveable { mutableStateOf(true) }
|
val navController = LocalNavController.current
|
||||||
val scope = rememberCoroutineScope()
|
val snackbar = SnackbarController.current
|
||||||
|
|
||||||
val sheetState = rememberModalBottomSheetState()
|
|
||||||
var showBottomSheet by remember { mutableStateOf(false) }
|
var showBottomSheet by remember { mutableStateOf(false) }
|
||||||
var configType by remember { mutableStateOf(ConfigType.WIREGUARD) }
|
var showVpnPermissionDialog by remember { mutableStateOf(false) }
|
||||||
|
var isFabVisible by rememberSaveable { mutableStateOf(true) }
|
||||||
// Nested scroll for control FAB
|
|
||||||
val nestedScrollConnection = remember {
|
|
||||||
object : NestedScrollConnection {
|
|
||||||
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
|
|
||||||
// Hide FAB
|
|
||||||
if (available.y < -1) {
|
|
||||||
isVisible.value = false
|
|
||||||
}
|
|
||||||
// Show FAB
|
|
||||||
if (available.y > 1) {
|
|
||||||
isVisible.value = true
|
|
||||||
}
|
|
||||||
|
|
||||||
return Offset.Zero
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) }
|
var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) }
|
||||||
var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) }
|
var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) }
|
||||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
|
||||||
|
val nestedScrollConnection = remember {
|
||||||
|
NestedScrollListener({ isFabVisible = false }, { isFabVisible = true })
|
||||||
|
}
|
||||||
|
|
||||||
|
val vpnActivityResultState =
|
||||||
|
rememberLauncherForActivityResult(
|
||||||
|
ActivityResultContracts.StartActivityForResult(),
|
||||||
|
onResult = {
|
||||||
|
if (it.resultCode != RESULT_OK) showVpnPermissionDialog = true
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
if (context.isRunningOnTv()) {
|
||||||
|
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||||
|
runCatching {
|
||||||
|
focusRequester.requestFocus()
|
||||||
|
}.onFailure {
|
||||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||||
focusRequester.requestFocus()
|
focusRequester.requestFocus()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val tunnelFileImportResultLauncher =
|
val tunnelFileImportResultLauncher = rememberFileImportLauncherForResult(onNoFileExplorer = {
|
||||||
rememberLauncherForActivityResult(
|
snackbar.showMessage(
|
||||||
object : ActivityResultContracts.GetContent() {
|
context.getString(R.string.error_no_file_explorer),
|
||||||
override fun createIntent(context: Context, input: String): Intent {
|
)
|
||||||
val intent = super.createIntent(context, input)
|
}, onData = { data ->
|
||||||
|
viewModel.onTunnelFileSelected(data, context)
|
||||||
|
})
|
||||||
|
|
||||||
/* 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)
|
|
||||||
}
|
|
||||||
) {
|
|
||||||
appViewModel.showSnackbarMessage(context.getString(R.string.error_no_file_explorer))
|
|
||||||
}
|
|
||||||
return intent
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) { data ->
|
|
||||||
if (data == null) return@rememberLauncherForActivityResult
|
|
||||||
scope.launch {
|
|
||||||
viewModel.onTunnelFileSelected(data, configType, context).onFailure {
|
|
||||||
appViewModel.showSnackbarMessage(it.getMessage(context))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val scanLauncher =
|
val scanLauncher =
|
||||||
rememberLauncherForActivityResult(
|
rememberLauncherForActivityResult(
|
||||||
contract = ScanContract(),
|
contract = ScanContract(),
|
||||||
onResult = {
|
onResult = {
|
||||||
if (it.contents != null) {
|
if (it.contents != null) {
|
||||||
scope.launch {
|
viewModel.onTunnelQrResult(it.contents)
|
||||||
viewModel.onTunnelQrResult(it.contents, configType).onFailure { error ->
|
|
||||||
appViewModel.showSnackbarMessage(error.getMessage(context))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
AnimatedVisibility(showDeleteTunnelAlertDialog) {
|
VpnDeniedDialog(showVpnPermissionDialog, onDismiss = { showVpnPermissionDialog = false })
|
||||||
AlertDialog(
|
|
||||||
onDismissRequest = { showDeleteTunnelAlertDialog = false },
|
if (showDeleteTunnelAlertDialog) {
|
||||||
confirmButton = {
|
InfoDialog(
|
||||||
TextButton(
|
onDismiss = { showDeleteTunnelAlertDialog = false },
|
||||||
onClick = {
|
onAttest = {
|
||||||
selectedTunnel?.let { viewModel.onDelete(it, context) }
|
selectedTunnel?.let { viewModel.onDelete(it, context) }
|
||||||
showDeleteTunnelAlertDialog = false
|
showDeleteTunnelAlertDialog = false
|
||||||
selectedTunnel = null
|
selectedTunnel = null
|
||||||
},
|
},
|
||||||
) {
|
|
||||||
Text(text = stringResource(R.string.yes))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
dismissButton = {
|
|
||||||
TextButton(onClick = { showDeleteTunnelAlertDialog = false }) {
|
|
||||||
Text(text = stringResource(R.string.cancel))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
title = { Text(text = stringResource(R.string.delete_tunnel)) },
|
title = { Text(text = stringResource(R.string.delete_tunnel)) },
|
||||||
text = { Text(text = stringResource(R.string.delete_tunnel_message)) },
|
body = { Text(text = stringResource(R.string.delete_tunnel_message)) },
|
||||||
|
confirmText = { Text(text = stringResource(R.string.yes)) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) {
|
fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) {
|
||||||
if (appViewModel.isRequiredPermissionGranted()) {
|
val intent = if (uiState.settings.isKernelEnabled) null else VpnService.prepare(context)
|
||||||
if (checked) viewModel.onTunnelStart(tunnel, context) else viewModel.onTunnelStop(
|
if (intent != null) return vpnActivityResultState.launch(intent)
|
||||||
context,
|
if (!checked) viewModel.onTunnelStop(tunnel).also { return }
|
||||||
)
|
if (uiState.settings.isKernelEnabled) {
|
||||||
|
context.startTunnelBackground(tunnel.id)
|
||||||
|
} else {
|
||||||
|
viewModel.onTunnelStart(tunnel)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (uiState.loading) {
|
|
||||||
return LoadingScreen()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun launchQrScanner() {
|
fun launchQrScanner() {
|
||||||
val scanOptions = ScanOptions()
|
val scanOptions = ScanOptions()
|
||||||
scanOptions.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
scanOptions.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
||||||
@@ -262,174 +150,44 @@ fun MainScreen(
|
|||||||
context.getString(R.string.scanning_qr),
|
context.getString(R.string.scanning_qr),
|
||||||
)
|
)
|
||||||
scanOptions.setBeepEnabled(false)
|
scanOptions.setBeepEnabled(false)
|
||||||
scanOptions.captureActivity =
|
|
||||||
CaptureActivityPortrait::class.java
|
|
||||||
scanLauncher.launch(scanOptions)
|
scanLauncher.launch(scanOptions)
|
||||||
}
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
modifier =
|
modifier =
|
||||||
Modifier.pointerInput(Unit) {
|
Modifier.pointerInput(Unit) {
|
||||||
if (uiState.tunnels.isNotEmpty()) {
|
if (uiState.tunnels.isEmpty()) return@pointerInput
|
||||||
detectTapGestures(
|
detectTapGestures(
|
||||||
onTap = {
|
onTap = {
|
||||||
selectedTunnel = null
|
selectedTunnel = null
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
|
||||||
|
|
||||||
},
|
},
|
||||||
floatingActionButtonPosition = FabPosition.End,
|
floatingActionButtonPosition = FabPosition.End,
|
||||||
floatingActionButton = {
|
floatingActionButton = {
|
||||||
AnimatedVisibility(
|
ScrollDismissFab({
|
||||||
visible = isVisible.value,
|
val icon = Icons.Filled.Add
|
||||||
enter = slideInVertically(initialOffsetY = { it * 2 }),
|
Icon(
|
||||||
exit = slideOutVertically(targetOffsetY = { it * 2 }),
|
imageVector = icon,
|
||||||
modifier = Modifier
|
contentDescription = icon.name,
|
||||||
.focusRequester(focusRequester)
|
tint = MaterialTheme.colorScheme.onPrimary,
|
||||||
.focusGroup(),
|
|
||||||
) {
|
|
||||||
val secondaryColor = MaterialTheme.colorScheme.secondary
|
|
||||||
val tvFobColor = MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp)
|
|
||||||
val fobColor =
|
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) tvFobColor else secondaryColor
|
|
||||||
val fobIconColor =
|
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) Color.White else MaterialTheme.colorScheme.background
|
|
||||||
MultiFloatingActionButton(
|
|
||||||
fabIcon = FabIcon(
|
|
||||||
iconRes = R.drawable.add,
|
|
||||||
iconResAfterRotate = R.drawable.close,
|
|
||||||
iconRotate = 180f,
|
|
||||||
),
|
|
||||||
fabOption = FabOption(
|
|
||||||
iconTint = fobIconColor,
|
|
||||||
backgroundTint = fobColor,
|
|
||||||
),
|
|
||||||
itemsMultiFab = listOf(
|
|
||||||
MultiFabItem(
|
|
||||||
label = {
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.amnezia),
|
|
||||||
color = Color.White,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(end = 10.dp),
|
|
||||||
)
|
)
|
||||||
},
|
}, focusRequester, isVisible = isFabVisible, onClick = {
|
||||||
modifier = Modifier
|
|
||||||
.size(40.dp),
|
|
||||||
icon = R.drawable.add,
|
|
||||||
value = ConfigType.AMNEZIA.name,
|
|
||||||
miniFabOption = FabOption(
|
|
||||||
backgroundTint = fobColor,
|
|
||||||
fobIconColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
MultiFabItem(
|
|
||||||
label = {
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.wireguard),
|
|
||||||
color = Color.White,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(end = 10.dp),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
icon = R.drawable.add,
|
|
||||||
value = ConfigType.WIREGUARD.name,
|
|
||||||
miniFabOption = FabOption(
|
|
||||||
backgroundTint = fobColor,
|
|
||||||
fobIconColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
onFabItemClicked = {
|
|
||||||
showBottomSheet = true
|
showBottomSheet = true
|
||||||
configType = ConfigType.valueOf(it.value)
|
})
|
||||||
},
|
|
||||||
shape = RoundedCornerShape(16.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
if (showBottomSheet) {
|
TunnelImportSheet(
|
||||||
ModalBottomSheet(
|
showBottomSheet,
|
||||||
onDismissRequest = {
|
onDismiss = { showBottomSheet = false },
|
||||||
showBottomSheet = false
|
onFileClick = { tunnelFileImportResultLauncher.launch(Constants.ALLOWED_TV_FILE_TYPES) },
|
||||||
|
onQrClick = { launchQrScanner() },
|
||||||
},
|
onManualImportClick = {
|
||||||
sheetState = sheetState,
|
|
||||||
) {
|
|
||||||
// Sheet content
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.clickable {
|
|
||||||
showBottomSheet = false
|
|
||||||
tunnelFileImportResultLauncher.launch(Constants.ALLOWED_FILE_TYPES)
|
|
||||||
}
|
|
||||||
.padding(10.dp),
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
Icons.Filled.FileOpen,
|
|
||||||
contentDescription = stringResource(id = R.string.open_file),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.add_tunnels_text),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
|
||||||
HorizontalDivider()
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.clickable {
|
|
||||||
scope.launch {
|
|
||||||
showBottomSheet = false
|
|
||||||
launchQrScanner()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding(10.dp),
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
Icons.Filled.QrCode,
|
|
||||||
contentDescription = stringResource(id = R.string.qr_scan),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.add_from_qr),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
HorizontalDivider()
|
|
||||||
Row(
|
|
||||||
modifier =
|
|
||||||
Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.clickable {
|
|
||||||
showBottomSheet = false
|
|
||||||
navController.navigate(
|
navController.navigate(
|
||||||
"${Screen.Config.route}/${Constants.MANUAL_TUNNEL_CONFIG_ID}?configType=${configType}",
|
Route.Config(Constants.MANUAL_TUNNEL_CONFIG_ID),
|
||||||
)
|
)
|
||||||
}
|
},
|
||||||
.padding(10.dp),
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
Icons.Filled.Create,
|
|
||||||
contentDescription = stringResource(id = R.string.create_import),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
)
|
||||||
Text(
|
|
||||||
stringResource(id = R.string.create_import),
|
|
||||||
modifier = Modifier.padding(10.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
horizontalAlignment = Alignment.Start,
|
horizontalAlignment = Alignment.Start,
|
||||||
verticalArrangement = Arrangement.Top,
|
verticalArrangement = Arrangement.Top,
|
||||||
@@ -443,314 +201,37 @@ fun MainScreen(
|
|||||||
reverseLayout = false,
|
reverseLayout = false,
|
||||||
flingBehavior = ScrollableDefaults.flingBehavior(),
|
flingBehavior = ScrollableDefaults.flingBehavior(),
|
||||||
) {
|
) {
|
||||||
|
if (uiState.tunnels.isEmpty()) {
|
||||||
item {
|
item {
|
||||||
AnimatedVisibility(
|
GettingStartedLabel(onClick = { context.openWebUrl(it) })
|
||||||
uiState.tunnels.isEmpty(), exit = fadeOut(), enter = fadeIn(),
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
verticalArrangement = Arrangement.Center,
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(top = 100.dp)
|
|
||||||
.fillMaxSize(),
|
|
||||||
) {
|
|
||||||
val gettingStarted = buildAnnotatedString {
|
|
||||||
append(stringResource(id = R.string.see_the))
|
|
||||||
append(" ")
|
|
||||||
pushStringAnnotation(
|
|
||||||
tag = "gettingStarted",
|
|
||||||
annotation = stringResource(id = R.string.getting_started_url),
|
|
||||||
)
|
|
||||||
withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.primary)) {
|
|
||||||
append(stringResource(id = R.string.getting_started_guide))
|
|
||||||
}
|
|
||||||
pop()
|
|
||||||
append(" ")
|
|
||||||
append(stringResource(R.string.unsure_how))
|
|
||||||
append(".")
|
|
||||||
}
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.no_tunnels),
|
|
||||||
fontStyle = FontStyle.Italic,
|
|
||||||
)
|
|
||||||
ClickableText(
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(vertical = 10.dp, horizontal = 24.dp),
|
|
||||||
text = gettingStarted,
|
|
||||||
style = MaterialTheme.typography.bodyMedium.copy(
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
),
|
|
||||||
) {
|
|
||||||
gettingStarted.getStringAnnotations(tag = "gettingStarted", it, it)
|
|
||||||
.firstOrNull()?.let { annotation ->
|
|
||||||
appViewModel.openWebPage(annotation.item, context)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
item {
|
|
||||||
if (uiState.settings.isAutoTunnelEnabled) {
|
if (uiState.settings.isAutoTunnelEnabled) {
|
||||||
val autoTunnelingLabel = buildAnnotatedString {
|
item {
|
||||||
append(stringResource(id = R.string.auto_tunneling))
|
AutoTunnelRowItem(uiState.settings, { viewModel.onToggleAutoTunnelingPause() }, focusRequester)
|
||||||
append(": ")
|
|
||||||
if (uiState.settings.isAutoTunnelPaused) append(
|
|
||||||
stringResource(id = R.string.paused),
|
|
||||||
) else append(
|
|
||||||
stringResource(id = R.string.active),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
RowListItem(
|
|
||||||
icon = {
|
|
||||||
val icon = Icons.Rounded.Bolt
|
|
||||||
Icon(
|
|
||||||
icon,
|
|
||||||
icon.name,
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(end = 8.5.dp)
|
|
||||||
.size(25.dp),
|
|
||||||
tint =
|
|
||||||
if (uiState.settings.isAutoTunnelPaused) Color.Gray
|
|
||||||
else mint,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
text = autoTunnelingLabel.text,
|
|
||||||
rowButton = {
|
|
||||||
if (uiState.settings.isAutoTunnelPaused) {
|
|
||||||
TextButton(
|
|
||||||
onClick = { viewModel.resumeAutoTunneling() },
|
|
||||||
) {
|
|
||||||
Text(stringResource(id = R.string.resume))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
TextButton(
|
|
||||||
onClick = { viewModel.pauseAutoTunneling() },
|
|
||||||
) {
|
|
||||||
Text(stringResource(id = R.string.pause))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onClick = {},
|
|
||||||
onHold = {},
|
|
||||||
expanded = false,
|
|
||||||
statistics = null,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
items(
|
items(
|
||||||
uiState.tunnels,
|
uiState.tunnels,
|
||||||
key = { tunnel -> tunnel.id },
|
key = { tunnel -> tunnel.id },
|
||||||
) { tunnel ->
|
) { tunnel ->
|
||||||
val leadingIconColor =
|
val isActive = uiState.tunnels.any {
|
||||||
(if (
|
it.id == tunnel.id &&
|
||||||
uiState.vpnState.tunnelConfig?.name == tunnel.name &&
|
it.isActive
|
||||||
uiState.vpnState.status == TunnelState.UP
|
|
||||||
) {
|
|
||||||
uiState.vpnState.statistics
|
|
||||||
?.mapPeerStats()
|
|
||||||
?.map { it.value?.handshakeStatus() }
|
|
||||||
.let { statuses ->
|
|
||||||
when {
|
|
||||||
statuses?.all { it == HandshakeStatus.HEALTHY } == true -> mint
|
|
||||||
statuses?.any { it == HandshakeStatus.STALE } == true -> corn
|
|
||||||
statuses?.all { it == HandshakeStatus.NOT_STARTED } == true ->
|
|
||||||
Color.Gray
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
Color.Gray
|
|
||||||
}
|
}
|
||||||
}
|
val expanded = uiState.generalState.isTunnelStatsExpanded
|
||||||
}
|
TunnelRowItem(
|
||||||
} else {
|
isActive,
|
||||||
Color.Gray
|
expanded,
|
||||||
})
|
selectedTunnel?.id == tunnel.id,
|
||||||
val expanded = remember { mutableStateOf(false) }
|
tunnel,
|
||||||
RowListItem(
|
vpnState = uiState.vpnState,
|
||||||
icon = {
|
{ selectedTunnel = tunnel },
|
||||||
val circleIcon = Icons.Rounded.Circle
|
{ viewModel.onExpandedChanged(!expanded) },
|
||||||
val icon = if (tunnel.isPrimaryTunnel) {
|
onDelete = { showDeleteTunnelAlertDialog = true },
|
||||||
Icons.Rounded.Star
|
onCopy = { viewModel.onCopyTunnel(tunnel) },
|
||||||
} else if (tunnel.isMobileDataTunnel) {
|
onSwitchClick = { onTunnelToggle(it, tunnel) },
|
||||||
Icons.Rounded.Smartphone
|
focusRequester = focusRequester,
|
||||||
} else {
|
|
||||||
circleIcon
|
|
||||||
}
|
|
||||||
Icon(
|
|
||||||
icon,
|
|
||||||
icon.name,
|
|
||||||
tint = leadingIconColor,
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(
|
|
||||||
end = if (icon == circleIcon) 12.5.dp else 10.dp,
|
|
||||||
start = if (icon == circleIcon) 2.5.dp else 0.dp,
|
|
||||||
)
|
|
||||||
.size(if (icon == circleIcon) 15.dp else 20.dp),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
text = tunnel.name,
|
|
||||||
onHold = {
|
|
||||||
if (
|
|
||||||
(uiState.vpnState.status == TunnelState.UP) &&
|
|
||||||
(tunnel.name == uiState.vpnState.tunnelConfig?.name)
|
|
||||||
) {
|
|
||||||
appViewModel.showSnackbarMessage(context.getString(R.string.turn_off_tunnel))
|
|
||||||
return@RowListItem
|
|
||||||
}
|
|
||||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
|
||||||
selectedTunnel = tunnel
|
|
||||||
},
|
|
||||||
onClick = {
|
|
||||||
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
|
||||||
if (
|
|
||||||
uiState.vpnState.status == TunnelState.UP &&
|
|
||||||
(uiState.vpnState.tunnelConfig?.name == tunnel.name)
|
|
||||||
) {
|
|
||||||
expanded.value = !expanded.value
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
selectedTunnel = tunnel
|
|
||||||
focusRequester.requestFocus()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
statistics = uiState.vpnState.statistics,
|
|
||||||
expanded = expanded.value,
|
|
||||||
rowButton = {
|
|
||||||
if (
|
|
||||||
tunnel.id == selectedTunnel?.id &&
|
|
||||||
!WireGuardAutoTunnel.isRunningOnAndroidTv()
|
|
||||||
) {
|
|
||||||
Row {
|
|
||||||
IconButton(
|
|
||||||
onClick = {
|
|
||||||
if (
|
|
||||||
uiState.settings.isAutoTunnelEnabled &&
|
|
||||||
!uiState.settings.isAutoTunnelPaused
|
|
||||||
) {
|
|
||||||
appViewModel.showSnackbarMessage(
|
|
||||||
context.getString(R.string.turn_off_tunnel),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
navController.navigate(
|
|
||||||
"${Screen.Option.route}/${selectedTunnel?.id}",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
val icon = Icons.Rounded.Settings
|
|
||||||
Icon(
|
|
||||||
icon,
|
|
||||||
icon.name,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
IconButton(
|
|
||||||
modifier = Modifier.focusable(),
|
|
||||||
onClick = { viewModel.onCopyTunnel(selectedTunnel) },
|
|
||||||
) {
|
|
||||||
val icon = Icons.Rounded.CopyAll
|
|
||||||
Icon(icon, icon.name)
|
|
||||||
}
|
|
||||||
IconButton(
|
|
||||||
modifier = Modifier.focusable(),
|
|
||||||
onClick = { showDeleteTunnelAlertDialog = true },
|
|
||||||
) {
|
|
||||||
val icon = Icons.Rounded.Delete
|
|
||||||
Icon(icon, icon.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
val checked by remember {
|
|
||||||
derivedStateOf {
|
|
||||||
(uiState.vpnState.status == TunnelState.UP &&
|
|
||||||
tunnel.name == uiState.vpnState.tunnelConfig?.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!checked) expanded.value = false
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun TunnelSwitch() =
|
|
||||||
Switch(
|
|
||||||
modifier = Modifier.focusRequester(focusRequester),
|
|
||||||
checked = checked,
|
|
||||||
onCheckedChange = { checked ->
|
|
||||||
if (!checked) expanded.value = false
|
|
||||||
onTunnelToggle(checked, tunnel)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
|
|
||||||
Row {
|
|
||||||
IconButton(
|
|
||||||
onClick = {
|
|
||||||
if (uiState.settings.isAutoTunnelEnabled) {
|
|
||||||
appViewModel.showSnackbarMessage(
|
|
||||||
context.getString(R.string.turn_off_auto),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
selectedTunnel = tunnel
|
|
||||||
navController.navigate(
|
|
||||||
"${Screen.Option.route}/${selectedTunnel?.id}",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
val icon = Icons.Rounded.Settings
|
|
||||||
Icon(
|
|
||||||
icon,
|
|
||||||
icon.name,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
IconButton(
|
|
||||||
modifier = Modifier.focusRequester(focusRequester),
|
|
||||||
onClick = {
|
|
||||||
if (
|
|
||||||
uiState.vpnState.status == TunnelState.UP &&
|
|
||||||
(uiState.vpnState.tunnelConfig?.name == tunnel.name)
|
|
||||||
) {
|
|
||||||
expanded.value = !expanded.value
|
|
||||||
} else {
|
|
||||||
appViewModel.showSnackbarMessage(
|
|
||||||
context.getString(R.string.turn_on_tunnel),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
val icon = Icons.Rounded.Info
|
|
||||||
Icon(icon, icon.name)
|
|
||||||
}
|
|
||||||
IconButton(
|
|
||||||
onClick = { viewModel.onCopyTunnel(tunnel) },
|
|
||||||
) {
|
|
||||||
val icon = Icons.Rounded.CopyAll
|
|
||||||
Icon(icon, icon.name)
|
|
||||||
}
|
|
||||||
IconButton(
|
|
||||||
onClick = {
|
|
||||||
if (
|
|
||||||
uiState.vpnState.status == TunnelState.UP &&
|
|
||||||
tunnel.name == uiState.vpnState.tunnelConfig?.name
|
|
||||||
) {
|
|
||||||
appViewModel.showSnackbarMessage(
|
|
||||||
context.getString(R.string.turn_off_tunnel),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
selectedTunnel = tunnel
|
|
||||||
showDeleteTunnelAlertDialog = true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
val icon = Icons.Rounded.Delete
|
|
||||||
Icon(
|
|
||||||
icon,
|
|
||||||
icon.name,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
TunnelSwitch()
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
TunnelSwitch()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
|
||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
|
|
||||||
|
|
||||||
data class MainUiState(
|
|
||||||
val settings: Settings = Settings(),
|
|
||||||
val tunnels: TunnelConfigs = emptyList(),
|
|
||||||
val vpnState: VpnState = VpnState(),
|
|
||||||
val loading: Boolean = true
|
|
||||||
)
|
|
||||||
+74
-204
@@ -6,23 +6,22 @@ import android.net.Uri
|
|||||||
import android.provider.OpenableColumns
|
import android.provider.OpenableColumns
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.wireguard.config.Config
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.FileReadException
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.InvalidFileExtensionException
|
||||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||||
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||||
import com.zaneschepke.wireguardautotunnel.util.toWgQuickString
|
import com.zaneschepke.wireguardautotunnel.util.extensions.toWgQuickString
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
|
||||||
import kotlinx.coroutines.flow.combine
|
|
||||||
import kotlinx.coroutines.flow.stateIn
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
@@ -35,27 +34,12 @@ class MainViewModel
|
|||||||
@Inject
|
@Inject
|
||||||
constructor(
|
constructor(
|
||||||
private val appDataRepository: AppDataRepository,
|
private val appDataRepository: AppDataRepository,
|
||||||
private val serviceManager: ServiceManager,
|
val tunnelService: TunnelService,
|
||||||
val vpnService: VpnService,
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
val uiState =
|
|
||||||
combine(
|
|
||||||
appDataRepository.settings.getSettingsFlow(),
|
|
||||||
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
|
||||||
vpnService.vpnState,
|
|
||||||
) { settings, tunnels, vpnState ->
|
|
||||||
MainUiState(settings, tunnels, vpnState, false)
|
|
||||||
}
|
|
||||||
.stateIn(
|
|
||||||
viewModelScope,
|
|
||||||
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
|
||||||
MainUiState(),
|
|
||||||
)
|
|
||||||
|
|
||||||
private fun stopWatcherService(context: Context) {
|
private fun stopWatcherService(context: Context) {
|
||||||
serviceManager.stopWatcherService(context)
|
ServiceManager.stopWatcherService(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onDelete(tunnel: TunnelConfig, context: Context) {
|
fun onDelete(tunnel: TunnelConfig, context: Context) {
|
||||||
@@ -67,7 +51,6 @@ constructor(
|
|||||||
resetTunnelSetting(settings)
|
resetTunnelSetting(settings)
|
||||||
}
|
}
|
||||||
appDataRepository.tunnels.delete(tunnel)
|
appDataRepository.tunnels.delete(tunnel)
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,49 +63,31 @@ constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onTunnelStart(tunnelConfig: TunnelConfig, context: Context) =
|
fun onExpandedChanged(expanded: Boolean) = viewModelScope.launch {
|
||||||
viewModelScope.launch {
|
appDataRepository.appState.setTunnelStatsExpanded(expanded)
|
||||||
Timber.d("On start called!")
|
|
||||||
serviceManager.startVpnService(
|
|
||||||
context,
|
|
||||||
tunnelConfig.id,
|
|
||||||
isManualStart = true,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun onTunnelStart(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||||
|
Timber.i("Starting tunnel ${tunnelConfig.name}")
|
||||||
|
tunnelService.startTunnel(tunnelConfig)
|
||||||
|
}
|
||||||
|
|
||||||
fun onTunnelStop(context: Context) =
|
fun onTunnelStop(tunnel: TunnelConfig) = viewModelScope.launch {
|
||||||
viewModelScope.launch {
|
|
||||||
Timber.i("Stopping active tunnel")
|
Timber.i("Stopping active tunnel")
|
||||||
serviceManager.stopVpnService(context, isManualStop = true)
|
tunnelService.stopTunnel(tunnel)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun validateConfigString(config: String, configType: ConfigType) {
|
private fun generateQrCodeDefaultName(config: String): String {
|
||||||
when (configType) {
|
|
||||||
ConfigType.AMNEZIA -> TunnelConfig.configFromAmQuick(config)
|
|
||||||
ConfigType.WIREGUARD -> TunnelConfig.configFromWgQuick(config)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun generateQrCodeDefaultName(config: String, configType: ConfigType): String {
|
|
||||||
return try {
|
return try {
|
||||||
when (configType) {
|
|
||||||
ConfigType.AMNEZIA -> {
|
|
||||||
TunnelConfig.configFromAmQuick(config).peers[0].endpoint.get().host
|
TunnelConfig.configFromAmQuick(config).peers[0].endpoint.get().host
|
||||||
}
|
|
||||||
|
|
||||||
ConfigType.WIREGUARD -> {
|
|
||||||
TunnelConfig.configFromWgQuick(config).peers[0].endpoint.get().host
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
NumberUtils.generateRandomTunnelName()
|
NumberUtils.generateRandomTunnelName()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun generateQrCodeTunnelName(config: String, configType: ConfigType): String {
|
private fun generateQrCodeTunnelName(config: String): String {
|
||||||
var defaultName = generateQrCodeDefaultName(config, configType)
|
var defaultName = generateQrCodeDefaultName(config)
|
||||||
val lines = config.lines().toMutableList()
|
val lines = config.lines().toMutableList()
|
||||||
val linesIterator = lines.iterator()
|
val linesIterator = lines.iterator()
|
||||||
while (linesIterator.hasNext()) {
|
while (linesIterator.hasNext()) {
|
||||||
@@ -135,27 +100,18 @@ constructor(
|
|||||||
return defaultName
|
return defaultName
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun onTunnelQrResult(result: String, configType: ConfigType): Result<Unit> {
|
fun onTunnelQrResult(result: String) = viewModelScope.launch(ioDispatcher) {
|
||||||
return withContext(ioDispatcher) {
|
kotlin.runCatching {
|
||||||
try {
|
val amConfig = TunnelConfig.configFromAmQuick(result)
|
||||||
validateConfigString(result, configType)
|
val amQuick = amConfig.toAwgQuickString(true)
|
||||||
val tunnelName = makeTunnelNameUnique(generateQrCodeTunnelName(result, configType))
|
val wgQuick = amConfig.toWgQuickString()
|
||||||
val tunnelConfig = when (configType) {
|
|
||||||
ConfigType.AMNEZIA -> {
|
|
||||||
TunnelConfig(
|
|
||||||
name = tunnelName, amQuick = result,
|
|
||||||
wgQuick = TunnelConfig.configFromAmQuick(result).toWgQuickString(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
ConfigType.WIREGUARD -> TunnelConfig(name = tunnelName, wgQuick = result)
|
val tunnelName = makeTunnelNameUnique(generateQrCodeTunnelName(result))
|
||||||
}
|
val tunnelConfig = TunnelConfig(name = tunnelName, wgQuick = wgQuick, amQuick = amQuick)
|
||||||
addTunnel(tunnelConfig)
|
saveTunnel(tunnelConfig)
|
||||||
Result.success(Unit)
|
}.onFailure {
|
||||||
} catch (e: Exception) {
|
Timber.e(it)
|
||||||
Timber.e(e)
|
SnackbarController.showMessage(StringValue.StringResource(R.string.error_invalid_code))
|
||||||
Result.failure(WgTunnelExceptions.InvalidQrCode())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,163 +121,84 @@ constructor(
|
|||||||
var tunnelName = name
|
var tunnelName = name
|
||||||
var num = 1
|
var num = 1
|
||||||
while (tunnels.any { it.name == tunnelName }) {
|
while (tunnels.any { it.name == tunnelName }) {
|
||||||
tunnelName = name + "(${num})"
|
tunnelName = "$name($num)"
|
||||||
num++
|
num++
|
||||||
}
|
}
|
||||||
tunnelName
|
tunnelName
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun saveTunnelConfigFromStream(
|
private suspend fun saveTunnelConfigFromStream(stream: InputStream, fileName: String) {
|
||||||
stream: InputStream,
|
val amConfig = stream.use { org.amnezia.awg.config.Config.parse(it) }
|
||||||
fileName: String,
|
|
||||||
type: ConfigType
|
|
||||||
) {
|
|
||||||
var amQuick: String? = null
|
|
||||||
val wgQuick = stream.use {
|
|
||||||
when (type) {
|
|
||||||
ConfigType.AMNEZIA -> {
|
|
||||||
val config = org.amnezia.awg.config.Config.parse(it)
|
|
||||||
amQuick = config.toAwgQuickString()
|
|
||||||
config.toWgQuickString()
|
|
||||||
}
|
|
||||||
|
|
||||||
ConfigType.WIREGUARD -> {
|
|
||||||
Config.parse(it).toWgQuickString()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
viewModelScope.launch {
|
|
||||||
val tunnelName = makeTunnelNameUnique(getNameFromFileName(fileName))
|
val tunnelName = makeTunnelNameUnique(getNameFromFileName(fileName))
|
||||||
addTunnel(
|
saveTunnel(
|
||||||
TunnelConfig(
|
TunnelConfig(
|
||||||
name = tunnelName,
|
name = tunnelName,
|
||||||
wgQuick = wgQuick,
|
wgQuick = amConfig.toWgQuickString(),
|
||||||
amQuick = amQuick ?: TunnelConfig.AM_QUICK_DEFAULT,
|
amQuick = amConfig.toAwgQuickString(true),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private fun getInputStreamFromUri(uri: Uri, context: Context): InputStream? {
|
private fun getInputStreamFromUri(uri: Uri, context: Context): InputStream? {
|
||||||
return context.applicationContext.contentResolver.openInputStream(uri)
|
return context.applicationContext.contentResolver.openInputStream(uri)
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun onTunnelFileSelected(
|
fun onTunnelFileSelected(uri: Uri, context: Context) = viewModelScope.launch(ioDispatcher) {
|
||||||
uri: Uri,
|
kotlin.runCatching {
|
||||||
configType: ConfigType,
|
if (!isValidUriContentScheme(uri)) throw InvalidFileExtensionException
|
||||||
context: Context
|
|
||||||
): Result<Unit> {
|
|
||||||
return withContext(ioDispatcher) {
|
|
||||||
try {
|
|
||||||
if (isValidUriContentScheme(uri)) {
|
|
||||||
val fileName = getFileName(context, uri)
|
val fileName = getFileName(context, uri)
|
||||||
return@withContext when (getFileExtensionFromFileName(fileName)) {
|
when (getFileExtensionFromFileName(fileName)) {
|
||||||
Constants.CONF_FILE_EXTENSION ->
|
Constants.CONF_FILE_EXTENSION ->
|
||||||
saveTunnelFromConfUri(fileName, uri, configType, context)
|
saveTunnelFromConfUri(fileName, uri, context)
|
||||||
|
Constants.ZIP_FILE_EXTENSION ->
|
||||||
Constants.ZIP_FILE_EXTENSION -> saveTunnelsFromZipUri(
|
saveTunnelsFromZipUri(
|
||||||
uri,
|
uri,
|
||||||
configType,
|
|
||||||
context,
|
context,
|
||||||
)
|
)
|
||||||
|
else -> throw InvalidFileExtensionException
|
||||||
else -> Result.failure(WgTunnelExceptions.InvalidFileExtension())
|
|
||||||
}
|
}
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
if (it is InvalidFileExtensionException) {
|
||||||
|
SnackbarController.showMessage(StringValue.StringResource(R.string.error_file_extension))
|
||||||
} else {
|
} else {
|
||||||
Result.failure(WgTunnelExceptions.InvalidFileExtension())
|
SnackbarController.showMessage(StringValue.StringResource(R.string.error_file_format))
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e(e)
|
|
||||||
Result.failure(WgTunnelExceptions.FileReadFailed())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun saveTunnelsFromZipUri(
|
private suspend fun saveTunnelsFromZipUri(uri: Uri, context: Context) {
|
||||||
uri: Uri,
|
|
||||||
configType: ConfigType,
|
|
||||||
context: Context
|
|
||||||
): Result<Unit> {
|
|
||||||
return withContext(ioDispatcher) {
|
|
||||||
ZipInputStream(getInputStreamFromUri(uri, context)).use { zip ->
|
ZipInputStream(getInputStreamFromUri(uri, context)).use { zip ->
|
||||||
generateSequence { zip.nextEntry }
|
generateSequence { zip.nextEntry }
|
||||||
.filterNot {
|
.filterNot {
|
||||||
it.isDirectory ||
|
it.isDirectory ||
|
||||||
getFileExtensionFromFileName(it.name) != Constants.CONF_FILE_EXTENSION
|
getFileExtensionFromFileName(it.name) != Constants.CONF_FILE_EXTENSION
|
||||||
}
|
}
|
||||||
.forEach {
|
.forEach { entry ->
|
||||||
val name = getNameFromFileName(it.name)
|
val name = getNameFromFileName(entry.name)
|
||||||
withContext(viewModelScope.coroutineContext) {
|
val amConf = org.amnezia.awg.config.Config.parse(zip.bufferedReader())
|
||||||
try {
|
saveTunnel(
|
||||||
var amQuick: String? = null
|
|
||||||
val wgQuick =
|
|
||||||
when (configType) {
|
|
||||||
ConfigType.AMNEZIA -> {
|
|
||||||
val config = org.amnezia.awg.config.Config.parse(zip)
|
|
||||||
amQuick = config.toAwgQuickString()
|
|
||||||
config.toWgQuickString()
|
|
||||||
}
|
|
||||||
|
|
||||||
ConfigType.WIREGUARD -> {
|
|
||||||
Config.parse(zip).toWgQuickString()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
addTunnel(
|
|
||||||
TunnelConfig(
|
TunnelConfig(
|
||||||
name = makeTunnelNameUnique(name),
|
name = makeTunnelNameUnique(name),
|
||||||
wgQuick = wgQuick,
|
wgQuick = amConf.toWgQuickString(),
|
||||||
amQuick = amQuick ?: TunnelConfig.AM_QUICK_DEFAULT,
|
amQuick = amConf.toAwgQuickString(true),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
Result.success(Unit)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Result.failure(WgTunnelExceptions.FileReadFailed())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Result.success(Unit)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun saveTunnelFromConfUri(
|
private suspend fun saveTunnelFromConfUri(name: String, uri: Uri, context: Context) {
|
||||||
name: String,
|
val stream = getInputStreamFromUri(uri, context) ?: throw FileReadException
|
||||||
uri: Uri,
|
saveTunnelConfigFromStream(stream, name)
|
||||||
configType: ConfigType,
|
|
||||||
context: Context
|
|
||||||
): Result<Unit> {
|
|
||||||
return withContext(ioDispatcher) {
|
|
||||||
val stream = getInputStreamFromUri(uri, context)
|
|
||||||
return@withContext if (stream != null) {
|
|
||||||
try {
|
|
||||||
saveTunnelConfigFromStream(stream, name, configType)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
return@withContext Result.failure(WgTunnelExceptions.ConfigParseError())
|
|
||||||
}
|
|
||||||
Result.success(Unit)
|
|
||||||
} else {
|
|
||||||
Result.failure(WgTunnelExceptions.FileReadFailed())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun addTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
fun onToggleAutoTunnelingPause() = viewModelScope.launch {
|
||||||
val firstTunnel = appDataRepository.tunnels.count() == 0
|
val settings = appDataRepository.settings.getSettings()
|
||||||
saveTunnel(tunnelConfig)
|
appDataRepository.settings.save(
|
||||||
if (firstTunnel) WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
settings.copy(isAutoTunnelPaused = !settings.isAutoTunnelPaused),
|
||||||
}
|
)
|
||||||
|
|
||||||
fun pauseAutoTunneling() =
|
|
||||||
viewModelScope.launch {
|
|
||||||
appDataRepository.settings.save(uiState.value.settings.copy(isAutoTunnelPaused = true))
|
|
||||||
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun resumeAutoTunneling() =
|
|
||||||
viewModelScope.launch {
|
|
||||||
appDataRepository.settings.save(uiState.value.settings.copy(isAutoTunnelPaused = false))
|
|
||||||
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun saveTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
private fun saveTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||||
@@ -329,28 +206,23 @@ constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun getFileNameByCursor(context: Context, uri: Uri): String? {
|
private fun getFileNameByCursor(context: Context, uri: Uri): String? {
|
||||||
context.contentResolver.query(uri, null, null, null, null)?.use {
|
return context.contentResolver.query(uri, null, null, null, null)?.use {
|
||||||
return getDisplayNameByCursor(it)
|
getDisplayNameByCursor(it)
|
||||||
}
|
}
|
||||||
return null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getDisplayNameColumnIndex(cursor: Cursor): Int? {
|
private fun getDisplayNameColumnIndex(cursor: Cursor): Int? {
|
||||||
val columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
val columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||||
return if (columnIndex != -1) {
|
if (columnIndex == -1) return null
|
||||||
return columnIndex
|
return columnIndex
|
||||||
} else {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getDisplayNameByCursor(cursor: Cursor): String? {
|
private fun getDisplayNameByCursor(cursor: Cursor): String? {
|
||||||
return if (cursor.moveToFirst()) {
|
val move = cursor.moveToFirst()
|
||||||
|
if (!move) return null
|
||||||
val index = getDisplayNameColumnIndex(cursor)
|
val index = getDisplayNameColumnIndex(cursor)
|
||||||
if (index != null) {
|
if (index == null) return index
|
||||||
cursor.getString(index)
|
return cursor.getString(index)
|
||||||
} else null
|
|
||||||
} else null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isValidUriContentScheme(uri: Uri): Boolean {
|
private fun isValidUriContentScheme(uri: Uri): Boolean {
|
||||||
@@ -374,9 +246,7 @@ constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun saveSettings(settings: Settings) =
|
private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
|
||||||
viewModelScope.launch { appDataRepository.settings.save(settings) }
|
|
||||||
|
|
||||||
|
|
||||||
fun onCopyTunnel(tunnel: TunnelConfig?) = viewModelScope.launch {
|
fun onCopyTunnel(tunnel: TunnelConfig?) = viewModelScope.launch {
|
||||||
tunnel?.let {
|
tunnel?.let {
|
||||||
|
|||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.rounded.Bolt
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.scale
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.ExpandingRowListItem
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.theme.SilverTree
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AutoTunnelRowItem(settings: Settings, onToggle: () -> Unit, focusRequester: FocusRequester) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val itemFocusRequester = remember { FocusRequester() }
|
||||||
|
val autoTunnelingLabel =
|
||||||
|
buildAnnotatedString {
|
||||||
|
append(stringResource(id = R.string.auto_tunneling))
|
||||||
|
append(": ")
|
||||||
|
if (settings.isAutoTunnelPaused) {
|
||||||
|
append(
|
||||||
|
stringResource(id = R.string.paused),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
append(
|
||||||
|
stringResource(id = R.string.active),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ExpandingRowListItem(
|
||||||
|
leading = {
|
||||||
|
val icon = Icons.Rounded.Bolt
|
||||||
|
Icon(
|
||||||
|
icon,
|
||||||
|
icon.name,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.size(iconSize).scale(1.5f),
|
||||||
|
tint =
|
||||||
|
if (settings.isAutoTunnelPaused) {
|
||||||
|
Color.Gray
|
||||||
|
} else {
|
||||||
|
SilverTree
|
||||||
|
},
|
||||||
|
)
|
||||||
|
},
|
||||||
|
text = autoTunnelingLabel.text,
|
||||||
|
trailing = {
|
||||||
|
TextButton(
|
||||||
|
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||||
|
onClick = { onToggle() },
|
||||||
|
) {
|
||||||
|
Text(stringResource(id = if (settings.isAutoTunnelPaused) R.string.resume else R.string.pause))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onClick = {
|
||||||
|
if (context.isRunningOnTv()) {
|
||||||
|
itemFocusRequester.requestFocus()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
isExpanded = false,
|
||||||
|
focusRequester = focusRequester,
|
||||||
|
)
|
||||||
|
}
|
||||||
+71
@@ -0,0 +1,71 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.text.ClickableText
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.SpanStyle
|
||||||
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
|
import androidx.compose.ui.text.font.FontStyle
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.text.withStyle
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun GettingStartedLabel(onClick: (url: String) -> Unit) {
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.padding(top = 100.dp)
|
||||||
|
.fillMaxSize(),
|
||||||
|
) {
|
||||||
|
val gettingStarted =
|
||||||
|
buildAnnotatedString {
|
||||||
|
append(stringResource(id = R.string.see_the))
|
||||||
|
append(" ")
|
||||||
|
pushStringAnnotation(
|
||||||
|
tag = "gettingStarted",
|
||||||
|
annotation = stringResource(id = R.string.getting_started_url),
|
||||||
|
)
|
||||||
|
withStyle(
|
||||||
|
style = SpanStyle(color = MaterialTheme.colorScheme.primary),
|
||||||
|
) {
|
||||||
|
append(stringResource(id = R.string.getting_started_guide))
|
||||||
|
}
|
||||||
|
pop()
|
||||||
|
append(" ")
|
||||||
|
append(stringResource(R.string.unsure_how))
|
||||||
|
append(".")
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.no_tunnels),
|
||||||
|
fontStyle = FontStyle.Italic,
|
||||||
|
)
|
||||||
|
ClickableText(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.padding(vertical = 10.dp, horizontal = 24.dp),
|
||||||
|
text = gettingStarted,
|
||||||
|
style =
|
||||||
|
MaterialTheme.typography.bodyMedium.copy(
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
gettingStarted.getStringAnnotations(tag = "gettingStarted", it, it)
|
||||||
|
.firstOrNull()?.let { annotation ->
|
||||||
|
onClick(annotation.item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||||
|
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.slideInVertically
|
||||||
|
import androidx.compose.animation.slideOutVertically
|
||||||
|
import androidx.compose.foundation.focusGroup
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.FloatingActionButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ScrollDismissFab(icon: @Composable () -> Unit, focusRequester: FocusRequester, isVisible: Boolean, onClick: () -> Unit) {
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = isVisible,
|
||||||
|
enter = slideInVertically(initialOffsetY = { it * 2 }),
|
||||||
|
exit = slideOutVertically(targetOffsetY = { it * 2 }),
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.focusRequester(focusRequester)
|
||||||
|
.focusGroup(),
|
||||||
|
) {
|
||||||
|
FloatingActionButton(
|
||||||
|
onClick = {
|
||||||
|
onClick()
|
||||||
|
},
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
containerColor = MaterialTheme.colorScheme.primary,
|
||||||
|
) {
|
||||||
|
icon()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user