mirror of
https://github.com/wgtunnel/android.git
synced 2026-07-03 14:07:49 +02:00
Compare commits
170 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 44353df400 | |||
| 0da6e3e82c | |||
| dbaf0312f8 | |||
| 7cf7817cea | |||
| 133bd6caf7 | |||
| 25b986ef2f | |||
| fe45a2fad9 | |||
| a3eb53f90f | |||
| 246916ab0d | |||
| 7f89dcaab0 | |||
| 1d2b305047 | |||
| 0201523262 | |||
| fcc1c1e7a1 | |||
| cd82b83789 | |||
| 9f1af0140f | |||
| 14cd49983a | |||
| 40dd14ca16 | |||
| 048bcd4ad7 | |||
| 94bd23f2a4 | |||
| 7285af5c2d | |||
| 11efad703c | |||
| b81f43c7cf | |||
| 68865843dc | |||
| 62daf138dd | |||
| 1120a8fc81 | |||
| ab10be7266 | |||
| 88f9d43e51 | |||
| 2877757396 | |||
| c657c62640 | |||
| d84d9df57d | |||
| 6762d4733e | |||
| add18d5cef | |||
| c5b42b55c3 | |||
| 670d9d680c | |||
| bbfc0e2fab | |||
| 708b4c7646 | |||
| efba604c31 | |||
| 1441488053 | |||
| bb3b05d224 | |||
| cda747deee | |||
| c3a2e05eb2 | |||
| a992009c71 | |||
| 57676bf4bb | |||
| 921e33cb70 | |||
| 70649383e0 | |||
| 64a7680b81 | |||
| a81d3a8843 | |||
| bad2f55121 | |||
| fecc55fe9c | |||
| 4d2e9629f9 | |||
| 347c79741f | |||
| 9bb30069fe | |||
| 9a2d77c8bf | |||
| f79f922838 | |||
| a9d5994070 | |||
| f967b38af1 | |||
| a060f00490 | |||
| b15cdbce7c | |||
| 63d46c1817 | |||
| f9ef308f8a | |||
| b2938c3ac8 | |||
| 17b575b7f2 | |||
| 777a948244 | |||
| 72bf0a1979 | |||
| c7a45845d6 | |||
| c2725bf066 | |||
| 2993f1db22 | |||
| e9ae48f96c | |||
| 5cc2ae0d01 | |||
| 7fdec509e9 | |||
| cab2945930 | |||
| 6a90cd02b9 | |||
| 7d810c7c3d | |||
| dad34b9e24 | |||
| fb33b8996f | |||
| ec3a5dcd65 | |||
| 7b443add3a | |||
| d70ef658e2 | |||
| c01b045022 | |||
| d3ea75869a | |||
| 0784c96011 | |||
| 553279ea76 | |||
| 89f6dec357 | |||
| ab7499a616 | |||
| 105c753c66 | |||
| d9f0de2dd4 | |||
| 82280091ad | |||
| b97b7cf989 | |||
| f83e40f6cc | |||
| 1fab9dfdf2 | |||
| a670931b06 | |||
| 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 |
+23
-11
@@ -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
|
||||||
@@ -82,4 +82,16 @@ ij_kotlin_variable_annotation_wrap = off
|
|||||||
ij_kotlin_while_on_new_line = false
|
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
|
||||||
+2
-1
@@ -1,2 +1,3 @@
|
|||||||
ko_fi: zaneschepke
|
ko_fi: zaneschepke
|
||||||
liberapay: zaneschepke
|
liberapay: zaneschepke
|
||||||
|
github: zaneschepke
|
||||||
|
|||||||
@@ -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
|
||||||
+117
-26
@@ -2,7 +2,7 @@ name: release-android
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: "4 3 * * *"
|
- cron: "4 3 * * *"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
track:
|
track:
|
||||||
@@ -14,7 +14,7 @@ on:
|
|||||||
- alpha
|
- alpha
|
||||||
- beta
|
- beta
|
||||||
- production
|
- production
|
||||||
default: alpha
|
default: none
|
||||||
required: true
|
required: true
|
||||||
release_type:
|
release_type:
|
||||||
type: choice
|
type: choice
|
||||||
@@ -30,13 +30,34 @@ on:
|
|||||||
description: "Tag name for release"
|
description: "Tag name for release"
|
||||||
required: false
|
required: false
|
||||||
default: nightly
|
default: nightly
|
||||||
|
workflow_call:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
check_commits:
|
||||||
name: Build Signed APK
|
name: Check for New Commits
|
||||||
if: ${{ inputs.release_type != 'none' }}
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
has_new_commits: ${{ steps.check.outputs.new_commits }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout Repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0 # This fetches all history so we can check commits
|
||||||
|
|
||||||
|
- name: Check for new commits
|
||||||
|
id: check
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
run: |
|
||||||
|
# This script checks for commits newer than 23 hours ago
|
||||||
|
NEW_COMMITS=$(git rev-list --count --after="$(date -Iseconds -d '23 hours ago')" ${{ github.sha }})
|
||||||
|
echo "new_commits=$NEW_COMMITS" >> $GITHUB_OUTPUT
|
||||||
|
build:
|
||||||
|
needs: check_commits
|
||||||
|
if: ${{ needs.check_commits.outputs.has_new_commits > 0 && inputs.release_type != 'none' }}
|
||||||
|
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 }}
|
||||||
@@ -73,6 +94,32 @@ jobs:
|
|||||||
fileDir: ${{ env.KEY_STORE_LOCATION }}
|
fileDir: ${{ env.KEY_STORE_LOCATION }}
|
||||||
encodedString: ${{ secrets.KEYSTORE }}
|
encodedString: ${{ secrets.KEYSTORE }}
|
||||||
|
|
||||||
|
# update latest tag
|
||||||
|
- name: Set latest tag
|
||||||
|
uses: rickstaa/action-create-tag@v1
|
||||||
|
id: tag_creation
|
||||||
|
with:
|
||||||
|
tag: "latest" # or any tag name you wish to use
|
||||||
|
message: "Automated tag for HEAD commit"
|
||||||
|
force_push_tag: true
|
||||||
|
tag_exists_error: false
|
||||||
|
|
||||||
|
- name: Get latest release
|
||||||
|
id: latest_release
|
||||||
|
uses: kaliber5/action-get-release@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
latest: true
|
||||||
|
|
||||||
|
- name: Generate Changelog
|
||||||
|
id: changelog
|
||||||
|
uses: requarks/changelog-action@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
toTag: ${{ github.event_name == 'schedule' && 'nightly' || steps.latest_release.outputs.tag_name }}
|
||||||
|
fromTag: "latest"
|
||||||
|
writeToFile: false # we won't write to file, just output
|
||||||
|
|
||||||
# create keystore path for gradle to read
|
# create keystore path for gradle to read
|
||||||
- name: Create keystore path env var
|
- name: Create keystore path env var
|
||||||
run: |
|
run: |
|
||||||
@@ -86,9 +133,12 @@ jobs:
|
|||||||
# Build and sign APK ("-x test" argument is used to skip tests)
|
# Build and sign APK ("-x test" argument is used to skip tests)
|
||||||
# add fdroid flavor for apk upload
|
# add fdroid flavor for apk upload
|
||||||
- name: Build Fdroid Release APK
|
- name: Build Fdroid Release APK
|
||||||
if: ${{ inputs.release_type != '' && inputs.release_type != 'nightly' }}
|
if: ${{ inputs.release_type != '' && inputs.release_type == 'release' }}
|
||||||
run: ./gradlew :app:assembleFdroidRelease -x test
|
run: ./gradlew :app:assembleFdroidRelease -x test
|
||||||
|
|
||||||
|
- name: Build Fdroid Prerelease APK
|
||||||
|
if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }}
|
||||||
|
run: ./gradlew :app:assembleFdroidPrerelease -x test
|
||||||
|
|
||||||
- name: Build Fdroid Nightly APK
|
- name: Build Fdroid Nightly APK
|
||||||
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
|
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
|
||||||
@@ -96,18 +146,35 @@ jobs:
|
|||||||
|
|
||||||
- if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
|
- if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
|
||||||
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/nightly/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
|
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/nightly/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
|
||||||
- if: ${{ inputs.release_type != '' && inputs.release_type != 'nightly' }}
|
- if: ${{ inputs.release_type != '' && inputs.release_type == 'release' }}
|
||||||
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
|
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
|
||||||
|
- if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }}
|
||||||
|
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/prerelease/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Get version code
|
- name: Get version code
|
||||||
if: ${{ inputs.release_type == 'release' || inputs.release_type == 'prerelease' }}
|
if: ${{ inputs.release_type == 'release' }}
|
||||||
run: |
|
run: |
|
||||||
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
|
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
|
||||||
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
|
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- 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.4
|
uses: actions/upload-artifact@v4.5.0
|
||||||
with:
|
with:
|
||||||
name: wgtunnel
|
name: wgtunnel
|
||||||
path: ${{ env.APK_PATH }}
|
path: ${{ env.APK_PATH }}
|
||||||
@@ -125,31 +192,32 @@ jobs:
|
|||||||
repository: zaneschepke/fdroid
|
repository: zaneschepke/fdroid
|
||||||
event-type: fdroid-update
|
event-type: fdroid-update
|
||||||
|
|
||||||
- name: Set version release notes
|
|
||||||
if: ${{ inputs.release_type == 'release' || inputs.release_type == 'prerelease' }}
|
|
||||||
run: |
|
|
||||||
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
|
|
||||||
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
|
|
||||||
echo "$RELEASE_NOTES" >> $GITHUB_ENV
|
|
||||||
echo "EOF" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: On nightly release
|
|
||||||
if: ${{ contains(env.TAG_NAME, 'nightly') }}
|
|
||||||
run: |
|
|
||||||
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
|
|
||||||
gh release delete nightly --yes || true
|
|
||||||
|
|
||||||
# Setup TAG_NAME, which is used as a general "name"
|
# Setup TAG_NAME, which is used as a general "name"
|
||||||
- if: github.event_name == 'workflow_dispatch'
|
- if: github.event_name == 'workflow_dispatch'
|
||||||
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
|
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
|
||||||
- if: github.event_name == 'schedule'
|
- if: github.event_name == 'schedule'
|
||||||
run: echo "TAG_NAME=nightly" >> $GITHUB_ENV
|
run: echo "TAG_NAME=nightly" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: On nightly release
|
- name: Set version release notes
|
||||||
|
if: ${{ inputs.release_type == 'release' }}
|
||||||
|
run: |
|
||||||
|
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
|
||||||
|
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
|
||||||
|
echo "$RELEASE_NOTES" >> $GITHUB_ENV
|
||||||
|
echo "EOF" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: On nightly release notes
|
||||||
if: ${{ contains(env.TAG_NAME, 'nightly') }}
|
if: ${{ contains(env.TAG_NAME, 'nightly') }}
|
||||||
run: |
|
run: |
|
||||||
echo "RELEASE_NOTES=Nightly build of the latest development version of the android client." >> $GITHUB_ENV
|
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
|
||||||
gh release delete nightly --yes || true
|
gh release delete nightly --yes || true
|
||||||
|
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
|
- name: Get checksum
|
||||||
id: checksum
|
id: checksum
|
||||||
@@ -164,9 +232,12 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
body: |
|
body: |
|
||||||
${{ env.RELEASE_NOTES }}
|
${{ env.RELEASE_NOTES }}
|
||||||
|
|
||||||
SHA256 fingerprint:
|
SHA256 fingerprint:
|
||||||
```${{ steps.checksum.outputs.checksum }}```
|
```${{ steps.checksum.outputs.checksum }}```
|
||||||
|
|
||||||
|
### Changelog
|
||||||
|
${{ steps.changelog.outputs.changes }}
|
||||||
tag_name: ${{ env.TAG_NAME }}
|
tag_name: ${{ env.TAG_NAME }}
|
||||||
name: ${{ env.TAG_NAME }}
|
name: ${{ env.TAG_NAME }}
|
||||||
draft: false
|
draft: false
|
||||||
@@ -200,6 +271,26 @@ jobs:
|
|||||||
- name: Grant execute permission for gradlew
|
- name: Grant execute permission for gradlew
|
||||||
run: chmod +x gradlew
|
run: chmod +x gradlew
|
||||||
|
|
||||||
|
# Here we need to decode keystore.jks from base64 string and place it
|
||||||
|
# in the folder specified in the release signing configuration
|
||||||
|
- name: Decode Keystore
|
||||||
|
id: decode_keystore
|
||||||
|
uses: timheuer/base64-to-file@v1.2
|
||||||
|
with:
|
||||||
|
fileName: ${{ env.KEY_STORE_FILE }}
|
||||||
|
fileDir: ${{ env.KEY_STORE_LOCATION }}
|
||||||
|
encodedString: ${{ secrets.KEYSTORE }}
|
||||||
|
|
||||||
|
# create keystore path for gradle to read
|
||||||
|
- name: Create keystore path env var
|
||||||
|
run: |
|
||||||
|
store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }}
|
||||||
|
echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Create service_account.json
|
||||||
|
id: createServiceAccount
|
||||||
|
run: echo '${{ secrets.SERVICE_ACCOUNT_JSON }}' > service_account.json
|
||||||
|
|
||||||
- name: Deploy with fastlane
|
- name: Deploy with fastlane
|
||||||
uses: ruby/setup-ruby@v1
|
uses: ruby/setup-ruby@v1
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -71,3 +71,4 @@ app/release/output.json
|
|||||||
.idea/codeStyles/
|
.idea/codeStyles/
|
||||||
# where we keep our signing secrets locally
|
# where we keep our signing secrets locally
|
||||||
app/signing.properties
|
app/signing.properties
|
||||||
|
/.kotlin/
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ WG Tunnel
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
[](https://discord.gg/rbRRNh6H7V)
|
[](https://discord.gg/rbRRNh6H7V)
|
||||||
[](https://twitter.com/i/communities/1780655267685736818)
|
|
||||||
[](https://t.me/wgtunnel)
|
[](https://t.me/wgtunnel)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
@@ -55,13 +54,13 @@ 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)
|
||||||
|
|
||||||
|
|||||||
+208
-157
@@ -1,194 +1,245 @@
|
|||||||
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.compose.compiler)
|
||||||
alias(libs.plugins.grgit)
|
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 {
|
||||||
namespace = Constants.APP_ID
|
namespace = Constants.APP_ID
|
||||||
compileSdk = Constants.TARGET_SDK
|
compileSdk = Constants.TARGET_SDK
|
||||||
compileSdkPreview = "VanillaIceCream"
|
|
||||||
|
|
||||||
androidResources {
|
androidResources {
|
||||||
generateLocaleConfig = true
|
generateLocaleConfig = true
|
||||||
}
|
}
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
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") }
|
||||||
|
|
||||||
sourceSets {
|
sourceSets {
|
||||||
getByName("debug").assets.srcDirs(files("$projectDir/schemas")) // Room
|
getByName("debug").assets.srcDirs(files("$projectDir/schemas")) // Room
|
||||||
}
|
}
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
buildConfigField("String[]", "LANGUAGES", "new String[]{ ${languageList().joinToString(separator = ", ") { "\"$it\"" }} }")
|
||||||
vectorDrawables { useSupportLibrary = true }
|
|
||||||
}
|
|
||||||
|
|
||||||
signingConfigs {
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
create(Constants.RELEASE) {
|
vectorDrawables { useSupportLibrary = true }
|
||||||
storeFile = getStoreFile()
|
}
|
||||||
storePassword = getSigningProperty(Constants.STORE_PASS_VAR)
|
|
||||||
keyAlias = getSigningProperty(Constants.KEY_ALIAS_VAR)
|
|
||||||
keyPassword = getSigningProperty(Constants.KEY_PASS_VAR)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
buildTypes {
|
signingConfigs {
|
||||||
// don't strip
|
create(Constants.RELEASE) {
|
||||||
packaging.jniLibs.keepDebugSymbols.addAll(
|
storeFile = getStoreFile()
|
||||||
listOf("libwg-go.so", "libwg-quick.so", "libwg.so"),
|
storePassword = getSigningProperty(Constants.STORE_PASS_VAR)
|
||||||
)
|
keyAlias = getSigningProperty(Constants.KEY_ALIAS_VAR)
|
||||||
|
keyPassword = getSigningProperty(Constants.KEY_PASS_VAR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
applicationVariants.all {
|
buildTypes {
|
||||||
val variant = this
|
// don't strip
|
||||||
variant.outputs
|
packaging.jniLibs.keepDebugSymbols.addAll(
|
||||||
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
|
listOf("libwg-go.so", "libwg-quick.so", "libwg.so"),
|
||||||
.forEach { output ->
|
)
|
||||||
val outputFileName =
|
|
||||||
"${Constants.APP_NAME}-${variant.flavorName}-${variant.buildType.name}-${variant.versionName}.apk"
|
|
||||||
output.outputFileName = outputFileName
|
|
||||||
}
|
|
||||||
}
|
|
||||||
release {
|
|
||||||
isDebuggable = false
|
|
||||||
isMinifyEnabled = true
|
|
||||||
isShrinkResources = true
|
|
||||||
proguardFiles(
|
|
||||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
|
||||||
"proguard-rules.pro",
|
|
||||||
)
|
|
||||||
signingConfig = signingConfigs.getByName(Constants.RELEASE)
|
|
||||||
}
|
|
||||||
debug { isDebuggable = true }
|
|
||||||
|
|
||||||
create(Constants.NIGHTLY) {
|
release {
|
||||||
initWith(getByName("release"))
|
isDebuggable = false
|
||||||
defaultConfig.versionName = nightlyVersionName()
|
isMinifyEnabled = true
|
||||||
defaultConfig.versionCode = nightlyVersionCode()
|
isShrinkResources = true
|
||||||
}
|
proguardFiles(
|
||||||
}
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
flavorDimensions.add(Constants.TYPE)
|
"proguard-rules.pro",
|
||||||
productFlavors {
|
)
|
||||||
create("fdroid") {
|
signingConfig = signingConfigs.getByName(Constants.RELEASE)
|
||||||
dimension = Constants.TYPE
|
resValue("string", "provider", "\"${Constants.APP_NAME}.provider\"")
|
||||||
proguardFile("fdroid-rules.pro")
|
}
|
||||||
}
|
debug {
|
||||||
create("general") {
|
applicationIdSuffix = ".debug"
|
||||||
dimension = Constants.TYPE
|
versionNameSuffix = "-debug"
|
||||||
}
|
resValue("string", "app_name", "WG Tunnel - Debug")
|
||||||
}
|
isDebuggable = true
|
||||||
compileOptions {
|
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.debug\"")
|
||||||
sourceCompatibility = JavaVersion.VERSION_17
|
}
|
||||||
targetCompatibility = JavaVersion.VERSION_17
|
|
||||||
isCoreLibraryDesugaringEnabled = true
|
create(Constants.PRERELEASE) {
|
||||||
}
|
initWith(buildTypes.getByName(Constants.RELEASE))
|
||||||
kotlinOptions { jvmTarget = Constants.JVM_TARGET }
|
applicationIdSuffix = ".prerelease"
|
||||||
buildFeatures {
|
versionNameSuffix = "-pre"
|
||||||
compose = true
|
resValue("string", "app_name", "WG Tunnel - Pre")
|
||||||
buildConfig = true
|
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.pre\"")
|
||||||
}
|
}
|
||||||
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flavorDimensions.add(Constants.TYPE)
|
||||||
|
productFlavors {
|
||||||
|
create("fdroid") {
|
||||||
|
dimension = Constants.TYPE
|
||||||
|
proguardFile("fdroid-rules.pro")
|
||||||
|
}
|
||||||
|
create("general") {
|
||||||
|
dimension = Constants.TYPE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
isCoreLibraryDesugaringEnabled = true
|
||||||
|
}
|
||||||
|
kotlinOptions { jvmTarget = Constants.JVM_TARGET }
|
||||||
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
buildConfig = true
|
||||||
|
}
|
||||||
|
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
|
||||||
}
|
}
|
||||||
|
|
||||||
val generalImplementation by configurations
|
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
|
||||||
implementation(project(":logcatter"))
|
implementation(project(":logcatter"))
|
||||||
|
|
||||||
implementation(libs.androidx.core.ktx)
|
implementation(libs.androidx.core.ktx)
|
||||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||||
|
|
||||||
// helpers for implementing LifecycleOwner in a Service
|
// helpers for implementing LifecycleOwner in a Service
|
||||||
implementation(libs.androidx.lifecycle.service)
|
implementation(libs.androidx.lifecycle.service)
|
||||||
implementation(libs.androidx.activity.compose)
|
implementation(libs.androidx.activity.compose)
|
||||||
implementation(platform(libs.androidx.compose.bom))
|
implementation(platform(libs.androidx.compose.bom))
|
||||||
implementation(libs.androidx.compose.ui)
|
implementation(libs.androidx.compose.ui)
|
||||||
implementation(libs.androidx.compose.ui.graphics)
|
implementation(libs.androidx.compose.ui.graphics)
|
||||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||||
implementation(libs.androidx.material3)
|
implementation(libs.androidx.material3)
|
||||||
implementation(libs.androidx.appcompat)
|
implementation(libs.androidx.appcompat)
|
||||||
|
implementation(libs.material)
|
||||||
|
|
||||||
// test
|
// test
|
||||||
testImplementation(libs.junit)
|
testImplementation(libs.junit)
|
||||||
testImplementation(libs.androidx.junit)
|
testImplementation(libs.androidx.junit)
|
||||||
androidTestImplementation(libs.androidx.junit)
|
androidTestImplementation(libs.androidx.junit)
|
||||||
androidTestImplementation(libs.androidx.espresso.core)
|
androidTestImplementation(libs.androidx.espresso.core)
|
||||||
androidTestImplementation(platform(libs.androidx.compose.bom))
|
androidTestImplementation(platform(libs.androidx.compose.bom))
|
||||||
androidTestImplementation(libs.androidx.compose.ui.test)
|
androidTestImplementation(libs.androidx.compose.ui.test)
|
||||||
androidTestImplementation(libs.androidx.room.testing)
|
androidTestImplementation(libs.androidx.room.testing)
|
||||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||||
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(libs.tunnel)
|
// implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.aar"))))
|
||||||
implementation(libs.amneziawg.android)
|
implementation(libs.tunnel)
|
||||||
coreLibraryDesugaring(libs.desugar.jdk.libs)
|
implementation(libs.amneziawg.android)
|
||||||
|
coreLibraryDesugaring(libs.desugar.jdk.libs)
|
||||||
|
|
||||||
// logging
|
// logging
|
||||||
implementation(libs.timber)
|
implementation(libs.timber)
|
||||||
|
|
||||||
|
// compose navigation
|
||||||
|
implementation(libs.androidx.navigation.compose)
|
||||||
|
implementation(libs.androidx.hilt.navigation.compose)
|
||||||
|
|
||||||
// compose navigation
|
// hilt
|
||||||
implementation(libs.androidx.navigation.compose)
|
implementation(libs.hilt.android)
|
||||||
implementation(libs.androidx.hilt.navigation.compose)
|
ksp(libs.hilt.android.compiler)
|
||||||
|
|
||||||
implementation(libs.zaneschepke.multifab)
|
// accompanist
|
||||||
|
implementation(libs.accompanist.permissions)
|
||||||
|
implementation(libs.accompanist.flowlayout)
|
||||||
|
implementation(libs.accompanist.drawablepainter)
|
||||||
|
|
||||||
// hilt
|
// storage
|
||||||
implementation(libs.hilt.android)
|
implementation(libs.androidx.room.runtime)
|
||||||
ksp(libs.hilt.android.compiler)
|
ksp(libs.androidx.room.compiler)
|
||||||
|
implementation(libs.androidx.room.ktx)
|
||||||
|
implementation(libs.androidx.datastore.preferences)
|
||||||
|
|
||||||
// accompanist
|
// lifecycle
|
||||||
implementation(libs.accompanist.permissions)
|
implementation(libs.lifecycle.runtime.compose)
|
||||||
implementation(libs.accompanist.flowlayout)
|
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||||
implementation(libs.accompanist.drawablepainter)
|
implementation(libs.androidx.lifecycle.process)
|
||||||
|
|
||||||
// storage
|
// icons
|
||||||
implementation(libs.androidx.room.runtime)
|
implementation(libs.material.icons.extended)
|
||||||
ksp(libs.androidx.room.compiler)
|
// serialization
|
||||||
implementation(libs.androidx.room.ktx)
|
implementation(libs.kotlinx.serialization.json)
|
||||||
implementation(libs.androidx.datastore.preferences)
|
|
||||||
|
|
||||||
// lifecycle
|
// barcode scanning
|
||||||
implementation(libs.lifecycle.runtime.compose)
|
implementation(libs.zxing.android.embedded)
|
||||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
|
||||||
implementation(libs.androidx.lifecycle.process)
|
|
||||||
|
|
||||||
// icons
|
// bio
|
||||||
implementation(libs.material.icons.extended)
|
implementation(libs.androidx.biometric.ktx)
|
||||||
// serialization
|
implementation(libs.pin.lock.compose)
|
||||||
implementation(libs.kotlinx.serialization.json)
|
|
||||||
|
|
||||||
// barcode scanning
|
// shortcuts
|
||||||
implementation(libs.zxing.android.embedded)
|
implementation(libs.androidx.core)
|
||||||
|
implementation(libs.androidx.core.google.shortcuts)
|
||||||
|
|
||||||
// bio
|
// splash
|
||||||
implementation(libs.androidx.biometric.ktx)
|
implementation(libs.androidx.core.splashscreen)
|
||||||
implementation(libs.pin.lock.compose)
|
|
||||||
|
|
||||||
// shortcuts
|
|
||||||
implementation(libs.androidx.core)
|
|
||||||
implementation(libs.androidx.core.google.shortcuts)
|
|
||||||
|
|
||||||
// splash
|
|
||||||
implementation(libs.androidx.core.splashscreen)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun nightlyVersionCode() : Int {
|
fun determineVersionName(): String {
|
||||||
return Constants.VERSION_CODE + Constants.NIGHTLY_CODE
|
return with(getBuildTaskName().lowercase()) {
|
||||||
|
when {
|
||||||
|
contains(Constants.NIGHTLY) || contains(Constants.PRERELEASE) ->
|
||||||
|
Constants.VERSION_NAME +
|
||||||
|
"-${grgitService.service.get().grgit.head().abbreviatedId}"
|
||||||
|
else -> Constants.VERSION_NAME
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun nightlyVersionName() : String {
|
val incrementVersionCode by tasks.registering {
|
||||||
return Constants.VERSION_NAME + "-${grgitService.service.get().grgit.head().abbreviatedId}"
|
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,232 @@
|
|||||||
|
{
|
||||||
|
"formatVersion": 1,
|
||||||
|
"database": {
|
||||||
|
"version": 11,
|
||||||
|
"identityHash": "4c9418386f72dfac5d28ab96c1e5ea0b",
|
||||||
|
"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_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_wifi_by_shell_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": "isPingEnabled",
|
||||||
|
"columnName": "is_ping_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isAmneziaEnabled",
|
||||||
|
"columnName": "is_amnezia_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isWildcardsEnabled",
|
||||||
|
"columnName": "is_wildcards_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isWifiNameByShellEnabled",
|
||||||
|
"columnName": "is_wifi_by_shell_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, '4c9418386f72dfac5d28ab96c1e5ea0b')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
{
|
||||||
|
"formatVersion": 1,
|
||||||
|
"database": {
|
||||||
|
"version": 12,
|
||||||
|
"identityHash": "acf79ac5defacda5be6c3f976e777de3",
|
||||||
|
"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_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_wifi_by_shell_enabled` INTEGER NOT NULL DEFAULT false, `is_stop_on_no_internet_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": "isPingEnabled",
|
||||||
|
"columnName": "is_ping_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isAmneziaEnabled",
|
||||||
|
"columnName": "is_amnezia_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isWildcardsEnabled",
|
||||||
|
"columnName": "is_wildcards_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isWifiNameByShellEnabled",
|
||||||
|
"columnName": "is_wifi_by_shell_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isStopOnNoInternetEnabled",
|
||||||
|
"columnName": "is_stop_on_no_internet_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, `is_ethernet_tunnel` 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"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isEthernetTunnel",
|
||||||
|
"columnName": "is_ethernet_tunnel",
|
||||||
|
"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, 'acf79ac5defacda5be6c3f976e777de3')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
{
|
||||||
|
"formatVersion": 1,
|
||||||
|
"database": {
|
||||||
|
"version": 13,
|
||||||
|
"identityHash": "ff209157b98a641c424f5086818ec585",
|
||||||
|
"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_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_wifi_by_shell_enabled` INTEGER NOT NULL DEFAULT false, `is_stop_on_no_internet_enabled` INTEGER NOT NULL DEFAULT false, `is_vpn_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `is_lan_on_kill_switch_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": "isPingEnabled",
|
||||||
|
"columnName": "is_ping_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isAmneziaEnabled",
|
||||||
|
"columnName": "is_amnezia_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isWildcardsEnabled",
|
||||||
|
"columnName": "is_wildcards_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isWifiNameByShellEnabled",
|
||||||
|
"columnName": "is_wifi_by_shell_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isStopOnNoInternetEnabled",
|
||||||
|
"columnName": "is_stop_on_no_internet_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isVpnKillSwitchEnabled",
|
||||||
|
"columnName": "is_vpn_kill_switch_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isKernelKillSwitchEnabled",
|
||||||
|
"columnName": "is_kernel_kill_switch_enabled",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isLanOnKillSwitchEnabled",
|
||||||
|
"columnName": "is_lan_on_kill_switch_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, `is_ethernet_tunnel` 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"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isEthernetTunnel",
|
||||||
|
"columnName": "is_ethernet_tunnel",
|
||||||
|
"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, 'ff209157b98a641c424f5086818ec585')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-6
@@ -13,10 +13,10 @@ import org.junit.runner.RunWith
|
|||||||
*/
|
*/
|
||||||
@RunWith(AndroidJUnit4::class)
|
@RunWith(AndroidJUnit4::class)
|
||||||
class ExampleInstrumentedTest {
|
class ExampleInstrumentedTest {
|
||||||
@Test
|
@Test
|
||||||
fun useAppContext() {
|
fun useAppContext() {
|
||||||
// Context of the app under test.
|
// Context of the app under test.
|
||||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||||
assertEquals("com.zaneschepke.wireguardautotunnel", appContext.packageName)
|
assertEquals("com.zaneschepke.wireguardautotunnel", appContext.packageName)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,33 +12,33 @@ import java.io.IOException
|
|||||||
|
|
||||||
@RunWith(AndroidJUnit4::class)
|
@RunWith(AndroidJUnit4::class)
|
||||||
class MigrationTest {
|
class MigrationTest {
|
||||||
private val dbName = "migration-test"
|
private val dbName = "migration-test"
|
||||||
|
|
||||||
@get:Rule
|
@get:Rule
|
||||||
val helper: MigrationTestHelper =
|
val helper: MigrationTestHelper =
|
||||||
MigrationTestHelper(
|
MigrationTestHelper(
|
||||||
InstrumentationRegistry.getInstrumentation(),
|
InstrumentationRegistry.getInstrumentation(),
|
||||||
AppDatabase::class.java,
|
AppDatabase::class.java,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Throws(IOException::class)
|
@Throws(IOException::class)
|
||||||
fun migrate6To7() {
|
fun migrate6To7() {
|
||||||
helper.createDatabase(dbName, 6).apply {
|
helper.createDatabase(dbName, 6).apply {
|
||||||
// Database has schema version 1. Insert some data using SQL queries.
|
// Database has schema version 1. Insert some data using SQL queries.
|
||||||
// You can't use DAO classes because they expect the latest schema.
|
// You can't use DAO classes because they expect the latest schema.
|
||||||
execSQL(Queries.createDefaultSettings())
|
execSQL(Queries.createDefaultSettings())
|
||||||
execSQL(
|
execSQL(
|
||||||
Queries.createTunnelConfig(),
|
Queries.createTunnelConfig(),
|
||||||
)
|
)
|
||||||
// Prepare for the next version.
|
// Prepare for the next version.
|
||||||
close()
|
close()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Re-open the database with version 2 and provide
|
// Re-open the database with version 2 and provide
|
||||||
// MIGRATION_1_2 as the migration process.
|
// MIGRATION_1_2 as the migration process.
|
||||||
helper.runMigrationsAndValidate(dbName, 7, true)
|
helper.runMigrationsAndValidate(dbName, 7, true)
|
||||||
// MigrationTestHelper automatically verifies the schema changes,
|
// MigrationTestHelper automatically verifies the schema changes,
|
||||||
// but you need to validate that the data was migrated properly.
|
// but you need to validate that the data was migrated properly.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,17 +3,7 @@
|
|||||||
xmlns:tools="http://schemas.android.com/tools">
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission
|
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
|
||||||
android:maxSdkVersion="32" />
|
|
||||||
<uses-permission
|
|
||||||
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
|
||||||
android:maxSdkVersion="32"
|
|
||||||
tools:ignore="ScopedStorage" />
|
|
||||||
<uses-permission
|
|
||||||
android:name="android.permission.ACCESS_WIFI_STATE"
|
|
||||||
android:maxSdkVersion="30"
|
|
||||||
tools:ignore="LeanbackUsesWifi" />
|
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||||
@@ -22,7 +12,8 @@
|
|||||||
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
|
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
|
||||||
<!--foreground service exempt android 14-->
|
<!--foreground service exempt android 14-->
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
||||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"
|
||||||
|
tools:ignore="ProtectedPermissions" />
|
||||||
|
|
||||||
<!--foreground service permissions-->
|
<!--foreground service permissions-->
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
@@ -31,6 +22,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" />
|
||||||
@@ -43,6 +40,12 @@
|
|||||||
<uses-feature
|
<uses-feature
|
||||||
android:name="android.hardware.screen.portrait"
|
android:name="android.hardware.screen.portrait"
|
||||||
android:required="false" />
|
android:required="false" />
|
||||||
|
<uses-feature
|
||||||
|
android:name="android.hardware.gamepad"
|
||||||
|
android:required="false"/>
|
||||||
|
|
||||||
|
<uses-feature android:name="android.hardware.wifi"
|
||||||
|
android:required="false"/>
|
||||||
|
|
||||||
<queries>
|
<queries>
|
||||||
<intent>
|
<intent>
|
||||||
@@ -60,28 +63,20 @@
|
|||||||
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.AppSplashScreen"
|
android:theme="@style/Theme.App.Start"
|
||||||
tools:targetApi="tiramisu">
|
tools:targetApi="tiramisu">
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.SplashActivity"
|
android:name=".ui.MainActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:theme="@style/Theme.AppSplashScreen">
|
android:windowSoftInputMode="adjustResize"
|
||||||
|
android:theme="@style/Theme.WireguardAutoTunnel"
|
||||||
|
android:configChanges="orientation|screenSize|keyboardHidden"
|
||||||
|
>
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||||
|
|
||||||
</intent-filter>
|
|
||||||
<meta-data
|
|
||||||
android:name="android.app.shortcuts"
|
|
||||||
android:resource="@xml/shortcuts" />
|
|
||||||
</activity>
|
|
||||||
<activity
|
|
||||||
android:name=".ui.MainActivity"
|
|
||||||
android:exported="true"
|
|
||||||
android:theme="@style/Theme.WireguardAutoTunnel">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
|
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
@@ -89,19 +84,27 @@
|
|||||||
android:name="com.journeyapps.barcodescanner.CaptureActivity"
|
android:name="com.journeyapps.barcodescanner.CaptureActivity"
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
tools:replace="screenOrientation" />
|
tools:replace="screenOrientation" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".service.shortcut.ShortcutsActivity"
|
android:name=".service.shortcut.ShortcutsActivity"
|
||||||
android:enabled="true"
|
android:enabled="true"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:finishOnTaskLaunch="true"
|
android:noHistory="true"
|
||||||
|
android:excludeFromRecents="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"
|
||||||
@@ -136,23 +139,23 @@
|
|||||||
<action android:name="android.service.quicksettings.action.QS_TILE" />
|
<action android:name="android.service.quicksettings.action.QS_TILE" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</service>
|
</service>
|
||||||
|
<service
|
||||||
|
android:name=".service.tunnel.AlwaysOnVpnService"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="false"
|
||||||
|
android:foregroundServiceType="systemExempted"
|
||||||
|
android:permission="android.permission.BIND_VPN_SERVICE"
|
||||||
|
android:persistent="true"
|
||||||
|
tools:node="merge">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.net.VpnService" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
|
||||||
|
android:value="true" />
|
||||||
|
</service>
|
||||||
<service
|
<service
|
||||||
android:name=".service.foreground.WireGuardTunnelService"
|
android:name=".service.foreground.autotunnel.AutoTunnelService"
|
||||||
android:enabled="true"
|
|
||||||
android:exported="false"
|
|
||||||
android:foregroundServiceType="systemExempted"
|
|
||||||
android:permission="android.permission.BIND_VPN_SERVICE"
|
|
||||||
android:persistent="true"
|
|
||||||
tools:node="merge">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.net.VpnService" />
|
|
||||||
</intent-filter>
|
|
||||||
<meta-data
|
|
||||||
android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
|
|
||||||
android:value="true" />
|
|
||||||
</service>
|
|
||||||
<service
|
|
||||||
android:name=".service.foreground.WireGuardConnectivityWatcherService"
|
|
||||||
android:enabled="true"
|
android:enabled="true"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:foregroundServiceType="systemExempted"
|
android:foregroundServiceType="systemExempted"
|
||||||
@@ -160,6 +163,17 @@
|
|||||||
android:stopWithTask="false"
|
android:stopWithTask="false"
|
||||||
tools:node="merge" />
|
tools:node="merge" />
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".service.foreground.TunnelBackgroundService"
|
||||||
|
android:exported="false"
|
||||||
|
android:persistent="true"
|
||||||
|
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"
|
||||||
@@ -173,8 +187,25 @@
|
|||||||
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
|
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".receiver.NotificationActionReceiver"
|
android:name=".receiver.AppUpdateReceiver"
|
||||||
android:exported="false" />
|
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>
|
||||||
|
<receiver
|
||||||
|
android:name=".receiver.NotificationActionReceiver"
|
||||||
|
android:exported="false"
|
||||||
|
android:permission="${applicationId}.permission.CONTROL_TUNNELS">
|
||||||
|
</receiver>
|
||||||
</application>
|
</application>
|
||||||
</manifest>
|
</manifest>
|
||||||
|
|||||||
@@ -1,57 +1,93 @@
|
|||||||
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.wireguardautotunnel.service.tile.AutoTunnelControlTile
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tile.TunnelControlTile
|
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.MainDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.BackendState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||||
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.CoroutineScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
@HiltAndroidApp
|
@HiltAndroidApp
|
||||||
class WireGuardAutoTunnel : Application() {
|
class WireGuardAutoTunnel : Application() {
|
||||||
|
|
||||||
override fun onCreate() {
|
@Inject
|
||||||
super.onCreate()
|
@ApplicationScope
|
||||||
instance = this
|
lateinit var applicationScope: CoroutineScope
|
||||||
if (BuildConfig.DEBUG) {
|
|
||||||
Timber.plant(Timber.DebugTree())
|
|
||||||
StrictMode.setThreadPolicy(
|
|
||||||
ThreadPolicy.Builder()
|
|
||||||
.detectDiskReads()
|
|
||||||
.detectDiskWrites()
|
|
||||||
.detectNetwork()
|
|
||||||
.penaltyLog()
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
} else Timber.plant(ReleaseTree())
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
@Inject
|
||||||
|
lateinit var logReader: LogReader
|
||||||
|
|
||||||
lateinit var instance: WireGuardAutoTunnel
|
@Inject
|
||||||
private set
|
lateinit var appStateRepository: AppStateRepository
|
||||||
|
|
||||||
fun isRunningOnAndroidTv(): Boolean {
|
@Inject
|
||||||
return instance.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
|
lateinit var settingsRepository: SettingsRepository
|
||||||
}
|
|
||||||
|
|
||||||
fun requestTunnelTileServiceStateUpdate() {
|
@Inject
|
||||||
TileService.requestListeningState(
|
lateinit var tunnelService: TunnelService
|
||||||
instance,
|
|
||||||
ComponentName(instance, TunnelControlTile::class.java),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun requestAutoTunnelTileServiceUpdate() {
|
@Inject
|
||||||
TileService.requestListeningState(
|
@IoDispatcher
|
||||||
instance,
|
lateinit var ioDispatcher: CoroutineDispatcher
|
||||||
ComponentName(instance, AutoTunnelControlTile::class.java),
|
|
||||||
)
|
@Inject
|
||||||
}
|
@MainDispatcher
|
||||||
}
|
lateinit var mainDispatcher: CoroutineDispatcher
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
instance = this
|
||||||
|
if (BuildConfig.DEBUG) {
|
||||||
|
Timber.plant(Timber.DebugTree())
|
||||||
|
StrictMode.setThreadPolicy(
|
||||||
|
ThreadPolicy.Builder()
|
||||||
|
.detectDiskReads()
|
||||||
|
.detectDiskWrites()
|
||||||
|
.detectNetwork()
|
||||||
|
.penaltyLog()
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Timber.plant(ReleaseTree())
|
||||||
|
}
|
||||||
|
|
||||||
|
applicationScope.launch {
|
||||||
|
withContext(mainDispatcher) {
|
||||||
|
if (appStateRepository.isLocalLogsEnabled() && !isRunningOnTv()) logReader.initialize()
|
||||||
|
}
|
||||||
|
if (!settingsRepository.getSettings().isKernelEnabled) {
|
||||||
|
tunnelService.setBackendState(BackendState.SERVICE_ACTIVE, emptyList())
|
||||||
|
}
|
||||||
|
appStateRepository.getLocale()?.let {
|
||||||
|
LocaleUtil.changeLocale(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onTerminate() {
|
||||||
|
applicationScope.launch {
|
||||||
|
tunnelService.setBackendState(BackendState.INACTIVE, emptyList())
|
||||||
|
}
|
||||||
|
super.onTerminate()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
lateinit var instance: WireGuardAutoTunnel
|
||||||
|
private set
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,46 +10,67 @@ import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
|||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
|
|
||||||
@Database(
|
@Database(
|
||||||
entities = [Settings::class, TunnelConfig::class],
|
entities = [Settings::class, TunnelConfig::class],
|
||||||
version = 8,
|
version = 13,
|
||||||
autoMigrations =
|
autoMigrations =
|
||||||
[
|
[
|
||||||
AutoMigration(from = 1, to = 2),
|
AutoMigration(from = 1, to = 2),
|
||||||
AutoMigration(from = 2, to = 3),
|
AutoMigration(from = 2, to = 3),
|
||||||
AutoMigration(
|
AutoMigration(
|
||||||
from = 3,
|
from = 3,
|
||||||
to = 4,
|
to = 4,
|
||||||
),
|
),
|
||||||
AutoMigration(
|
AutoMigration(
|
||||||
from = 4,
|
from = 4,
|
||||||
to = 5,
|
to = 5,
|
||||||
),
|
),
|
||||||
AutoMigration(
|
AutoMigration(
|
||||||
from = 5,
|
from = 5,
|
||||||
to = 6,
|
to = 6,
|
||||||
),
|
),
|
||||||
AutoMigration(
|
AutoMigration(
|
||||||
from = 6,
|
from = 6,
|
||||||
to = 7,
|
to = 7,
|
||||||
spec = RemoveLegacySettingColumnsMigration::class,
|
spec = RemoveLegacySettingColumnsMigration::class,
|
||||||
),
|
),
|
||||||
AutoMigration(7, 8),
|
AutoMigration(7, 8),
|
||||||
],
|
AutoMigration(8, 9),
|
||||||
exportSchema = true,
|
AutoMigration(9, 10),
|
||||||
|
AutoMigration(
|
||||||
|
from = 10,
|
||||||
|
to = 11,
|
||||||
|
spec = RemoveTunnelPauseMigration::class,
|
||||||
|
),
|
||||||
|
AutoMigration(
|
||||||
|
from = 11,
|
||||||
|
to = 12,
|
||||||
|
),
|
||||||
|
AutoMigration(
|
||||||
|
from = 12,
|
||||||
|
to = 13,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
exportSchema = true,
|
||||||
)
|
)
|
||||||
@TypeConverters(DatabaseListConverters::class)
|
@TypeConverters(DatabaseListConverters::class)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
abstract fun settingDao(): SettingsDao
|
abstract fun settingDao(): SettingsDao
|
||||||
|
|
||||||
abstract fun tunnelConfigDoa(): TunnelConfigDao
|
abstract fun tunnelConfigDoa(): TunnelConfigDao
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteColumn(
|
@DeleteColumn(
|
||||||
tableName = "Settings",
|
tableName = "Settings",
|
||||||
columnName = "default_tunnel",
|
columnName = "default_tunnel",
|
||||||
)
|
)
|
||||||
@DeleteColumn(
|
@DeleteColumn(
|
||||||
tableName = "Settings",
|
tableName = "Settings",
|
||||||
columnName = "is_battery_saver_enabled",
|
columnName = "is_battery_saver_enabled",
|
||||||
)
|
)
|
||||||
class RemoveLegacySettingColumnsMigration : AutoMigrationSpec
|
class RemoveLegacySettingColumnsMigration : AutoMigrationSpec
|
||||||
|
|
||||||
|
@DeleteColumn(
|
||||||
|
tableName = "Settings",
|
||||||
|
columnName = "is_auto_tunnel_paused",
|
||||||
|
)
|
||||||
|
class RemoveTunnelPauseMigration : AutoMigrationSpec
|
||||||
|
|||||||
@@ -5,17 +5,17 @@ import androidx.sqlite.db.SupportSQLiteDatabase
|
|||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
|
||||||
class DatabaseCallback : RoomDatabase.Callback() {
|
class DatabaseCallback : RoomDatabase.Callback() {
|
||||||
override fun onCreate(db: SupportSQLiteDatabase) = db.run {
|
override fun onCreate(db: SupportSQLiteDatabase) = db.run {
|
||||||
// Notice non-ui thread is here
|
// Notice non-ui thread is here
|
||||||
beginTransaction()
|
beginTransaction()
|
||||||
try {
|
try {
|
||||||
execSQL(Queries.createDefaultSettings())
|
execSQL(Queries.createDefaultSettings())
|
||||||
Timber.i("Bootstrapping settings data")
|
Timber.i("Bootstrapping settings data")
|
||||||
setTransactionSuccessful()
|
setTransactionSuccessful()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
} finally {
|
} finally {
|
||||||
endTransaction()
|
endTransaction()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-15
@@ -5,20 +5,20 @@ import kotlinx.serialization.encodeToString
|
|||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
|
|
||||||
class DatabaseListConverters {
|
class DatabaseListConverters {
|
||||||
@TypeConverter
|
@TypeConverter
|
||||||
fun listToString(value: MutableList<String>): String {
|
fun listToString(value: MutableList<String>): String {
|
||||||
return Json.encodeToString(value)
|
return Json.encodeToString(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
@TypeConverter
|
@TypeConverter
|
||||||
fun stringToList(value: String): MutableList<String> {
|
fun stringToList(value: String): MutableList<String> {
|
||||||
if (value.isBlank() || value.isEmpty()) return mutableListOf()
|
if (value.isBlank() || value.isEmpty()) return mutableListOf()
|
||||||
return try {
|
return try {
|
||||||
Json.decodeFromString<MutableList<String>>(value)
|
Json.decodeFromString<MutableList<String>>(value)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
val list = value.split(",").toMutableList()
|
val list = value.split(",").toMutableList()
|
||||||
val json = listToString(list)
|
val json = listToString(list)
|
||||||
Json.decodeFromString<MutableList<String>>(json)
|
Json.decodeFromString<MutableList<String>>(json)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,35 +1,35 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.data
|
package com.zaneschepke.wireguardautotunnel.data
|
||||||
|
|
||||||
object Queries {
|
object Queries {
|
||||||
fun createDefaultSettings(): String {
|
fun createDefaultSettings(): String {
|
||||||
return """
|
return """
|
||||||
INSERT INTO Settings (is_tunnel_enabled,
|
INSERT INTO Settings (is_tunnel_enabled,
|
||||||
is_tunnel_on_mobile_data_enabled,
|
is_tunnel_on_mobile_data_enabled,
|
||||||
trusted_network_ssids,
|
trusted_network_ssids,
|
||||||
is_always_on_vpn_enabled,
|
is_always_on_vpn_enabled,
|
||||||
is_tunnel_on_ethernet_enabled,
|
is_tunnel_on_ethernet_enabled,
|
||||||
is_shortcuts_enabled,
|
is_shortcuts_enabled,
|
||||||
is_tunnel_on_wifi_enabled,
|
is_tunnel_on_wifi_enabled,
|
||||||
is_kernel_enabled,
|
is_kernel_enabled,
|
||||||
is_restore_on_boot_enabled,
|
is_restore_on_boot_enabled,
|
||||||
is_multi_tunnel_enabled)
|
is_multi_tunnel_enabled)
|
||||||
VALUES
|
VALUES
|
||||||
('false',
|
('false',
|
||||||
'false',
|
'false',
|
||||||
'sampleSSID1,sampleSSID2',
|
'',
|
||||||
'false',
|
'false',
|
||||||
'false',
|
'false',
|
||||||
'false',
|
'false',
|
||||||
'false',
|
'false',
|
||||||
'false',
|
'false',
|
||||||
'false',
|
'false',
|
||||||
'false')
|
'false')
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun createTunnelConfig(): String {
|
fun createTunnelConfig(): String {
|
||||||
return """
|
return """
|
||||||
INSERT INTO TunnelConfig (name, wg_quick) VALUES ('test', 'test')
|
INSERT INTO TunnelConfig (name, wg_quick) VALUES ('test', 'test')
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,27 +10,27 @@ import kotlinx.coroutines.flow.Flow
|
|||||||
|
|
||||||
@Dao
|
@Dao
|
||||||
interface SettingsDao {
|
interface SettingsDao {
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun save(t: Settings)
|
suspend fun save(t: Settings)
|
||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun saveAll(t: List<Settings>)
|
suspend fun saveAll(t: List<Settings>)
|
||||||
|
|
||||||
@Query("SELECT * FROM settings WHERE id=:id")
|
@Query("SELECT * FROM settings WHERE id=:id")
|
||||||
suspend fun getById(id: Long): Settings?
|
suspend fun getById(id: Long): Settings?
|
||||||
|
|
||||||
@Query("SELECT * FROM settings")
|
@Query("SELECT * FROM settings")
|
||||||
suspend fun getAll(): List<Settings>
|
suspend fun getAll(): List<Settings>
|
||||||
|
|
||||||
@Query("SELECT * FROM settings LIMIT 1")
|
@Query("SELECT * FROM settings LIMIT 1")
|
||||||
fun getSettingsFlow(): Flow<Settings>
|
fun getSettingsFlow(): Flow<Settings>
|
||||||
|
|
||||||
@Query("SELECT * FROM settings")
|
@Query("SELECT * FROM settings")
|
||||||
fun getAllFlow(): Flow<MutableList<Settings>>
|
fun getAllFlow(): Flow<MutableList<Settings>>
|
||||||
|
|
||||||
@Delete
|
@Delete
|
||||||
suspend fun delete(t: Settings)
|
suspend fun delete(t: Settings)
|
||||||
|
|
||||||
@Query("SELECT COUNT('id') FROM settings")
|
@Query("SELECT COUNT('id') FROM settings")
|
||||||
suspend fun count(): Long
|
suspend fun count(): Long
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,47 +6,53 @@ 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
|
||||||
interface TunnelConfigDao {
|
interface TunnelConfigDao {
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun save(t: TunnelConfig)
|
suspend fun save(t: TunnelConfig)
|
||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun saveAll(t: TunnelConfigs)
|
suspend fun saveAll(t: TunnelConfigs)
|
||||||
|
|
||||||
@Query("SELECT * FROM TunnelConfig WHERE id=:id")
|
@Query("SELECT * FROM TunnelConfig WHERE id=:id")
|
||||||
suspend fun getById(id: Long): TunnelConfig?
|
suspend fun getById(id: Long): TunnelConfig?
|
||||||
|
|
||||||
@Query("SELECT * FROM TunnelConfig WHERE name=:name")
|
@Query("SELECT * FROM TunnelConfig WHERE name=:name")
|
||||||
suspend fun getByName(name: String): TunnelConfig?
|
suspend fun getByName(name: String): TunnelConfig?
|
||||||
|
|
||||||
@Query("SELECT * FROM TunnelConfig")
|
@Query("SELECT * FROM TunnelConfig WHERE is_Active=1")
|
||||||
suspend fun getAll(): TunnelConfigs
|
suspend fun getActive(): TunnelConfigs
|
||||||
|
|
||||||
@Delete
|
@Query("SELECT * FROM TunnelConfig")
|
||||||
suspend fun delete(t: TunnelConfig)
|
suspend fun getAll(): TunnelConfigs
|
||||||
|
|
||||||
@Query("SELECT COUNT('id') FROM TunnelConfig")
|
@Delete
|
||||||
suspend fun count(): Long
|
suspend fun delete(t: TunnelConfig)
|
||||||
|
|
||||||
@Query("SELECT * FROM TunnelConfig WHERE tunnel_networks LIKE '%' || :name || '%'")
|
@Query("SELECT COUNT('id') FROM TunnelConfig")
|
||||||
suspend fun findByTunnelNetworkName(name: String): TunnelConfigs
|
suspend fun count(): Long
|
||||||
|
|
||||||
@Query("UPDATE TunnelConfig SET is_primary_tunnel = 0 WHERE is_primary_tunnel =1")
|
@Query("SELECT * FROM TunnelConfig WHERE tunnel_networks LIKE '%' || :name || '%'")
|
||||||
suspend fun resetPrimaryTunnel()
|
suspend fun findByTunnelNetworkName(name: String): TunnelConfigs
|
||||||
|
|
||||||
@Query("UPDATE TunnelConfig SET is_mobile_data_tunnel = 0 WHERE is_mobile_data_tunnel =1")
|
@Query("UPDATE TunnelConfig SET is_primary_tunnel = 0 WHERE is_primary_tunnel =1")
|
||||||
suspend fun resetMobileDataTunnel()
|
suspend fun resetPrimaryTunnel()
|
||||||
|
|
||||||
@Query("SELECT * FROM TUNNELCONFIG WHERE is_primary_tunnel=1")
|
@Query("UPDATE TunnelConfig SET is_mobile_data_tunnel = 0 WHERE is_mobile_data_tunnel =1")
|
||||||
suspend fun findByPrimary(): TunnelConfigs
|
suspend fun resetMobileDataTunnel()
|
||||||
|
|
||||||
@Query("SELECT * FROM TUNNELCONFIG WHERE is_mobile_data_tunnel=1")
|
@Query("UPDATE TunnelConfig SET is_ethernet_tunnel = 0 WHERE is_ethernet_tunnel =1")
|
||||||
suspend fun findByMobileDataTunnel(): TunnelConfigs
|
suspend fun resetEthernetTunnel()
|
||||||
|
|
||||||
@Query("SELECT * FROM tunnelconfig")
|
@Query("SELECT * FROM TUNNELCONFIG WHERE is_primary_tunnel=1")
|
||||||
fun getAllFlow(): Flow<MutableList<TunnelConfig>>
|
suspend fun findByPrimary(): TunnelConfigs
|
||||||
|
|
||||||
|
@Query("SELECT * FROM TUNNELCONFIG WHERE is_mobile_data_tunnel=1")
|
||||||
|
suspend fun findByMobileDataTunnel(): TunnelConfigs
|
||||||
|
|
||||||
|
@Query("SELECT * FROM tunnelconfig")
|
||||||
|
fun getAllFlow(): Flow<MutableList<TunnelConfig>>
|
||||||
}
|
}
|
||||||
|
|||||||
+64
-54
@@ -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
|
||||||
@@ -18,66 +17,77 @@ import timber.log.Timber
|
|||||||
import java.io.IOException
|
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 locationDisclosureShown = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
|
||||||
val BATTERY_OPTIMIZE_DISABLE_SHOWN = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
val batteryDisableShown = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
||||||
val TUNNEL_RUNNING_FROM_MANUAL_START =
|
val currentSSID = stringPreferencesKey("CURRENT_SSID")
|
||||||
booleanPreferencesKey("TUNNEL_RUNNING_FROM_MANUAL_START")
|
val pinLockEnabled = booleanPreferencesKey("PIN_LOCK_ENABLED")
|
||||||
val ACTIVE_TUNNEL = intPreferencesKey("ACTIVE_TUNNEL")
|
val tunnelStatsExpanded = booleanPreferencesKey("TUNNEL_STATS_EXPANDED")
|
||||||
val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
|
val isLocalLogsEnabled = booleanPreferencesKey("LOCAL_LOGS_ENABLED")
|
||||||
val IS_PIN_LOCK_ENABLED = booleanPreferencesKey("PIN_LOCK_ENABLED")
|
val locale = stringPreferencesKey("LOCALE")
|
||||||
}
|
val theme = stringPreferencesKey("THEME")
|
||||||
|
}
|
||||||
|
|
||||||
// preferences
|
// preferences
|
||||||
private val preferencesKey = "preferences"
|
private val preferencesKey = "preferences"
|
||||||
private val Context.dataStore by
|
private val Context.dataStore by
|
||||||
preferencesDataStore(
|
preferencesDataStore(
|
||||||
name = preferencesKey,
|
name = preferencesKey,
|
||||||
)
|
)
|
||||||
|
|
||||||
suspend fun init() {
|
suspend fun init() {
|
||||||
withContext(ioDispatcher) {
|
withContext(ioDispatcher) {
|
||||||
try {
|
try {
|
||||||
context.dataStore.data.first()
|
context.dataStore.data.first()
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun <T> saveToDataStore(key: Preferences.Key<T>, value: T) {
|
suspend fun <T> saveToDataStore(key: Preferences.Key<T>, value: T) {
|
||||||
withContext(ioDispatcher) {
|
withContext(ioDispatcher) {
|
||||||
try {
|
try {
|
||||||
context.dataStore.edit { it[key] = value }
|
context.dataStore.edit { it[key] = value }
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun <T> removeFromDataStore(key: Preferences.Key<T>) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
try {
|
||||||
|
context.dataStore.edit { it.remove(key) }
|
||||||
|
} catch (e: IOException) {
|
||||||
|
Timber.e(e)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Timber.e(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun <T> getFromStoreFlow(key: Preferences.Key<T>) = context.dataStore.data.map { it[key] }
|
fun <T> getFromStoreFlow(key: Preferences.Key<T>) = context.dataStore.data.map { it[key] }
|
||||||
|
|
||||||
suspend fun <T> getFromStore(key: Preferences.Key<T>): T? {
|
suspend fun <T> getFromStore(key: Preferences.Key<T>): T? {
|
||||||
return withContext(ioDispatcher) {
|
return withContext(ioDispatcher) {
|
||||||
try {
|
try {
|
||||||
context.dataStore.data.map { it[key] }.first()
|
context.dataStore.data.map { it[key] }.first()
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
Timber.e(e)
|
Timber.e(e)
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking {
|
||||||
|
context.dataStore.data.map { it[key] }.first()
|
||||||
|
}
|
||||||
|
|
||||||
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking {
|
val preferencesFlow: Flow<Preferences?> = context.dataStore.data
|
||||||
context.dataStore.data.map { it[key] }.first()
|
|
||||||
}
|
|
||||||
|
|
||||||
val preferencesFlow: Flow<Preferences?> = context.dataStore.data
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,21 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.data.domain
|
package com.zaneschepke.wireguardautotunnel.data.domain
|
||||||
|
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||||
|
|
||||||
data class GeneralState(
|
data class GeneralState(
|
||||||
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
||||||
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
||||||
val isTunnelRunningFromManualStart: Boolean = TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
|
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
|
||||||
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
|
val isTunnelStatsExpanded: Boolean = IS_TUNNEL_STATS_EXPANDED,
|
||||||
val activeTunnelId: Int? = null
|
val isLocalLogsEnabled: Boolean = IS_LOGS_ENABLED_DEFAULT,
|
||||||
|
val locale: String? = null,
|
||||||
|
val theme: Theme = Theme.AUTOMATIC,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
|
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
|
||||||
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
|
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
|
||||||
const val TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT = false
|
const val PIN_LOCK_ENABLED_DEFAULT = false
|
||||||
const val PIN_LOCK_ENABLED_DEFAULT = false
|
const val IS_TUNNEL_STATS_EXPANDED = false
|
||||||
}
|
const val IS_LOGS_ENABLED_DEFAULT = false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,53 +6,78 @@ import androidx.room.PrimaryKey
|
|||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
data class Settings(
|
data class Settings(
|
||||||
@PrimaryKey(autoGenerate = true) val id: Int = 0,
|
@PrimaryKey(autoGenerate = true) val id: Int = 0,
|
||||||
@ColumnInfo(name = "is_tunnel_enabled") val isAutoTunnelEnabled: Boolean = false,
|
@ColumnInfo(name = "is_tunnel_enabled") val isAutoTunnelEnabled: Boolean = false,
|
||||||
@ColumnInfo(name = "is_tunnel_on_mobile_data_enabled")
|
@ColumnInfo(name = "is_tunnel_on_mobile_data_enabled")
|
||||||
val isTunnelOnMobileDataEnabled: Boolean = false,
|
val isTunnelOnMobileDataEnabled: Boolean = false,
|
||||||
@ColumnInfo(name = "trusted_network_ssids")
|
@ColumnInfo(name = "trusted_network_ssids")
|
||||||
val trustedNetworkSSIDs: MutableList<String> = mutableListOf(),
|
val trustedNetworkSSIDs: MutableList<String> = mutableListOf(),
|
||||||
@ColumnInfo(name = "is_always_on_vpn_enabled") val isAlwaysOnVpnEnabled: Boolean = false,
|
@ColumnInfo(name = "is_always_on_vpn_enabled") val isAlwaysOnVpnEnabled: Boolean = false,
|
||||||
@ColumnInfo(name = "is_tunnel_on_ethernet_enabled")
|
@ColumnInfo(name = "is_tunnel_on_ethernet_enabled")
|
||||||
val isTunnelOnEthernetEnabled: Boolean = false,
|
val isTunnelOnEthernetEnabled: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_shortcuts_enabled",
|
name = "is_shortcuts_enabled",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isShortcutsEnabled: Boolean = false,
|
val isShortcutsEnabled: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_tunnel_on_wifi_enabled",
|
name = "is_tunnel_on_wifi_enabled",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isTunnelOnWifiEnabled: Boolean = false,
|
val isTunnelOnWifiEnabled: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_kernel_enabled",
|
name = "is_kernel_enabled",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isKernelEnabled: Boolean = false,
|
val isKernelEnabled: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_restore_on_boot_enabled",
|
name = "is_restore_on_boot_enabled",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isRestoreOnBootEnabled: Boolean = false,
|
val isRestoreOnBootEnabled: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_multi_tunnel_enabled",
|
name = "is_multi_tunnel_enabled",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isMultiTunnelEnabled: Boolean = false,
|
val isMultiTunnelEnabled: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_auto_tunnel_paused",
|
name = "is_ping_enabled",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isAutoTunnelPaused: Boolean = false,
|
val isPingEnabled: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_ping_enabled",
|
name = "is_amnezia_enabled",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isPingEnabled: Boolean = false,
|
val isAmneziaEnabled: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_amnezia_enabled",
|
name = "is_wildcards_enabled",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isAmneziaEnabled: Boolean = false,
|
val isWildcardsEnabled: Boolean = false,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "is_wifi_by_shell_enabled",
|
||||||
|
defaultValue = "false",
|
||||||
|
)
|
||||||
|
val isWifiNameByShellEnabled: Boolean = false,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "is_stop_on_no_internet_enabled",
|
||||||
|
defaultValue = "false",
|
||||||
|
)
|
||||||
|
val isStopOnNoInternetEnabled: Boolean = false,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "is_vpn_kill_switch_enabled",
|
||||||
|
defaultValue = "false",
|
||||||
|
)
|
||||||
|
val isVpnKillSwitchEnabled: Boolean = false,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "is_kernel_kill_switch_enabled",
|
||||||
|
defaultValue = "false",
|
||||||
|
)
|
||||||
|
val isKernelKillSwitchEnabled: Boolean = false,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "is_lan_on_kill_switch_enabled",
|
||||||
|
defaultValue = "false",
|
||||||
|
)
|
||||||
|
val isLanOnKillSwitchEnabled: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -5,49 +5,105 @@ import androidx.room.Entity
|
|||||||
import androidx.room.Index
|
import androidx.room.Index
|
||||||
import androidx.room.PrimaryKey
|
import androidx.room.PrimaryKey
|
||||||
import com.wireguard.config.Config
|
import com.wireguard.config.Config
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.toWgQuickString
|
||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
|
|
||||||
@Entity(indices = [Index(value = ["name"], unique = true)])
|
@Entity(indices = [Index(value = ["name"], unique = true)])
|
||||||
data class TunnelConfig(
|
data class TunnelConfig(
|
||||||
@PrimaryKey(autoGenerate = true) val id: Int = 0,
|
@PrimaryKey(autoGenerate = true) val id: Int = 0,
|
||||||
@ColumnInfo(name = "name") val name: String,
|
@ColumnInfo(name = "name") val name: String,
|
||||||
@ColumnInfo(name = "wg_quick") val wgQuick: String,
|
@ColumnInfo(name = "wg_quick") val wgQuick: String,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "tunnel_networks",
|
name = "tunnel_networks",
|
||||||
defaultValue = "",
|
defaultValue = "",
|
||||||
)
|
)
|
||||||
val tunnelNetworks: MutableList<String> = mutableListOf(),
|
val tunnelNetworks: MutableList<String> = mutableListOf(),
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_mobile_data_tunnel",
|
name = "is_mobile_data_tunnel",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isMobileDataTunnel: Boolean = false,
|
val isMobileDataTunnel: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "is_primary_tunnel",
|
name = "is_primary_tunnel",
|
||||||
defaultValue = "false",
|
defaultValue = "false",
|
||||||
)
|
)
|
||||||
val isPrimaryTunnel: Boolean = false,
|
val isPrimaryTunnel: Boolean = false,
|
||||||
@ColumnInfo(
|
@ColumnInfo(
|
||||||
name = "am_quick",
|
name = "am_quick",
|
||||||
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,
|
||||||
|
@ColumnInfo(
|
||||||
|
name = "is_ethernet_tunnel",
|
||||||
|
defaultValue = "false",
|
||||||
|
)
|
||||||
|
var isEthernetTunnel: Boolean = false,
|
||||||
) {
|
) {
|
||||||
companion object {
|
|
||||||
fun configFromWgQuick(wgQuick: String): Config {
|
|
||||||
val inputStream: InputStream = wgQuick.byteInputStream()
|
|
||||||
return inputStream.bufferedReader(Charsets.UTF_8).use {
|
|
||||||
Config.parse(it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun configFromAmQuick(amQuick: String): org.amnezia.awg.config.Config {
|
fun toAmConfig(): org.amnezia.awg.config.Config {
|
||||||
val inputStream: InputStream = amQuick.byteInputStream()
|
return configFromAmQuick(if (amQuick != "") amQuick else wgQuick)
|
||||||
return inputStream.bufferedReader(Charsets.UTF_8).use {
|
}
|
||||||
org.amnezia.awg.config.Config.parse(it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const val AM_QUICK_DEFAULT = ""
|
fun toWgConfig(): Config {
|
||||||
}
|
return configFromWgQuick(wgQuick)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
fun configFromWgQuick(wgQuick: String): Config {
|
||||||
|
val inputStream: InputStream = wgQuick.byteInputStream()
|
||||||
|
return inputStream.bufferedReader(Charsets.UTF_8).use {
|
||||||
|
Config.parse(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun configFromAmQuick(amQuick: String): org.amnezia.awg.config.Config {
|
||||||
|
val inputStream: InputStream = amQuick.byteInputStream()
|
||||||
|
return inputStream.bufferedReader(Charsets.UTF_8).use {
|
||||||
|
org.amnezia.awg.config.Config.parse(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun tunnelConfigFromAmConfig(config: org.amnezia.awg.config.Config, name: String): TunnelConfig {
|
||||||
|
val amQuick = config.toAwgQuickString(true)
|
||||||
|
val wgQuick = config.toWgQuickString()
|
||||||
|
return TunnelConfig(name = name, wgQuick = wgQuick, amQuick = amQuick)
|
||||||
|
}
|
||||||
|
|
||||||
|
const val AM_QUICK_DEFAULT = ""
|
||||||
|
|
||||||
|
val IPV4_PUBLIC_NETWORKS = setOf(
|
||||||
|
"0.0.0.0/5", "8.0.0.0/7", "11.0.0.0/8", "12.0.0.0/6", "16.0.0.0/4", "32.0.0.0/3",
|
||||||
|
"64.0.0.0/2", "128.0.0.0/3", "160.0.0.0/5", "168.0.0.0/6", "172.0.0.0/12",
|
||||||
|
"172.32.0.0/11", "172.64.0.0/10", "172.128.0.0/9", "173.0.0.0/8", "174.0.0.0/7",
|
||||||
|
"176.0.0.0/4", "192.0.0.0/9", "192.128.0.0/11", "192.160.0.0/13", "192.169.0.0/16",
|
||||||
|
"192.170.0.0/15", "192.172.0.0/14", "192.176.0.0/12", "192.192.0.0/10",
|
||||||
|
"193.0.0.0/8", "194.0.0.0/7", "196.0.0.0/6", "200.0.0.0/5", "208.0.0.0/4",
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-6
@@ -3,12 +3,11 @@ package com.zaneschepke.wireguardautotunnel.data.repository
|
|||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
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
|
||||||
val appState: AppStateRepository
|
val appState: AppStateRepository
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-26
@@ -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
|
||||||
override val settings: SettingsRepository,
|
@Inject
|
||||||
override val tunnels: TunnelConfigRepository,
|
constructor(
|
||||||
override val appState: AppStateRepository
|
override val settings: SettingsRepository,
|
||||||
|
override val tunnels: TunnelConfigRepository,
|
||||||
|
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,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-13
@@ -1,29 +1,37 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.data.repository
|
package com.zaneschepke.wireguardautotunnel.data.repository
|
||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
interface AppStateRepository {
|
interface AppStateRepository {
|
||||||
suspend fun isLocationDisclosureShown(): Boolean
|
suspend fun isLocationDisclosureShown(): Boolean
|
||||||
suspend fun setLocationDisclosureShown(shown: Boolean)
|
|
||||||
|
|
||||||
suspend fun isPinLockEnabled(): Boolean
|
suspend fun setLocationDisclosureShown(shown: Boolean)
|
||||||
suspend fun setPinLockEnabled(enabled: Boolean)
|
|
||||||
|
|
||||||
suspend fun isBatteryOptimizationDisableShown(): Boolean
|
suspend fun isPinLockEnabled(): Boolean
|
||||||
suspend fun setBatteryOptimizationDisableShown(shown: Boolean)
|
|
||||||
|
|
||||||
suspend fun isTunnelRunningFromManualStart(): Boolean
|
suspend fun setPinLockEnabled(enabled: Boolean)
|
||||||
suspend fun setTunnelRunningFromManualStart(id: Int)
|
|
||||||
|
|
||||||
suspend fun setManualStop()
|
suspend fun isBatteryOptimizationDisableShown(): Boolean
|
||||||
|
|
||||||
suspend fun getActiveTunnelId(): Int?
|
suspend fun setBatteryOptimizationDisableShown(shown: Boolean)
|
||||||
|
|
||||||
suspend fun getCurrentSsid(): String?
|
suspend fun isTunnelStatsExpanded(): Boolean
|
||||||
|
|
||||||
suspend fun setCurrentSsid(ssid: String)
|
suspend fun setTunnelStatsExpanded(expanded: Boolean)
|
||||||
|
|
||||||
val generalStateFlow: Flow<GeneralState>
|
suspend fun setTheme(theme: Theme)
|
||||||
|
|
||||||
|
suspend fun getTheme(): Theme
|
||||||
|
|
||||||
|
suspend fun isLocalLogsEnabled(): Boolean
|
||||||
|
|
||||||
|
suspend fun setLocalLogsEnabled(enabled: Boolean)
|
||||||
|
|
||||||
|
suspend fun setLocale(localeTag: String)
|
||||||
|
|
||||||
|
suspend fun getLocale(): String?
|
||||||
|
|
||||||
|
val generalStateFlow: Flow<GeneralState>
|
||||||
}
|
}
|
||||||
|
|||||||
+82
-69
@@ -2,91 +2,104 @@ package com.zaneschepke.wireguardautotunnel.data.repository
|
|||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
|
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||||
import kotlinx.coroutines.flow.Flow
|
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(
|
||||||
AppStateRepository {
|
private val dataStoreManager: DataStoreManager,
|
||||||
override suspend fun isLocationDisclosureShown(): Boolean {
|
) :
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN)
|
AppStateRepository {
|
||||||
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT
|
override suspend fun isLocationDisclosureShown(): Boolean {
|
||||||
}
|
return dataStoreManager.getFromStore(DataStoreManager.locationDisclosureShown)
|
||||||
|
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun setLocationDisclosureShown(shown: Boolean) {
|
override suspend fun setLocationDisclosureShown(shown: Boolean) {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown)
|
dataStoreManager.saveToDataStore(DataStoreManager.locationDisclosureShown, shown)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun isPinLockEnabled(): Boolean {
|
override suspend fun isPinLockEnabled(): Boolean {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.IS_PIN_LOCK_ENABLED)
|
return dataStoreManager.getFromStore(DataStoreManager.pinLockEnabled)
|
||||||
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT
|
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun setPinLockEnabled(enabled: Boolean) {
|
override suspend fun setPinLockEnabled(enabled: Boolean) {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.IS_PIN_LOCK_ENABLED, enabled)
|
dataStoreManager.saveToDataStore(DataStoreManager.pinLockEnabled, enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun isBatteryOptimizationDisableShown(): Boolean {
|
override suspend fun isBatteryOptimizationDisableShown(): Boolean {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN)
|
return dataStoreManager.getFromStore(DataStoreManager.batteryDisableShown)
|
||||||
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
|
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun setBatteryOptimizationDisableShown(shown: Boolean) {
|
override suspend fun setBatteryOptimizationDisableShown(shown: Boolean) {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN, shown)
|
dataStoreManager.saveToDataStore(DataStoreManager.batteryDisableShown, shown)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun isTunnelRunningFromManualStart(): Boolean {
|
override suspend fun isTunnelStatsExpanded(): Boolean {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START)
|
return dataStoreManager.getFromStore(DataStoreManager.tunnelStatsExpanded)
|
||||||
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT
|
?: GeneralState.IS_TUNNEL_STATS_EXPANDED
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun setTunnelRunningFromManualStart(id: Int) {
|
override suspend fun setTunnelStatsExpanded(expanded: Boolean) {
|
||||||
setTunnelRunningFromManualStart(true)
|
dataStoreManager.saveToDataStore(DataStoreManager.tunnelStatsExpanded, expanded)
|
||||||
setActiveTunnelId(id)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun setManualStop() {
|
override suspend fun setTheme(theme: Theme) {
|
||||||
setTunnelRunningFromManualStart(false)
|
dataStoreManager.saveToDataStore(DataStoreManager.theme, theme.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun setTunnelRunningFromManualStart(running: Boolean) {
|
override suspend fun getTheme(): Theme {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START, running)
|
return dataStoreManager.getFromStore(DataStoreManager.theme)?.let {
|
||||||
}
|
try {
|
||||||
|
Theme.valueOf(it)
|
||||||
|
} catch (_: IllegalArgumentException) {
|
||||||
|
Theme.AUTOMATIC
|
||||||
|
}
|
||||||
|
} ?: Theme.AUTOMATIC
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun getActiveTunnelId(): Int? {
|
override suspend fun isLocalLogsEnabled(): Boolean {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.ACTIVE_TUNNEL)
|
return dataStoreManager.getFromStore(DataStoreManager.isLocalLogsEnabled) ?: GeneralState.IS_LOGS_ENABLED_DEFAULT
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun setActiveTunnelId(id: Int) {
|
override suspend fun setLocalLogsEnabled(enabled: Boolean) {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.ACTIVE_TUNNEL, id)
|
dataStoreManager.saveToDataStore(DataStoreManager.isLocalLogsEnabled, enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getCurrentSsid(): String? {
|
override suspend fun setLocale(localeTag: String) {
|
||||||
return dataStoreManager.getFromStore(DataStoreManager.CURRENT_SSID)
|
dataStoreManager.saveToDataStore(DataStoreManager.locale, localeTag)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun setCurrentSsid(ssid: String) {
|
override suspend fun getLocale(): String? {
|
||||||
dataStoreManager.saveToDataStore(DataStoreManager.CURRENT_SSID, ssid)
|
return dataStoreManager.getFromStore(DataStoreManager.locale)
|
||||||
}
|
}
|
||||||
|
|
||||||
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(
|
||||||
isLocationDisclosureShown = pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
|
isLocationDisclosureShown =
|
||||||
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
pref[DataStoreManager.locationDisclosureShown]
|
||||||
isBatteryOptimizationDisableShown = pref[DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN]
|
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
||||||
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
isBatteryOptimizationDisableShown =
|
||||||
isTunnelRunningFromManualStart = pref[DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START]
|
pref[DataStoreManager.batteryDisableShown]
|
||||||
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
|
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
||||||
isPinLockEnabled = pref[DataStoreManager.IS_PIN_LOCK_ENABLED]
|
isPinLockEnabled =
|
||||||
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
|
pref[DataStoreManager.pinLockEnabled]
|
||||||
)
|
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT,
|
||||||
} catch (e: IllegalArgumentException) {
|
isTunnelStatsExpanded = pref[DataStoreManager.tunnelStatsExpanded] ?: GeneralState.IS_TUNNEL_STATS_EXPANDED,
|
||||||
Timber.e(e)
|
isLocalLogsEnabled = pref[DataStoreManager.isLocalLogsEnabled] ?: GeneralState.IS_LOGS_ENABLED_DEFAULT,
|
||||||
GeneralState()
|
locale = pref[DataStoreManager.locale],
|
||||||
}
|
theme = getTheme(),
|
||||||
} ?: GeneralState()
|
)
|
||||||
}
|
} catch (e: IllegalArgumentException) {
|
||||||
|
Timber.e(e)
|
||||||
|
GeneralState()
|
||||||
|
}
|
||||||
|
} ?: GeneralState()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-14
@@ -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) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
settingsDoa.save(settings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun save(settings: Settings) {
|
override fun getSettingsFlow(): Flow<Settings> {
|
||||||
settingsDoa.save(settings)
|
return settingsDoa.getSettingsFlow()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getSettingsFlow(): Flow<Settings> {
|
override suspend fun getSettings(): Settings {
|
||||||
return settingsDoa.getSettingsFlow()
|
return withContext(ioDispatcher) {
|
||||||
}
|
settingsDoa.getAll().firstOrNull() ?: Settings()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun getSettings(): Settings {
|
override suspend fun getAll(): List<Settings> {
|
||||||
return settingsDoa.getAll().firstOrNull() ?: Settings()
|
return withContext(ioDispatcher) { settingsDoa.getAll() }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getAll(): List<Settings> {
|
|
||||||
return settingsDoa.getAll()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+85
-53
@@ -2,71 +2,103 @@ package com.zaneschepke.wireguardautotunnel.data.repository
|
|||||||
|
|
||||||
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 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(
|
||||||
TunnelConfigRepository {
|
private val tunnelConfigDao: TunnelConfigDao,
|
||||||
override fun getTunnelConfigsFlow(): Flow<TunnelConfigs> {
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
return tunnelConfigDao.getAllFlow()
|
) :
|
||||||
}
|
TunnelConfigRepository {
|
||||||
|
override fun getTunnelConfigsFlow(): Flow<TunnelConfigs> {
|
||||||
|
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) {
|
||||||
tunnelConfigDao.save(tunnelConfig)
|
withContext(ioDispatcher) {
|
||||||
}
|
tunnelConfigDao.save(tunnelConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?) {
|
override suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?) {
|
||||||
tunnelConfigDao.resetPrimaryTunnel()
|
withContext(ioDispatcher) {
|
||||||
tunnelConfig?.let {
|
tunnelConfigDao.resetPrimaryTunnel()
|
||||||
save(
|
tunnelConfig?.let {
|
||||||
it.copy(
|
save(
|
||||||
isPrimaryTunnel = true,
|
it.copy(
|
||||||
),
|
isPrimaryTunnel = true,
|
||||||
)
|
),
|
||||||
}
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
tunnelConfigDao.resetMobileDataTunnel()
|
||||||
|
tunnelConfig?.let {
|
||||||
|
save(
|
||||||
|
it.copy(
|
||||||
|
isMobileDataTunnel = true,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
|
override suspend fun updateEthernetTunnel(tunnelConfig: TunnelConfig?) {
|
||||||
tunnelConfigDao.resetMobileDataTunnel()
|
withContext(ioDispatcher) {
|
||||||
tunnelConfig?.let {
|
tunnelConfigDao.resetEthernetTunnel()
|
||||||
save(
|
tunnelConfig?.let {
|
||||||
it.copy(
|
save(
|
||||||
isMobileDataTunnel = true,
|
it.copy(
|
||||||
),
|
isEthernetTunnel = true,
|
||||||
)
|
),
|
||||||
}
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun delete(tunnelConfig: TunnelConfig) {
|
override suspend fun delete(tunnelConfig: TunnelConfig) {
|
||||||
tunnelConfigDao.delete(tunnelConfig)
|
withContext(ioDispatcher) {
|
||||||
}
|
tunnelConfigDao.delete(tunnelConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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 count(): Int {
|
override suspend fun getActive(): TunnelConfigs {
|
||||||
return tunnelConfigDao.count().toInt()
|
return withContext(ioDispatcher) {
|
||||||
}
|
tunnelConfigDao.getActive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun findByTunnelName(name: String): TunnelConfig? {
|
override suspend fun count(): Int {
|
||||||
return tunnelConfigDao.getByName(name)
|
return withContext(ioDispatcher) { tunnelConfigDao.count().toInt() }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findByTunnelNetworksName(name: String): TunnelConfigs {
|
override suspend fun findByTunnelName(name: String): TunnelConfig? {
|
||||||
return tunnelConfigDao.findByTunnelNetworkName(name)
|
return withContext(ioDispatcher) { tunnelConfigDao.getByName(name) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findByMobileDataTunnel(): TunnelConfigs {
|
override suspend fun findByTunnelNetworksName(name: String): TunnelConfigs {
|
||||||
return tunnelConfigDao.findByMobileDataTunnel()
|
return withContext(ioDispatcher) { tunnelConfigDao.findByTunnelNetworkName(name) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun findPrimary(): TunnelConfigs {
|
override suspend fun findByMobileDataTunnel(): TunnelConfigs {
|
||||||
return tunnelConfigDao.findByPrimary()
|
return withContext(ioDispatcher) { tunnelConfigDao.findByMobileDataTunnel() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun findPrimary(): TunnelConfigs {
|
||||||
|
return withContext(ioDispatcher) { tunnelConfigDao.findByPrimary() }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -4,11 +4,11 @@ import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
|||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
interface SettingsRepository {
|
interface SettingsRepository {
|
||||||
suspend fun save(settings: Settings)
|
suspend fun save(settings: Settings)
|
||||||
|
|
||||||
fun getSettingsFlow(): Flow<Settings>
|
fun getSettingsFlow(): Flow<Settings>
|
||||||
|
|
||||||
suspend fun getSettings(): Settings
|
suspend fun getSettings(): Settings
|
||||||
|
|
||||||
suspend fun getAll(): List<Settings>
|
suspend fun getAll(): List<Settings>
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-13
@@ -1,32 +1,35 @@
|
|||||||
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
|
suspend fun save(tunnelConfig: TunnelConfig)
|
||||||
|
|
||||||
suspend fun save(tunnelConfig: TunnelConfig)
|
suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?)
|
||||||
|
|
||||||
suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?)
|
suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?)
|
||||||
|
|
||||||
suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?)
|
suspend fun updateEthernetTunnel(tunnelConfig: TunnelConfig?)
|
||||||
|
|
||||||
suspend fun delete(tunnelConfig: TunnelConfig)
|
suspend fun delete(tunnelConfig: TunnelConfig)
|
||||||
|
|
||||||
suspend fun getById(id: Int): TunnelConfig?
|
suspend fun getById(id: Int): TunnelConfig?
|
||||||
|
|
||||||
suspend fun count(): Int
|
suspend fun getActive(): TunnelConfigs
|
||||||
|
|
||||||
suspend fun findByTunnelName(name: String): TunnelConfig?
|
suspend fun count(): Int
|
||||||
|
|
||||||
suspend fun findByTunnelNetworksName(name: String): TunnelConfigs
|
suspend fun findByTunnelName(name: String): TunnelConfig?
|
||||||
|
|
||||||
suspend fun findByMobileDataTunnel(): TunnelConfigs
|
suspend fun findByTunnelNetworksName(name: String): TunnelConfigs
|
||||||
|
|
||||||
suspend fun findPrimary(): TunnelConfigs
|
suspend fun findByMobileDataTunnel(): TunnelConfigs
|
||||||
|
|
||||||
|
suspend fun findPrimary(): TunnelConfigs
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
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.LogcatReader
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.WireGuardNotification
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.shortcut.DynamicShortcutManager
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.shortcut.ShortcutManager
|
||||||
import dagger.Module
|
import dagger.Module
|
||||||
import dagger.Provides
|
import dagger.Provides
|
||||||
import dagger.hilt.InstallIn
|
import dagger.hilt.InstallIn
|
||||||
@@ -16,15 +20,27 @@ import javax.inject.Singleton
|
|||||||
@Module
|
@Module
|
||||||
@InstallIn(SingletonComponent::class)
|
@InstallIn(SingletonComponent::class)
|
||||||
class AppModule {
|
class AppModule {
|
||||||
@Singleton
|
@Singleton
|
||||||
@ApplicationScope
|
@ApplicationScope
|
||||||
@Provides
|
@Provides
|
||||||
fun providesApplicationScope(@DefaultDispatcher defaultDispatcher: CoroutineDispatcher): CoroutineScope =
|
fun providesApplicationScope(@DefaultDispatcher defaultDispatcher: CoroutineDispatcher): CoroutineScope =
|
||||||
CoroutineScope(SupervisorJob() + defaultDispatcher)
|
CoroutineScope(SupervisorJob() + defaultDispatcher)
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector {
|
fun provideLogCollect(@ApplicationContext context: Context): LogReader {
|
||||||
return LogcatHelper.init(context = context)
|
return LogcatReader.init(storageDir = context.filesDir.absolutePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun provideNotificationService(@ApplicationContext context: Context): NotificationService {
|
||||||
|
return WireGuardNotification(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun provideShortcutManager(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): ShortcutManager {
|
||||||
|
return DynamicShortcutManager(context, ioDispatcher)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,3 +9,11 @@ annotation class Kernel
|
|||||||
@Qualifier
|
@Qualifier
|
||||||
@Retention(AnnotationRetention.BINARY)
|
@Retention(AnnotationRetention.BINARY)
|
||||||
annotation class Userspace
|
annotation class Userspace
|
||||||
|
|
||||||
|
@Qualifier
|
||||||
|
@Retention(AnnotationRetention.BINARY)
|
||||||
|
annotation class TunnelShell
|
||||||
|
|
||||||
|
@Qualifier
|
||||||
|
@Retention(AnnotationRetention.BINARY)
|
||||||
|
annotation class AppShell
|
||||||
|
|||||||
+12
-12
@@ -10,19 +10,19 @@ import kotlinx.coroutines.Dispatchers
|
|||||||
@Module
|
@Module
|
||||||
@InstallIn(SingletonComponent::class)
|
@InstallIn(SingletonComponent::class)
|
||||||
object CoroutinesDispatchersModule {
|
object CoroutinesDispatchersModule {
|
||||||
@DefaultDispatcher
|
@DefaultDispatcher
|
||||||
@Provides
|
@Provides
|
||||||
fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
|
fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
|
||||||
|
|
||||||
@IoDispatcher
|
@IoDispatcher
|
||||||
@Provides
|
@Provides
|
||||||
fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
|
fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
|
||||||
|
|
||||||
@MainDispatcher
|
@MainDispatcher
|
||||||
@Provides
|
@Provides
|
||||||
fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main
|
fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main
|
||||||
|
|
||||||
@MainImmediateDispatcher
|
@MainImmediateDispatcher
|
||||||
@Provides
|
@Provides
|
||||||
fun providesMainImmediateDispatcher(): CoroutineDispatcher = Dispatchers.Main.immediate
|
fun providesMainImmediateDispatcher(): CoroutineDispatcher = Dispatchers.Main.immediate
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.module
|
||||||
|
|
||||||
|
import javax.inject.Qualifier
|
||||||
|
|
||||||
|
@Qualifier
|
||||||
|
@Retention(AnnotationRetention.BINARY)
|
||||||
|
annotation class Wifi
|
||||||
|
|
||||||
|
@Qualifier
|
||||||
|
@Retention(AnnotationRetention.BINARY)
|
||||||
|
annotation class MobileData
|
||||||
|
|
||||||
|
@Qualifier
|
||||||
|
@Retention(AnnotationRetention.BINARY)
|
||||||
|
annotation class Ethernet
|
||||||
@@ -27,67 +27,62 @@ import javax.inject.Singleton
|
|||||||
@Module
|
@Module
|
||||||
@InstallIn(SingletonComponent::class)
|
@InstallIn(SingletonComponent::class)
|
||||||
class RepositoryModule {
|
class RepositoryModule {
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideDatabase(@ApplicationContext context: Context): AppDatabase {
|
fun provideDatabase(@ApplicationContext context: Context): AppDatabase {
|
||||||
return Room.databaseBuilder(
|
return Room.databaseBuilder(
|
||||||
context,
|
context,
|
||||||
AppDatabase::class.java,
|
AppDatabase::class.java,
|
||||||
context.getString(R.string.db_name),
|
context.getString(R.string.db_name),
|
||||||
)
|
)
|
||||||
.fallbackToDestructiveMigration()
|
.fallbackToDestructiveMigration()
|
||||||
.addCallback(DatabaseCallback())
|
.addCallback(DatabaseCallback())
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun provideSettingsDoa(appDatabase: AppDatabase): SettingsDao {
|
fun provideSettingsDoa(appDatabase: AppDatabase): SettingsDao {
|
||||||
return appDatabase.settingDao()
|
return appDatabase.settingDao()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@Provides
|
@Provides
|
||||||
fun provideTunnelConfigDoa(appDatabase: AppDatabase): TunnelConfigDao {
|
fun provideTunnelConfigDoa(appDatabase: AppDatabase): TunnelConfigDao {
|
||||||
return appDatabase.tunnelConfigDoa()
|
return appDatabase.tunnelConfigDoa()
|
||||||
}
|
}
|
||||||
|
|
||||||
@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,
|
return DataStoreManager(context, ioDispatcher)
|
||||||
@IoDispatcher ioDispatcher: CoroutineDispatcher
|
}
|
||||||
): DataStoreManager {
|
|
||||||
return DataStoreManager(context, ioDispatcher)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Provides
|
|
||||||
@Singleton
|
|
||||||
fun provideGeneralStateRepository(dataStoreManager: DataStoreManager): AppStateRepository {
|
|
||||||
return DataStoreAppStateRepository(dataStoreManager)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Provides
|
|
||||||
@Singleton
|
|
||||||
fun provideAppDataRepository(
|
|
||||||
settingsRepository: SettingsRepository,
|
|
||||||
tunnelConfigRepository: TunnelConfigRepository,
|
|
||||||
appStateRepository: AppStateRepository
|
|
||||||
): AppDataRepository {
|
|
||||||
return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideGeneralStateRepository(dataStoreManager: DataStoreManager): AppStateRepository {
|
||||||
|
return DataStoreAppStateRepository(dataStoreManager)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideAppDataRepository(
|
||||||
|
settingsRepository: SettingsRepository,
|
||||||
|
tunnelConfigRepository: TunnelConfigRepository,
|
||||||
|
appStateRepository: AppStateRepository,
|
||||||
|
): AppDataRepository {
|
||||||
|
return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ import com.zaneschepke.wireguardautotunnel.service.network.EthernetService
|
|||||||
import com.zaneschepke.wireguardautotunnel.service.network.MobileDataService
|
import com.zaneschepke.wireguardautotunnel.service.network.MobileDataService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.NetworkService
|
import com.zaneschepke.wireguardautotunnel.service.network.NetworkService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.WifiService
|
import com.zaneschepke.wireguardautotunnel.service.network.WifiService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.notification.WireGuardNotification
|
|
||||||
import dagger.Binds
|
import dagger.Binds
|
||||||
import dagger.Module
|
import dagger.Module
|
||||||
import dagger.hilt.InstallIn
|
import dagger.hilt.InstallIn
|
||||||
@@ -15,25 +13,19 @@ import dagger.hilt.android.scopes.ServiceScoped
|
|||||||
@Module
|
@Module
|
||||||
@InstallIn(ServiceComponent::class)
|
@InstallIn(ServiceComponent::class)
|
||||||
abstract class ServiceModule {
|
abstract class ServiceModule {
|
||||||
@Binds
|
|
||||||
@ServiceScoped
|
|
||||||
abstract fun provideNotificationService(
|
|
||||||
wireGuardNotification: WireGuardNotification
|
|
||||||
): NotificationService
|
|
||||||
|
|
||||||
@Binds
|
@Binds
|
||||||
@ServiceScoped
|
@Wifi
|
||||||
abstract fun provideWifiService(wifiService: WifiService): NetworkService<WifiService>
|
@ServiceScoped
|
||||||
|
abstract fun provideWifiService(wifiService: WifiService): NetworkService
|
||||||
|
|
||||||
@Binds
|
@Binds
|
||||||
@ServiceScoped
|
@MobileData
|
||||||
abstract fun provideMobileDataService(
|
@ServiceScoped
|
||||||
mobileDataService: MobileDataService
|
abstract fun provideMobileDataService(mobileDataService: MobileDataService): NetworkService
|
||||||
): NetworkService<MobileDataService>
|
|
||||||
|
|
||||||
@Binds
|
@Binds
|
||||||
@ServiceScoped
|
@Ethernet
|
||||||
abstract fun provideEthernetService(
|
@ServiceScoped
|
||||||
ethernetService: EthernetService
|
abstract fun provideEthernetService(ethernetService: EthernetService): NetworkService
|
||||||
): NetworkService<EthernetService>
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,15 @@ 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.data.repository.TunnelConfigRepository
|
||||||
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.notification.NotificationService
|
||||||
|
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
|
||||||
@@ -23,58 +26,78 @@ import javax.inject.Singleton
|
|||||||
@Module
|
@Module
|
||||||
@InstallIn(SingletonComponent::class)
|
@InstallIn(SingletonComponent::class)
|
||||||
class TunnelModule {
|
class TunnelModule {
|
||||||
@Provides
|
|
||||||
@Singleton
|
|
||||||
fun provideRootShell(@ApplicationContext context: Context): RootShell {
|
|
||||||
return RootShell(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
@Userspace
|
@TunnelShell
|
||||||
fun provideUserspaceBackend(@ApplicationContext context: Context): Backend {
|
fun provideTunnelRootShell(@ApplicationContext context: Context): RootShell {
|
||||||
return GoBackend(context)
|
return RootShell(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
@Kernel
|
@AppShell
|
||||||
fun provideKernelBackend(@ApplicationContext context: Context, rootShell: RootShell): Backend {
|
fun provideAppRootShell(@ApplicationContext context: Context): RootShell {
|
||||||
return WgQuickBackend(context, rootShell, ToolsInstaller(context, rootShell))
|
return RootShell(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideAmneziaBackend(@ApplicationContext context: Context): org.amnezia.awg.backend.Backend {
|
fun provideRootShellAm(@ApplicationContext context: Context): org.amnezia.awg.util.RootShell {
|
||||||
return org.amnezia.awg.backend.GoBackend(context)
|
return org.amnezia.awg.util.RootShell(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideVpnService(
|
@Userspace
|
||||||
amneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
fun provideUserspaceBackend(@ApplicationContext context: Context, @TunnelShell rootShell: RootShell): Backend {
|
||||||
@Userspace userspaceBackend: Provider<Backend>,
|
return GoBackend(context, RootTunnelActionHandler(rootShell))
|
||||||
@Kernel kernelBackend: Provider<Backend>,
|
}
|
||||||
appDataRepository: AppDataRepository,
|
|
||||||
@ApplicationScope applicationScope: CoroutineScope,
|
|
||||||
@IoDispatcher ioDispatcher: CoroutineDispatcher
|
|
||||||
): VpnService {
|
|
||||||
return WireGuardTunnel(
|
|
||||||
amneziaBackend,
|
|
||||||
userspaceBackend,
|
|
||||||
kernelBackend,
|
|
||||||
appDataRepository,
|
|
||||||
applicationScope,
|
|
||||||
ioDispatcher,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideServiceManager(
|
@Kernel
|
||||||
appDataRepository: AppDataRepository,
|
fun provideKernelBackend(@ApplicationContext context: Context, @TunnelShell rootShell: RootShell): Backend {
|
||||||
@IoDispatcher ioDispatcher: CoroutineDispatcher
|
return WgQuickBackend(context, rootShell, ToolsInstaller(context, rootShell), RootTunnelActionHandler(rootShell))
|
||||||
): ServiceManager {
|
}
|
||||||
return ServiceManager(appDataRepository, ioDispatcher)
|
|
||||||
}
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideAmneziaBackend(@ApplicationContext context: Context, rootShell: org.amnezia.awg.util.RootShell): org.amnezia.awg.backend.Backend {
|
||||||
|
return org.amnezia.awg.backend.GoBackend(context, org.amnezia.awg.backend.RootTunnelActionHandler(rootShell))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideVpnService(
|
||||||
|
amneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
||||||
|
@Kernel kernelBackend: Provider<Backend>,
|
||||||
|
appDataRepository: AppDataRepository,
|
||||||
|
tunnelConfigRepository: TunnelConfigRepository,
|
||||||
|
@ApplicationScope applicationScope: CoroutineScope,
|
||||||
|
@IoDispatcher ioDispatcher: CoroutineDispatcher,
|
||||||
|
serviceManager: ServiceManager,
|
||||||
|
notificationService: NotificationService,
|
||||||
|
): TunnelService {
|
||||||
|
return WireGuardTunnel(
|
||||||
|
amneziaBackend,
|
||||||
|
tunnelConfigRepository,
|
||||||
|
kernelBackend,
|
||||||
|
appDataRepository,
|
||||||
|
applicationScope,
|
||||||
|
ioDispatcher,
|
||||||
|
serviceManager,
|
||||||
|
notificationService,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun provideServiceManager(
|
||||||
|
@ApplicationContext context: Context,
|
||||||
|
@IoDispatcher ioDispatcher: CoroutineDispatcher,
|
||||||
|
appDataRepository: AppDataRepository,
|
||||||
|
): ServiceManager {
|
||||||
|
return ServiceManager(context, ioDispatcher, appDataRepository)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): FileUtils {
|
||||||
fun provideFileUtils(
|
return FileUtils(context, ioDispatcher)
|
||||||
@ApplicationContext context: Context,
|
}
|
||||||
@IoDispatcher ioDispatcher: CoroutineDispatcher
|
|
||||||
): FileUtils {
|
|
||||||
return FileUtils(context, ioDispatcher)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
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 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 AppUpdateReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
|
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.startAutoTunnel(true)
|
||||||
|
}
|
||||||
|
if (!settings.isAutoTunnelEnabled) {
|
||||||
|
val tunnels = appDataRepository.tunnels.getAll().filter { it.isActive }
|
||||||
|
if (tunnels.isNotEmpty()) tunnelService.get().startTunnel(tunnels.first(), true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,51 +6,47 @@ import android.content.Intent
|
|||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class BootReceiver : BroadcastReceiver() {
|
class BootReceiver : BroadcastReceiver() {
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
@ApplicationScope
|
lateinit var serviceManager: ServiceManager
|
||||||
lateinit var applicationScope: CoroutineScope
|
|
||||||
|
|
||||||
override fun onReceive(context: Context?, intent: Intent?) {
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
if (Intent.ACTION_BOOT_COMPLETED != intent?.action) return
|
if (Intent.ACTION_BOOT_COMPLETED != intent.action) return
|
||||||
context?.run {
|
applicationScope.launch {
|
||||||
applicationScope.launch {
|
with(appDataRepository.settings.getSettings()) {
|
||||||
val settings = appDataRepository.settings.getSettings()
|
if (isRestoreOnBootEnabled) {
|
||||||
if(settings.isRestoreOnBootEnabled) {
|
val activeTunnels = appDataRepository.tunnels.getActive()
|
||||||
if (settings.isAutoTunnelEnabled) {
|
val tunState = tunnelService.get().vpnState.value.status
|
||||||
Timber.i("Starting watcher service from boot")
|
if (activeTunnels.isNotEmpty() && tunState != TunnelState.UP) {
|
||||||
serviceManager.startWatcherServiceForeground(context)
|
Timber.i("Starting previously active tunnel")
|
||||||
}
|
tunnelService.get().startTunnel(activeTunnels.first(), true)
|
||||||
if (appDataRepository.appState.isTunnelRunningFromManualStart()) {
|
}
|
||||||
appDataRepository.appState.getActiveTunnelId()?.let {
|
if (isAutoTunnelEnabled) {
|
||||||
Timber.i("Starting tunnel that was active before reboot")
|
Timber.i("Starting watcher service from boot")
|
||||||
serviceManager.startVpnServiceForeground(
|
serviceManager.startAutoTunnel(true)
|
||||||
context,
|
}
|
||||||
appDataRepository.tunnels.getById(it)?.id,
|
}
|
||||||
)
|
}
|
||||||
return@launch
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if (settings.isAlwaysOnVpnEnabled) {
|
|
||||||
Timber.i("Starting vpn service from boot AOVPN")
|
|
||||||
serviceManager.startVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
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 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
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
serviceManager.updateTunnelTile()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val REFRESH_TUNNELS_ACTION = "com.wireguard.android.action.REFRESH_TUNNEL_STATES"
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
-26
@@ -3,42 +3,34 @@ package com.zaneschepke.wireguardautotunnel.receiver
|
|||||||
import android.content.BroadcastReceiver
|
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.SettingsRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationAction
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class NotificationActionReceiver : BroadcastReceiver() {
|
class NotificationActionReceiver : BroadcastReceiver() {
|
||||||
@Inject
|
|
||||||
lateinit var settingsRepository: SettingsRepository
|
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
@ApplicationScope
|
lateinit var tunnelService: TunnelService
|
||||||
lateinit var applicationScope: CoroutineScope
|
|
||||||
|
|
||||||
override fun onReceive(context: Context, intent: Intent?) {
|
@Inject
|
||||||
applicationScope.launch {
|
@ApplicationScope
|
||||||
try {
|
lateinit var applicationScope: CoroutineScope
|
||||||
//TODO fix for manual start changes when enabled
|
|
||||||
serviceManager.stopVpnServiceForeground(context)
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
delay(Constants.TOGGLE_TUNNEL_DELAY)
|
applicationScope.launch {
|
||||||
serviceManager.startVpnServiceForeground(context)
|
when (intent.action) {
|
||||||
} catch (e: Exception) {
|
NotificationAction.AUTO_TUNNEL_OFF.name -> serviceManager.stopAutoTunnel()
|
||||||
Timber.e(e)
|
NotificationAction.TUNNEL_OFF.name -> tunnelService.stopTunnel()
|
||||||
} finally {
|
}
|
||||||
cancel()
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
enum class Action {
|
|
||||||
START,
|
|
||||||
START_FOREGROUND,
|
|
||||||
STOP,
|
|
||||||
STOP_FOREGROUND
|
|
||||||
}
|
|
||||||
-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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+97
-110
@@ -3,130 +3,117 @@ 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.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.service.foreground.autotunnel.AutoTunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.service.tile.AutoTunnelControlTile
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tile.TunnelControlTile
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||||
|
import jakarta.inject.Inject
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
|
||||||
class ServiceManager(
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
private val appDataRepository: AppDataRepository,
|
class ServiceManager
|
||||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
@Inject constructor(private val context: Context, private val ioDispatcher: CoroutineDispatcher, private val appDataRepository: AppDataRepository) {
|
||||||
) {
|
|
||||||
|
|
||||||
private fun <T : Service> actionOnService(
|
private val _autoTunnelActive = MutableStateFlow(false)
|
||||||
action: Action,
|
|
||||||
context: Context,
|
|
||||||
cls: Class<T>,
|
|
||||||
extras: Map<String, Int>? = null
|
|
||||||
) {
|
|
||||||
val intent =
|
|
||||||
Intent(context, cls).also {
|
|
||||||
it.action = action.name
|
|
||||||
extras?.forEach { (k, v) -> it.putExtra(k, v) }
|
|
||||||
}
|
|
||||||
intent.component?.javaClass
|
|
||||||
try {
|
|
||||||
when (action) {
|
|
||||||
Action.START_FOREGROUND, Action.STOP_FOREGROUND -> context.startForegroundService(
|
|
||||||
intent,
|
|
||||||
)
|
|
||||||
|
|
||||||
Action.START, Action.STOP -> context.startService(intent)
|
val autoTunnelActive = _autoTunnelActive.asStateFlow()
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e(e.message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun startVpnService(
|
var autoTunnelService = CompletableDeferred<AutoTunnelService>()
|
||||||
context: Context,
|
var backgroundService = CompletableDeferred<TunnelBackgroundService>()
|
||||||
tunnelId: Int? = null,
|
var autoTunnelTile = CompletableDeferred<AutoTunnelControlTile>()
|
||||||
isManualStart: Boolean = false
|
var tunnelControlTile = CompletableDeferred<TunnelControlTile>()
|
||||||
) {
|
|
||||||
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) {
|
private fun <T : Service> startService(cls: Class<T>, background: Boolean) {
|
||||||
withContext(ioDispatcher) {
|
runCatching {
|
||||||
if (isManualStop) onManualStop()
|
val intent = Intent(context, cls)
|
||||||
Timber.i("Stopping vpn service")
|
if (background) {
|
||||||
actionOnService(
|
context.startForegroundService(intent)
|
||||||
Action.STOP_FOREGROUND,
|
} else {
|
||||||
context,
|
context.startService(intent)
|
||||||
WireGuardTunnelService::class.java,
|
}
|
||||||
)
|
}.onFailure { Timber.e(it) }
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun stopVpnService(context: Context, isManualStop: Boolean = false) {
|
suspend fun startAutoTunnel(background: Boolean) {
|
||||||
withContext(ioDispatcher) {
|
val settings = appDataRepository.settings.getSettings()
|
||||||
if (isManualStop) onManualStop()
|
appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = true))
|
||||||
Timber.i("Stopping vpn service")
|
if (autoTunnelService.isCompleted) return _autoTunnelActive.update { true }
|
||||||
actionOnService(
|
kotlin.runCatching {
|
||||||
Action.STOP,
|
startService(AutoTunnelService::class.java, background)
|
||||||
context,
|
autoTunnelService.await()
|
||||||
WireGuardTunnelService::class.java,
|
autoTunnelService.getCompleted().start()
|
||||||
)
|
_autoTunnelActive.update { true }
|
||||||
}
|
updateAutoTunnelTile()
|
||||||
}
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun onManualStop() {
|
suspend fun startBackgroundService(tunnelConfig: TunnelConfig?) {
|
||||||
appDataRepository.appState.setManualStop()
|
if (backgroundService.isCompleted) return
|
||||||
}
|
kotlin.runCatching {
|
||||||
|
startService(TunnelBackgroundService::class.java, true)
|
||||||
|
backgroundService.await()
|
||||||
|
backgroundService.getCompleted().start(tunnelConfig)
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun onManualStart(tunnelId: Int?) {
|
fun stopBackgroundService() {
|
||||||
tunnelId?.let {
|
if (!backgroundService.isCompleted) return
|
||||||
appDataRepository.appState.setTunnelRunningFromManualStart(it)
|
runCatching {
|
||||||
}
|
backgroundService.getCompleted().stop()
|
||||||
}
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun startVpnServiceForeground(
|
suspend fun toggleAutoTunnel(background: Boolean) {
|
||||||
context: Context,
|
withContext(ioDispatcher) {
|
||||||
tunnelId: Int? = null,
|
if (_autoTunnelActive.value) return@withContext stopAutoTunnel()
|
||||||
isManualStart: Boolean = false
|
startAutoTunnel(background)
|
||||||
) {
|
}
|
||||||
withContext(ioDispatcher) {
|
}
|
||||||
if (isManualStart) onManualStart(tunnelId)
|
|
||||||
actionOnService(
|
|
||||||
Action.START_FOREGROUND,
|
|
||||||
context,
|
|
||||||
WireGuardTunnelService::class.java,
|
|
||||||
tunnelId?.let { mapOf(Constants.TUNNEL_EXTRA_KEY to it) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun startWatcherServiceForeground(
|
private fun updateAutoTunnelTile() {
|
||||||
context: Context,
|
if (autoTunnelTile.isCompleted) {
|
||||||
) {
|
autoTunnelTile.getCompleted().updateTileState()
|
||||||
actionOnService(
|
} else {
|
||||||
Action.START_FOREGROUND,
|
context.requestAutoTunnelTileServiceUpdate()
|
||||||
context,
|
}
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
}
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun startWatcherService(context: Context) {
|
fun updateTunnelTile() {
|
||||||
actionOnService(
|
if (tunnelControlTile.isCompleted) {
|
||||||
Action.START,
|
tunnelControlTile.getCompleted().updateTileState()
|
||||||
context,
|
} else {
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
context.requestTunnelTileServiceStateUpdate()
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun stopWatcherService(context: Context) {
|
suspend fun stopAutoTunnel() {
|
||||||
actionOnService(
|
withContext(ioDispatcher) {
|
||||||
Action.STOP,
|
val settings = appDataRepository.settings.getSettings()
|
||||||
context,
|
appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = false))
|
||||||
WireGuardConnectivityWatcherService::class.java,
|
if (!autoTunnelService.isCompleted) return@withContext
|
||||||
)
|
runCatching {
|
||||||
}
|
autoTunnelService.getCompleted().stop()
|
||||||
|
_autoTunnelActive.update { false }
|
||||||
|
updateAutoTunnelTile()
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+70
@@ -0,0 +1,70 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.IBinder
|
||||||
|
import androidx.core.app.ServiceCompat
|
||||||
|
import androidx.lifecycle.LifecycleService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationAction
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.WireGuardNotification
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class TunnelBackgroundService : LifecycleService() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var notificationService: NotificationService
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
serviceManager.backgroundService.complete(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent): IBinder? {
|
||||||
|
super.onBind(intent)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
serviceManager.backgroundService.complete(this)
|
||||||
|
return super.onStartCommand(intent, flags, startId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start(tunnelConfig: TunnelConfig?) {
|
||||||
|
ServiceCompat.startForeground(
|
||||||
|
this,
|
||||||
|
NotificationService.KERNEL_SERVICE_NOTIFICATION_ID,
|
||||||
|
createNotification(tunnelConfig),
|
||||||
|
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
serviceManager.backgroundService = CompletableDeferred()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createNotification(tunnelConfig: TunnelConfig?): Notification {
|
||||||
|
return notificationService.createNotification(
|
||||||
|
WireGuardNotification.NotificationChannels.VPN,
|
||||||
|
title = "${getString(R.string.tunnel_running)} - ${tunnelConfig?.name}",
|
||||||
|
actions = listOf(
|
||||||
|
notificationService.createNotificationAction(NotificationAction.TUNNEL_OFF),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
-56
@@ -1,56 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
|
||||||
|
|
||||||
data class WatcherState(
|
|
||||||
val isWifiConnected: Boolean = false,
|
|
||||||
val isEthernetConnected: Boolean = false,
|
|
||||||
val isMobileDataConnected: Boolean = false,
|
|
||||||
val currentNetworkSSID: String = "",
|
|
||||||
val settings: Settings = Settings()
|
|
||||||
) {
|
|
||||||
fun isEthernetConditionMet(): Boolean {
|
|
||||||
return (isEthernetConnected &&
|
|
||||||
settings.isTunnelOnEthernetEnabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isMobileDataConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
settings.isTunnelOnMobileDataEnabled &&
|
|
||||||
!isWifiConnected &&
|
|
||||||
isMobileDataConnected)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTunnelOffOnMobileDataConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
!settings.isTunnelOnMobileDataEnabled &&
|
|
||||||
isMobileDataConnected &&
|
|
||||||
!isWifiConnected)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isUntrustedWifiConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
isWifiConnected &&
|
|
||||||
!settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
|
|
||||||
settings.isTunnelOnWifiEnabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTrustedWifiConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
(isWifiConnected &&
|
|
||||||
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTunnelOffOnWifiConditionMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
(isWifiConnected &&
|
|
||||||
!settings.isTunnelOnWifiEnabled))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTunnelOffOnNoConnectivityMet(): Boolean {
|
|
||||||
return (!isEthernetConnected &&
|
|
||||||
!isWifiConnected &&
|
|
||||||
!isMobileDataConnected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
-456
@@ -1,456 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.os.PowerManager
|
|
||||||
import androidx.core.app.ServiceCompat
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.EthernetService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.MobileDataService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.NetworkService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.NetworkStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.network.WifiService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.collectLatest
|
|
||||||
import kotlinx.coroutines.flow.update
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import timber.log.Timber
|
|
||||||
import java.net.InetAddress
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class WireGuardConnectivityWatcherService : ForegroundService() {
|
|
||||||
private val foregroundId = 122
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var wifiService: NetworkService<WifiService>
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var mobileDataService: NetworkService<MobileDataService>
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var ethernetService: NetworkService<EthernetService>
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var appDataRepository: AppDataRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var notificationService: NotificationService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var vpnService: VpnService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var serviceManager: ServiceManager
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@IoDispatcher
|
|
||||||
lateinit var ioDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@MainImmediateDispatcher
|
|
||||||
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
private val networkEventsFlow = MutableStateFlow(WatcherState())
|
|
||||||
|
|
||||||
private var watcherJob: Job? = null
|
|
||||||
|
|
||||||
private var wakeLock: PowerManager.WakeLock? = null
|
|
||||||
private val tag = this.javaClass.name
|
|
||||||
|
|
||||||
override fun onCreate() {
|
|
||||||
super.onCreate()
|
|
||||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
|
||||||
try {
|
|
||||||
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
|
|
||||||
launchWatcherPausedNotification()
|
|
||||||
} else launchWatcherNotification()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e("Failed to start watcher service, not enough permissions")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun startService(extras: Bundle?) {
|
|
||||||
super.startService(extras)
|
|
||||||
try {
|
|
||||||
// we need this lock so our service gets not affected by Doze Mode
|
|
||||||
lifecycleScope.launch { initWakeLock() }
|
|
||||||
cancelWatcherJob()
|
|
||||||
startWatcherJob()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e("Failed to launch watcher service, no permissions")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun stopService() {
|
|
||||||
super.stopService()
|
|
||||||
wakeLock?.let {
|
|
||||||
if (it.isHeld) {
|
|
||||||
it.release()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cancelWatcherJob()
|
|
||||||
stopSelf()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchWatcherNotification(
|
|
||||||
description: String = getString(R.string.watcher_notification_text_active)
|
|
||||||
) {
|
|
||||||
val notification =
|
|
||||||
notificationService.createNotification(
|
|
||||||
channelId = getString(R.string.watcher_channel_id),
|
|
||||||
channelName = getString(R.string.watcher_channel_name),
|
|
||||||
title = getString(R.string.auto_tunnel_title),
|
|
||||||
description = description,
|
|
||||||
)
|
|
||||||
ServiceCompat.startForeground(
|
|
||||||
this,
|
|
||||||
foregroundId,
|
|
||||||
notification,
|
|
||||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchWatcherPausedNotification() {
|
|
||||||
launchWatcherNotification(getString(R.string.watcher_notification_text_paused))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun initWakeLock() {
|
|
||||||
wakeLock =
|
|
||||||
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
|
|
||||||
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply {
|
|
||||||
try {
|
|
||||||
Timber.i("Initiating wakelock with 10 min timeout")
|
|
||||||
acquire(Constants.BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT)
|
|
||||||
} finally {
|
|
||||||
release()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun cancelWatcherJob() {
|
|
||||||
try {
|
|
||||||
watcherJob?.cancel()
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
Timber.i("Watcher job cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startWatcherJob() {
|
|
||||||
watcherJob =
|
|
||||||
lifecycleScope.launch {
|
|
||||||
val setting = appDataRepository.settings.getSettings()
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting wifi watcher")
|
|
||||||
watchForWifiConnectivityChanges()
|
|
||||||
}
|
|
||||||
if (setting.isTunnelOnMobileDataEnabled) {
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting mobile data watcher")
|
|
||||||
watchForMobileDataConnectivityChanges()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (setting.isTunnelOnEthernetEnabled) {
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting ethernet data watcher")
|
|
||||||
watchForEthernetConnectivityChanges()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting settings watcher")
|
|
||||||
watchForSettingsChanges()
|
|
||||||
}
|
|
||||||
if (setting.isPingEnabled) {
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting ping watcher")
|
|
||||||
watchForPingFailure()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
launch {
|
|
||||||
Timber.i("Starting management watcher")
|
|
||||||
manageVpn()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForMobileDataConnectivityChanges() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
mobileDataService.networkStatus.collect { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Available -> {
|
|
||||||
Timber.i("Gained Mobile data connection")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isMobileDataConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.CapabilitiesChanged -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isMobileDataConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Mobile data capabilities changed")
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.Unavailable -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isMobileDataConnected = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Lost mobile data connection")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForPingFailure() {
|
|
||||||
val context = this
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
try {
|
|
||||||
do {
|
|
||||||
if (vpnService.vpnState.value.status == TunnelState.UP) {
|
|
||||||
val tunnelConfig = vpnService.vpnState.value.tunnelConfig
|
|
||||||
tunnelConfig?.let {
|
|
||||||
val config = TunnelConfig.configFromWgQuick(it.wgQuick)
|
|
||||||
val results = config.peers.map { peer ->
|
|
||||||
val host = if (peer.endpoint.isPresent &&
|
|
||||||
peer.endpoint.get().resolved.isPresent)
|
|
||||||
peer.endpoint.get().resolved.get().host
|
|
||||||
else Constants.DEFAULT_PING_IP
|
|
||||||
Timber.i("Checking reachability of: $host")
|
|
||||||
val reachable = InetAddress.getByName(host)
|
|
||||||
.isReachable(Constants.PING_TIMEOUT.toInt())
|
|
||||||
Timber.i("Result: reachable - $reachable")
|
|
||||||
reachable
|
|
||||||
}
|
|
||||||
if (results.contains(false)) {
|
|
||||||
Timber.i("Restarting VPN for ping failure")
|
|
||||||
serviceManager.stopVpnServiceForeground(context)
|
|
||||||
delay(Constants.VPN_RESTART_DELAY)
|
|
||||||
serviceManager.startVpnServiceForeground(context, it.id)
|
|
||||||
delay(Constants.PING_COOLDOWN)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
delay(Constants.PING_INTERVAL)
|
|
||||||
} while (true)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForSettingsChanges() {
|
|
||||||
appDataRepository.settings.getSettingsFlow().collect { settings ->
|
|
||||||
if (networkEventsFlow.value.settings.isAutoTunnelPaused != settings.isAutoTunnelPaused) {
|
|
||||||
when (settings.isAutoTunnelPaused) {
|
|
||||||
true -> launchWatcherPausedNotification()
|
|
||||||
false -> launchWatcherNotification()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
settings = settings,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForEthernetConnectivityChanges() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
ethernetService.networkStatus.collect { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Available -> {
|
|
||||||
Timber.i("Gained Ethernet connection")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isEthernetConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.CapabilitiesChanged -> {
|
|
||||||
Timber.i("Ethernet capabilities changed")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isEthernetConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.Unavailable -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isEthernetConnected = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Lost Ethernet connection")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun watchForWifiConnectivityChanges() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
wifiService.networkStatus.collect { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Available -> {
|
|
||||||
Timber.i("Gained Wi-Fi connection")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isWifiConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.CapabilitiesChanged -> {
|
|
||||||
Timber.i("Wifi capabilities changed")
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isWifiConnected = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
val ssid = wifiService.getNetworkName(status.networkCapabilities)
|
|
||||||
ssid?.let { name ->
|
|
||||||
if (name.contains(Constants.UNREADABLE_SSID)) {
|
|
||||||
Timber.w("SSID unreadable: missing permissions")
|
|
||||||
} else Timber.i("Detected valid SSID")
|
|
||||||
appDataRepository.appState.setCurrentSsid(name)
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
currentNetworkSSID = name,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} ?: Timber.w("Failed to read ssid")
|
|
||||||
}
|
|
||||||
|
|
||||||
is NetworkStatus.Unavailable -> {
|
|
||||||
networkEventsFlow.update {
|
|
||||||
it.copy(
|
|
||||||
isWifiConnected = false,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Timber.i("Lost Wi-Fi connection")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun getMobileDataTunnel(): TunnelConfig? {
|
|
||||||
return appDataRepository.tunnels.findByMobileDataTunnel().firstOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun getSsidTunnel(ssid: String): TunnelConfig? {
|
|
||||||
return appDataRepository.tunnels.findByTunnelNetworksName(ssid).firstOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun isTunnelDown(): Boolean {
|
|
||||||
return vpnService.vpnState.value.status == TunnelState.DOWN
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun manageVpn() {
|
|
||||||
val context = this
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
networkEventsFlow.collectLatest { watcherState ->
|
|
||||||
val autoTunnel = "Auto-tunnel watcher"
|
|
||||||
if (!watcherState.settings.isAutoTunnelPaused) {
|
|
||||||
//delay for rapid network state changes and then collect latest
|
|
||||||
delay(Constants.WATCHER_COLLECTION_DELAY)
|
|
||||||
val tunnelConfig = vpnService.vpnState.value.tunnelConfig
|
|
||||||
when {
|
|
||||||
watcherState.isEthernetConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
|
|
||||||
if (isTunnelDown()) serviceManager.startVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isMobileDataConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel on mobile data condition met")
|
|
||||||
val mobileDataTunnel = getMobileDataTunnel()
|
|
||||||
val tunnel =
|
|
||||||
mobileDataTunnel ?: appDataRepository.getPrimaryOrFirstTunnel()
|
|
||||||
if (isTunnelDown() || tunnelConfig?.isMobileDataTunnel == false) {
|
|
||||||
serviceManager.startVpnServiceForeground(
|
|
||||||
context,
|
|
||||||
tunnel?.id,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnMobileDataConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isUntrustedWifiConditionMet() -> {
|
|
||||||
if (tunnelConfig?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false ||
|
|
||||||
tunnelConfig == null) {
|
|
||||||
Timber.i("$autoTunnel - tunnel on ssid not associated with current tunnel condition met")
|
|
||||||
getSsidTunnel(watcherState.currentNetworkSSID)?.let {
|
|
||||||
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}")
|
|
||||||
if (isTunnelDown() || tunnelConfig?.id != it.id) serviceManager.startVpnServiceForeground(
|
|
||||||
context,
|
|
||||||
it.id,
|
|
||||||
)
|
|
||||||
} ?: suspend {
|
|
||||||
Timber.i("No tunnel associated with this SSID, using defaults")
|
|
||||||
val default = appDataRepository.getPrimaryOrFirstTunnel()
|
|
||||||
if (default?.name != vpnService.name) {
|
|
||||||
default?.let {
|
|
||||||
serviceManager.startVpnServiceForeground(context, it.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}.invoke()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTrustedWifiConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnWifiConditionMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on wifi condition met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
watcherState.isTunnelOffOnNoConnectivityMet() -> {
|
|
||||||
Timber.i("$autoTunnel - tunnel off on no connectivity met, turning vpn off")
|
|
||||||
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
Timber.i("$autoTunnel - no condition met")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-201
@@ -1,201 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
|
||||||
|
|
||||||
import android.app.PendingIntent
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.core.app.ServiceCompat
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
|
|
||||||
import com.zaneschepke.wireguardautotunnel.receiver.NotificationActionReceiver
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.handshakeStatus
|
|
||||||
import com.zaneschepke.wireguardautotunnel.util.mapPeerStats
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import timber.log.Timber
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class WireGuardTunnelService : ForegroundService() {
|
|
||||||
private val foregroundId = 123
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var vpnService: VpnService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var appDataRepository: AppDataRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var notificationService: NotificationService
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@MainImmediateDispatcher
|
|
||||||
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@IoDispatcher
|
|
||||||
lateinit var ioDispatcher: CoroutineDispatcher
|
|
||||||
|
|
||||||
private var job: Job? = null
|
|
||||||
|
|
||||||
private var didShowConnected = false
|
|
||||||
|
|
||||||
override fun onCreate() {
|
|
||||||
super.onCreate()
|
|
||||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
|
||||||
//TODO fix this to not launch if AOVPN
|
|
||||||
if (appDataRepository.tunnels.count() != 0) {
|
|
||||||
launchVpnNotification()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun startService(extras: Bundle?) {
|
|
||||||
super.startService(extras)
|
|
||||||
cancelJob()
|
|
||||||
job =
|
|
||||||
lifecycleScope.launch {
|
|
||||||
launch {
|
|
||||||
val tunnelId = extras?.getInt(Constants.TUNNEL_EXTRA_KEY)
|
|
||||||
if (vpnService.getState() == TunnelState.UP) {
|
|
||||||
vpnService.stopTunnel()
|
|
||||||
}
|
|
||||||
vpnService.startTunnel(
|
|
||||||
tunnelId?.let {
|
|
||||||
appDataRepository.tunnels.getById(it)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
launch {
|
|
||||||
handshakeNotifications()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//TODO improve tunnel notifications
|
|
||||||
private suspend fun handshakeNotifications() {
|
|
||||||
withContext(ioDispatcher) {
|
|
||||||
var tunnelName: String? = null
|
|
||||||
vpnService.vpnState.collect { state ->
|
|
||||||
state.statistics
|
|
||||||
?.mapPeerStats()
|
|
||||||
?.map { it.value?.handshakeStatus() }
|
|
||||||
.let { statuses ->
|
|
||||||
when {
|
|
||||||
statuses?.all { it == HandshakeStatus.HEALTHY } == true -> {
|
|
||||||
if (!didShowConnected) {
|
|
||||||
delay(Constants.VPN_CONNECTED_NOTIFICATION_DELAY)
|
|
||||||
tunnelName = state.tunnelConfig?.name
|
|
||||||
launchVpnNotification(
|
|
||||||
getString(R.string.tunnel_start_title),
|
|
||||||
"${getString(R.string.tunnel_start_text)} - $tunnelName",
|
|
||||||
)
|
|
||||||
didShowConnected = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
statuses?.any { it == HandshakeStatus.STALE } == true -> {}
|
|
||||||
statuses?.all { it == HandshakeStatus.NOT_STARTED } ==
|
|
||||||
true -> {
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (state.status == TunnelState.UP && state.tunnelConfig?.name != tunnelName) {
|
|
||||||
tunnelName = state.tunnelConfig?.name
|
|
||||||
launchVpnNotification(
|
|
||||||
getString(R.string.tunnel_start_title),
|
|
||||||
"${getString(R.string.tunnel_start_text)} - $tunnelName",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchAlwaysOnDisabledNotification() {
|
|
||||||
launchVpnNotification(
|
|
||||||
title = this.getString(R.string.vpn_connection_failed),
|
|
||||||
description = this.getString(R.string.always_on_disabled),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun stopService() {
|
|
||||||
super.stopService()
|
|
||||||
lifecycleScope.launch {
|
|
||||||
vpnService.stopTunnel()
|
|
||||||
didShowConnected = false
|
|
||||||
}
|
|
||||||
cancelJob()
|
|
||||||
stopSelf()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchVpnNotification(
|
|
||||||
title: String = getString(R.string.vpn_starting),
|
|
||||||
description: String = getString(R.string.attempt_connection)
|
|
||||||
) {
|
|
||||||
val notification =
|
|
||||||
notificationService.createNotification(
|
|
||||||
channelId = getString(R.string.vpn_channel_id),
|
|
||||||
channelName = getString(R.string.vpn_channel_name),
|
|
||||||
title = title,
|
|
||||||
onGoing = false,
|
|
||||||
vibration = false,
|
|
||||||
showTimestamp = true,
|
|
||||||
description = description,
|
|
||||||
)
|
|
||||||
ServiceCompat.startForeground(
|
|
||||||
this,
|
|
||||||
foregroundId,
|
|
||||||
notification,
|
|
||||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchVpnConnectionFailedNotification(message: String) {
|
|
||||||
val notification =
|
|
||||||
notificationService.createNotification(
|
|
||||||
channelId = getString(R.string.vpn_channel_id),
|
|
||||||
channelName = getString(R.string.vpn_channel_name),
|
|
||||||
action =
|
|
||||||
PendingIntent.getBroadcast(
|
|
||||||
this,
|
|
||||||
0,
|
|
||||||
Intent(this, NotificationActionReceiver::class.java),
|
|
||||||
PendingIntent.FLAG_IMMUTABLE,
|
|
||||||
),
|
|
||||||
actionText = getString(R.string.restart),
|
|
||||||
title = getString(R.string.vpn_connection_failed),
|
|
||||||
onGoing = false,
|
|
||||||
vibration = true,
|
|
||||||
showTimestamp = true,
|
|
||||||
description = message,
|
|
||||||
)
|
|
||||||
ServiceCompat.startForeground(
|
|
||||||
this,
|
|
||||||
foregroundId,
|
|
||||||
notification,
|
|
||||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun cancelJob() {
|
|
||||||
try {
|
|
||||||
job?.cancel()
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
Timber.i("Tunnel job cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+300
@@ -0,0 +1,300 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground.autotunnel
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.os.PowerManager
|
||||||
|
import androidx.core.app.ServiceCompat
|
||||||
|
import androidx.lifecycle.LifecycleService
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import com.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.AppShell
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.Ethernet
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.MobileData
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.Wifi
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.foreground.autotunnel.model.AutoTunnelEvent
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.foreground.autotunnel.model.AutoTunnelState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.foreground.autotunnel.model.NetworkState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.network.NetworkService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationAction
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.WireGuardNotification
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.cancelWithMessage
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isReachable
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.onNotRunning
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.FlowPreview
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.debounce
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
import kotlinx.coroutines.flow.filterNot
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import timber.log.Timber
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class AutoTunnelService : LifecycleService() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@AppShell
|
||||||
|
lateinit var rootShell: Provider<RootShell>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@Wifi
|
||||||
|
lateinit var wifiService: NetworkService
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@MobileData
|
||||||
|
lateinit var mobileDataService: NetworkService
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@Ethernet
|
||||||
|
lateinit var ethernetService: NetworkService
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: Provider<AppDataRepository>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var notificationService: NotificationService
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@IoDispatcher
|
||||||
|
lateinit var ioDispatcher: CoroutineDispatcher
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@MainImmediateDispatcher
|
||||||
|
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
||||||
|
|
||||||
|
private val defaultState = AutoTunnelState()
|
||||||
|
|
||||||
|
private val autoTunnelStateFlow = MutableStateFlow(defaultState)
|
||||||
|
|
||||||
|
private var wakeLock: PowerManager.WakeLock? = null
|
||||||
|
|
||||||
|
private val pingTunnelRestartActive = AtomicBoolean(false)
|
||||||
|
|
||||||
|
private var pingJob: Job? = null
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
serviceManager.autoTunnelService.complete(this)
|
||||||
|
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||||
|
kotlin.runCatching {
|
||||||
|
launchWatcherNotification()
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent): IBinder? {
|
||||||
|
super.onBind(intent)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
Timber.d("onStartCommand executed with startId: $startId")
|
||||||
|
serviceManager.autoTunnelService.complete(this)
|
||||||
|
return super.onStartCommand(intent, flags, startId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start() {
|
||||||
|
kotlin.runCatching {
|
||||||
|
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||||
|
launchWatcherNotification()
|
||||||
|
initWakeLock()
|
||||||
|
}
|
||||||
|
startAutoTunnelJob()
|
||||||
|
startAutoTunnelStateJob()
|
||||||
|
startPingStateJob()
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
wakeLock?.let { if (it.isHeld) it.release() }
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
cancelAndResetPingJob()
|
||||||
|
serviceManager.autoTunnelService = CompletableDeferred()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun launchWatcherNotification(description: String = getString(R.string.monitoring_state_changes)) {
|
||||||
|
val notification =
|
||||||
|
notificationService.createNotification(
|
||||||
|
WireGuardNotification.NotificationChannels.AUTO_TUNNEL,
|
||||||
|
title = getString(R.string.auto_tunnel_title),
|
||||||
|
description = description,
|
||||||
|
actions = listOf(
|
||||||
|
notificationService.createNotificationAction(NotificationAction.AUTO_TUNNEL_OFF),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
ServiceCompat.startForeground(
|
||||||
|
this,
|
||||||
|
NotificationService.AUTO_TUNNEL_NOTIFICATION_ID,
|
||||||
|
notification,
|
||||||
|
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initWakeLock() {
|
||||||
|
wakeLock = (getSystemService(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 startPingJob() = lifecycleScope.launch {
|
||||||
|
watchForPingFailure()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startPingStateJob() = lifecycleScope.launch {
|
||||||
|
autoTunnelStateFlow.collect {
|
||||||
|
if (it == defaultState) return@collect
|
||||||
|
if (it.isPingEnabled()) {
|
||||||
|
pingJob.onNotRunning { pingJob = startPingJob() }
|
||||||
|
} else {
|
||||||
|
if (!pingTunnelRestartActive.get()) cancelAndResetPingJob()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun watchForPingFailure() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
Timber.i("Starting ping watcher")
|
||||||
|
runCatching {
|
||||||
|
do {
|
||||||
|
val vpnState = autoTunnelStateFlow.value.vpnState
|
||||||
|
if (vpnState.status.isUp() && !autoTunnelStateFlow.value.isNoConnectivity()) {
|
||||||
|
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
|
||||||
|
pingTunnelRestartActive.set(true)
|
||||||
|
tunnelService.get().bounceTunnel()
|
||||||
|
pingTunnelRestartActive.set(false)
|
||||||
|
delay(cooldown ?: Constants.PING_COOLDOWN)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delay(vpnState.tunnelConfig?.pingInterval ?: Constants.PING_INTERVAL)
|
||||||
|
} while (true)
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startAutoTunnelStateJob() = lifecycleScope.launch(ioDispatcher) {
|
||||||
|
combine(
|
||||||
|
combineSettings(),
|
||||||
|
combineNetworkEventsJob(),
|
||||||
|
) { double, networkState ->
|
||||||
|
AutoTunnelState(tunnelService.get().vpnState.value, networkState, double.first, double.second)
|
||||||
|
}.collect { state ->
|
||||||
|
Timber.d("Network state: ${state.networkState}")
|
||||||
|
autoTunnelStateFlow.update {
|
||||||
|
it.copy(vpnState = state.vpnState, networkState = state.networkState, settings = state.settings, tunnels = state.tunnels)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelAndResetPingJob() {
|
||||||
|
pingJob?.cancelWithMessage("Ping job canceled")
|
||||||
|
pingJob = null
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(FlowPreview::class)
|
||||||
|
private fun combineNetworkEventsJob(): Flow<NetworkState> {
|
||||||
|
return combine(
|
||||||
|
wifiService.status,
|
||||||
|
mobileDataService.status,
|
||||||
|
) { wifi, mobileData ->
|
||||||
|
NetworkState(
|
||||||
|
wifi.available,
|
||||||
|
mobileData.available,
|
||||||
|
false,
|
||||||
|
wifi.name,
|
||||||
|
)
|
||||||
|
}.distinctUntilChanged().filterNot { it.isWifiConnected && it.wifiName == null }.debounce(500L)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun combineSettings(): Flow<Pair<Settings, TunnelConfigs>> {
|
||||||
|
return combine(
|
||||||
|
appDataRepository.get().settings.getSettingsFlow(),
|
||||||
|
appDataRepository.get().tunnels.getTunnelConfigsFlow().map { tunnels ->
|
||||||
|
// isActive is ignored for equality checks so user can manually toggle off tunnel with auto-tunnel
|
||||||
|
tunnels.map { it.copy(isActive = false) }
|
||||||
|
},
|
||||||
|
) { settings, tunnels ->
|
||||||
|
Pair(settings, tunnels)
|
||||||
|
}.distinctUntilChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(FlowPreview::class)
|
||||||
|
private fun startAutoTunnelJob() = lifecycleScope.launch(ioDispatcher) {
|
||||||
|
Timber.i("Starting auto-tunnel network event watcher")
|
||||||
|
autoTunnelStateFlow.debounce(1000L).collect { watcherState ->
|
||||||
|
if (watcherState == defaultState) return@collect
|
||||||
|
Timber.d("New auto tunnel state emitted")
|
||||||
|
when (val event = watcherState.asAutoTunnelEvent()) {
|
||||||
|
is AutoTunnelEvent.Start -> tunnelService.get().startTunnel(
|
||||||
|
event.tunnelConfig
|
||||||
|
?: appDataRepository.get().getPrimaryOrFirstTunnel(),
|
||||||
|
)
|
||||||
|
is AutoTunnelEvent.Stop -> tunnelService.get().stopTunnel()
|
||||||
|
AutoTunnelEvent.DoNothing -> Timber.i("Auto-tunneling: no condition met")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground.autotunnel.model
|
||||||
|
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
|
|
||||||
|
sealed class AutoTunnelEvent {
|
||||||
|
data class Start(val tunnelConfig: TunnelConfig? = null) : AutoTunnelEvent()
|
||||||
|
data object Stop : AutoTunnelEvent()
|
||||||
|
data object DoNothing : AutoTunnelEvent()
|
||||||
|
}
|
||||||
+145
@@ -0,0 +1,145 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground.autotunnel.model
|
||||||
|
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList
|
||||||
|
|
||||||
|
data class AutoTunnelState(
|
||||||
|
val vpnState: VpnState = VpnState(),
|
||||||
|
val networkState: NetworkState = NetworkState(),
|
||||||
|
val settings: Settings = Settings(),
|
||||||
|
val tunnels: TunnelConfigs = emptyList(),
|
||||||
|
) {
|
||||||
|
|
||||||
|
private fun isMobileDataActive(): Boolean {
|
||||||
|
return !networkState.isEthernetConnected && !networkState.isWifiConnected && networkState.isMobileDataConnected
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isMobileTunnelDataChangeNeeded(): Boolean {
|
||||||
|
val preferredTunnel = preferredMobileDataTunnel()
|
||||||
|
return preferredTunnel != null &&
|
||||||
|
vpnState.status.isUp() && preferredTunnel.id != vpnState.tunnelConfig?.id
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isEthernetTunnelChangeNeeded(): Boolean {
|
||||||
|
val preferredTunnel = preferredEthernetTunnel()
|
||||||
|
return preferredTunnel != null && vpnState.status.isUp() && preferredTunnel.id != vpnState.tunnelConfig?.id
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun preferredMobileDataTunnel(): TunnelConfig? {
|
||||||
|
return tunnels.firstOrNull { it.isMobileDataTunnel } ?: tunnels.firstOrNull { it.isPrimaryTunnel }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun preferredEthernetTunnel(): TunnelConfig? {
|
||||||
|
return tunnels.firstOrNull { it.isEthernetTunnel } ?: tunnels.firstOrNull { it.isPrimaryTunnel }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun preferredWifiTunnel(): TunnelConfig? {
|
||||||
|
return getTunnelWithMatchingTunnelNetwork() ?: tunnels.firstOrNull { it.isPrimaryTunnel }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isWifiActive(): Boolean {
|
||||||
|
return !networkState.isEthernetConnected && networkState.isWifiConnected
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startOnEthernet(): Boolean {
|
||||||
|
return networkState.isEthernetConnected && settings.isTunnelOnEthernetEnabled && vpnState.status.isDown()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopOnEthernet(): Boolean {
|
||||||
|
return networkState.isEthernetConnected && !settings.isTunnelOnEthernetEnabled && vpnState.status.isUp()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isNoConnectivity(): Boolean {
|
||||||
|
return !networkState.isEthernetConnected && !networkState.isWifiConnected && !networkState.isMobileDataConnected
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopOnMobileData(): Boolean {
|
||||||
|
return isMobileDataActive() && !settings.isTunnelOnMobileDataEnabled && vpnState.status.isUp()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startOnMobileData(): Boolean {
|
||||||
|
return isMobileDataActive() && settings.isTunnelOnMobileDataEnabled && vpnState.status.isDown()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun changeOnMobileData(): Boolean {
|
||||||
|
return isMobileDataActive() && settings.isTunnelOnMobileDataEnabled && isMobileTunnelDataChangeNeeded()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun changeOnEthernet(): Boolean {
|
||||||
|
return networkState.isEthernetConnected && settings.isTunnelOnEthernetEnabled && isEthernetTunnelChangeNeeded()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopOnWifi(): Boolean {
|
||||||
|
return isWifiActive() && !settings.isTunnelOnWifiEnabled && vpnState.status.isUp()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopOnTrustedWifi(): Boolean {
|
||||||
|
return isWifiActive() && settings.isTunnelOnWifiEnabled && vpnState.status.isUp() && isCurrentSSIDTrusted()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startOnUntrustedWifi(): Boolean {
|
||||||
|
return isWifiActive() && settings.isTunnelOnWifiEnabled && vpnState.status.isDown() && !isCurrentSSIDTrusted()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun changeOnUntrustedWifi(): Boolean {
|
||||||
|
return isWifiActive() && settings.isTunnelOnWifiEnabled && vpnState.status.isUp() && !isCurrentSSIDTrusted() && !isWifiTunnelPreferred()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isWifiTunnelPreferred(): Boolean {
|
||||||
|
val preferred = preferredWifiTunnel()
|
||||||
|
val vpnTunnel = vpnState.tunnelConfig
|
||||||
|
return if (preferred != null && vpnTunnel != null) {
|
||||||
|
preferred.id == vpnTunnel.id
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun asAutoTunnelEvent(): AutoTunnelEvent {
|
||||||
|
return when {
|
||||||
|
// ethernet scenarios
|
||||||
|
stopOnEthernet() -> AutoTunnelEvent.Stop
|
||||||
|
startOnEthernet() || changeOnEthernet() -> AutoTunnelEvent.Start(preferredEthernetTunnel())
|
||||||
|
// mobile data scenarios
|
||||||
|
stopOnMobileData() -> AutoTunnelEvent.Stop
|
||||||
|
startOnMobileData() || changeOnMobileData() -> AutoTunnelEvent.Start(preferredMobileDataTunnel())
|
||||||
|
// wifi scenarios
|
||||||
|
stopOnWifi() -> AutoTunnelEvent.Stop
|
||||||
|
stopOnTrustedWifi() -> AutoTunnelEvent.Stop
|
||||||
|
startOnUntrustedWifi() || changeOnUntrustedWifi() -> AutoTunnelEvent.Start(preferredWifiTunnel())
|
||||||
|
// no connectivity
|
||||||
|
isNoConnectivity() && settings.isStopOnNoInternetEnabled -> AutoTunnelEvent.Stop
|
||||||
|
else -> AutoTunnelEvent.DoNothing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isCurrentSSIDTrusted(): Boolean {
|
||||||
|
return networkState.wifiName?.let {
|
||||||
|
hasTrustedWifiName(it)
|
||||||
|
} == true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasTrustedWifiName(wifiName: String, wifiNames: List<String> = settings.trustedNetworkSSIDs): Boolean {
|
||||||
|
return if (settings.isWildcardsEnabled) {
|
||||||
|
wifiNames.isMatchingToWildcardList(wifiName)
|
||||||
|
} else {
|
||||||
|
wifiNames.contains(wifiName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getTunnelWithMatchingTunnelNetwork(): TunnelConfig? {
|
||||||
|
return networkState.wifiName?.let { wifiName ->
|
||||||
|
tunnels.firstOrNull {
|
||||||
|
hasTrustedWifiName(wifiName, it.tunnelNetworks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isPingEnabled(): Boolean {
|
||||||
|
return settings.isPingEnabled ||
|
||||||
|
(vpnState.status.isUp() && vpnState.tunnelConfig != null && tunnels.first { it.id == vpnState.tunnelConfig.id }.isPingEnabled)
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.foreground.autotunnel.model
|
||||||
|
|
||||||
|
data class NetworkState(
|
||||||
|
val isWifiConnected: Boolean = false,
|
||||||
|
val isMobileDataConnected: Boolean = false,
|
||||||
|
val isEthernetConnected: Boolean = false,
|
||||||
|
val wifiName: String? = null,
|
||||||
|
)
|
||||||
-132
@@ -1,132 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.network
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.net.ConnectivityManager
|
|
||||||
import android.net.Network
|
|
||||||
import android.net.NetworkCapabilities
|
|
||||||
import android.net.NetworkRequest
|
|
||||||
import android.net.wifi.SupplicantState
|
|
||||||
import android.net.wifi.WifiInfo
|
|
||||||
import android.net.wifi.WifiManager
|
|
||||||
import android.os.Build
|
|
||||||
import kotlinx.coroutines.channels.awaitClose
|
|
||||||
import kotlinx.coroutines.flow.Flow
|
|
||||||
import kotlinx.coroutines.flow.callbackFlow
|
|
||||||
import kotlinx.coroutines.flow.map
|
|
||||||
|
|
||||||
abstract class BaseNetworkService<T : BaseNetworkService<T>>(
|
|
||||||
val context: Context,
|
|
||||||
networkCapability: Int
|
|
||||||
) : NetworkService<T> {
|
|
||||||
private val connectivityManager =
|
|
||||||
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
|
||||||
|
|
||||||
private val wifiManager =
|
|
||||||
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
|
||||||
|
|
||||||
override val networkStatus = callbackFlow {
|
|
||||||
val networkStatusCallback =
|
|
||||||
when (Build.VERSION.SDK_INT) {
|
|
||||||
in Build.VERSION_CODES.S..Int.MAX_VALUE -> {
|
|
||||||
object :
|
|
||||||
ConnectivityManager.NetworkCallback(
|
|
||||||
FLAG_INCLUDE_LOCATION_INFO,
|
|
||||||
) {
|
|
||||||
override fun onAvailable(network: Network) {
|
|
||||||
trySend(NetworkStatus.Available(network))
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onLost(network: Network) {
|
|
||||||
trySend(NetworkStatus.Unavailable(network))
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCapabilitiesChanged(
|
|
||||||
network: Network,
|
|
||||||
networkCapabilities: NetworkCapabilities
|
|
||||||
) {
|
|
||||||
trySend(
|
|
||||||
NetworkStatus.CapabilitiesChanged(
|
|
||||||
network,
|
|
||||||
networkCapabilities,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
object : ConnectivityManager.NetworkCallback() {
|
|
||||||
override fun onAvailable(network: Network) {
|
|
||||||
trySend(NetworkStatus.Available(network))
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onLost(network: Network) {
|
|
||||||
trySend(NetworkStatus.Unavailable(network))
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCapabilitiesChanged(
|
|
||||||
network: Network,
|
|
||||||
networkCapabilities: NetworkCapabilities
|
|
||||||
) {
|
|
||||||
trySend(
|
|
||||||
NetworkStatus.CapabilitiesChanged(
|
|
||||||
network,
|
|
||||||
networkCapabilities,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val request =
|
|
||||||
NetworkRequest.Builder()
|
|
||||||
.addTransportType(networkCapability)
|
|
||||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
|
||||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
|
||||||
.build()
|
|
||||||
connectivityManager.registerNetworkCallback(request, 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(
|
|
||||||
crossinline onUnavailable: suspend (network: Network) -> Result,
|
|
||||||
crossinline onAvailable: suspend (network: Network) -> Result,
|
|
||||||
crossinline onCapabilitiesChanged:
|
|
||||||
suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result
|
|
||||||
): Flow<Result> = map { status ->
|
|
||||||
when (status) {
|
|
||||||
is NetworkStatus.Unavailable -> onUnavailable(status.network)
|
|
||||||
is NetworkStatus.Available -> onAvailable(status.network)
|
|
||||||
is NetworkStatus.CapabilitiesChanged ->
|
|
||||||
onCapabilitiesChanged(
|
|
||||||
status.network,
|
|
||||||
status.networkCapabilities,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+57
-2
@@ -1,9 +1,64 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.network
|
package com.zaneschepke.wireguardautotunnel.service.network
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.Network
|
||||||
import android.net.NetworkCapabilities
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.NetworkRequest
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
|
import kotlinx.coroutines.flow.callbackFlow
|
||||||
|
import kotlinx.coroutines.flow.catch
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.onStart
|
||||||
|
import timber.log.Timber
|
||||||
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,
|
||||||
|
) : NetworkService {
|
||||||
|
|
||||||
|
private val connectivityManager =
|
||||||
|
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||||
|
|
||||||
|
override val status = callbackFlow {
|
||||||
|
val networkStatusCallback = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(network: Network) {
|
||||||
|
trySend(NetworkStatus.Available(network))
|
||||||
|
}
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
trySend(NetworkStatus.Unavailable())
|
||||||
|
}
|
||||||
|
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
|
||||||
|
trySend(
|
||||||
|
NetworkStatus.CapabilitiesChanged(
|
||||||
|
network,
|
||||||
|
networkCapabilities,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val request =
|
||||||
|
NetworkRequest.Builder()
|
||||||
|
.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||||
|
.build()
|
||||||
|
connectivityManager.registerNetworkCallback(request, networkStatusCallback)
|
||||||
|
|
||||||
|
awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) }
|
||||||
|
}.onStart {
|
||||||
|
// needed for services that are not yet available as it will impact later combine flows if we don't emit
|
||||||
|
emit(NetworkStatus.Unavailable())
|
||||||
|
}.catch {
|
||||||
|
Timber.e(it)
|
||||||
|
emit(NetworkStatus.Unavailable())
|
||||||
|
}.map {
|
||||||
|
when (it) {
|
||||||
|
is NetworkStatus.Available, is NetworkStatus.CapabilitiesChanged -> Status(true, null)
|
||||||
|
is NetworkStatus.Unavailable -> Status(false, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+56
-2
@@ -1,9 +1,63 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.network
|
package com.zaneschepke.wireguardautotunnel.service.network
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.Network
|
||||||
import android.net.NetworkCapabilities
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.NetworkRequest
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
|
import kotlinx.coroutines.flow.callbackFlow
|
||||||
|
import kotlinx.coroutines.flow.catch
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.onStart
|
||||||
|
import timber.log.Timber
|
||||||
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,
|
||||||
|
) : NetworkService {
|
||||||
|
private val connectivityManager =
|
||||||
|
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||||
|
|
||||||
|
override val status = callbackFlow {
|
||||||
|
val networkStatusCallback = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(network: Network) {
|
||||||
|
trySend(NetworkStatus.Available(network))
|
||||||
|
}
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
trySend(NetworkStatus.Unavailable())
|
||||||
|
}
|
||||||
|
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
|
||||||
|
trySend(
|
||||||
|
NetworkStatus.CapabilitiesChanged(
|
||||||
|
network,
|
||||||
|
networkCapabilities,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val request =
|
||||||
|
NetworkRequest.Builder()
|
||||||
|
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||||
|
.build()
|
||||||
|
connectivityManager.registerNetworkCallback(request, networkStatusCallback)
|
||||||
|
|
||||||
|
awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) }
|
||||||
|
}.onStart {
|
||||||
|
// needed for services that are not yet available as it will impact later combine flows if we don't emit
|
||||||
|
emit(NetworkStatus.Unavailable())
|
||||||
|
}.catch {
|
||||||
|
Timber.e(it)
|
||||||
|
emit(NetworkStatus.Unavailable())
|
||||||
|
}.map {
|
||||||
|
when (it) {
|
||||||
|
is NetworkStatus.Available, is NetworkStatus.CapabilitiesChanged -> Status(true, null)
|
||||||
|
is NetworkStatus.Unavailable -> Status(false, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+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
|
||||||
|
}
|
||||||
+21
-4
@@ -1,10 +1,27 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.network
|
package com.zaneschepke.wireguardautotunnel.service.network
|
||||||
|
|
||||||
|
import android.net.Network
|
||||||
import android.net.NetworkCapabilities
|
import android.net.NetworkCapabilities
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
|
||||||
interface NetworkService<T> {
|
interface NetworkService {
|
||||||
fun getNetworkName(networkCapabilities: NetworkCapabilities): String?
|
val status: Flow<Status>
|
||||||
|
}
|
||||||
val networkStatus: Flow<NetworkStatus>
|
|
||||||
|
inline fun <Result> Flow<NetworkStatus>.map(
|
||||||
|
crossinline onUnavailable: suspend () -> Result,
|
||||||
|
crossinline onAvailable: suspend (network: Network) -> Result,
|
||||||
|
crossinline onCapabilitiesChanged:
|
||||||
|
suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result,
|
||||||
|
): Flow<Result> = map { status ->
|
||||||
|
when (status) {
|
||||||
|
is NetworkStatus.Unavailable -> onUnavailable()
|
||||||
|
is NetworkStatus.Available -> onAvailable(status.network)
|
||||||
|
is NetworkStatus.CapabilitiesChanged ->
|
||||||
|
onCapabilitiesChanged(
|
||||||
|
status.network,
|
||||||
|
status.networkCapabilities,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-4
@@ -4,10 +4,11 @@ import android.net.Network
|
|||||||
import android.net.NetworkCapabilities
|
import android.net.NetworkCapabilities
|
||||||
|
|
||||||
sealed class NetworkStatus {
|
sealed class NetworkStatus {
|
||||||
class Available(val network: Network) : NetworkStatus()
|
abstract val isConnected: Boolean
|
||||||
|
class Available(val network: Network, override val isConnected: Boolean = true) : NetworkStatus()
|
||||||
|
|
||||||
class Unavailable(val network: Network) : NetworkStatus()
|
class Unavailable(override val isConnected: Boolean = false) : NetworkStatus()
|
||||||
|
|
||||||
class CapabilitiesChanged(val network: Network, val networkCapabilities: NetworkCapabilities) :
|
class CapabilitiesChanged(val network: Network, val networkCapabilities: NetworkCapabilities, override val isConnected: Boolean = true) :
|
||||||
NetworkStatus()
|
NetworkStatus()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.network
|
||||||
|
|
||||||
|
data class Status(
|
||||||
|
val available: Boolean,
|
||||||
|
val name: String?,
|
||||||
|
)
|
||||||
+132
-2
@@ -1,9 +1,139 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.network
|
package com.zaneschepke.wireguardautotunnel.service.network
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.ConnectivityManager.NetworkCallback.FLAG_INCLUDE_LOCATION_INFO
|
||||||
|
import android.net.Network
|
||||||
import android.net.NetworkCapabilities
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.NetworkRequest
|
||||||
|
import android.net.wifi.SupplicantState
|
||||||
|
import android.net.wifi.WifiManager
|
||||||
|
import android.os.Build
|
||||||
|
import com.wireguard.android.util.RootShell
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.AppShell
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.getCurrentWifiName
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
|
import kotlinx.coroutines.flow.callbackFlow
|
||||||
|
import kotlinx.coroutines.flow.catch
|
||||||
|
import kotlinx.coroutines.flow.onStart
|
||||||
|
import kotlinx.coroutines.flow.transform
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
class WifiService @Inject constructor(@ApplicationContext context: Context) :
|
class WifiService
|
||||||
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI)
|
@Inject
|
||||||
|
constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
private val settingsRepository: SettingsRepository,
|
||||||
|
@AppShell private val rootShell: Provider<RootShell>,
|
||||||
|
) : NetworkService {
|
||||||
|
|
||||||
|
val mutex = Mutex()
|
||||||
|
|
||||||
|
private var ssid: String? = null
|
||||||
|
private var available: Boolean = false
|
||||||
|
|
||||||
|
private val connectivityManager =
|
||||||
|
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||||
|
|
||||||
|
override val status = callbackFlow {
|
||||||
|
val networkStatusCallback =
|
||||||
|
when (Build.VERSION.SDK_INT) {
|
||||||
|
in Build.VERSION_CODES.S..Int.MAX_VALUE -> {
|
||||||
|
object :
|
||||||
|
ConnectivityManager.NetworkCallback(
|
||||||
|
FLAG_INCLUDE_LOCATION_INFO,
|
||||||
|
) {
|
||||||
|
override fun onAvailable(network: Network) {
|
||||||
|
trySend(NetworkStatus.Available(network))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
trySend(NetworkStatus.Unavailable())
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
|
||||||
|
trySend(
|
||||||
|
NetworkStatus.CapabilitiesChanged(
|
||||||
|
network,
|
||||||
|
networkCapabilities,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(network: Network) {
|
||||||
|
trySend(NetworkStatus.Available(network))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
trySend(NetworkStatus.Unavailable())
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
|
||||||
|
trySend(
|
||||||
|
NetworkStatus.CapabilitiesChanged(
|
||||||
|
network,
|
||||||
|
networkCapabilities,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val request =
|
||||||
|
NetworkRequest.Builder()
|
||||||
|
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||||
|
.build()
|
||||||
|
connectivityManager.registerNetworkCallback(request, networkStatusCallback)
|
||||||
|
|
||||||
|
awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) }
|
||||||
|
}.onStart {
|
||||||
|
// needed for services that are not yet available as it will impact later combine flows if we don't emit
|
||||||
|
emit(NetworkStatus.Unavailable())
|
||||||
|
}.catch {
|
||||||
|
Timber.e(it)
|
||||||
|
emit(NetworkStatus.Unavailable())
|
||||||
|
}.transform {
|
||||||
|
when (it) {
|
||||||
|
is NetworkStatus.Available -> mutex.withLock {
|
||||||
|
available = true
|
||||||
|
}
|
||||||
|
is NetworkStatus.CapabilitiesChanged -> mutex.withLock {
|
||||||
|
if (available) {
|
||||||
|
available = false
|
||||||
|
Timber.d("Getting SSID from capabilities")
|
||||||
|
ssid = getNetworkName(it.networkCapabilities)
|
||||||
|
}
|
||||||
|
emit(Status(true, ssid))
|
||||||
|
}
|
||||||
|
is NetworkStatus.Unavailable -> emit(Status(false, null))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
||||||
|
if (settingsRepository.getSettings().isWifiNameByShellEnabled) return rootShell.get().getCurrentWifiName()
|
||||||
|
var ssid = networkCapabilities.getWifiName()
|
||||||
|
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
|
||||||
|
val wifiManager =
|
||||||
|
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val info = wifiManager.connectionInfo
|
||||||
|
if (info.supplicantState === SupplicantState.COMPLETED) {
|
||||||
|
ssid = info.ssid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ssid?.trim('"')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.notification
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
|
||||||
|
enum class NotificationAction {
|
||||||
|
TUNNEL_OFF,
|
||||||
|
AUTO_TUNNEL_OFF,
|
||||||
|
;
|
||||||
|
|
||||||
|
fun title(context: Context): String {
|
||||||
|
return when (this) {
|
||||||
|
TUNNEL_OFF -> context.getString(R.string.stop)
|
||||||
|
AUTO_TUNNEL_OFF -> context.getString(R.string.stop)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
-15
@@ -2,21 +2,32 @@ package com.zaneschepke.wireguardautotunnel.service.notification
|
|||||||
|
|
||||||
import android.app.Notification
|
import android.app.Notification
|
||||||
import android.app.NotificationManager
|
import android.app.NotificationManager
|
||||||
import android.app.PendingIntent
|
import android.content.Context
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.WireGuardNotification.NotificationChannels
|
||||||
|
|
||||||
interface NotificationService {
|
interface NotificationService {
|
||||||
fun createNotification(
|
val context: Context
|
||||||
channelId: String,
|
fun createNotification(
|
||||||
channelName: String,
|
channel: NotificationChannels,
|
||||||
title: String = "",
|
title: String = "",
|
||||||
action: PendingIntent? = null,
|
actions: Collection<NotificationCompat.Action> = emptyList(),
|
||||||
actionText: String? = null,
|
description: String = "",
|
||||||
description: String,
|
showTimestamp: Boolean = false,
|
||||||
showTimestamp: Boolean = false,
|
importance: Int = NotificationManager.IMPORTANCE_HIGH,
|
||||||
importance: Int = NotificationManager.IMPORTANCE_HIGH,
|
onGoing: Boolean = true,
|
||||||
vibration: Boolean = false,
|
onlyAlertOnce: Boolean = true,
|
||||||
onGoing: Boolean = true,
|
): Notification
|
||||||
lights: Boolean = true,
|
|
||||||
onlyAlertOnce: Boolean = true,
|
fun createNotificationAction(notificationAction: NotificationAction): NotificationCompat.Action
|
||||||
): Notification
|
|
||||||
|
fun remove(notificationId: Int)
|
||||||
|
|
||||||
|
fun show(notificationId: Int, notification: Notification)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val KERNEL_SERVICE_NOTIFICATION_ID = 123
|
||||||
|
const val AUTO_TUNNEL_NOTIFICATION_ID = 122
|
||||||
|
const val VPN_NOTIFICATION_ID = 100
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+123
-82
@@ -1,102 +1,143 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.notification
|
package com.zaneschepke.wireguardautotunnel.service.notification
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
import android.app.Notification
|
import android.app.Notification
|
||||||
import android.app.NotificationChannel
|
import android.app.NotificationChannel
|
||||||
import android.app.NotificationManager
|
import android.app.NotificationManager
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
import android.graphics.Color
|
import android.graphics.Color
|
||||||
|
import androidx.core.app.ActivityCompat
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.receiver.NotificationActionReceiver
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.MainActivity
|
import com.zaneschepke.wireguardautotunnel.ui.MainActivity
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.SplashActivity
|
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
class WireGuardNotification @Inject constructor(@ApplicationContext private val context: Context) :
|
class WireGuardNotification
|
||||||
NotificationService {
|
@Inject
|
||||||
private val notificationManager =
|
constructor(
|
||||||
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
@ApplicationContext override val context: Context,
|
||||||
|
) : NotificationService {
|
||||||
|
|
||||||
private val watcherBuilder: NotificationCompat.Builder =
|
enum class NotificationChannels {
|
||||||
NotificationCompat.Builder(
|
VPN,
|
||||||
context,
|
AUTO_TUNNEL,
|
||||||
context.getString(R.string.watcher_channel_id),
|
}
|
||||||
)
|
|
||||||
private val tunnelBuilder: NotificationCompat.Builder =
|
|
||||||
NotificationCompat.Builder(
|
|
||||||
context,
|
|
||||||
context.getString(R.string.vpn_channel_id),
|
|
||||||
)
|
|
||||||
|
|
||||||
override fun createNotification(
|
private val notificationManager = NotificationManagerCompat.from(context)
|
||||||
channelId: String,
|
|
||||||
channelName: String,
|
|
||||||
title: String,
|
|
||||||
action: PendingIntent?,
|
|
||||||
actionText: String?,
|
|
||||||
description: String,
|
|
||||||
showTimestamp: Boolean,
|
|
||||||
importance: Int,
|
|
||||||
vibration: Boolean,
|
|
||||||
onGoing: Boolean,
|
|
||||||
lights: Boolean,
|
|
||||||
onlyAlertOnce: Boolean,
|
|
||||||
): Notification {
|
|
||||||
val channel =
|
|
||||||
NotificationChannel(
|
|
||||||
channelId,
|
|
||||||
channelName,
|
|
||||||
importance,
|
|
||||||
)
|
|
||||||
.let {
|
|
||||||
it.description = title
|
|
||||||
it.enableLights(lights)
|
|
||||||
it.lightColor = Color.RED
|
|
||||||
it.enableVibration(vibration)
|
|
||||||
it.vibrationPattern = longArrayOf(100, 200, 300)
|
|
||||||
it
|
|
||||||
}
|
|
||||||
notificationManager.createNotificationChannel(channel)
|
|
||||||
val pendingIntent: PendingIntent =
|
|
||||||
Intent(context, SplashActivity::class.java).let { notificationIntent ->
|
|
||||||
PendingIntent.getActivity(
|
|
||||||
context,
|
|
||||||
0,
|
|
||||||
notificationIntent,
|
|
||||||
PendingIntent.FLAG_IMMUTABLE,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
val builder =
|
override fun createNotification(
|
||||||
when (channelId) {
|
channel: NotificationChannels,
|
||||||
context.getString(R.string.watcher_channel_id) -> watcherBuilder
|
title: String,
|
||||||
context.getString(R.string.vpn_channel_id) -> tunnelBuilder
|
actions: Collection<NotificationCompat.Action>,
|
||||||
else -> {
|
description: String,
|
||||||
NotificationCompat.Builder(
|
showTimestamp: Boolean,
|
||||||
context,
|
importance: Int,
|
||||||
channelId,
|
onGoing: Boolean,
|
||||||
)
|
onlyAlertOnce: Boolean,
|
||||||
}
|
): Notification {
|
||||||
}
|
notificationManager.createNotificationChannel(channel.asChannel())
|
||||||
|
return channel.asBuilder().apply {
|
||||||
|
actions.forEach {
|
||||||
|
addAction(it)
|
||||||
|
}
|
||||||
|
setContentTitle(title)
|
||||||
|
setContentIntent(
|
||||||
|
PendingIntent.getActivity(
|
||||||
|
context,
|
||||||
|
0,
|
||||||
|
Intent(context, MainActivity::class.java),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
setContentText(description)
|
||||||
|
setOnlyAlertOnce(onlyAlertOnce)
|
||||||
|
setOngoing(onGoing)
|
||||||
|
setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||||
|
setShowWhen(showTimestamp)
|
||||||
|
setSmallIcon(R.drawable.ic_launcher)
|
||||||
|
}.build()
|
||||||
|
}
|
||||||
|
|
||||||
return builder.let {
|
override fun createNotificationAction(notificationAction: NotificationAction): NotificationCompat.Action {
|
||||||
if (action != null && actionText != null) {
|
val pendingIntent = PendingIntent.getBroadcast(
|
||||||
it.addAction(
|
context,
|
||||||
NotificationCompat.Action.Builder(0, actionText, action).build(),
|
0,
|
||||||
)
|
Intent(context, NotificationActionReceiver::class.java).apply {
|
||||||
it.setAutoCancel(true)
|
action = notificationAction.name
|
||||||
}
|
},
|
||||||
it.setContentTitle(title)
|
PendingIntent.FLAG_IMMUTABLE,
|
||||||
.setContentText(description)
|
)
|
||||||
.setOnlyAlertOnce(onlyAlertOnce)
|
return NotificationCompat.Action.Builder(
|
||||||
.setContentIntent(pendingIntent)
|
R.drawable.ic_launcher,
|
||||||
.setOngoing(onGoing)
|
notificationAction.title(context).uppercase(),
|
||||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
pendingIntent,
|
||||||
.setShowWhen(showTimestamp)
|
).build()
|
||||||
.setSmallIcon(R.drawable.ic_launcher)
|
}
|
||||||
.build()
|
|
||||||
}
|
override fun remove(notificationId: Int) {
|
||||||
}
|
notificationManager.cancel(notificationId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun show(notificationId: Int, notification: Notification) {
|
||||||
|
with(notificationManager) {
|
||||||
|
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
notify(notificationId, notification)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun NotificationChannels.asBuilder(): NotificationCompat.Builder {
|
||||||
|
return when (this) {
|
||||||
|
NotificationChannels.AUTO_TUNNEL -> {
|
||||||
|
NotificationCompat.Builder(
|
||||||
|
context,
|
||||||
|
context.getString(R.string.auto_tunnel_channel_id),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
NotificationChannels.VPN -> {
|
||||||
|
NotificationCompat.Builder(
|
||||||
|
context,
|
||||||
|
context.getString(R.string.vpn_channel_id),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun NotificationChannels.asChannel(): NotificationChannel {
|
||||||
|
return when (this) {
|
||||||
|
NotificationChannels.VPN -> {
|
||||||
|
NotificationChannel(
|
||||||
|
context.getString(R.string.vpn_channel_id),
|
||||||
|
context.getString(R.string.vpn_channel_name),
|
||||||
|
NotificationManager.IMPORTANCE_HIGH,
|
||||||
|
).apply {
|
||||||
|
description = context.getString(R.string.vpn_channel_description)
|
||||||
|
enableLights(true)
|
||||||
|
lightColor = Color.WHITE
|
||||||
|
enableVibration(false)
|
||||||
|
vibrationPattern = longArrayOf(100, 200, 300)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NotificationChannels.AUTO_TUNNEL -> {
|
||||||
|
NotificationChannel(
|
||||||
|
context.getString(R.string.auto_tunnel_channel_id),
|
||||||
|
context.getString(R.string.auto_tunnel_channel_name),
|
||||||
|
NotificationManager.IMPORTANCE_HIGH,
|
||||||
|
).apply {
|
||||||
|
description = context.getString(R.string.auto_tunnel_channel_description)
|
||||||
|
enableLights(true)
|
||||||
|
lightColor = Color.WHITE
|
||||||
|
enableVibration(false)
|
||||||
|
vibrationPattern = longArrayOf(100, 200, 300)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+79
@@ -0,0 +1,79 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.shortcut
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import androidx.core.content.pm.ShortcutInfoCompat
|
||||||
|
import androidx.core.content.pm.ShortcutManagerCompat
|
||||||
|
import androidx.core.graphics.drawable.IconCompat
|
||||||
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
class DynamicShortcutManager(private val context: Context, @IoDispatcher private val ioDispatcher: CoroutineDispatcher) : ShortcutManager {
|
||||||
|
override suspend fun addShortcuts() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
ShortcutManagerCompat.setDynamicShortcuts(context, createShortcuts())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun removeShortcuts() {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
ShortcutManagerCompat.removeDynamicShortcuts(context, createShortcuts().map { it.id })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createShortcuts(): List<ShortcutInfoCompat> {
|
||||||
|
return listOf(
|
||||||
|
buildShortcut(
|
||||||
|
context.getString(R.string.vpn_off),
|
||||||
|
context.getString(R.string.vpn_off),
|
||||||
|
context.getString(R.string.vpn_off),
|
||||||
|
intent = Intent(context, ShortcutsActivity::class.java).apply {
|
||||||
|
putExtra("className", "WireGuardTunnelService")
|
||||||
|
action = ShortcutsActivity.Action.STOP.name
|
||||||
|
},
|
||||||
|
shortcutIcon = R.drawable.vpn_off,
|
||||||
|
),
|
||||||
|
buildShortcut(
|
||||||
|
context.getString(R.string.vpn_on),
|
||||||
|
context.getString(R.string.vpn_on),
|
||||||
|
context.getString(R.string.vpn_on),
|
||||||
|
intent = Intent(context, ShortcutsActivity::class.java).apply {
|
||||||
|
putExtra("className", "WireGuardTunnelService")
|
||||||
|
action = ShortcutsActivity.Action.START.name
|
||||||
|
},
|
||||||
|
shortcutIcon = R.drawable.vpn_on,
|
||||||
|
),
|
||||||
|
buildShortcut(
|
||||||
|
context.getString(R.string.start_auto),
|
||||||
|
context.getString(R.string.start_auto),
|
||||||
|
context.getString(R.string.start_auto),
|
||||||
|
intent = Intent(context, ShortcutsActivity::class.java).apply {
|
||||||
|
putExtra("className", "WireGuardConnectivityWatcherService")
|
||||||
|
action = ShortcutsActivity.Action.START.name
|
||||||
|
},
|
||||||
|
shortcutIcon = R.drawable.auto_play,
|
||||||
|
),
|
||||||
|
buildShortcut(
|
||||||
|
context.getString(R.string.stop_auto),
|
||||||
|
context.getString(R.string.stop_auto),
|
||||||
|
context.getString(R.string.stop_auto),
|
||||||
|
intent = Intent(context, ShortcutsActivity::class.java).apply {
|
||||||
|
putExtra("className", "WireGuardConnectivityWatcherService")
|
||||||
|
action = ShortcutsActivity.Action.STOP.name
|
||||||
|
},
|
||||||
|
shortcutIcon = R.drawable.auto_pause,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildShortcut(id: String, shortLabel: String, longLabel: String, intent: Intent, shortcutIcon: Int): ShortcutInfoCompat {
|
||||||
|
return ShortcutInfoCompat.Builder(context, id)
|
||||||
|
.setShortLabel(shortLabel)
|
||||||
|
.setLongLabel(longLabel)
|
||||||
|
.setIntent(intent)
|
||||||
|
.setIcon(IconCompat.createWithResource(context, shortcutIcon))
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.shortcut
|
||||||
|
|
||||||
|
interface ShortcutManager {
|
||||||
|
suspend fun addShortcuts()
|
||||||
|
suspend fun removeShortcuts()
|
||||||
|
}
|
||||||
+56
-58
@@ -4,76 +4,74 @@ import android.os.Bundle
|
|||||||
import androidx.activity.ComponentActivity
|
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.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardConnectivityWatcherService
|
import com.zaneschepke.wireguardautotunnel.service.foreground.autotunnel.AutoTunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardTunnelService
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class ShortcutsActivity : ComponentActivity() {
|
class ShortcutsActivity : ComponentActivity() {
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
@ApplicationScope
|
@ApplicationScope
|
||||||
lateinit var applicationScope: CoroutineScope
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
applicationScope.launch {
|
applicationScope.launch {
|
||||||
val settings = appDataRepository.settings.getSettings()
|
val settings = appDataRepository.settings.getSettings()
|
||||||
if (settings.isShortcutsEnabled) {
|
if (settings.isShortcutsEnabled) {
|
||||||
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
|
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
|
||||||
WireGuardTunnelService::class.java.simpleName -> {
|
LEGACY_TUNNEL_SERVICE_NAME, TunnelService::class.java.simpleName -> {
|
||||||
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
|
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
|
||||||
val tunnelConfig = tunnelName?.let {
|
Timber.d("Tunnel name extra: $tunnelName")
|
||||||
appDataRepository.tunnels.getAll().firstOrNull {
|
val tunnelConfig = tunnelName?.let {
|
||||||
it.name == tunnelName
|
appDataRepository.tunnels.getAll()
|
||||||
}
|
.firstOrNull { it.name == tunnelName }
|
||||||
}
|
} ?: appDataRepository.getStartTunnelConfig()
|
||||||
when (intent.action) {
|
Timber.d("Shortcut action on name: ${tunnelConfig?.name}")
|
||||||
Action.START.name -> serviceManager.startVpnServiceForeground(
|
tunnelConfig?.let {
|
||||||
this@ShortcutsActivity, tunnelConfig?.id, isManualStart = true,
|
when (intent.action) {
|
||||||
)
|
Action.START.name -> tunnelService.get().startTunnel(it, true)
|
||||||
|
Action.STOP.name -> tunnelService.get().stopTunnel()
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AutoTunnelService::class.java.simpleName, LEGACY_AUTO_TUNNEL_SERVICE_NAME -> {
|
||||||
|
when (intent.action) {
|
||||||
|
Action.START.name -> serviceManager.startAutoTunnel(true)
|
||||||
|
Action.STOP.name -> serviceManager.stopAutoTunnel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
|
||||||
Action.STOP.name -> serviceManager.stopVpnServiceForeground(
|
enum class Action {
|
||||||
this@ShortcutsActivity,
|
START,
|
||||||
isManualStop = true,
|
STOP,
|
||||||
)
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
WireGuardConnectivityWatcherService::class.java.simpleName -> {
|
companion object {
|
||||||
when (intent.action) {
|
const val LEGACY_TUNNEL_SERVICE_NAME = "WireGuardTunnelService"
|
||||||
Action.START.name -> appDataRepository.settings.save(
|
const val LEGACY_AUTO_TUNNEL_SERVICE_NAME = "WireGuardConnectivityWatcherService"
|
||||||
settings.copy(
|
const val TUNNEL_NAME_EXTRA_KEY = "tunnelName"
|
||||||
isAutoTunnelPaused = false,
|
const val CLASS_NAME_EXTRA_KEY = "className"
|
||||||
),
|
}
|
||||||
)
|
|
||||||
|
|
||||||
Action.STOP.name -> appDataRepository.settings.save(
|
|
||||||
settings.copy(
|
|
||||||
isAutoTunnelPaused = true,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
const val TUNNEL_NAME_EXTRA_KEY = "tunnelName"
|
|
||||||
const val CLASS_NAME_EXTRA_KEY = "className"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+62
-83
@@ -1,107 +1,86 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.tile
|
package com.zaneschepke.wireguardautotunnel.service.tile
|
||||||
|
|
||||||
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.ServiceLifecycleDispatcher
|
|
||||||
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.data.repository.AppDataRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ServiceScope
|
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
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 javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
class AutoTunnelControlTile : TileService() {
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
private val dispatcher = ServiceLifecycleDispatcher(this)
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
serviceManager.autoTunnelTile.complete(this)
|
||||||
|
}
|
||||||
|
|
||||||
private var manualStartConfig: TunnelConfig? = null
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
serviceManager.autoTunnelTile = CompletableDeferred()
|
||||||
|
}
|
||||||
|
|
||||||
override fun onStartListening() {
|
override fun onStartListening() {
|
||||||
super.onStartListening()
|
super.onStartListening()
|
||||||
lifecycleScope.launch {
|
serviceManager.autoTunnelTile.complete(this)
|
||||||
val settings = appDataRepository.settings.getSettings()
|
applicationScope.launch {
|
||||||
when (settings.isAutoTunnelEnabled) {
|
if (appDataRepository.tunnels.getAll().isEmpty()) return@launch setUnavailable()
|
||||||
true -> {
|
updateTileState()
|
||||||
if (settings.isAutoTunnelPaused) {
|
}
|
||||||
setInactive()
|
}
|
||||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.paused))
|
|
||||||
} else {
|
|
||||||
setActive()
|
|
||||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.active))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
false -> {
|
|
||||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.disabled))
|
|
||||||
setUnavailable()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onTileAdded() {
|
fun updateTileState() {
|
||||||
super.onTileAdded()
|
serviceManager.autoTunnelActive.value.let {
|
||||||
onStartListening()
|
if (it) setActive() else setInactive()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onClick() {
|
override fun onClick() {
|
||||||
super.onClick()
|
super.onClick()
|
||||||
unlockAndRun {
|
unlockAndRun {
|
||||||
lifecycleScope.launch {
|
applicationScope.launch {
|
||||||
try {
|
if (serviceManager.autoTunnelActive.value) {
|
||||||
appDataRepository.toggleWatcherServicePause()
|
serviceManager.stopAutoTunnel()
|
||||||
onStartListening()
|
setInactive()
|
||||||
} catch (e: Exception) {
|
} else {
|
||||||
Timber.e(e.message)
|
serviceManager.startAutoTunnel(true)
|
||||||
} finally {
|
setActive()
|
||||||
cancel()
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private fun setActive() {
|
private fun setActive() {
|
||||||
qsTile.state = Tile.STATE_ACTIVE
|
kotlin.runCatching {
|
||||||
qsTile.updateTile()
|
qsTile.state = Tile.STATE_ACTIVE
|
||||||
}
|
qsTile.updateTile()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun setInactive() {
|
private fun setInactive() {
|
||||||
qsTile.state = Tile.STATE_INACTIVE
|
kotlin.runCatching {
|
||||||
qsTile.updateTile()
|
qsTile.state = Tile.STATE_INACTIVE
|
||||||
}
|
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) {
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
|
||||||
qsTile.subtitle = description
|
|
||||||
}
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
|
||||||
qsTile.stateDescription = description
|
|
||||||
}
|
|
||||||
qsTile.updateTile()
|
|
||||||
}
|
|
||||||
|
|
||||||
override val lifecycle: Lifecycle
|
|
||||||
get() = dispatcher.lifecycle
|
|
||||||
}
|
}
|
||||||
|
|||||||
+90
-93
@@ -3,120 +3,117 @@ 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.LifecycleService
|
|
||||||
import androidx.lifecycle.ServiceLifecycleDispatcher
|
|
||||||
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.foreground.ServiceManager
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
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 javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class TunnelControlTile : TileService(), LifecycleOwner {
|
class TunnelControlTile : TileService() {
|
||||||
|
@Inject
|
||||||
|
lateinit var appDataRepository: AppDataRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appDataRepository: AppDataRepository
|
lateinit var tunnelService: Provider<TunnelService>
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var vpnService: VpnService
|
@ApplicationScope
|
||||||
|
lateinit var applicationScope: CoroutineScope
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var serviceManager: ServiceManager
|
||||||
|
|
||||||
private val dispatcher = ServiceLifecycleDispatcher(this)
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
serviceManager.tunnelControlTile.complete(this)
|
||||||
|
}
|
||||||
|
|
||||||
private var manualStartConfig: TunnelConfig? = null
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
serviceManager.tunnelControlTile = CompletableDeferred()
|
||||||
|
}
|
||||||
|
|
||||||
override fun onStartListening() {
|
override fun onStartListening() {
|
||||||
super.onStartListening()
|
super.onStartListening()
|
||||||
Timber.d("On start listening called")
|
serviceManager.tunnelControlTile.complete(this)
|
||||||
lifecycleScope.launch {
|
applicationScope.launch {
|
||||||
when (vpnService.getState()) {
|
if (appDataRepository.tunnels.getAll().isEmpty()) return@launch setUnavailable()
|
||||||
TunnelState.UP -> {
|
updateTileState()
|
||||||
setActive()
|
}
|
||||||
setTileDescription(vpnService.name)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
TunnelState.DOWN -> {
|
fun updateTileState() = applicationScope.launch {
|
||||||
setInactive()
|
val lastActive = appDataRepository.getStartTunnelConfig()
|
||||||
val config = appDataRepository.getStartTunnelConfig()?.also { config ->
|
lastActive?.let {
|
||||||
manualStartConfig = config
|
updateTile(it)
|
||||||
} ?: appDataRepository.getPrimaryOrFirstTunnel()
|
}
|
||||||
config?.let {
|
}
|
||||||
setTileDescription(it.name)
|
|
||||||
} ?: setUnavailable()
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> setInactive()
|
override fun onClick() {
|
||||||
}
|
super.onClick()
|
||||||
}
|
unlockAndRun {
|
||||||
}
|
applicationScope.launch {
|
||||||
|
val lastActive = appDataRepository.getStartTunnelConfig()
|
||||||
|
lastActive?.let { tunnel ->
|
||||||
|
if (tunnel.isActive) {
|
||||||
|
tunnelService.get().stopTunnel()
|
||||||
|
} else {
|
||||||
|
tunnelService.get().startTunnel(tunnel, true)
|
||||||
|
}
|
||||||
|
updateTileState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onTileAdded() {
|
private fun setActive() {
|
||||||
super.onTileAdded()
|
kotlin.runCatching {
|
||||||
onStartListening()
|
qsTile.state = Tile.STATE_ACTIVE
|
||||||
}
|
qsTile.updateTile()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onClick() {
|
private fun setInactive() {
|
||||||
super.onClick()
|
kotlin.runCatching {
|
||||||
unlockAndRun {
|
qsTile.state = Tile.STATE_INACTIVE
|
||||||
lifecycleScope.launch {
|
qsTile.updateTile()
|
||||||
try {
|
}
|
||||||
if (vpnService.getState() == TunnelState.UP) {
|
}
|
||||||
serviceManager.stopVpnServiceForeground(
|
|
||||||
this@TunnelControlTile,
|
|
||||||
isManualStop = true,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
serviceManager.startVpnServiceForeground(
|
|
||||||
this@TunnelControlTile, manualStartConfig?.id, isManualStart = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Timber.e(e.message)
|
|
||||||
} finally {
|
|
||||||
cancel()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun setActive() {
|
private fun setUnavailable() {
|
||||||
qsTile.state = Tile.STATE_ACTIVE
|
kotlin.runCatching {
|
||||||
qsTile.updateTile()
|
qsTile.state = Tile.STATE_UNAVAILABLE
|
||||||
}
|
setTileDescription("")
|
||||||
|
qsTile.updateTile()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun setInactive() {
|
private fun setTileDescription(description: String) {
|
||||||
qsTile.state = Tile.STATE_INACTIVE
|
kotlin.runCatching {
|
||||||
qsTile.updateTile()
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
}
|
qsTile.subtitle = description
|
||||||
|
}
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
qsTile.stateDescription = description
|
||||||
|
}
|
||||||
|
qsTile.updateTile()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun setUnavailable() {
|
private fun updateTile(tunnelConfig: TunnelConfig?) {
|
||||||
manualStartConfig = null
|
kotlin.runCatching {
|
||||||
qsTile.state = Tile.STATE_UNAVAILABLE
|
tunnelConfig?.let {
|
||||||
qsTile.updateTile()
|
setTileDescription(it.name)
|
||||||
}
|
if (it.isActive) return setActive()
|
||||||
|
setInactive()
|
||||||
private fun setTileDescription(description: String) {
|
}
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
}
|
||||||
qsTile.subtitle = description
|
}
|
||||||
}
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
|
||||||
qsTile.stateDescription = description
|
|
||||||
}
|
|
||||||
qsTile.updateTile()
|
|
||||||
}
|
|
||||||
|
|
||||||
override val lifecycle: Lifecycle
|
|
||||||
get() = dispatcher.lifecycle
|
|
||||||
}
|
}
|
||||||
|
|||||||
+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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
||||||
|
|
||||||
|
enum class BackendState {
|
||||||
|
KILL_SWITCH_ACTIVE,
|
||||||
|
SERVICE_ACTIVE,
|
||||||
|
INACTIVE,
|
||||||
|
}
|
||||||
+12
-11
@@ -1,16 +1,17 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
||||||
|
|
||||||
enum class HandshakeStatus {
|
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
|
||||||
const val STATUS_CHANGE_TIME_BUFFER = 30
|
const val STATUS_CHANGE_TIME_BUFFER = 30
|
||||||
const val STALE_TIME_LIMIT_SEC =
|
const val STALE_TIME_LIMIT_SEC =
|
||||||
WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC + STATUS_CHANGE_TIME_BUFFER
|
WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC + STATUS_CHANGE_TIME_BUFFER
|
||||||
const val NEVER_CONNECTED_TO_UNHEALTHY_TIME_LIMIT_SEC = 30
|
const val NEVER_CONNECTED_TO_UNHEALTHY_TIME_LIMIT_SEC = 30
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
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?, background: Boolean = false)
|
||||||
|
|
||||||
|
suspend fun stopTunnel()
|
||||||
|
|
||||||
|
suspend fun bounceTunnel()
|
||||||
|
|
||||||
|
suspend fun getBackendState(): BackendState
|
||||||
|
|
||||||
|
suspend fun setBackendState(backendState: BackendState, allowedIps: Collection<String>)
|
||||||
|
|
||||||
|
val vpnState: StateFlow<VpnState>
|
||||||
|
|
||||||
|
suspend fun runningTunnelNames(): Set<String>
|
||||||
|
|
||||||
|
suspend fun getState(): TunnelState
|
||||||
|
|
||||||
|
fun cancelActiveTunnelJobs()
|
||||||
|
|
||||||
|
fun startActiveTunnelJobs()
|
||||||
|
}
|
||||||
+42
-33
@@ -3,41 +3,50 @@ package com.zaneschepke.wireguardautotunnel.service.tunnel
|
|||||||
import com.wireguard.android.backend.Tunnel
|
import com.wireguard.android.backend.Tunnel
|
||||||
|
|
||||||
enum class TunnelState {
|
enum class TunnelState {
|
||||||
UP,
|
UP,
|
||||||
DOWN,
|
DOWN,
|
||||||
TOGGLE;
|
TOGGLE,
|
||||||
|
;
|
||||||
|
|
||||||
fun toWgState(): Tunnel.State {
|
fun toWgState(): Tunnel.State {
|
||||||
return when (this) {
|
return when (this) {
|
||||||
UP -> Tunnel.State.UP
|
UP -> Tunnel.State.UP
|
||||||
DOWN -> Tunnel.State.DOWN
|
DOWN -> Tunnel.State.DOWN
|
||||||
TOGGLE -> Tunnel.State.TOGGLE
|
TOGGLE -> Tunnel.State.TOGGLE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun toAmState(): org.amnezia.awg.backend.Tunnel.State {
|
fun toAmState(): org.amnezia.awg.backend.Tunnel.State {
|
||||||
return when (this) {
|
return when (this) {
|
||||||
UP -> org.amnezia.awg.backend.Tunnel.State.UP
|
UP -> org.amnezia.awg.backend.Tunnel.State.UP
|
||||||
DOWN -> org.amnezia.awg.backend.Tunnel.State.DOWN
|
DOWN -> org.amnezia.awg.backend.Tunnel.State.DOWN
|
||||||
TOGGLE -> org.amnezia.awg.backend.Tunnel.State.TOGGLE
|
TOGGLE -> org.amnezia.awg.backend.Tunnel.State.TOGGLE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
fun isDown(): Boolean {
|
||||||
fun from(state: Tunnel.State): TunnelState {
|
return this == DOWN
|
||||||
return when (state) {
|
}
|
||||||
Tunnel.State.DOWN -> DOWN
|
|
||||||
Tunnel.State.TOGGLE -> TOGGLE
|
|
||||||
Tunnel.State.UP -> UP
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun from(state: org.amnezia.awg.backend.Tunnel.State): TunnelState {
|
fun isUp(): Boolean {
|
||||||
return when (state) {
|
return this == UP
|
||||||
org.amnezia.awg.backend.Tunnel.State.DOWN -> DOWN
|
}
|
||||||
org.amnezia.awg.backend.Tunnel.State.TOGGLE -> TOGGLE
|
|
||||||
org.amnezia.awg.backend.Tunnel.State.UP -> UP
|
companion object {
|
||||||
}
|
fun from(state: Tunnel.State): TunnelState {
|
||||||
}
|
return when (state) {
|
||||||
}
|
Tunnel.State.DOWN -> DOWN
|
||||||
|
Tunnel.State.TOGGLE -> TOGGLE
|
||||||
|
Tunnel.State.UP -> UP
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun from(state: org.amnezia.awg.backend.Tunnel.State): TunnelState {
|
||||||
|
return when (state) {
|
||||||
|
org.amnezia.awg.backend.Tunnel.State.DOWN -> DOWN
|
||||||
|
org.amnezia.awg.backend.Tunnel.State.TOGGLE -> TOGGLE
|
||||||
|
org.amnezia.awg.backend.Tunnel.State.UP -> UP
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.service.tunnel
|
|
||||||
|
|
||||||
import com.wireguard.android.backend.Tunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
|
|
||||||
interface VpnService : Tunnel, org.amnezia.awg.backend.Tunnel {
|
|
||||||
suspend fun startTunnel(tunnelConfig: TunnelConfig? = null): TunnelState
|
|
||||||
|
|
||||||
suspend fun stopTunnel()
|
|
||||||
|
|
||||||
val vpnState: StateFlow<VpnState>
|
|
||||||
|
|
||||||
fun getState(): TunnelState
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
|||||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
||||||
|
|
||||||
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,
|
||||||
)
|
)
|
||||||
|
|||||||
+295
-170
@@ -1,20 +1,24 @@
|
|||||||
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.R
|
||||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.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.foreground.ServiceManager
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationAction
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService.Companion.VPN_NOTIFICATION_ID
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.notification.WireGuardNotification
|
||||||
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 com.zaneschepke.wireguardautotunnel.util.extensions.asAmBackendState
|
||||||
import kotlinx.coroutines.CancellationException
|
import com.zaneschepke.wireguardautotunnel.util.extensions.asBackendState
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
@@ -22,7 +26,10 @@ import kotlinx.coroutines.delay
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
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
|
||||||
@@ -32,191 +39,309 @@ import javax.inject.Provider
|
|||||||
class WireGuardTunnel
|
class WireGuardTunnel
|
||||||
@Inject
|
@Inject
|
||||||
constructor(
|
constructor(
|
||||||
private val userspaceAmneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
private val amneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
||||||
@Userspace private val userspaceBackend: Provider<Backend>,
|
private val tunnelConfigRepository: TunnelConfigRepository,
|
||||||
@Kernel private val kernelBackend: Provider<Backend>,
|
@Kernel private val kernelBackend: Provider<Backend>,
|
||||||
private val appDataRepository: AppDataRepository,
|
private val appDataRepository: AppDataRepository,
|
||||||
@ApplicationScope private val applicationScope: CoroutineScope,
|
@ApplicationScope private val applicationScope: CoroutineScope,
|
||||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||||
) : VpnService {
|
private val serviceManager: ServiceManager,
|
||||||
private val _vpnState = MutableStateFlow(VpnState())
|
private val notificationService: NotificationService,
|
||||||
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
|
) : TunnelService {
|
||||||
|
|
||||||
|
private val _vpnState = MutableStateFlow(VpnState())
|
||||||
|
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
|
||||||
|
|
||||||
private var statsJob: Job? = null
|
private var statsJob: Job? = null
|
||||||
|
private var tunnelChangesJob: Job? = null
|
||||||
|
|
||||||
private var backendIsWgUserspace = true
|
@get:Synchronized @set:Synchronized
|
||||||
|
private var isKernelBackend: Boolean? = null
|
||||||
|
|
||||||
private var backendIsAmneziaUserspace = false
|
private val tunnelControlMutex = Mutex()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
applicationScope.launch(ioDispatcher) {
|
applicationScope.launch(ioDispatcher) {
|
||||||
appDataRepository.settings.getSettingsFlow().collect {
|
appDataRepository.settings.getSettingsFlow().collect {
|
||||||
if (it.isKernelEnabled && (backendIsWgUserspace || backendIsAmneziaUserspace)) {
|
isKernelBackend = it.isKernelEnabled
|
||||||
Timber.i("Setting kernel backend")
|
}
|
||||||
backendIsWgUserspace = false
|
}
|
||||||
backendIsAmneziaUserspace = false
|
}
|
||||||
} else if (!it.isKernelEnabled && !it.isAmneziaEnabled && !backendIsWgUserspace) {
|
|
||||||
Timber.i("Setting WireGuard userspace backend")
|
|
||||||
backendIsWgUserspace = true
|
|
||||||
backendIsAmneziaUserspace = false
|
|
||||||
} else if (it.isAmneziaEnabled && !backendIsAmneziaUserspace) {
|
|
||||||
Timber.i("Setting Amnezia userspace backend")
|
|
||||||
backendIsAmneziaUserspace = true
|
|
||||||
backendIsWgUserspace = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun setState(tunnelConfig: TunnelConfig?, tunnelState: TunnelState): TunnelState {
|
private suspend fun backend(): Any {
|
||||||
return if (backendIsAmneziaUserspace) {
|
val isKernelEnabled = isKernelBackend
|
||||||
Timber.i("Using Amnezia backend")
|
?: appDataRepository.settings.getSettings().isKernelEnabled
|
||||||
val config = tunnelConfig?.let {
|
if (isKernelEnabled) return kernelBackend.get()
|
||||||
if (it.amQuick != "") TunnelConfig.configFromAmQuick(it.amQuick) else {
|
return amneziaBackend.get()
|
||||||
Timber.w("Using backwards compatible wg config, amnezia specific config not found.")
|
}
|
||||||
TunnelConfig.configFromAmQuick(it.wgQuick)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val state =
|
|
||||||
userspaceAmneziaBackend.get().setState(this, tunnelState.toAmState(), config)
|
|
||||||
TunnelState.from(state)
|
|
||||||
} else {
|
|
||||||
Timber.i("Using Wg backend")
|
|
||||||
val wgConfig = tunnelConfig?.let { TunnelConfig.configFromWgQuick(it.wgQuick) }
|
|
||||||
val state = backend().setState(
|
|
||||||
this,
|
|
||||||
tunnelState.toWgState(),
|
|
||||||
wgConfig,
|
|
||||||
)
|
|
||||||
TunnelState.from(state)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun startTunnel(tunnelConfig: TunnelConfig?): TunnelState {
|
override suspend fun runningTunnelNames(): Set<String> {
|
||||||
return withContext(ioDispatcher) {
|
return when (val backend = backend()) {
|
||||||
try {
|
is Backend -> backend.runningTunnelNames
|
||||||
//TODO we need better error handling here
|
is org.amnezia.awg.backend.Backend -> backend.runningTunnelNames
|
||||||
// need to bubble up these errors to the UI
|
else -> emptySet()
|
||||||
val config = tunnelConfig ?: appDataRepository.getPrimaryOrFirstTunnel()
|
}
|
||||||
if (config != null) {
|
}
|
||||||
emitTunnelConfig(config)
|
|
||||||
setState(config, TunnelState.UP)
|
|
||||||
} else throw Exception("No tunnels")
|
|
||||||
} catch (e: BackendException) {
|
|
||||||
Timber.e("Failed to start tunnel with error: ${e.message}")
|
|
||||||
TunnelState.from(State.DOWN)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun backend(): Backend {
|
private suspend fun setState(tunnelConfig: TunnelConfig, tunnelState: TunnelState): Result<TunnelState> {
|
||||||
return when {
|
return runCatching {
|
||||||
backendIsWgUserspace -> {
|
when (val backend = backend()) {
|
||||||
userspaceBackend.get()
|
is Backend -> backend.setState(this, tunnelState.toWgState(), TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick)).let { TunnelState.from(it) }
|
||||||
}
|
is org.amnezia.awg.backend.Backend -> {
|
||||||
|
val config = if (tunnelConfig.amQuick.isBlank()) {
|
||||||
|
TunnelConfig.configFromAmQuick(
|
||||||
|
tunnelConfig.wgQuick,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
TunnelConfig.configFromAmQuick(tunnelConfig.amQuick)
|
||||||
|
}
|
||||||
|
backend.setState(this, tunnelState.toAmState(), config).let {
|
||||||
|
TunnelState.from(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> throw NotImplementedError()
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
// TODO add better error message to user, especially for kernel as exceptions contain no details
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
!backendIsWgUserspace && !backendIsAmneziaUserspace -> {
|
private fun isTunnelAlreadyRunning(tunnelConfig: TunnelConfig): Boolean {
|
||||||
kernelBackend.get()
|
val isRunning = tunnelConfig == _vpnState.value.tunnelConfig && _vpnState.value.status.isUp()
|
||||||
}
|
if (isRunning) Timber.w("Tunnel already running")
|
||||||
|
return isRunning
|
||||||
|
}
|
||||||
|
|
||||||
else -> {
|
override suspend fun startTunnel(tunnelConfig: TunnelConfig?, background: Boolean) {
|
||||||
userspaceBackend.get()
|
withContext(ioDispatcher) {
|
||||||
}
|
if (tunnelConfig == null || isTunnelAlreadyRunning(tunnelConfig)) return@withContext
|
||||||
}
|
updateTunnelConfig(tunnelConfig) // need to update this here
|
||||||
}
|
withServiceActive {
|
||||||
|
onBeforeStart(background)
|
||||||
|
tunnelControlMutex.withLock {
|
||||||
|
setState(tunnelConfig, TunnelState.UP).onSuccess {
|
||||||
|
updateTunnelState(it, tunnelConfig)
|
||||||
|
onTunnelStart(tunnelConfig, background)
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun emitTunnelState(state: TunnelState) {
|
override suspend fun stopTunnel() {
|
||||||
_vpnState.tryEmit(
|
withContext(ioDispatcher) {
|
||||||
_vpnState.value.copy(
|
if (_vpnState.value.status.isDown()) return@withContext
|
||||||
status = state,
|
with(_vpnState.value) {
|
||||||
),
|
if (tunnelConfig == null) return@withContext
|
||||||
)
|
tunnelControlMutex.withLock {
|
||||||
}
|
setState(tunnelConfig, TunnelState.DOWN).onSuccess {
|
||||||
|
onTunnelStop(tunnelConfig)
|
||||||
|
updateTunnelState(it, null)
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun emitBackendStatistics(statistics: TunnelStatistics) {
|
private suspend fun toggleTunnel(tunnelConfig: TunnelConfig) {
|
||||||
_vpnState.tryEmit(
|
withContext(ioDispatcher) {
|
||||||
_vpnState.value.copy(
|
tunnelControlMutex.withLock {
|
||||||
statistics = statistics,
|
setState(tunnelConfig, TunnelState.TOGGLE)
|
||||||
),
|
}
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun emitTunnelConfig(tunnelConfig: TunnelConfig?) {
|
// utility to keep vpnService alive during rapid changes to prevent bad states
|
||||||
_vpnState.emit(
|
private suspend fun withServiceActive(callback: suspend () -> Unit) {
|
||||||
_vpnState.value.copy(
|
when (val backend = backend()) {
|
||||||
tunnelConfig = tunnelConfig,
|
is org.amnezia.awg.backend.Backend -> {
|
||||||
),
|
val backendState = backend.backendState
|
||||||
)
|
if (backendState == org.amnezia.awg.backend.Backend.BackendState.INACTIVE) {
|
||||||
}
|
backend.setBackendState(org.amnezia.awg.backend.Backend.BackendState.SERVICE_ACTIVE, emptyList())
|
||||||
|
}
|
||||||
|
callback()
|
||||||
|
}
|
||||||
|
is Backend -> callback()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun resetVpnState() {
|
override suspend fun bounceTunnel() {
|
||||||
_vpnState.tryEmit(VpnState())
|
_vpnState.value.tunnelConfig?.let {
|
||||||
}
|
withServiceActive {
|
||||||
|
toggleTunnel(it)
|
||||||
|
toggleTunnel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun stopTunnel() {
|
override suspend fun getBackendState(): BackendState {
|
||||||
withContext(ioDispatcher) {
|
return when (val backend = backend()) {
|
||||||
try {
|
is org.amnezia.awg.backend.Backend -> {
|
||||||
if (getState() == TunnelState.UP) {
|
backend.backendState.asBackendState()
|
||||||
val state = setState(null, TunnelState.DOWN)
|
}
|
||||||
resetVpnState()
|
is Backend -> BackendState.SERVICE_ACTIVE
|
||||||
emitTunnelState(state)
|
else -> BackendState.INACTIVE
|
||||||
}
|
}
|
||||||
} 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 suspend fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) {
|
||||||
return if (backendIsAmneziaUserspace) TunnelState.from(
|
kotlin.runCatching {
|
||||||
userspaceAmneziaBackend.get().getState(this),
|
when (val backend = backend()) {
|
||||||
)
|
is org.amnezia.awg.backend.Backend -> {
|
||||||
else TunnelState.from(backend().getState(this))
|
backend.setBackendState(backendState.asAmBackendState(), allowedIps)
|
||||||
}
|
}
|
||||||
|
is Backend -> {
|
||||||
|
// TODO not yet implemented
|
||||||
|
Timber.d("Kernel backend state not yet implemented")
|
||||||
|
}
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun getName(): String {
|
private suspend fun onBeforeStart(background: Boolean) {
|
||||||
return _vpnState.value.tunnelConfig?.name ?: ""
|
with(_vpnState.value) {
|
||||||
}
|
if (status.isUp()) stopTunnel() else clearJobsAndStats()
|
||||||
|
if (isKernelBackend == true || background) serviceManager.startBackgroundService(tunnelConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun onTunnelStart(tunnelConfig: TunnelConfig, background: Boolean) {
|
||||||
|
startActiveTunnelJobs()
|
||||||
|
if (_vpnState.value.status.isUp()) {
|
||||||
|
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = true))
|
||||||
|
}
|
||||||
|
if (isKernelBackend == false && !background) launchUserspaceTunnelNotification()
|
||||||
|
}
|
||||||
|
|
||||||
override fun onStateChange(newState: Tunnel.State) {
|
private fun launchUserspaceTunnelNotification() {
|
||||||
handleStateChange(TunnelState.from(newState))
|
with(notificationService) {
|
||||||
}
|
val notification = createNotification(
|
||||||
|
WireGuardNotification.NotificationChannels.VPN,
|
||||||
|
title = "${context.getString(R.string.tunnel_running)} - ${_vpnState.value.tunnelConfig?.name}",
|
||||||
|
actions = listOf(
|
||||||
|
notificationService.createNotificationAction(NotificationAction.TUNNEL_OFF),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
show(VPN_NOTIFICATION_ID, notification)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun handleStateChange(state: TunnelState) {
|
private suspend fun onTunnelStop(tunnelConfig: TunnelConfig) {
|
||||||
emitTunnelState(state)
|
runCatching {
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = false))
|
||||||
if (state == TunnelState.UP) {
|
serviceManager.stopBackgroundService()
|
||||||
statsJob = startTunnelStatisticsJob()
|
notificationService.remove(VPN_NOTIFICATION_ID)
|
||||||
}
|
clearJobsAndStats()
|
||||||
if (state == TunnelState.DOWN) {
|
}
|
||||||
try {
|
}
|
||||||
statsJob?.cancel()
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
Timber.i("Stats job cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startTunnelStatisticsJob() = applicationScope.launch(ioDispatcher) {
|
private fun clearJobsAndStats() {
|
||||||
while (true) {
|
cancelActiveTunnelJobs()
|
||||||
if (backendIsAmneziaUserspace) {
|
resetBackendStatistics()
|
||||||
emitBackendStatistics(
|
}
|
||||||
AmneziaStatistics(
|
|
||||||
userspaceAmneziaBackend.get().getStatistics(this@WireGuardTunnel),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
emitBackendStatistics(WireGuardStatistics(backend().getStatistics(this@WireGuardTunnel)))
|
|
||||||
}
|
|
||||||
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onStateChange(state: State) {
|
private fun updateTunnelState(state: TunnelState, tunnelConfig: TunnelConfig?) {
|
||||||
handleStateChange(TunnelState.from(state))
|
_vpnState.update {
|
||||||
}
|
it.copy(status = state, tunnelConfig = tunnelConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) {
|
||||||
|
_vpnState.update {
|
||||||
|
it.copy(tunnelConfig = tunnelConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateBackendStatistics(statistics: TunnelStatistics) {
|
||||||
|
_vpnState.update {
|
||||||
|
it.copy(statistics = statistics)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resetBackendStatistics() {
|
||||||
|
_vpnState.update {
|
||||||
|
it.copy(statistics = null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getState(): TunnelState {
|
||||||
|
return when (val backend = backend()) {
|
||||||
|
is Backend -> backend.getState(this).let { TunnelState.from(it) }
|
||||||
|
is org.amnezia.awg.backend.Backend -> backend.getState(this).let { TunnelState.from(it) }
|
||||||
|
else -> TunnelState.DOWN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun cancelActiveTunnelJobs() {
|
||||||
|
statsJob?.cancel()
|
||||||
|
tunnelChangesJob?.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun startActiveTunnelJobs() {
|
||||||
|
statsJob = startTunnelStatisticsJob()
|
||||||
|
tunnelChangesJob = startTunnelConfigChangesJob()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getName(): String {
|
||||||
|
return _vpnState.value.tunnelConfig?.name ?: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startTunnelStatisticsJob() = applicationScope.launch(ioDispatcher) {
|
||||||
|
val backend = backend()
|
||||||
|
delay(STATS_START_DELAY)
|
||||||
|
while (true) {
|
||||||
|
when (backend) {
|
||||||
|
is Backend -> updateBackendStatistics(
|
||||||
|
WireGuardStatistics(backend.getStatistics(this@WireGuardTunnel)),
|
||||||
|
)
|
||||||
|
is org.amnezia.awg.backend.Backend -> updateBackendStatistics(
|
||||||
|
AmneziaStatistics(
|
||||||
|
backend.getStatistics(this@WireGuardTunnel),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
delay(VPN_STATISTIC_CHECK_INTERVAL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startTunnelConfigChangesJob() = applicationScope.launch(ioDispatcher) {
|
||||||
|
tunnelConfigRepository.getTunnelConfigsFlow().collect {
|
||||||
|
with(_vpnState.value) {
|
||||||
|
if (status.isDown() || tunnelConfig == null) return@collect
|
||||||
|
val vpnConfigFromStorage = it.first { it.id == tunnelConfig.id }
|
||||||
|
val isRestartNeeded = vpnConfigFromStorage.wgQuick != tunnelConfig.wgQuick ||
|
||||||
|
vpnConfigFromStorage.amQuick != tunnelConfig.amQuick
|
||||||
|
updateTunnelConfig(vpnConfigFromStorage)
|
||||||
|
if (isRestartNeeded) {
|
||||||
|
Timber.d("Bouncing tunnel on config change")
|
||||||
|
bounceTunnel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStateChange(newState: Tunnel.State) {
|
||||||
|
_vpnState.update {
|
||||||
|
it.copy(status = TunnelState.from(newState))
|
||||||
|
}
|
||||||
|
serviceManager.updateTunnelTile()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStateChange(state: State) {
|
||||||
|
_vpnState.update {
|
||||||
|
it.copy(status = TunnelState.from(state))
|
||||||
|
}
|
||||||
|
serviceManager.updateTunnelTile()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val STATS_START_DELAY = 1_000L
|
||||||
|
const val VPN_STATISTIC_CHECK_INTERVAL = 1_000L
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-23
@@ -4,31 +4,31 @@ import org.amnezia.awg.backend.Statistics
|
|||||||
import org.amnezia.awg.crypto.Key
|
import org.amnezia.awg.crypto.Key
|
||||||
|
|
||||||
class AmneziaStatistics(private val statistics: Statistics) : TunnelStatistics() {
|
class AmneziaStatistics(private val statistics: Statistics) : TunnelStatistics() {
|
||||||
override fun peerStats(peer: Key): PeerStats? {
|
override fun peerStats(peer: Key): PeerStats? {
|
||||||
val key = Key.fromBase64(peer.toBase64())
|
val key = Key.fromBase64(peer.toBase64())
|
||||||
val stats = statistics.peer(key)
|
val stats = statistics.peer(key)
|
||||||
return stats?.let {
|
return stats?.let {
|
||||||
PeerStats(
|
PeerStats(
|
||||||
rxBytes = stats.rxBytes,
|
rxBytes = stats.rxBytes,
|
||||||
txBytes = stats.txBytes,
|
txBytes = stats.txBytes,
|
||||||
latestHandshakeEpochMillis = stats.latestHandshakeEpochMillis,
|
latestHandshakeEpochMillis = stats.latestHandshakeEpochMillis,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun isTunnelStale(): Boolean {
|
override fun isTunnelStale(): Boolean {
|
||||||
return statistics.isStale
|
return statistics.isStale
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getPeers(): Array<Key> {
|
override fun getPeers(): Array<Key> {
|
||||||
return statistics.peers()
|
return statistics.peers()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun rx(): Long {
|
override fun rx(): Long {
|
||||||
return statistics.totalRx()
|
return statistics.totalRx()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun tx(): Long {
|
override fun tx(): Long {
|
||||||
return statistics.totalTx()
|
return statistics.totalTx()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-7
@@ -3,16 +3,16 @@ package com.zaneschepke.wireguardautotunnel.service.tunnel.statistics
|
|||||||
import org.amnezia.awg.crypto.Key
|
import org.amnezia.awg.crypto.Key
|
||||||
|
|
||||||
abstract class TunnelStatistics {
|
abstract class TunnelStatistics {
|
||||||
@JvmRecord
|
@JvmRecord
|
||||||
data class PeerStats(val rxBytes: Long, val txBytes: Long, val latestHandshakeEpochMillis: Long)
|
data class PeerStats(val rxBytes: Long, val txBytes: Long, val latestHandshakeEpochMillis: Long)
|
||||||
|
|
||||||
abstract fun peerStats(peer: Key): PeerStats?
|
abstract fun peerStats(peer: Key): PeerStats?
|
||||||
|
|
||||||
abstract fun isTunnelStale(): Boolean
|
abstract fun isTunnelStale(): Boolean
|
||||||
|
|
||||||
abstract fun getPeers(): Array<Key>
|
abstract fun getPeers(): Array<Key>
|
||||||
|
|
||||||
abstract fun rx(): Long
|
abstract fun rx(): Long
|
||||||
|
|
||||||
abstract fun tx(): Long
|
abstract fun tx(): Long
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-25
@@ -4,33 +4,33 @@ import com.wireguard.android.backend.Statistics
|
|||||||
import org.amnezia.awg.crypto.Key
|
import org.amnezia.awg.crypto.Key
|
||||||
|
|
||||||
class WireGuardStatistics(private val statistics: Statistics) : TunnelStatistics() {
|
class WireGuardStatistics(private val statistics: Statistics) : TunnelStatistics() {
|
||||||
override fun peerStats(peer: Key): PeerStats? {
|
override fun peerStats(peer: Key): PeerStats? {
|
||||||
val key = com.wireguard.crypto.Key.fromBase64(peer.toBase64())
|
val key = com.wireguard.crypto.Key.fromBase64(peer.toBase64())
|
||||||
val peerStats = statistics.peer(key)
|
val peerStats = statistics.peer(key)
|
||||||
return peerStats?.let {
|
return peerStats?.let {
|
||||||
PeerStats(
|
PeerStats(
|
||||||
txBytes = peerStats.txBytes,
|
txBytes = peerStats.txBytes,
|
||||||
rxBytes = peerStats.rxBytes,
|
rxBytes = peerStats.rxBytes,
|
||||||
latestHandshakeEpochMillis = peerStats.latestHandshakeEpochMillis,
|
latestHandshakeEpochMillis = peerStats.latestHandshakeEpochMillis,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun isTunnelStale(): Boolean {
|
override fun isTunnelStale(): Boolean {
|
||||||
return statistics.isStale
|
return statistics.isStale
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getPeers(): Array<Key> {
|
override fun getPeers(): Array<Key> {
|
||||||
return statistics.peers().map {
|
return statistics.peers().map {
|
||||||
Key.fromBase64(it.toBase64())
|
Key.fromBase64(it.toBase64())
|
||||||
}.toTypedArray()
|
}.toTypedArray()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun rx(): Long {
|
override fun rx(): Long {
|
||||||
return statistics.totalRx()
|
return statistics.totalRx()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun tx(): Long {
|
override fun tx(): Long {
|
||||||
return statistics.totalTx()
|
return statistics.totalTx()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
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
|
val autoTunnelActive: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,123 +1,354 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui
|
package com.zaneschepke.wireguardautotunnel.ui
|
||||||
|
|
||||||
import android.content.ActivityNotFoundException
|
|
||||||
import android.content.Context
|
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.wireguard.android.backend.WgQuickBackend
|
||||||
|
import com.wireguard.android.util.RootShell
|
||||||
|
import com.wireguard.config.Config
|
||||||
|
import com.zaneschepke.logcatter.LogReader
|
||||||
import com.zaneschepke.wireguardautotunnel.R
|
import com.zaneschepke.wireguardautotunnel.R
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||||
|
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.AppShell
|
||||||
|
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.BackendState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.tunneloptions.config.model.InterfaceProxy
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.tunneloptions.config.model.PeerProxy
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.tunneloptions.splittunnel.SplitTunnelApp
|
||||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.getAllInternetCapablePackages
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.collect
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.onCompletion
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
|
import kotlinx.coroutines.flow.takeWhile
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.plus
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
|
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,
|
||||||
|
@AppShell private val rootShell: Provider<RootShell>,
|
||||||
|
private val serviceManager: ServiceManager,
|
||||||
|
private val logReader: LogReader,
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance)
|
private val _popBackStack = MutableSharedFlow<Boolean>()
|
||||||
|
val popBackStack = _popBackStack.asSharedFlow()
|
||||||
|
|
||||||
private val _appUiState = MutableStateFlow(
|
private val _isAppReady = MutableStateFlow(false)
|
||||||
AppUiState(
|
val isAppReady = _isAppReady.asStateFlow()
|
||||||
vpnPermissionAccepted = vpnIntent == null,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
val appUiState = _appUiState.asStateFlow()
|
|
||||||
|
|
||||||
|
private val _configurationChange = MutableStateFlow(false)
|
||||||
|
val configurationChange = _configurationChange.asStateFlow()
|
||||||
|
|
||||||
fun isRequiredPermissionGranted(): Boolean {
|
private val _splitTunnelApps = MutableStateFlow<List<SplitTunnelApp>>(emptyList())
|
||||||
val allAccepted =
|
val splitTunnelApps = _splitTunnelApps.asStateFlow()
|
||||||
(_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted)
|
|
||||||
if (!allAccepted) requestPermissions()
|
|
||||||
return allAccepted
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun requestPermissions() {
|
val uiState =
|
||||||
_appUiState.update {
|
combine(
|
||||||
it.copy(
|
appDataRepository.settings.getSettingsFlow(),
|
||||||
requestPermissions = true,
|
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
||||||
)
|
tunnelService.get().vpnState,
|
||||||
}
|
appDataRepository.appState.generalStateFlow,
|
||||||
}
|
serviceManager.autoTunnelActive,
|
||||||
|
) { settings, tunnels, tunnelState, generalState, autoTunnel ->
|
||||||
|
AppUiState(
|
||||||
|
settings,
|
||||||
|
tunnels,
|
||||||
|
tunnelState,
|
||||||
|
generalState,
|
||||||
|
autoTunnel,
|
||||||
|
)
|
||||||
|
}.stateIn(
|
||||||
|
viewModelScope + ioDispatcher,
|
||||||
|
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||||
|
AppUiState(),
|
||||||
|
)
|
||||||
|
|
||||||
fun permissionsRequested() {
|
init {
|
||||||
_appUiState.update {
|
viewModelScope.launch {
|
||||||
it.copy(
|
initPin()
|
||||||
requestPermissions = false,
|
initServices()
|
||||||
)
|
launch {
|
||||||
}
|
initTunnel()
|
||||||
}
|
}
|
||||||
|
appReadyCheck()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun openWebPage(url: String, context: Context) {
|
private suspend fun appReadyCheck() {
|
||||||
try {
|
val tunnelCount = appDataRepository.tunnels.count()
|
||||||
val webpage: Uri = Uri.parse(url)
|
uiState.takeWhile { it.tunnels.size != tunnelCount }.onCompletion {
|
||||||
val intent = Intent(Intent.ACTION_VIEW, webpage).apply {
|
_isAppReady.emit(true)
|
||||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
}.collect()
|
||||||
}
|
}
|
||||||
context.startActivity(intent)
|
|
||||||
} catch (e: ActivityNotFoundException) {
|
|
||||||
Timber.e(e)
|
|
||||||
showSnackbarMessage(context.getString(R.string.no_browser_detected))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onVpnPermissionAccepted() {
|
private suspend fun initTunnel() {
|
||||||
_appUiState.update {
|
if (tunnelService.get().getState() == TunnelState.UP) tunnelService.get().startActiveTunnelJobs()
|
||||||
it.copy(
|
val activeTunnels = appDataRepository.tunnels.getActive()
|
||||||
vpnPermissionAccepted = true,
|
if (activeTunnels.isNotEmpty() &&
|
||||||
)
|
tunnelService.get().getState() == TunnelState.DOWN
|
||||||
}
|
) {
|
||||||
}
|
tunnelService.get().startTunnel(activeTunnels.first())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun launchEmail(context: Context) {
|
private suspend fun initPin() {
|
||||||
try {
|
val isPinEnabled = appDataRepository.appState.isPinLockEnabled()
|
||||||
val intent =
|
if (isPinEnabled) PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||||
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) {
|
private suspend fun initServices() {
|
||||||
_appUiState.update {
|
withContext(ioDispatcher) {
|
||||||
it.copy(
|
val settings = appDataRepository.settings.getSettings()
|
||||||
snackbarMessage = message,
|
handleVpnKillSwitchChange(settings.isVpnKillSwitchEnabled)
|
||||||
snackbarMessageConsumed = false,
|
if (settings.isAutoTunnelEnabled) serviceManager.startAutoTunnel(false)
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fun snackbarMessageConsumed() {
|
fun onPinLockDisabled() = viewModelScope.launch(ioDispatcher) {
|
||||||
_appUiState.update {
|
PinManager.clearPin()
|
||||||
it.copy(
|
appDataRepository.appState.setPinLockEnabled(false)
|
||||||
snackbarMessage = "",
|
}
|
||||||
snackbarMessageConsumed = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setNotificationPermissionAccepted(accepted: Boolean) {
|
fun onPinLockEnabled() = viewModelScope.launch {
|
||||||
_appUiState.update {
|
appDataRepository.appState.setPinLockEnabled(true)
|
||||||
it.copy(
|
}
|
||||||
notificationPermissionAccepted = accepted,
|
|
||||||
)
|
fun setLocationDisclosureShown() = viewModelScope.launch {
|
||||||
}
|
appDataRepository.appState.setLocationDisclosureShown(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun onToggleLocalLogging() = viewModelScope.launch(ioDispatcher) {
|
||||||
|
with(uiState.value.generalState) {
|
||||||
|
val toggledOn = !isLocalLogsEnabled
|
||||||
|
appDataRepository.appState.setLocalLogsEnabled(toggledOn)
|
||||||
|
if (!toggledOn) onLoggerStop()
|
||||||
|
_configurationChange.update {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun onLoggerStop() {
|
||||||
|
logReader.deleteAndClearLogs()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onToggleAlwaysOnVPN() = viewModelScope.launch {
|
||||||
|
with(uiState.value.settings) {
|
||||||
|
appDataRepository.settings.save(
|
||||||
|
copy(
|
||||||
|
isAlwaysOnVpnEnabled = !isAlwaysOnVpnEnabled,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onLocaleChange(localeTag: String) = viewModelScope.launch {
|
||||||
|
appDataRepository.appState.setLocale(localeTag)
|
||||||
|
LocaleUtil.changeLocale(localeTag)
|
||||||
|
_configurationChange.update {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onToggleRestartAtBoot() = viewModelScope.launch {
|
||||||
|
with(uiState.value.settings) {
|
||||||
|
appDataRepository.settings.save(
|
||||||
|
copy(
|
||||||
|
isRestoreOnBootEnabled = !isRestoreOnBootEnabled,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onToggleVpnKillSwitch(enabled: Boolean) = viewModelScope.launch {
|
||||||
|
with(uiState.value.settings) {
|
||||||
|
appDataRepository.settings.save(
|
||||||
|
copy(
|
||||||
|
isVpnKillSwitchEnabled = enabled,
|
||||||
|
isLanOnKillSwitchEnabled = if (enabled) isLanOnKillSwitchEnabled else false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
handleVpnKillSwitchChange(enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun handleVpnKillSwitchChange(enabled: Boolean) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
if (enabled) {
|
||||||
|
Timber.d("Starting kill switch")
|
||||||
|
val allowedIps = if (appDataRepository.settings.getSettings().isLanOnKillSwitchEnabled) {
|
||||||
|
TunnelConfig.IPV4_PUBLIC_NETWORKS
|
||||||
|
} else {
|
||||||
|
emptySet()
|
||||||
|
}
|
||||||
|
tunnelService.get().setBackendState(BackendState.KILL_SWITCH_ACTIVE, allowedIps)
|
||||||
|
} else {
|
||||||
|
Timber.d("Sending shutdown of kill switch")
|
||||||
|
tunnelService.get().setBackendState(BackendState.SERVICE_ACTIVE, emptySet())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onToggleLanOnKillSwitch(enabled: Boolean) = viewModelScope.launch(ioDispatcher) {
|
||||||
|
appDataRepository.settings.save(
|
||||||
|
uiState.value.settings.copy(
|
||||||
|
isLanOnKillSwitchEnabled = enabled,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val allowedIps = if (enabled) TunnelConfig.IPV4_PUBLIC_NETWORKS else emptySet()
|
||||||
|
Timber.d("Setting allowedIps $allowedIps")
|
||||||
|
tunnelService.get().setBackendState(BackendState.KILL_SWITCH_ACTIVE, allowedIps)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onToggleShortcutsEnabled() = viewModelScope.launch {
|
||||||
|
with(uiState.value.settings) {
|
||||||
|
appDataRepository.settings.save(
|
||||||
|
copy(
|
||||||
|
isShortcutsEnabled = !isShortcutsEnabled,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saveKernelMode(enabled: Boolean) = viewModelScope.launch {
|
||||||
|
with(uiState.value.settings) {
|
||||||
|
appDataRepository.settings.save(
|
||||||
|
this.copy(
|
||||||
|
isKernelEnabled = enabled,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onToggleKernelMode() = viewModelScope.launch {
|
||||||
|
with(uiState.value.settings) {
|
||||||
|
if (!isKernelEnabled) {
|
||||||
|
requestRoot().onSuccess {
|
||||||
|
if (!isKernelSupported()) return@onSuccess SnackbarController.showMessage(StringValue.StringResource(R.string.kernel_not_supported))
|
||||||
|
tunnelService.get().setBackendState(BackendState.INACTIVE, emptyList())
|
||||||
|
appDataRepository.settings.save(
|
||||||
|
copy(
|
||||||
|
isKernelEnabled = true,
|
||||||
|
isAmneziaEnabled = false,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
saveKernelMode(enabled = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun isKernelSupported(): Boolean {
|
||||||
|
return withContext(ioDispatcher) {
|
||||||
|
WgQuickBackend.hasKernelSupport()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun getEmitSplitTunnelApps(context: Context) {
|
||||||
|
withContext(ioDispatcher) {
|
||||||
|
val apps = context.getAllInternetCapablePackages().filter { it.applicationInfo != null }.map { pack ->
|
||||||
|
SplitTunnelApp(
|
||||||
|
context.packageManager.getApplicationIcon(pack.applicationInfo!!),
|
||||||
|
context.packageManager.getApplicationLabel(pack.applicationInfo!!).toString(),
|
||||||
|
pack.packageName,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
_splitTunnelApps.emit(apps)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun requestRoot(): Result<Unit> {
|
||||||
|
return withContext(ioDispatcher) {
|
||||||
|
kotlin.runCatching {
|
||||||
|
rootShell.get().start()
|
||||||
|
SnackbarController.showMessage(StringValue.StringResource(R.string.root_accepted))
|
||||||
|
}.onFailure {
|
||||||
|
SnackbarController.showMessage(StringValue.StringResource(R.string.error_root_denied))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveConfigChanges(config: TunnelConfig, peers: List<PeerProxy>? = null, `interface`: InterfaceProxy? = null) = viewModelScope.launch(
|
||||||
|
ioDispatcher,
|
||||||
|
) {
|
||||||
|
runCatching {
|
||||||
|
val amConfig = config.toAmConfig()
|
||||||
|
val wgConfig = config.toWgConfig()
|
||||||
|
rebuildConfigsAndSave(config, amConfig, wgConfig, peers, `interface`)
|
||||||
|
_popBackStack.emit(true)
|
||||||
|
SnackbarController.showMessage(StringValue.StringResource(R.string.config_changes_saved))
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
SnackbarController.showMessage(
|
||||||
|
it.message?.let { message ->
|
||||||
|
(StringValue.DynamicString(message))
|
||||||
|
} ?: StringValue.StringResource(R.string.unknown_error),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cleanUpUninstalledApps(tunnelConfig: TunnelConfig, packages: List<String>) = viewModelScope.launch(ioDispatcher) {
|
||||||
|
runCatching {
|
||||||
|
val amConfig = tunnelConfig.toAmConfig()
|
||||||
|
val wgConfig = tunnelConfig.toWgConfig()
|
||||||
|
val proxy = InterfaceProxy.from(amConfig.`interface`)
|
||||||
|
if (proxy.includedApplications.isEmpty() && proxy.excludedApplications.isEmpty()) return@launch
|
||||||
|
if (proxy.includedApplications.retainAll(packages.toSet()) || proxy.excludedApplications.retainAll(packages.toSet())) {
|
||||||
|
Timber.i("Removing split tunnel package for app that no longer exists on the device")
|
||||||
|
rebuildConfigsAndSave(tunnelConfig, amConfig, wgConfig, `interface` = proxy)
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
Timber.e(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun rebuildConfigsAndSave(
|
||||||
|
config: TunnelConfig,
|
||||||
|
amConfig: org.amnezia.awg.config.Config,
|
||||||
|
wgConfig: Config,
|
||||||
|
peers: List<PeerProxy>? = null,
|
||||||
|
`interface`: InterfaceProxy? = null,
|
||||||
|
) {
|
||||||
|
appDataRepository.tunnels.save(
|
||||||
|
config.copy(
|
||||||
|
wgQuick = Config.Builder().apply {
|
||||||
|
addPeers(peers?.map { it.toWgPeer() } ?: wgConfig.peers)
|
||||||
|
setInterface(`interface`?.toWgInterface() ?: wgConfig.`interface`)
|
||||||
|
}.build().toWgQuickString(true),
|
||||||
|
amQuick = org.amnezia.awg.config.Config.Builder().apply {
|
||||||
|
addPeers(peers?.map { it.toAmPeer() } ?: amConfig.peers)
|
||||||
|
setInterface(`interface`?.toAmInterface() ?: amConfig.`interface`)
|
||||||
|
}.build().toAwgQuickString(true),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,289 +1,264 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui
|
package com.zaneschepke.wireguardautotunnel.ui
|
||||||
|
|
||||||
import android.Manifest
|
import android.content.Intent
|
||||||
|
import android.graphics.Color.TRANSPARENT
|
||||||
import android.os.Build
|
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.foundation.focusable
|
import androidx.compose.animation.core.tween
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||||
|
import androidx.compose.foundation.layout.WindowInsets
|
||||||
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.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.focus.FocusRequester
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.focus.focusProperties
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.toArgb
|
|
||||||
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.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.repository.AppStateRepository
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
|
import com.zaneschepke.wireguardautotunnel.service.shortcut.ShortcutManager
|
||||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar
|
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar
|
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen
|
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.CustomSnackBar
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarControllerProvider
|
||||||
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.pinlock.PinLockScreen
|
import com.zaneschepke.wireguardautotunnel.ui.screens.pinlock.PinLockScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.scanner.ScannerScreen
|
||||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.SettingsScreen
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.SettingsScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.AppearanceScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.display.DisplayScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.language.LanguageScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.AutoTunnelScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.disclosure.LocationDisclosureScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.killswitch.KillSwitchScreen
|
||||||
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.screens.tunneloptions.OptionsScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.tunneloptions.config.ConfigScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.tunneloptions.splittunnel.SplitTunnelScreen
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.screens.tunneloptions.tunnelautotunnel.TunnelAutoTunnelScreen
|
||||||
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 dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import kotlin.system.exitProcess
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class MainActivity : AppCompatActivity() {
|
class MainActivity : AppCompatActivity() {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var appStateRepository: AppStateRepository
|
lateinit var appStateRepository: AppStateRepository
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var settingsRepository: SettingsRepository
|
lateinit var tunnelService: TunnelService
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var serviceManager: ServiceManager
|
lateinit var shortcutManager: ShortcutManager
|
||||||
|
|
||||||
@OptIn(
|
@OptIn(ExperimentalLayoutApi::class)
|
||||||
ExperimentalPermissionsApi::class,
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
)
|
enableEdgeToEdge(
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
statusBarStyle = SystemBarStyle.auto(TRANSPARENT, TRANSPARENT),
|
||||||
super.onCreate(savedInstanceState)
|
navigationBarStyle = SystemBarStyle.auto(TRANSPARENT, TRANSPARENT),
|
||||||
|
)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
window.isNavigationBarContrastEnforced = false
|
||||||
|
}
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
val isPinLockEnabled = intent.extras?.getBoolean(SplashActivity.IS_PIN_LOCK_ENABLED_KEY)
|
val viewModel by viewModels<AppViewModel>()
|
||||||
|
|
||||||
enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb()))
|
installSplashScreen().apply {
|
||||||
|
setKeepOnScreenCondition {
|
||||||
|
!viewModel.isAppReady.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
lifecycleScope.launch {
|
setContent {
|
||||||
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
|
val appUiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||||
val settings = settingsRepository.getSettings()
|
val configurationChange by viewModel.configurationChange.collectAsStateWithLifecycle()
|
||||||
if (settings.isAutoTunnelEnabled) {
|
val navController = rememberNavController()
|
||||||
serviceManager.startWatcherService(application.applicationContext)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setContent {
|
LaunchedEffect(configurationChange) {
|
||||||
val appViewModel = hiltViewModel<AppViewModel>()
|
if (configurationChange) {
|
||||||
val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle()
|
Intent(this@MainActivity, MainActivity::class.java).also {
|
||||||
val navController = rememberNavController()
|
startActivity(it)
|
||||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
exitProcess(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val notificationPermissionState =
|
LaunchedEffect(Unit) {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
|
viewModel.getEmitSplitTunnelApps(this@MainActivity)
|
||||||
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS) else null
|
}
|
||||||
|
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
LaunchedEffect(appUiState.autoTunnelActive) {
|
||||||
|
requestAutoTunnelTileServiceUpdate()
|
||||||
|
}
|
||||||
|
|
||||||
val vpnActivityResultState =
|
with(appUiState.settings) {
|
||||||
rememberLauncherForActivityResult(
|
LaunchedEffect(isAutoTunnelEnabled) {
|
||||||
ActivityResultContracts.StartActivityForResult(),
|
this@MainActivity.requestAutoTunnelTileServiceUpdate()
|
||||||
onResult = {
|
}
|
||||||
val accepted = (it.resultCode == RESULT_OK)
|
LaunchedEffect(isShortcutsEnabled) {
|
||||||
if (accepted) {
|
if (!isShortcutsEnabled) return@LaunchedEffect shortcutManager.removeShortcuts()
|
||||||
appViewModel.onVpnPermissionAccepted()
|
shortcutManager.addShortcuts()
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
)
|
|
||||||
|
|
||||||
fun showSnackBarMessage(message: StringValue) {
|
CompositionLocalProvider(LocalNavController provides navController) {
|
||||||
lifecycleScope.launch(Dispatchers.Main) {
|
SnackbarControllerProvider { host ->
|
||||||
val result =
|
WireguardAutoTunnelTheme(theme = appUiState.generalState.theme) {
|
||||||
snackbarHostState.showSnackbar(
|
Scaffold(
|
||||||
message = message.asString(this@MainActivity),
|
contentWindowInsets = WindowInsets(0),
|
||||||
duration = SnackbarDuration.Short,
|
snackbarHost = {
|
||||||
)
|
SnackbarHost(host) { snackbarData: SnackbarData ->
|
||||||
when (result) {
|
CustomSnackBar(
|
||||||
SnackbarResult.ActionPerformed,
|
snackbarData.visuals.message,
|
||||||
SnackbarResult.Dismissed -> {
|
isRtl = false,
|
||||||
snackbarHostState.currentSnackbarData?.dismiss()
|
containerColor =
|
||||||
}
|
MaterialTheme.colorScheme.surfaceColorAtElevation(
|
||||||
}
|
2.dp,
|
||||||
}
|
),
|
||||||
}
|
)
|
||||||
|
}
|
||||||
LaunchedEffect(appUiState.requestPermissions) {
|
},
|
||||||
if (appUiState.requestPermissions) {
|
bottomBar = {
|
||||||
appViewModel.permissionsRequested()
|
BottomNavBar(
|
||||||
if (notificationPermissionState != null && !notificationPermissionState.status.isGranted
|
navController,
|
||||||
) {
|
listOf(
|
||||||
showSnackBarMessage(StringValue.StringResource(R.string.notification_permission_required))
|
BottomNavItem(
|
||||||
return@LaunchedEffect notificationPermissionState.launchPermissionRequest()
|
name = stringResource(R.string.tunnels),
|
||||||
}
|
route = Route.Main,
|
||||||
if (!appUiState.vpnPermissionAccepted) {
|
icon = Icons.Rounded.Home,
|
||||||
return@LaunchedEffect appViewModel.vpnIntent?.let {
|
),
|
||||||
vpnActivityResultState.launch(
|
BottomNavItem(
|
||||||
it,
|
name = stringResource(R.string.settings),
|
||||||
)
|
route = Route.Settings,
|
||||||
}!!
|
icon = Icons.Rounded.Settings,
|
||||||
}
|
),
|
||||||
}
|
BottomNavItem(
|
||||||
}
|
name = stringResource(R.string.support),
|
||||||
|
route = Route.Support,
|
||||||
WireguardAutoTunnelTheme {
|
icon = Icons.Rounded.QuestionMark,
|
||||||
LaunchedEffect(Unit) {
|
),
|
||||||
appViewModel.setNotificationPermissionAccepted(
|
),
|
||||||
notificationPermissionState?.status?.isGranted ?: true,
|
)
|
||||||
)
|
},
|
||||||
}
|
) { padding ->
|
||||||
|
Box(modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||||
LaunchedEffect(appUiState.snackbarMessageConsumed) {
|
NavHost(
|
||||||
if (!appUiState.snackbarMessageConsumed) {
|
navController,
|
||||||
showSnackBarMessage(StringValue.DynamicString(appUiState.snackbarMessage))
|
enterTransition = { fadeIn(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||||
appViewModel.snackbarMessageConsumed()
|
exitTransition = { fadeOut(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||||
}
|
startDestination = (if (appUiState.generalState.isPinLockEnabled) Route.Lock else Route.Main),
|
||||||
}
|
) {
|
||||||
|
composable<Route.Main> {
|
||||||
val focusRequester = remember { FocusRequester() }
|
MainScreen(
|
||||||
|
uiState = appUiState,
|
||||||
Scaffold(
|
)
|
||||||
snackbarHost = {
|
}
|
||||||
SnackbarHost(snackbarHostState) { snackbarData: SnackbarData ->
|
composable<Route.Settings> {
|
||||||
CustomSnackBar(
|
SettingsScreen(
|
||||||
snackbarData.visuals.message,
|
appViewModel = viewModel,
|
||||||
isRtl = false,
|
uiState = appUiState,
|
||||||
containerColor =
|
)
|
||||||
MaterialTheme.colorScheme.surfaceColorAtElevation(
|
}
|
||||||
2.dp,
|
composable<Route.LocationDisclosure> {
|
||||||
),
|
LocationDisclosureScreen(viewModel, appUiState)
|
||||||
)
|
}
|
||||||
}
|
composable<Route.AutoTunnel> {
|
||||||
},
|
AutoTunnelScreen(
|
||||||
//TODO refactor
|
appUiState,
|
||||||
modifier = Modifier
|
)
|
||||||
.focusable()
|
}
|
||||||
.focusProperties {
|
composable<Route.Appearance> {
|
||||||
when (navBackStackEntry?.destination?.route) {
|
AppearanceScreen()
|
||||||
Screen.Lock.route -> Unit
|
}
|
||||||
else -> up = focusRequester
|
composable<Route.Language> {
|
||||||
}
|
LanguageScreen(appUiState, viewModel)
|
||||||
},
|
}
|
||||||
bottomBar = {
|
composable<Route.Display> {
|
||||||
BottomNavBar(
|
DisplayScreen(appUiState)
|
||||||
navController,
|
}
|
||||||
listOf(
|
composable<Route.Support> {
|
||||||
Screen.Main.navItem,
|
SupportScreen(appUiState, viewModel)
|
||||||
Screen.Settings.navItem,
|
}
|
||||||
Screen.Support.navItem,
|
composable<Route.Logs> {
|
||||||
),
|
LogsScreen()
|
||||||
)
|
}
|
||||||
},
|
composable<Route.Config> {
|
||||||
) { padding ->
|
val args = it.toRoute<Route.Config>()
|
||||||
NavHost(
|
ConfigScreen(
|
||||||
navController,
|
appUiState,
|
||||||
startDestination = (if (isPinLockEnabled == true) Screen.Lock.route else Screen.Main.route),
|
tunnelId = args.id,
|
||||||
modifier = Modifier
|
appViewModel = viewModel,
|
||||||
.padding(padding)
|
)
|
||||||
.fillMaxSize(),
|
}
|
||||||
) {
|
composable<Route.TunnelOptions> {
|
||||||
composable(
|
val args = it.toRoute<Route.TunnelOptions>()
|
||||||
Screen.Main.route,
|
OptionsScreen(
|
||||||
) {
|
tunnelId = args.id,
|
||||||
MainScreen(
|
appUiState = appUiState,
|
||||||
focusRequester = focusRequester,
|
)
|
||||||
appViewModel = appViewModel,
|
}
|
||||||
navController = navController,
|
composable<Route.Lock> {
|
||||||
)
|
PinLockScreen(
|
||||||
}
|
appViewModel = viewModel,
|
||||||
composable(
|
)
|
||||||
Screen.Settings.route,
|
}
|
||||||
) {
|
composable<Route.Scanner> {
|
||||||
SettingsScreen(
|
ScannerScreen()
|
||||||
appViewModel = appViewModel,
|
}
|
||||||
navController = navController,
|
composable<Route.KillSwitch> {
|
||||||
focusRequester = focusRequester,
|
KillSwitchScreen(appUiState, viewModel)
|
||||||
)
|
}
|
||||||
}
|
composable<Route.SplitTunnel> {
|
||||||
composable(
|
val args = it.toRoute<Route.SplitTunnel>()
|
||||||
Screen.Support.route,
|
SplitTunnelScreen(appUiState, args.id, viewModel)
|
||||||
) {
|
}
|
||||||
SupportScreen(
|
composable<Route.TunnelAutoTunnel> {
|
||||||
focusRequester = focusRequester,
|
val args = it.toRoute<Route.SplitTunnel>()
|
||||||
appViewModel = appViewModel,
|
TunnelAutoTunnelScreen(appUiState, args.id)
|
||||||
navController = navController,
|
}
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
composable(Screen.Support.Logs.route) {
|
}
|
||||||
LogsScreen()
|
}
|
||||||
}
|
}
|
||||||
composable(
|
}
|
||||||
"${Screen.Config.route}/{id}?configType={configType}",
|
}
|
||||||
arguments =
|
}
|
||||||
listOf(
|
override fun onDestroy() {
|
||||||
navArgument("id") {
|
super.onDestroy()
|
||||||
type = NavType.StringType
|
// save battery by not polling stats while app is closed
|
||||||
defaultValue = "0"
|
tunnelService.cancelActiveTunnelJobs()
|
||||||
},
|
}
|
||||||
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(
|
|
||||||
navController = navController,
|
|
||||||
tunnelId = id,
|
|
||||||
appViewModel = appViewModel,
|
|
||||||
focusRequester = focusRequester,
|
|
||||||
configType = configType,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
composable("${Screen.Option.route}/{id}") {
|
|
||||||
val id = it.arguments?.getString("id")
|
|
||||||
if (!id.isNullOrBlank()) {
|
|
||||||
OptionsScreen(
|
|
||||||
navController = navController,
|
|
||||||
tunnelId = id,
|
|
||||||
appViewModel = appViewModel,
|
|
||||||
focusRequester = focusRequester,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
composable(Screen.Lock.route) {
|
|
||||||
PinLockScreen(
|
|
||||||
navController = navController,
|
|
||||||
appViewModel = appViewModel,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
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 AutoTunnel : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object LocationDisclosure : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Appearance : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Display : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object KillSwitch : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Language : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Main : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class TunnelOptions(
|
||||||
|
val id: Int,
|
||||||
|
) : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Lock : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data object Scanner : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Config(
|
||||||
|
val id: Int,
|
||||||
|
) : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class SplitTunnel(
|
||||||
|
val id: Int,
|
||||||
|
) : Route()
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class TunnelAutoTunnel(
|
||||||
|
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,68 +0,0 @@
|
|||||||
package com.zaneschepke.wireguardautotunnel.ui
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.activity.ComponentActivity
|
|
||||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
|
||||||
import androidx.lifecycle.Lifecycle
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import androidx.lifecycle.repeatOnLifecycle
|
|
||||||
import com.zaneschepke.logcatter.LocalLogCollector
|
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
|
||||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel.Companion.isRunningOnAndroidTv
|
|
||||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
|
||||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@SuppressLint("CustomSplashScreen")
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class SplashActivity : ComponentActivity() {
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var appStateRepository: AppStateRepository
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
lateinit var localLogCollector: LocalLogCollector
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
@ApplicationScope
|
|
||||||
lateinit var applicationScope: CoroutineScope
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
|
||||||
val splashScreen = installSplashScreen()
|
|
||||||
splashScreen.setKeepOnScreenCondition { true }
|
|
||||||
}
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
|
|
||||||
applicationScope.launch {
|
|
||||||
if (!isRunningOnAndroidTv()) localLogCollector.start()
|
|
||||||
}
|
|
||||||
|
|
||||||
lifecycleScope.launch {
|
|
||||||
repeatOnLifecycle(Lifecycle.State.CREATED) {
|
|
||||||
val pinLockEnabled = appStateRepository.isPinLockEnabled()
|
|
||||||
if (pinLockEnabled) {
|
|
||||||
PinManager.initialize(WireGuardAutoTunnel.instance)
|
|
||||||
}
|
|
||||||
|
|
||||||
val intent = Intent(this@SplashActivity, MainActivity::class.java).apply {
|
|
||||||
putExtra(IS_PIN_LOCK_ENABLED_KEY, pinLockEnabled)
|
|
||||||
}
|
|
||||||
startActivity(intent)
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
const val IS_PIN_LOCK_ENABLED_KEY = "is_pin_lock_enabled"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
+22
-27
@@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Spacer
|
|||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.material3.ButtonDefaults
|
import androidx.compose.material3.ButtonDefaults
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
@@ -12,31 +13,25 @@ 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,
|
TextButton(
|
||||||
onIconClick: () -> Unit,
|
onClick = onClick,
|
||||||
text: String,
|
enabled = enabled,
|
||||||
icon: ImageVector,
|
) {
|
||||||
enabled: Boolean
|
Text(text, Modifier.weight(1f, false), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary)
|
||||||
) {
|
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
|
||||||
TextButton(
|
Icon(
|
||||||
onClick = onClick,
|
imageVector = icon,
|
||||||
enabled = enabled,
|
contentDescription = icon.name,
|
||||||
) {
|
modifier =
|
||||||
Text(text, Modifier.weight(1f, false))
|
Modifier
|
||||||
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
|
.size(ButtonDefaults.IconSize)
|
||||||
Icon(
|
.weight(1f, false)
|
||||||
imageVector = icon,
|
.clickable {
|
||||||
contentDescription = icon.name,
|
if (enabled) {
|
||||||
modifier =
|
onIconClick()
|
||||||
Modifier
|
}
|
||||||
.size(ButtonDefaults.IconSize)
|
},
|
||||||
.weight(1f, false)
|
)
|
||||||
.clickable {
|
}
|
||||||
if (enabled) {
|
|
||||||
onIconClick()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+71
@@ -0,0 +1,71 @@
|
|||||||
|
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.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 = {},
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.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,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
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,97 +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.focus.FocusRequester
|
|
||||||
import androidx.compose.ui.focus.focusRequester
|
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.compose.ui.unit.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?,
|
|
||||||
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, 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -26,57 +26,57 @@ import com.zaneschepke.wireguardautotunnel.R
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun SearchBar(onQuery: (queryString: String) -> Unit) {
|
fun SearchBar(onQuery: (queryString: String) -> Unit) {
|
||||||
// Immediately update and keep track of query from text field changes.
|
// Immediately update and keep track of query from text field changes.
|
||||||
var query: String by rememberSaveable { mutableStateOf("") }
|
var query: String by rememberSaveable { mutableStateOf("") }
|
||||||
var showClearIcon by rememberSaveable { mutableStateOf(false) }
|
var showClearIcon by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
if (query.isEmpty()) {
|
if (query.isEmpty()) {
|
||||||
showClearIcon = false
|
showClearIcon = false
|
||||||
} else if (query.isNotEmpty()) {
|
} else if (query.isNotEmpty()) {
|
||||||
showClearIcon = true
|
showClearIcon = true
|
||||||
}
|
}
|
||||||
|
|
||||||
TextField(
|
TextField(
|
||||||
value = query,
|
value = query,
|
||||||
onValueChange = { onQueryChanged ->
|
onValueChange = { onQueryChanged ->
|
||||||
// If user makes changes to text, immediately updated it.
|
// If user makes changes to text, immediately updated it.
|
||||||
query = onQueryChanged
|
query = onQueryChanged
|
||||||
onQuery(onQueryChanged)
|
onQuery(onQueryChanged)
|
||||||
},
|
},
|
||||||
leadingIcon = {
|
leadingIcon = {
|
||||||
val icon = Icons.Rounded.Search
|
val icon = Icons.Rounded.Search
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = icon,
|
imageVector = icon,
|
||||||
tint = MaterialTheme.colorScheme.onBackground,
|
tint = MaterialTheme.colorScheme.onBackground,
|
||||||
contentDescription = icon.name,
|
contentDescription = icon.name,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
trailingIcon = {
|
trailingIcon = {
|
||||||
if (showClearIcon) {
|
if (showClearIcon) {
|
||||||
IconButton(onClick = { query = "" }) {
|
IconButton(onClick = { query = "" }) {
|
||||||
val icon = Icons.Rounded.Clear
|
val icon = Icons.Rounded.Clear
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = icon,
|
imageVector = icon,
|
||||||
tint = MaterialTheme.colorScheme.onBackground,
|
tint = MaterialTheme.colorScheme.onBackground,
|
||||||
contentDescription = icon.name,
|
contentDescription = icon.name,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
colors =
|
colors =
|
||||||
TextFieldDefaults.colors(
|
TextFieldDefaults.colors(
|
||||||
focusedContainerColor = Color.Transparent,
|
focusedContainerColor = Color.Transparent,
|
||||||
unfocusedContainerColor = Color.Transparent,
|
unfocusedContainerColor = Color.Transparent,
|
||||||
disabledContainerColor = Color.Transparent,
|
disabledContainerColor = Color.Transparent,
|
||||||
),
|
),
|
||||||
placeholder = { Text(text = stringResource(R.string.hint_search_packages)) },
|
placeholder = { Text(text = stringResource(R.string.hint_search_packages)) },
|
||||||
textStyle = MaterialTheme.typography.bodySmall,
|
textStyle = MaterialTheme.typography.bodySmall,
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
|
||||||
modifier =
|
modifier =
|
||||||
Modifier
|
Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.background(color = MaterialTheme.colorScheme.background, shape = RectangleShape),
|
.background(color = MaterialTheme.colorScheme.background, shape = RectangleShape),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.outlined.CheckBox
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SelectedLabel() {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
horizontalArrangement = Arrangement.End,
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
val icon = Icons.Outlined.CheckBox
|
||||||
|
Icon(icon, icon.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
package com.zaneschepke.wireguardautotunnel.ui.common.button
|
||||||
|
|
||||||
|
import androidx.compose.foundation.BorderStroke
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.IntrinsicSize
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||||
|
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||||
|
|
||||||
|
@androidx.compose.runtime.Composable
|
||||||
|
fun IconSurfaceButton(title: String, onClick: () -> Unit, selected: Boolean, leadingIcon: ImageVector? = null, description: String? = null) {
|
||||||
|
val border: BorderStroke? =
|
||||||
|
if (selected) {
|
||||||
|
BorderStroke(
|
||||||
|
1.dp,
|
||||||
|
MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
Card(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(IntrinsicSize.Min),
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
border = border,
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier.clickable { onClick() }
|
||||||
|
.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.padding(horizontal = 8.dp.scaledWidth(), vertical = 10.dp.scaledHeight())
|
||||||
|
.padding(end = 16.dp.scaledWidth()).padding(start = 8.dp.scaledWidth())
|
||||||
|
.fillMaxSize(),
|
||||||
|
verticalArrangement = Arrangement.Center,
|
||||||
|
horizontalAlignment = Alignment.Start,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.Companion.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(16.dp.scaledWidth()),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(
|
||||||
|
16.dp.scaledWidth(),
|
||||||
|
),
|
||||||
|
verticalAlignment = Alignment.Companion.CenterVertically,
|
||||||
|
modifier = Modifier.padding(vertical = if (description == null) 10.dp.scaledHeight() else 0.dp),
|
||||||
|
) {
|
||||||
|
leadingIcon?.let {
|
||||||
|
Icon(
|
||||||
|
leadingIcon,
|
||||||
|
leadingIcon.name,
|
||||||
|
Modifier.size(iconSize),
|
||||||
|
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
)
|
||||||
|
description?.let {
|
||||||
|
Text(
|
||||||
|
description,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user