Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot] 5e7379f94b chore(deps): bump hiltAndroid from 2.55 to 2.56
Bumps `hiltAndroid` from 2.55 to 2.56.

Updates `com.google.dagger:hilt-android` from 2.55 to 2.56
- [Release notes](https://github.com/google/dagger/releases)
- [Changelog](https://github.com/google/dagger/blob/master/CHANGELOG.md)
- [Commits](https://github.com/google/dagger/compare/dagger-2.55...dagger-2.56)

Updates `com.google.dagger:hilt-android-compiler` from 2.55 to 2.56
- [Release notes](https://github.com/google/dagger/releases)
- [Changelog](https://github.com/google/dagger/blob/master/CHANGELOG.md)
- [Commits](https://github.com/google/dagger/compare/dagger-2.55...dagger-2.56)

Updates `com.google.dagger.hilt.android` from 2.55 to 2.56
- [Release notes](https://github.com/google/dagger/releases)
- [Changelog](https://github.com/google/dagger/blob/master/CHANGELOG.md)
- [Commits](https://github.com/google/dagger/compare/dagger-2.55...dagger-2.56)

---
updated-dependencies:
- dependency-name: com.google.dagger:hilt-android
  dependency-type: direct:production
  update-type: version-update:semver-minor
- dependency-name: com.google.dagger:hilt-android-compiler
  dependency-type: direct:production
  update-type: version-update:semver-minor
- dependency-name: com.google.dagger.hilt.android
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-20 13:34:19 +00:00
817 changed files with 14198 additions and 15904 deletions
+97
View File
@@ -0,0 +1,97 @@
root = true
[*]
charset = utf-8
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_java_names_count_to_use_import_on_demand = 9999
ij_kotlin_align_in_columns_case_branch = false
ij_kotlin_align_multiline_binary_operation = false
ij_kotlin_align_multiline_extends_list = false
ij_kotlin_align_multiline_method_parentheses = false
ij_kotlin_align_multiline_parameters = true
ij_kotlin_align_multiline_parameters_in_calls = false
ij_kotlin_assignment_wrap = normal
ij_kotlin_blank_lines_after_class_header = 0
ij_kotlin_blank_lines_around_block_when_branches = 0
ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1
ij_kotlin_block_comment_at_first_column = true
ij_kotlin_call_parameters_new_line_after_left_paren = true
ij_kotlin_call_parameters_right_paren_on_new_line = false
ij_kotlin_catch_on_new_line = false
ij_kotlin_continuation_indent_for_chained_calls = true
ij_kotlin_continuation_indent_for_expression_bodies = true
ij_kotlin_continuation_indent_in_argument_lists = true
ij_kotlin_continuation_indent_in_elvis = false
ij_kotlin_continuation_indent_in_if_conditions = false
ij_kotlin_continuation_indent_in_parameter_lists = false
ij_kotlin_continuation_indent_in_supertype_lists = false
ij_kotlin_else_on_new_line = false
ij_kotlin_enum_constants_wrap = off
ij_kotlin_extends_list_wrap = normal
ij_kotlin_field_annotation_wrap = split_into_lines
ij_kotlin_finally_on_new_line = false
ij_kotlin_if_rparen_on_new_line = false
ij_kotlin_import_nested_classes = false
ij_kotlin_insert_whitespaces_in_simple_one_line_method = true
ij_kotlin_keep_blank_lines_before_right_brace = 2
ij_kotlin_keep_blank_lines_in_code = 2
ij_kotlin_keep_blank_lines_in_declarations = 2
ij_kotlin_keep_first_column_comment = true
ij_kotlin_keep_indents_on_empty_lines = false
ij_kotlin_keep_line_breaks = true
ij_kotlin_lbrace_on_next_line = false
ij_kotlin_line_comment_add_space = false
ij_kotlin_line_comment_at_first_column = true
ij_kotlin_method_annotation_wrap = split_into_lines
ij_kotlin_method_call_chain_wrap = normal
ij_kotlin_method_parameters_new_line_after_left_paren = true
ij_kotlin_method_parameters_right_paren_on_new_line = true
ij_kotlin_name_count_to_use_star_import = 9999
ij_kotlin_name_count_to_use_star_import_for_members = 9999
ij_kotlin_parameter_annotation_wrap = off
ij_kotlin_space_after_comma = true
ij_kotlin_space_after_extend_colon = true
ij_kotlin_space_after_type_colon = true
ij_kotlin_space_before_catch_parentheses = true
ij_kotlin_space_before_comma = false
ij_kotlin_space_before_extend_colon = true
ij_kotlin_space_before_for_parentheses = true
ij_kotlin_space_before_if_parentheses = true
ij_kotlin_space_before_lambda_arrow = true
ij_kotlin_space_before_type_colon = false
ij_kotlin_space_before_when_parentheses = true
ij_kotlin_space_before_while_parentheses = true
ij_kotlin_spaces_around_additive_operators = true
ij_kotlin_spaces_around_assignment_operators = true
ij_kotlin_spaces_around_equality_operators = true
ij_kotlin_spaces_around_function_type_arrow = true
ij_kotlin_spaces_around_logical_operators = true
ij_kotlin_spaces_around_multiplicative_operators = true
ij_kotlin_spaces_around_range = false
ij_kotlin_spaces_around_relational_operators = true
ij_kotlin_spaces_around_unary_operator = false
ij_kotlin_spaces_around_when_arrow = true
ij_kotlin_variable_annotation_wrap = off
ij_kotlin_while_on_new_line = false
ij_kotlin_wrap_elvis_expressions = 1
ij_kotlin_wrap_expression_body_functions = 1
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
+39 -41
View File
@@ -1,7 +1,4 @@
name: build name: build
permissions:
contents: read
on: on:
workflow_dispatch: workflow_dispatch:
inputs: inputs:
@@ -15,14 +12,6 @@ on:
- prerelease - prerelease
- nightly - nightly
- release - release
flavor:
type: choice
description: "Product flavor"
required: true
default: fdroid
options:
- fdroid
- standalone
secrets: secrets:
SIGNING_KEY_ALIAS: SIGNING_KEY_ALIAS:
required: false required: false
@@ -41,11 +30,6 @@ on:
description: "Build type" description: "Build type"
required: true required: true
default: debug default: debug
flavor:
type: string
description: "Product flavor"
required: false
default: fdroid
secrets: secrets:
SIGNING_KEY_ALIAS: SIGNING_KEY_ALIAS:
required: false required: false
@@ -57,7 +41,6 @@ on:
required: false required: false
KEYSTORE: KEYSTORE:
required: false required: false
env: env:
UPLOAD_DIR_ANDROID: android_artifacts UPLOAD_DIR_ANDROID: android_artifacts
@@ -74,8 +57,6 @@ jobs:
UPLOAD_DIR_ANDROID: ${{ env.UPLOAD_DIR_ANDROID }} UPLOAD_DIR_ANDROID: ${{ env.UPLOAD_DIR_ANDROID }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up JDK 17 - name: Set up JDK 17
uses: actions/setup-java@v4 uses: actions/setup-java@v4
with: with:
@@ -84,6 +65,9 @@ jobs:
cache: gradle cache: gradle
- 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 - name: Decode Keystore
id: decode_keystore id: decode_keystore
uses: timheuer/base64-to-file@v1.2 uses: timheuer/base64-to-file@v1.2
@@ -91,37 +75,51 @@ jobs:
fileName: ${{ env.KEY_STORE_FILE }} fileName: ${{ env.KEY_STORE_FILE }}
fileDir: ${{ env.KEY_STORE_LOCATION }} fileDir: ${{ env.KEY_STORE_LOCATION }}
encodedString: ${{ secrets.KEYSTORE }} encodedString: ${{ secrets.KEYSTORE }}
# create keystore path for gradle to read
- name: Create keystore path env var - name: Create keystore path env var
if: ${{ inputs.build_type != 'debug' }} if: ${{ inputs.build_type != 'debug' }}
run: | run: |
store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }} store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }}
echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV
- name: Build APK - name: Create service_account.json
if: ${{ inputs.build_type != 'debug' }}
id: createServiceAccount
run: echo '${{ secrets.ANDROID_SERVICE_ACCOUNT_JSON }}' > service_account.json
- name: Build Fdroid Release APK
if: ${{ inputs.build_type == 'release' }}
run: ./gradlew :app:assembleFdroidRelease --info
- name: Build Fdroid Prerelease APK
if: ${{ inputs.build_type == 'prerelease' }}
run: ./gradlew :app:assembleFdroidPrerelease --info
- name: Build Fdroid Nightly APK
if: ${{ inputs.build_type == 'nightly' }}
run: ./gradlew :app:assembleFdroidNightly --info
- name: Build Debug APK
if: ${{ inputs.build_type == 'debug' }}
run: ./gradlew :app:assembleFdroidDebug --stacktrace
# bump versionCode for nightly and prerelease builds
- name: Commit and push versionCode changes
if: ${{ inputs.build_type == 'nightly' || inputs.build_type == 'prerelease' }}
run: | run: |
flavor=${{ inputs.flavor }} git config --global user.name 'GitHub Actions'
build_type=${{ inputs.build_type }} git config --global user.email 'actions@github.com'
case $build_type in git add versionCode.txt
"release") git commit -m "Automated build update"
./gradlew :app:assemble${flavor^}Release --info
;;
"prerelease")
./gradlew :app:assemble${flavor^}Prerelease --info
;;
"nightly")
./gradlew :app:assemble${flavor^}Nightly --info
;;
"debug")
./gradlew :app:assemble${flavor^}Debug --stacktrace
;;
esac
- name: Get release apk path - name: Get release apk path
id: apk-path id: apk-path
run: echo "path=$(find . -regex '^.*/build/outputs/apk/${{ inputs.flavor }}/${{ inputs.build_type }}/.*\.apk$' -type f | head -1 | tail -c+2)" >> $GITHUB_OUTPUT run: echo "path=$(find . -regex '^.*/build/outputs/apk/fdroid/${{ inputs.build_type }}/.*\.apk$' -type f | head -1 | tail -c+2)" >> $GITHUB_OUTPUT
- name: Upload APK
- name: Upload release apk
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: android_artifacts_${{ inputs.flavor }} name: ${{ env.UPLOAD_DIR_ANDROID }}
path: app/build/outputs/apk/${{ inputs.flavor }}/${{ inputs.build_type }}/wgtunnel-${{ inputs.flavor }}${{ inputs.flavor == 'fdroid' && '-release' || '' }}-*.apk path: ${{github.workspace}}/${{ steps.apk-path.outputs.path }}
retention-days: 1 retention-days: 1
if-no-files-found: warn
-127
View File
@@ -1,127 +0,0 @@
name: nightly
permissions:
contents: write
packages: write
on:
workflow_dispatch:
schedule:
- cron: "4 3 * * *"
jobs:
check_commits:
name: Check for New Commits
runs-on: ubuntu-latest
outputs:
has_new_commits: ${{ steps.check.outputs.new_commits }}
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Check for new commits
id: check
env:
GITHUB_TOKEN: ${{ secrets.PAT }}
run: |
NEW_COMMITS=$(git rev-list --count --after="$(date -Iseconds -d '23 hours ago')" ${{ github.sha }})
echo "new_commits=$NEW_COMMITS" >> $GITHUB_OUTPUT
build-standalone-nightly:
uses: ./.github/workflows/build.yml
secrets: inherit
with:
build_type: "nightly"
flavor: standalone
publish:
needs:
- check_commits
- build-standalone-nightly
if: ${{ needs.check_commits.outputs.has_new_commits > 0 && inputs.release_type != 'none' }}
name: publish-nightly
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install system dependencies
run: |
sudo apt update && sudo apt install -y gh apksigner
- name: Set latest tag
uses: rickstaa/action-create-tag@v1
id: tag_creation
with:
tag: "latest"
message: "Automated tag for HEAD commit"
force_push_tag: true
github_token: ${{ secrets.GITHUB_TOKEN }}
tag_exists_error: false
- name: Generate Changelog
id: changelog
uses: requarks/changelog-action@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
toTag: "nightly"
fromTag: "latest"
writeToFile: false
- name: Make download dir
run: mkdir ${{ github.workspace }}/temp
- name: Download artifacts
uses: actions/download-artifact@v4
with:
pattern: android_artifacts_*
path: ${{ github.workspace }}/temp
- name: Set release notes
run: |
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
- name: Delete previous nightly version
uses: ClementTsang/delete-tag-and-release@v0.4.0
with:
tag_name: "nightly"
delete_release: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Get checksum
id: checksum
run: |
file_path=$(find ${{ github.workspace }}/temp -type f -iname "*.apk" | head -n 1)
if [ -z "$file_path" ]; then
echo "No APK file found"
exit 1
fi
checksum=$(apksigner verify --print-certs "$file_path" | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")
echo "checksum=$checksum" >> $GITHUB_OUTPUT
- name: Create nightly release
id: create_release
uses: softprops/action-gh-release@v2
with:
body: |
${{ env.RELEASE_NOTES }}
SHA-256 fingerprints for the 4096-bit signing certificate:
```sh
${{ steps.checksum.outputs.checksum }}
```
To verify fingerprint:
```sh
apksigner verify --print-certs [path to APK file] | grep SHA-256
```
### Changelog
${{ steps.changelog.outputs.changes }}
tag_name: nightly
name: nightly
draft: false
prerelease: true
make_latest: false
files: |
${{ github.workspace }}/temp/**/*.apk
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+20
View File
@@ -0,0 +1,20 @@
name: on-issue
on:
issues:
types: [ opened, closed, reopened ]
jobs:
on-issue:
name: On new issue
runs-on: ubuntu-latest
steps:
- name: Send Telegram Message
run: |
msg_text='${{ github.actor }} updated an issue:
status: ${{ github.event.issue.state }} - #${{ github.event.issue.number }} ${{ github.event.issue.title }}
https://github.com/zaneschepke/wgtunnel/issues/${{ github.event.issue.number }}'
curl -s -X POST 'https://api.telegram.org/bot${{ secrets.TELEGRAM_TOKEN }}/sendMessage' \
-d "chat_id=${{ secrets.TELEGRAM_TO }}&text=${msg_text}&message_thread_id=${{ secrets.TELEGRAM_TOPIC }}"
@@ -1,6 +1,4 @@
name: on-pr name: on-pr
permissions:
contents: read
on: on:
workflow_dispatch: workflow_dispatch:
@@ -21,5 +19,5 @@ jobs:
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x gradlew run: chmod +x gradlew
- name: Run ktfmt - name: Run ktlint
run: ./gradlew ktfmtCheck run: ./gradlew ktlintCheck
+21
View File
@@ -0,0 +1,21 @@
name: on-publish
on:
release:
types: [ published ]
jobs:
on-publish:
name: On publish
runs-on: ubuntu-latest
steps:
- name: Send Telegram Message
run: |
msg_text='${{ github.actor }} published a new release:
Release: ${{ github.event.release.tag_name }}
${{ github.event.release.body }}
https://github.com/zaneschepke/wgtunnel/releases/tag/${{ github.event.release.tag_name }}'
curl -s -X POST 'https://api.telegram.org/bot${{ secrets.TELEGRAM_TOKEN }}/sendMessage' \
-d "chat_id=${{ secrets.TELEGRAM_TO }}&text=${msg_text}&message_thread_id=${{ secrets.TELEGRAM_TOPIC }}"
+93 -63
View File
@@ -1,14 +1,13 @@
name: publish name: publish
permissions:
contents: write
packages: write
on: on:
schedule:
- cron: "4 3 * * *"
workflow_dispatch: workflow_dispatch:
inputs: inputs:
track: track:
type: choice type: choice
description: "Google Play release track" description: "Google play release track"
options: options:
- none - none
- internal - internal
@@ -23,69 +22,76 @@ on:
options: options:
- none - none
- prerelease - prerelease
- nightly
- release - release
default: release default: release
required: true required: true
tag_name: tag_name:
description: "Tag name for release" description: "Tag name for release"
required: false required: false
default: 1.1.1 default: nightly
flavor:
type: choice
description: "Product flavor"
required: true
default: standalone
options:
- fdroid
- standalone
workflow_call: workflow_call:
inputs: env:
flavor: UPLOAD_DIR_ANDROID: android_artifacts
type: string
description: "Product flavor"
required: false
default: standalone
jobs: jobs:
check_commits:
name: Check for New Commits
runs-on: ubuntu-latest
outputs:
has_new_commits: ${{ steps.check.outputs.new_commits }}
build-fdroid: steps:
if: ${{ inputs.release_type == 'release' || inputs.flavor == 'fdroid' }} - 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:
if: ${{ inputs.release_type != 'none' }}
uses: ./.github/workflows/build.yml uses: ./.github/workflows/build.yml
secrets: inherit secrets: inherit
with: with:
build_type: ${{ inputs.release_type }} build_type: ${{ inputs.release_type == '' && 'nightly' || inputs.release_type }}
flavor: fdroid
build-standalone:
if: ${{ inputs.release_type == 'release' || inputs.release_type == 'prerelease' || inputs.flavor == 'standalone' }}
uses: ./.github/workflows/build.yml
secrets: inherit
with:
build_type: ${{ inputs.release_type }}
flavor: standalone
publish: publish:
needs: needs:
- build-standalone - check_commits
- build
if: ${{ needs.check_commits.outputs.has_new_commits > 0 && inputs.release_type != 'none' }}
name: publish-github name: publish-github
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
GH_USER: ${{ secrets.GH_USER }}
# GH needed for gh cli
GH_TOKEN: ${{ secrets.GH_TOKEN }}
GH_REPO: ${{ github.repository }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
ref: main
- name: Install system dependencies - name: Install system dependencies
run: | run: |
sudo apt update && sudo apt install -y gh apksigner sudo apt update && sudo apt install -y gh apksigner
# update latest tag
- name: Set latest tag - name: Set latest tag
uses: rickstaa/action-create-tag@v1 uses: rickstaa/action-create-tag@v1
id: tag_creation id: tag_creation
with: with:
tag: "latest" tag: "latest" # or any tag name you wish to use
message: "Automated tag for HEAD commit" message: "Automated tag for HEAD commit"
force_push_tag: true force_push_tag: true
github_token: ${{ secrets.GITHUB_TOKEN }}
tag_exists_error: false tag_exists_error: false
- name: Get latest release - name: Get latest release
id: latest_release id: latest_release
uses: kaliber5/action-get-release@v1 uses: kaliber5/action-get-release@v1
@@ -98,9 +104,22 @@ jobs:
uses: requarks/changelog-action@v1 uses: requarks/changelog-action@v1
with: with:
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}
toTag: ${{ steps.latest_release.outputs.tag_name }} toTag: ${{ github.event_name == 'schedule' && 'nightly' || steps.latest_release.outputs.tag_name }}
fromTag: "latest" fromTag: "latest"
writeToFile: false writeToFile: false # we won't write to file, just output
- name: Get version code
if: ${{ inputs.release_type == 'release' }}
run: |
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
- 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 }}
- name: Make download dir - name: Make download dir
run: mkdir ${{ github.workspace }}/temp run: mkdir ${{ github.workspace }}/temp
@@ -108,43 +127,53 @@ jobs:
- name: Download artifacts - name: Download artifacts
uses: actions/download-artifact@v4 uses: actions/download-artifact@v4
with: with:
pattern: android_artifacts_* name: ${{ env.UPLOAD_DIR_ANDROID }}
path: ${{ github.workspace }}/temp path: ${{ github.workspace }}/temp
merge-multiple: true
# Setup TAG_NAME, which is used as a general "name"
- if: github.event_name == 'workflow_dispatch'
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
- if: github.event_name == 'schedule'
run: echo "TAG_NAME=nightly" >> $GITHUB_ENV
- name: Set version release notes - name: Set version release notes
if: ${{ inputs.release_type == 'release' }} if: ${{ inputs.release_type == 'release' }}
run: | run: |
VERSION_NAME=$(grep "const val VERSION_NAME" buildSrc/src/main/kotlin/Constants.kt | awk -F'"' '{print $2}') RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${VERSION_NAME}.txt || echo "No changelog found for ${VERSION_NAME}")"
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
echo "$RELEASE_NOTES" >> $GITHUB_ENV echo "$RELEASE_NOTES" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV echo "EOF" >> $GITHUB_ENV
- name: On nightly release notes
if: ${{ contains(env.TAG_NAME, 'nightly') }}
run: |
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
gh release delete nightly --yes || true
git push origin :nightly || true
- name: On prerelease release notes - name: On prerelease release notes
if: ${{ inputs.release_type == 'prerelease' }} if: ${{ inputs.release_type == 'prerelease' }}
run: | run: |
echo "RELEASE_NOTES=Testing version of app for specific feature." >> $GITHUB_ENV echo "RELEASE_NOTES=Testing version of app for specific feature." >> $GITHUB_ENV
gh release delete ${{ github.event.inputs.tag_name }} --yes || true
- name: Get checksum - name: Get checksum
id: checksum id: checksum
run: | run: |
file_path=$(find ${{ github.workspace }}/temp -type f -iname "*.apk" | head -n 1) file_path=$(find ${{ github.workspace }}/temp -type f -iname "*.apk" | tail -n1)
if [ -z "$file_path" ]; then echo "checksum=$(apksigner verify -print-certs $file_path | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT
echo "No APK file found"
exit 1
fi
checksum=$(apksigner verify --print-certs "$file_path" | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")
echo "checksum=$checksum" >> $GITHUB_OUTPUT
- name: Create Release
- name: Create Release with Fastlane changelog notes
id: create_release id: create_release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
body: | body: |
${{ env.RELEASE_NOTES }} ${{ env.RELEASE_NOTES }}
SHA-256 fingerprints for the 4096-bit signing certificate: SHA-256 fingerprint for the 4096-bit signing certificate:
```sh ```sh
${{ steps.checksum.outputs.checksum }} ${{ steps.checksum.outputs.checksum }}
``` ```
@@ -156,31 +185,29 @@ jobs:
### Changelog ### Changelog
${{ steps.changelog.outputs.changes }} ${{ steps.changelog.outputs.changes }}
tag_name: ${{ github.event.inputs.tag_name }} tag_name: ${{ env.TAG_NAME }}
name: ${{ github.event.inputs.tag_name }} name: ${{ env.TAG_NAME }}
draft: false draft: false
prerelease: ${{ inputs.release_type == 'prerelease' }} prerelease: ${{ inputs.release_type == 'prerelease' || inputs.release_type == '' || inputs.release_type == 'nightly' }}
make_latest: ${{ inputs.release_type == 'release' }} make_latest: ${{ inputs.release_type == 'release' }}
files: | files: |
${{ github.workspace }}/temp/**/*.apk ${{ github.workspace }}/temp/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
publish-fdroid-public: publish-fdroid:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: needs:
- build-fdroid - build
if: inputs.release_type == 'release' if: inputs.release_type == 'release'
steps: steps:
- name: Dispatch update for fdroid repo - name: Dispatch update for fdroid repo
uses: peter-evans/repository-dispatch@v3 uses: peter-evans/repository-dispatch@v3
with: with:
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.PAT }}
repository: wgtunnel/fdroid repository: zaneschepke/fdroid
event-type: fdroid-update event-type: fdroid-update
publish-play: publish-play:
if: ${{ inputs.track != 'none' }} if: ${{ inputs.track != 'none' && inputs.track != '' }}
name: Publish to Google Play name: Publish to Google Play
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -190,6 +217,8 @@ jobs:
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }} SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
KEY_STORE_FILE: 'android_keystore.jks' KEY_STORE_FILE: 'android_keystore.jks'
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/ KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
GH_USER: ${{ secrets.GH_USER }}
GH_TOKEN: ${{ secrets.GH_TOKEN }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -230,4 +259,5 @@ jobs:
bundler-cache: true bundler-cache: true
- name: Distribute app to Prod track 🚀 - name: Distribute app to Prod track 🚀
run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane ${{ inputs.track }}) run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane ${{ inputs.track }})
+1 -1
View File
@@ -70,5 +70,5 @@ lint/tmp/
app/release/output.json 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
/.kotlin/ /.kotlin/
/app/keystore/
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License MIT License
Copyright © 2023-2025 Zane Schepke Copyright (c) 2023 WG Auto Tunnel
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+1 -1
View File
@@ -30,7 +30,7 @@ and [AmneziaWG](https://docs.amnezia.org/documentation/amnezia-wg/)
<div align="center"> <div align="center">
[<img src="https://img.shields.io/badge/Telegram-26A5E4.svg?style=for-the-badge&logo=Telegram&logoColor=white">](https://t.me/wgtunnel) [<img src="https://img.shields.io/badge/Telegram-26A5E4.svg?style=for-the-badge&logo=Telegram&logoColor=white">](https://t.me/wgtunnel)
[<img src="https://img.shields.io/badge/Matrix-000000.svg?style=for-the-badge&logo=Matrix&logoColor=white">](https://matrix.to/#/#wg-tunnel-space:matrix.org) [<img src="https://img.shields.io/badge/Matrix-000000.svg?style=for-the-badge&logo=Matrix&logoColor=white">](https://matrix.to/#/#wg-tunnel:matrix.zaneschepke.com)
</div> </div>
<details open="open"> <details open="open">
+1 -2
View File
@@ -1,3 +1,2 @@
/build /build
/release /release
/src/main/assets/licenses.json
+215 -193
View File
@@ -1,233 +1,255 @@
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)
alias(libs.plugins.licensee) }
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().trim().toInt() + 1
} else {
1
}
}
else -> 0
}
} }
android { android {
namespace = Constants.APP_ID namespace = Constants.APP_ID
compileSdk = Constants.TARGET_SDK compileSdk = Constants.TARGET_SDK
androidResources { generateLocaleConfig = true } androidResources {
generateLocaleConfig = true
}
dependenciesInfo { // reproducibility
includeInApk = false dependenciesInfo {
includeInBundle = false // Disables dependency metadata when building APKs.
} includeInApk = false
// Disables dependency metadata when building Android App Bundles.
includeInBundle = false
}
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 = computeVersionCode() versionCode = Constants.VERSION_CODE + versionCodeIncrement
versionName = computeVersionName() versionName = determineVersionName()
ksp { arg("room.schemaLocation", "$projectDir/schemas") } ksp { arg("room.schemaLocation", "$projectDir/schemas") }
sourceSets { getByName("debug").assets.srcDirs(files("$projectDir/schemas")) } sourceSets {
getByName("debug").assets.srcDirs(files("$projectDir/schemas")) // Room
}
buildConfigField( buildConfigField("String[]", "LANGUAGES", "new String[]{ ${languageList().joinToString(separator = ", ") { "\"$it\"" }} }")
"String[]",
"LANGUAGES",
"new String[]{ ${languageList().joinToString(separator = ", ") { "\"$it\"" }} }",
)
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables { useSupportLibrary = true } vectorDrawables { useSupportLibrary = true }
} }
signingConfigs { signingConfigs {
create(Constants.RELEASE) { create(Constants.RELEASE) {
storeFile = file(System.getenv("KEY_STORE_PATH") ?: "keystore/android_keystore.jks") storeFile = getStoreFile()
storePassword = storePassword = getSigningProperty(Constants.STORE_PASS_VAR)
LocalProperties.get("SIGNING_STORE_PASSWORD") keyAlias = getSigningProperty(Constants.KEY_ALIAS_VAR)
?: System.getenv("SIGNING_STORE_PASSWORD") keyPassword = getSigningProperty(Constants.KEY_PASS_VAR)
keyAlias = }
LocalProperties.get("SIGNING_KEY_ALIAS") ?: System.getenv("SIGNING_KEY_ALIAS") }
keyPassword =
LocalProperties.get("SIGNING_KEY_PASSWORD") ?: System.getenv("SIGNING_KEY_PASSWORD")
}
}
buildTypes { buildTypes {
packaging.jniLibs.keepDebugSymbols.addAll( // don't strip
listOf("libwg-go.so", "libwg-quick.so", "libwg.so") packaging.jniLibs.keepDebugSymbols.addAll(
) listOf("libwg-go.so", "libwg-quick.so", "libwg.so"),
)
release { release {
isDebuggable = false isDebuggable = false
isMinifyEnabled = true isMinifyEnabled = true
isShrinkResources = true isShrinkResources = true
proguardFiles( proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"), getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro", "proguard-rules.pro",
) )
signingConfig = signingConfigs.getByName(Constants.RELEASE) signingConfig = signingConfigs.getByName(Constants.RELEASE)
resValue("string", "provider", "\"${Constants.APP_NAME}.provider\"") resValue("string", "provider", "\"${Constants.APP_NAME}.provider\"")
} }
debug {
applicationIdSuffix = ".debug"
versionNameSuffix = "-debug"
resValue("string", "app_name", "WG Tunnel - Debug")
isDebuggable = true
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.debug\"")
}
debug { create(Constants.PRERELEASE) {
applicationIdSuffix = ".debug" initWith(buildTypes.getByName(Constants.RELEASE))
resValue("string", "app_name", "WG Tunnel - Debug") applicationIdSuffix = ".prerelease"
isDebuggable = true versionNameSuffix = "-pre"
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.debug\"") resValue("string", "app_name", "WG Tunnel - Pre")
} resValue("string", "provider", "\"${Constants.APP_NAME}.provider.pre\"")
}
create(Constants.PRERELEASE) { create(Constants.NIGHTLY) {
initWith(buildTypes.getByName(Constants.RELEASE)) initWith(buildTypes.getByName(Constants.RELEASE))
applicationIdSuffix = ".prerelease" applicationIdSuffix = ".nightly"
resValue("string", "app_name", "WG Tunnel - Pre") versionNameSuffix = "-nightly"
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.pre\"") resValue("string", "app_name", "WG Tunnel - Nightly")
} resValue("string", "provider", "\"${Constants.APP_NAME}.provider.nightly\"")
}
create(Constants.NIGHTLY) { applicationVariants.all {
initWith(buildTypes.getByName(Constants.RELEASE)) val variant = this
applicationIdSuffix = ".nightly" variant.outputs
resValue("string", "app_name", "WG Tunnel - Nightly") .map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.nightly\"") .forEach { output ->
} val outputFileName =
} "${Constants.APP_NAME}-${variant.flavorName}-" +
"${variant.buildType.name}-${variant.versionName}.apk"
flavorDimensions.add("type") output.outputFileName = outputFileName
productFlavors { }
create("fdroid") { }
dimension = "type" }
buildConfigField("String", "FLAVOR", "\"fdroid\"") flavorDimensions.add(Constants.TYPE)
} productFlavors {
create("google") { create("fdroid") {
dimension = "type" dimension = Constants.TYPE
buildConfigField("String", "FLAVOR", "\"google\"") proguardFile("fdroid-rules.pro")
} }
create("standalone") { create("general") {
dimension = "type" dimension = Constants.TYPE
buildConfigField("String", "FLAVOR", "\"standalone\"") }
} }
} compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
compileOptions { targetCompatibility = JavaVersion.VERSION_17
isCoreLibraryDesugaringEnabled = true isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.VERSION_17 }
targetCompatibility = JavaVersion.VERSION_17 kotlinOptions { jvmTarget = Constants.JVM_TARGET }
} buildFeatures {
kotlinOptions { jvmTarget = Constants.JVM_TARGET } compose = true
buildFeatures { buildConfig = true
compose = true }
buildConfig = true packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
}
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
licensee {
Constants.allowedLicenses.forEach { allow(it) }
allowUrl(Constants.XZING_LICENSE_URL)
}
applicationVariants.all {
val variant = this
variant.outputs
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
.forEach { output ->
val outputFileName =
if (variant.flavorName == "fdroid" && variant.buildType.name == "release") {
"${Constants.APP_NAME}-fdroid-release-${variant.versionName}.apk"
} else {
"${Constants.APP_NAME}-${variant.flavorName}-v${variant.versionName}.apk"
}
output.outputFileName = outputFileName
}
}
} }
dependencies { dependencies {
implementation(project(":logcatter")) implementation(project(":logcatter"))
implementation(project(":networkmonitor")) implementation(project(":networkmonitor"))
implementation(libs.androidx.core.ktx) implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.lifecycle.service)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.material3)
implementation(libs.androidx.appcompat)
implementation(libs.material)
implementation(libs.androidx.storage)
testImplementation(libs.junit) // helpers for implementing LifecycleOwner in a Service
testImplementation(libs.androidx.junit) implementation(libs.androidx.lifecycle.service)
androidTestImplementation(libs.androidx.junit) implementation(libs.androidx.activity.compose)
androidTestImplementation(libs.androidx.espresso.core) implementation(platform(libs.androidx.compose.bom))
androidTestImplementation(platform(libs.androidx.compose.bom)) implementation(libs.androidx.compose.ui)
androidTestImplementation(libs.androidx.compose.ui.test) implementation(libs.androidx.compose.ui.graphics)
androidTestImplementation(libs.androidx.room.testing) implementation(libs.androidx.compose.ui.tooling.preview)
debugImplementation(libs.androidx.compose.ui.tooling) implementation(libs.androidx.material3)
debugImplementation(libs.androidx.compose.manifest) implementation(libs.androidx.appcompat)
implementation(libs.material)
implementation(libs.tunnel) // test
implementation(libs.amneziawg.android) testImplementation(libs.junit)
coreLibraryDesugaring(libs.desugar.jdk.libs) testImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.compose.ui.test)
androidTestImplementation(libs.androidx.room.testing)
debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.androidx.compose.manifest)
implementation(libs.timber) // tunnel
implementation(libs.tunnel)
implementation(libs.amneziawg.android)
coreLibraryDesugaring(libs.desugar.jdk.libs)
implementation(libs.androidx.navigation.compose) // logging
implementation(libs.androidx.hilt.navigation.compose) implementation(libs.timber)
implementation(libs.hilt.android) // compose navigation
ksp(libs.hilt.android.compiler) implementation(libs.androidx.navigation.compose)
ksp(libs.androidx.hilt.compiler) implementation(libs.androidx.hilt.navigation.compose)
implementation(libs.accompanist.permissions) // hilt
implementation(libs.accompanist.drawablepainter) implementation(libs.hilt.android)
ksp(libs.hilt.android.compiler)
ksp(libs.androidx.hilt.compiler)
implementation(libs.androidx.room.runtime) // accompanist
ksp(libs.androidx.room.compiler) implementation(libs.accompanist.permissions)
implementation(libs.androidx.room.ktx) implementation(libs.accompanist.drawablepainter)
implementation(libs.androidx.datastore.preferences)
implementation(libs.lifecycle.runtime.compose) // storage
implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.room.runtime)
implementation(libs.androidx.lifecycle.process) ksp(libs.androidx.room.compiler)
implementation(libs.androidx.room.ktx)
implementation(libs.androidx.datastore.preferences)
implementation(libs.kotlinx.serialization.json) // lifecycle
implementation(libs.lifecycle.runtime.compose)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.lifecycle.process)
implementation(libs.zxing.android.embedded) // icons
implementation(libs.material.icons.extended)
// serialization
implementation(libs.kotlinx.serialization.json)
implementation(libs.material.icons.extended) // barcode scanning
implementation(libs.zxing.android.embedded)
implementation(libs.androidx.biometric.ktx) // bio
implementation(libs.pin.lock.compose) implementation(libs.androidx.biometric.ktx)
implementation(libs.pin.lock.compose)
implementation(libs.androidx.core) // shortcuts
implementation(libs.androidx.core)
implementation(libs.androidx.core.splashscreen) // splash
implementation(libs.androidx.core.splashscreen)
implementation(libs.androidx.work.runtime) // worker
implementation(libs.androidx.hilt.work) implementation(libs.androidx.work.runtime)
implementation(libs.androidx.hilt.work)
implementation(libs.qrose)
implementation(libs.semver4j)
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.okhttp)
implementation(libs.ktor.client.cio)
implementation(libs.ktor.client.content.negotiation)
implementation(libs.ktor.serialization.kotlinx.json)
implementation(libs.slf4j.android)
} }
tasks.register<Copy>("copyLicenseeJsonToAssets") { fun determineVersionName(): String {
dependsOn("licensee") return with(getBuildTaskName().lowercase()) {
val outputAssets = layout.projectDirectory.dir("src/main/assets") when {
from(layout.buildDirectory.file("reports/licensee/androidFdroidRelease/artifacts.json")) { contains(Constants.NIGHTLY) || contains(Constants.PRERELEASE) ->
rename("artifacts.json", "licenses.json") Constants.VERSION_NAME +
} "-${grgitService.service.get().grgit.head().abbreviatedId}"
into(outputAssets) else -> Constants.VERSION_NAME
}
}
} }
tasks.named("preBuild") { dependsOn("copyLicenseeJsonToAssets") } val incrementVersionCode by tasks.registering {
doLast {
val versionFile = file("$rootDir/versionCode.txt")
if (versionFile.exists()) {
versionFile.writeText(versionCodeIncrement.toString())
println("Incremented versionCode to $versionCodeIncrement")
}
}
}
tasks.whenTaskAdded {
if (name.startsWith("assemble") && !name.lowercase().contains("debug")) {
dependsOn(incrementVersionCode)
}
}
+42
View File
@@ -0,0 +1,42 @@
-dontwarn com.google.errorprone.annotations.**
-keepclassmembers class * extends androidx.datastore.preferences.protobuf.GeneratedMessageLite {
<fields>;
}
# Keep all classes in the org.xbill.DNS package and subpackages
-keep class org.xbill.DNS.** { *; }
-dontwarn org.xbill.DNS.**
# Preserve JNA classes if used (e.g., for IPHlpAPI on Windows)
-keep class com.sun.jna.** { *; }
-dontwarn com.sun.jna.**
# Keep DNS resolver configuration classes that might be loaded dynamically
-keep class org.xbill.DNS.config.** { *; }
-dontwarn org.xbill.DNS.config.**
-keep class org.xbill.DNS.** { *; }
# Prevent optimization issues with native or reflection-based calls
-dontoptimize
-dontshrink
# Uncomment the above if errors persist, but use sparingly as theyre broad
# Suppress warnings about missing classes if not all features are used
-dontwarn java.lang.management.**
-dontwarn sun.nio.ch.**
-dontwarn com.google.api.client.http.GenericUrl
-dontwarn com.google.api.client.http.HttpHeaders
-dontwarn com.google.api.client.http.HttpRequest
-dontwarn com.google.api.client.http.HttpRequestFactory
-dontwarn com.google.api.client.http.HttpResponse
-dontwarn com.google.api.client.http.HttpTransport
-dontwarn com.google.api.client.http.javanet.NetHttpTransport$Builder
-dontwarn com.google.api.client.http.javanet.NetHttpTransport
-dontwarn javax.lang.model.element.Modifier
-dontwarn org.joda.time.Instant
-dontwarn org.slf4j.impl.StaticLoggerBinder
-dontwarn org.slf4j.impl.StaticMDCBinder
-dontwarn org.slf4j.impl.StaticMarkerBinder
+61
View File
@@ -0,0 +1,61 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
-keepclassmembers class * extends androidx.datastore.preferences.protobuf.GeneratedMessageLite {
<fields>;
}
# Keep all classes in the org.xbill.DNS package and subpackages
-keep class org.xbill.DNS.** { *; }
-dontwarn org.xbill.DNS.**
# Preserve JNA classes if used (e.g., for IPHlpAPI on Windows)
-keep class com.sun.jna.** { *; }
-dontwarn com.sun.jna.**
# Keep DNS resolver configuration classes that might be loaded dynamically
-keep class org.xbill.DNS.config.** { *; }
-dontwarn org.xbill.DNS.config.**
-keep class org.xbill.DNS.** { *; }
# Prevent optimization issues with native or reflection-based calls
-dontoptimize
-dontshrink
# Uncomment the above if errors persist, but use sparingly as theyre broad
# Suppress warnings about missing classes if not all features are used
-dontwarn java.lang.management.**
-dontwarn sun.nio.ch.**
-dontwarn com.google.api.client.http.GenericUrl
-dontwarn com.google.api.client.http.HttpHeaders
-dontwarn com.google.api.client.http.HttpRequest
-dontwarn com.google.api.client.http.HttpRequestFactory
-dontwarn com.google.api.client.http.HttpResponse
-dontwarn com.google.api.client.http.HttpTransport
-dontwarn com.google.api.client.http.javanet.NetHttpTransport$Builder
-dontwarn com.google.api.client.http.javanet.NetHttpTransport
-dontwarn javax.lang.model.element.Modifier
-dontwarn org.joda.time.Instant
-dontwarn org.slf4j.impl.StaticLoggerBinder
-dontwarn org.slf4j.impl.StaticMDCBinder
-dontwarn org.slf4j.impl.StaticMarkerBinder
@@ -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)
} }
} }
@@ -5,35 +5,40 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry import androidx.test.platform.app.InstrumentationRegistry
import com.zaneschepke.wireguardautotunnel.data.AppDatabase import com.zaneschepke.wireguardautotunnel.data.AppDatabase
import com.zaneschepke.wireguardautotunnel.data.Queries import com.zaneschepke.wireguardautotunnel.data.Queries
import java.io.IOException
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
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(InstrumentationRegistry.getInstrumentation(), AppDatabase::class.java) MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
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(Queries.createTunnelConfig()) execSQL(
// Prepare for the next version. Queries.createTunnelConfig(),
close() )
} // Prepare for the next version.
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.
} }
} }
-5
View File
@@ -1,5 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Permissions specific to full -->
<!--updater-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
</manifest>
+14 -28
View File
@@ -2,7 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
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 android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!--foreground service exempt android 14--> <!--foreground service exempt android 14-->
@@ -16,11 +16,10 @@
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" /> <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<!--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-->
<permission <permission
android:name="${applicationId}.permission.CONTROL_TUNNELS" android:name="${applicationId}.permission.CONTROL_TUNNELS"
android:label="@string/app_permission_title"
android:description="@string/app_permission_description"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:protectionLevel="dangerous" /> android:protectionLevel="dangerous" />
@@ -46,13 +45,12 @@
<queries> <queries>
<intent> <intent>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent> </intent>
</queries> </queries>
<application <application
android:name=".WireGuardAutoTunnel" android:name=".WireGuardAutoTunnel"
android:allowBackup="false" android:allowBackup="false"
android:banner="@mipmap/ic_banner" android:banner="@drawable/ic_banner"
android:dataExtractionRules="@xml/data_extraction_rules" android:dataExtractionRules="@xml/data_extraction_rules"
android:enableOnBackInvokedCallback="true" android:enableOnBackInvokedCallback="true"
android:fullBackupContent="@xml/backup_rules" android:fullBackupContent="@xml/backup_rules"
@@ -62,14 +60,10 @@
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.App.Start" android:theme="@style/Theme.App.Start"
tools:targetApi="tiramisu"> tools:targetApi="tiramisu">
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="screenOrientation" />
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
android:windowSoftInputMode="adjustNothing" android:windowSoftInputMode="adjustResize"
android:theme="@style/Theme.WireguardAutoTunnel" android:theme="@style/Theme.WireguardAutoTunnel"
android:configChanges="orientation|screenSize|keyboardHidden" android:configChanges="orientation|screenSize|keyboardHidden"
> >
@@ -82,11 +76,15 @@
<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>
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="screenOrientation" />
<activity <activity
android:name=".core.shortcut.ShortcutsActivity" android:name=".core.shortcut.ShortcutsActivity"
android:enabled="true" android:enabled="true"
android:exported="false" android:exported="true"
android:noHistory="true" android:noHistory="true"
android:excludeFromRecents="true" android:excludeFromRecents="true"
android:finishOnTaskLaunch="true" android:finishOnTaskLaunch="true"
@@ -113,7 +111,7 @@
<service <service
android:name=".core.service.tile.TunnelControlTile" android:name=".core.service.tile.TunnelControlTile"
android:exported="true" android:exported="true"
android:icon="@drawable/ic_notification" android:icon="@drawable/ic_launcher"
android:label="@string/tunnel_control" android:label="@string/tunnel_control"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"> android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<meta-data <meta-data
@@ -130,7 +128,7 @@
<service <service
android:name=".core.service.tile.AutoTunnelControlTile" android:name=".core.service.tile.AutoTunnelControlTile"
android:exported="true" android:exported="true"
android:icon="@drawable/ic_notification" android:icon="@drawable/ic_launcher"
android:label="@string/auto_tunnel" android:label="@string/auto_tunnel"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"> android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<meta-data <meta-data
@@ -163,11 +161,13 @@
<action android:name="android.net.VpnService" /> <action android:name="android.net.VpnService" />
</intent-filter> </intent-filter>
</service> </service>
<receiver <receiver
android:name=".core.broadcast.RestartReceiver" android:name=".core.broadcast.RestartReceiver"
android:enabled="true" android:enabled="true"
android:exported="false"> android:exported="true">
<intent-filter> <intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" /> <action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" /> <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
@@ -182,20 +182,6 @@
<action android:name="com.wireguard.android.action.REFRESH_TUNNEL_STATES" /> <action android:name="com.wireguard.android.action.REFRESH_TUNNEL_STATES" />
</intent-filter> </intent-filter>
</receiver> </receiver>
<!--custom security solution for easier user integration-->
<receiver
android:name=".core.broadcast.RemoteControlReceiver"
android:enabled="true"
android:exported="true" tools:ignore="ExportedReceiver">
<intent-filter>
<action android:name="com.zaneschepke.wireguardautotunnel.START_TUNNEL" />
<action android:name="com.zaneschepke.wireguardautotunnel.STOP_TUNNEL" />
<action android:name="com.zaneschepke.wireguardautotunnel.START_AUTO_TUNNEL" />
<action android:name="com.zaneschepke.wireguardautotunnel.STOP_AUTO_TUNNEL" />
<action android:name="com.zaneschepke.wireguardautotunnel.START_KILL_SWITCH" />
<action android:name="com.zaneschepke.wireguardautotunnel.STOP_KILL_SWITCH" />
</intent-filter>
</receiver>
<receiver <receiver
android:name=".core.broadcast.NotificationActionReceiver" android:name=".core.broadcast.NotificationActionReceiver"
android:exported="false" android:exported="false"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 16 KiB

@@ -1,345 +1,287 @@
package com.zaneschepke.wireguardautotunnel package com.zaneschepke.wireguardautotunnel
import android.Manifest import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.graphics.Color import android.graphics.Color
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.provider.Settings
import androidx.activity.SystemBarStyle import androidx.activity.SystemBarStyle
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInVertically import androidx.compose.animation.fadeIn
import androidx.compose.animation.slideOutVertically import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.* import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.* 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.Scaffold
import androidx.compose.material3.SnackbarData
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
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.toRoute import androidx.navigation.toRoute
import com.zaneschepke.networkmonitor.NetworkMonitor import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.wireguardautotunnel.core.shortcut.ShortcutManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.ui.Route import com.zaneschepke.wireguardautotunnel.ui.Route
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.VpnDeniedDialog import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.CustomSnackBar import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.CustomSnackBar
import com.zaneschepke.wireguardautotunnel.ui.navigation.LocalIsAndroidTV import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarControllerProvider
import com.zaneschepke.wireguardautotunnel.ui.navigation.LocalNavController import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigScreen
import com.zaneschepke.wireguardautotunnel.ui.navigation.components.BottomNavbar
import com.zaneschepke.wireguardautotunnel.ui.navigation.components.DynamicTopAppBar
import com.zaneschepke.wireguardautotunnel.ui.navigation.components.currentNavBackStackEntryAsNavBarState
import com.zaneschepke.wireguardautotunnel.ui.screens.autotunnel.AutoTunnelScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.autotunnel.advanced.AutoTunnelAdvancedScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.autotunnel.disclosure.LocationDisclosureScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.autotunnel.TunnelAutoTunnelScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.OptionsScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.config.ConfigScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.PinLockScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.splittunnel.SplitTunnelScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.ScannerScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.tunneloptions.TunnelOptionsScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.SplitTunnelScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.pin.PinLockScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.TunnelAutoTunnelScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.AdvancedScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.AppearanceScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.DisplayScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.KillSwitchScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.LanguageScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.LocationDisclosureScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.SettingsScreen import com.zaneschepke.wireguardautotunnel.ui.screens.settings.SettingsScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.advanced.SettingsAdvancedScreen import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.AutoTunnelScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.AppearanceScreen import com.zaneschepke.wireguardautotunnel.ui.screens.support.LogsScreen
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.killswitch.KillSwitchScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.logs.LogsScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.support.SupportScreen import com.zaneschepke.wireguardautotunnel.ui.screens.support.SupportScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.support.license.LicenseScreen
import com.zaneschepke.wireguardautotunnel.ui.theme.WireguardAutoTunnelTheme import com.zaneschepke.wireguardautotunnel.ui.theme.WireguardAutoTunnelTheme
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.viewmodel.AppViewModel import com.zaneschepke.wireguardautotunnel.viewmodel.AppViewModel
import com.zaneschepke.wireguardautotunnel.viewmodel.event.AppEvent
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
import kotlin.system.exitProcess import kotlin.system.exitProcess
import org.amnezia.awg.backend.GoBackend.VpnService
import timber.log.Timber
@AndroidEntryPoint @AndroidEntryPoint
class MainActivity : AppCompatActivity() { class MainActivity : AppCompatActivity() {
@Inject lateinit var appStateRepository: AppStateRepository @Inject
lateinit var appStateRepository: AppStateRepository
@Inject lateinit var tunnelManager: TunnelManager @Inject
lateinit var tunnelManager: TunnelManager
@Inject lateinit var networkMonitor: NetworkMonitor @Inject
lateinit var shortcutManager: ShortcutManager
private var lastLocationPermissionState: Boolean? = null @Inject
lateinit var networkMonitor: NetworkMonitor
@SuppressLint("BatteryLife") private var lastLocationPermissionState: Boolean? = null
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge(
statusBarStyle = SystemBarStyle.Companion.auto(Color.TRANSPARENT, Color.TRANSPARENT),
navigationBarStyle = SystemBarStyle.Companion.auto(Color.TRANSPARENT, Color.TRANSPARENT),
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
window.isNavigationBarContrastEnforced = false
}
super.onCreate(savedInstanceState)
val viewModel by viewModels<AppViewModel>() override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge(
statusBarStyle = SystemBarStyle.Companion.auto(Color.TRANSPARENT, Color.TRANSPARENT),
navigationBarStyle = SystemBarStyle.Companion.auto(Color.TRANSPARENT, Color.TRANSPARENT),
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
window.isNavigationBarContrastEnforced = false
}
super.onCreate(savedInstanceState)
installSplashScreen().apply { val viewModel by viewModels<AppViewModel>()
setKeepOnScreenCondition { !viewModel.appViewState.value.isAppReady }
}
setContent { installSplashScreen().apply {
val isTv = isRunningOnTv() setKeepOnScreenCondition {
val appUiState by viewModel.uiState.collectAsStateWithLifecycle() !viewModel.isAppReady.value
val appViewState by viewModel.appViewState.collectAsStateWithLifecycle() }
val tunnelError by viewModel.tunnelManager.errorEvents.collectAsStateWithLifecycle(null) }
val navController = rememberNavController() setContent {
val backStackEntry by navController.currentBackStackEntryAsState() val appUiState by viewModel.uiState.collectAsStateWithLifecycle()
val navBarState by val configurationChange by viewModel.configurationChange.collectAsStateWithLifecycle()
currentNavBackStackEntryAsNavBarState( val navController = rememberNavController()
navController,
backStackEntry,
viewModel,
appUiState,
appViewState,
)
val snackbar = remember { SnackbarHostState() }
var showVpnPermissionDialog by remember { mutableStateOf(false) }
var vpnPermissionDenied by remember { mutableStateOf(false) }
val vpnActivity = LaunchedEffect(configurationChange) {
rememberLauncherForActivityResult( if (configurationChange) {
ActivityResultContracts.StartActivityForResult(), Intent(this@MainActivity, MainActivity::class.java).also {
onResult = { startActivity(it)
if (it.resultCode != RESULT_OK) { exitProcess(0)
showVpnPermissionDialog = true }
vpnPermissionDenied = true }
} else { }
vpnPermissionDenied = false
showVpnPermissionDialog = false
}
},
)
LaunchedEffect(appUiState.tunnels) { LaunchedEffect(Unit) {
if (!appViewState.isAppReady) { viewModel.getEmitSplitTunnelApps(this@MainActivity)
viewModel.handleEvent(AppEvent.AppReadyCheck(appUiState.tunnels)) }
}
}
val batteryActivity = with(appUiState.appSettings) {
rememberLauncherForActivityResult( LaunchedEffect(isShortcutsEnabled) {
ActivityResultContracts.StartActivityForResult() if (!isShortcutsEnabled) return@LaunchedEffect shortcutManager.removeShortcuts()
) { _: ActivityResult -> shortcutManager.addShortcuts()
viewModel.handleEvent(AppEvent.SetBatteryOptimizeDisableShown) }
} }
LaunchedEffect(tunnelError) { CompositionLocalProvider(LocalNavController provides navController) {
if (tunnelError == null) return@LaunchedEffect SnackbarControllerProvider { host ->
val message = tunnelError!!.second.toStringRes() WireguardAutoTunnelTheme(theme = appUiState.generalState.theme) {
val context = this@MainActivity Scaffold(
snackbar.showSnackbar( contentWindowInsets = WindowInsets(0),
context.getString(R.string.tunnel_error_template, context.getString(message)) snackbarHost = {
) SnackbarHost(host) { snackbarData: SnackbarData ->
} CustomSnackBar(
snackbarData.visuals.message,
isRtl = false,
containerColor =
MaterialTheme.colorScheme.surfaceColorAtElevation(
2.dp,
),
)
}
},
bottomBar = {
BottomNavBar(
navController,
listOf(
BottomNavItem(
name = stringResource(R.string.tunnels),
route = Route.Main,
icon = Icons.Rounded.Home,
),
BottomNavItem(
name = stringResource(R.string.settings),
route = Route.Settings,
icon = Icons.Rounded.Settings,
),
BottomNavItem(
name = stringResource(R.string.support),
route = Route.Support,
icon = Icons.Rounded.QuestionMark,
),
),
)
},
) { padding ->
Box(modifier = Modifier.Companion.fillMaxSize().padding(padding)) {
NavHost(
navController,
enterTransition = { fadeIn(tween(Constants.TRANSITION_ANIMATION_TIME)) },
exitTransition = { fadeOut(tween(Constants.TRANSITION_ANIMATION_TIME)) },
startDestination = (if (appUiState.generalState.isPinLockEnabled) Route.Lock else Route.Main),
) {
composable<Route.Main> {
MainScreen(
uiState = appUiState,
)
}
composable<Route.Settings> {
SettingsScreen(
appViewModel = viewModel,
uiState = appUiState,
)
}
composable<Route.LocationDisclosure> {
LocationDisclosureScreen(viewModel, appUiState)
}
composable<Route.AutoTunnel> {
AutoTunnelScreen(
appUiState.appSettings,
)
}
composable<Route.Appearance> {
AppearanceScreen()
}
composable<Route.Language> {
LanguageScreen(appUiState, viewModel)
}
composable<Route.Display> {
DisplayScreen(appUiState)
}
composable<Route.Support> {
SupportScreen(appUiState, viewModel)
}
composable<Route.AutoTunnelAdvanced> {
AdvancedScreen(appUiState.appSettings, viewModel)
}
composable<Route.Logs> {
LogsScreen()
}
composable<Route.Config> { backStack ->
val args = backStack.toRoute<Route.Config>()
val config =
appUiState.tunnels.firstOrNull { it.id == args.id }
ConfigScreen(config, viewModel)
}
composable<Route.TunnelOptions> { backStack ->
val args = backStack.toRoute<Route.TunnelOptions>()
appUiState.tunnels.firstOrNull { it.id == args.id }?.let { config ->
OptionsScreen(config, appUiState)
}
}
composable<Route.Lock> {
PinLockScreen(viewModel)
}
composable<Route.Scanner> {
ScannerScreen()
}
composable<Route.KillSwitch> {
KillSwitchScreen(appUiState, viewModel)
}
composable<Route.SplitTunnel> { backStack ->
val args = backStack.toRoute<Route.SplitTunnel>()
appUiState.tunnels.firstOrNull { it.id == args.id }?.let {
SplitTunnelScreen(it, viewModel)
}
}
composable<Route.TunnelAutoTunnel> { backStack ->
val args = backStack.toRoute<Route.TunnelOptions>()
appUiState.tunnels.firstOrNull { it.id == args.id }?.let {
TunnelAutoTunnelScreen(it, appUiState.appSettings)
}
}
}
BackHandler {
if (navController.previousBackStackEntry == null || !navController.popBackStack()) {
this@MainActivity.finish()
}
}
}
}
}
}
}
}
}
override fun onResume() {
super.onResume()
checkPermissionAndNotify()
}
with(appViewState) { private fun checkPermissionAndNotify() {
LaunchedEffect(isConfigChanged) { val hasLocation = ContextCompat.checkSelfPermission(
if (isConfigChanged) { this,
Intent(this@MainActivity, MainActivity::class.java).also { Manifest.permission.ACCESS_FINE_LOCATION,
startActivity(it) ) == PackageManager.PERMISSION_GRANTED
exitProcess(0) if (lastLocationPermissionState != hasLocation) {
} Timber.d("Location permission changed to: $hasLocation")
} if (hasLocation) {
} networkMonitor.sendLocationPermissionsGrantedBroadcast()
LaunchedEffect(errorMessage) { }
errorMessage?.let { lastLocationPermissionState = hasLocation
snackbar.showSnackbar(it.asString(this@MainActivity)) }
viewModel.handleEvent(AppEvent.MessageShown) }
}
}
LaunchedEffect(popBackStack) {
if (popBackStack) {
navController.popBackStack()
viewModel.handleEvent(AppEvent.PopBackStack(false))
}
}
LaunchedEffect(requestVpnPermission) {
if (requestVpnPermission) {
if (!vpnPermissionDenied) {
vpnActivity.launch(VpnService.prepare(this@MainActivity))
} else {
showVpnPermissionDialog = true
}
viewModel.handleEvent(AppEvent.VpnPermissionRequested)
}
}
LaunchedEffect(requestBatteryPermission) {
if (requestBatteryPermission) {
batteryActivity.launch(
Intent().apply {
action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
data = "package:${this@MainActivity.packageName}".toUri()
}
)
}
}
}
CompositionLocalProvider(LocalIsAndroidTV provides isTv) {
CompositionLocalProvider(LocalNavController provides navController) {
WireguardAutoTunnelTheme(theme = appUiState.appState.theme) {
VpnDeniedDialog(
showVpnPermissionDialog,
onDismiss = {
showVpnPermissionDialog = false
vpnPermissionDenied = false
},
)
Scaffold(
modifier =
Modifier.pointerInput(Unit) {
detectTapGestures {
viewModel.handleEvent(AppEvent.ClearSelectedTunnels)
}
},
snackbarHost = {
SnackbarHost(snackbar) { snackbarData: SnackbarData ->
CustomSnackBar(
snackbarData.visuals.message,
isRtl = false,
containerColor =
MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp),
)
}
},
topBar = { DynamicTopAppBar(navBarState) },
bottomBar = {
AnimatedVisibility(
visible = navBarState.showBottom,
enter = slideInVertically(initialOffsetY = { it }),
exit = slideOutVertically(targetOffsetY = { it }),
) {
BottomNavbar(appUiState = appUiState)
}
},
) { padding ->
Box(
modifier =
Modifier.fillMaxSize()
.background(MaterialTheme.colorScheme.surface)
.padding(padding)
.consumeWindowInsets(padding)
.imePadding()
) {
NavHost(
navController,
startDestination =
(if (appUiState.appState.isPinLockEnabled) Route.Lock
else Route.Main),
) {
composable<Route.Main> {
MainScreen(appUiState, appViewState, viewModel)
}
composable<Route.Settings> {
SettingsScreen(appUiState, viewModel)
}
composable<Route.SettingsAdvanced> {
SettingsAdvancedScreen(appUiState, viewModel)
}
composable<Route.LocationDisclosure> {
LocationDisclosureScreen(appUiState, viewModel)
}
composable<Route.AutoTunnel> {
AutoTunnelScreen(appUiState, viewModel)
}
composable<Route.Appearance> { AppearanceScreen() }
composable<Route.Language> {
LanguageScreen(appUiState, viewModel)
}
composable<Route.Display> {
DisplayScreen(appUiState, viewModel)
}
composable<Route.Support> {
SupportScreen(appViewModel = viewModel)
}
composable<Route.License> { LicenseScreen() }
composable<Route.AutoTunnelAdvanced> {
AutoTunnelAdvancedScreen(appUiState, viewModel)
}
composable<Route.Logs> { LogsScreen(appViewState, viewModel) }
composable<Route.Config> { backStack ->
val args = backStack.toRoute<Route.Config>()
val config =
appUiState.tunnels.firstOrNull { it.id == args.id }
ConfigScreen(config, viewModel)
}
composable<Route.TunnelOptions> { backStack ->
val args = backStack.toRoute<Route.TunnelOptions>()
appUiState.tunnels
.firstOrNull { it.id == args.id }
?.let { config ->
TunnelOptionsScreen(config, viewModel, appViewState)
}
}
composable<Route.Lock> { PinLockScreen(viewModel) }
composable<Route.KillSwitch> {
KillSwitchScreen(appUiState, viewModel)
}
composable<Route.SplitTunnel> { SplitTunnelScreen(viewModel) }
composable<Route.TunnelAutoTunnel> { backStack ->
val args = backStack.toRoute<Route.TunnelOptions>()
appUiState.tunnels
.firstOrNull { it.id == args.id }
?.let {
TunnelAutoTunnelScreen(
it,
appUiState.appSettings,
viewModel,
)
}
}
}
}
}
}
}
}
}
}
override fun onResume() {
super.onResume()
checkPermissionAndNotify()
}
private fun checkPermissionAndNotify() {
val hasLocation =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED
if (lastLocationPermissionState != hasLocation) {
Timber.d("Location permission changed to: $hasLocation")
if (hasLocation) {
networkMonitor.sendLocationPermissionsGrantedBroadcast()
}
lastLocationPermissionState = hasLocation
}
}
} }
@@ -19,116 +19,123 @@ import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil 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 javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
@HiltAndroidApp @HiltAndroidApp
class WireGuardAutoTunnel : Application(), Configuration.Provider { class WireGuardAutoTunnel : Application(), Configuration.Provider {
@Inject lateinit var workerFactory: HiltWorkerFactory @Inject
lateinit var workerFactory: HiltWorkerFactory
override val workManagerConfiguration: Configuration override val workManagerConfiguration: Configuration
get() = Configuration.Builder().setWorkerFactory(workerFactory).build() get() = Configuration.Builder()
.setWorkerFactory(workerFactory)
.build()
@Inject @ApplicationScope lateinit var applicationScope: CoroutineScope @Inject
@ApplicationScope
lateinit var applicationScope: CoroutineScope
@Inject lateinit var logReader: LogReader @Inject
lateinit var logReader: LogReader
@Inject lateinit var appDataRepository: AppDataRepository @Inject
lateinit var appDataRepository: AppDataRepository
@Inject @IoDispatcher lateinit var ioDispatcher: CoroutineDispatcher @Inject
@IoDispatcher
lateinit var ioDispatcher: CoroutineDispatcher
@Inject @MainDispatcher lateinit var mainDispatcher: CoroutineDispatcher @Inject
@MainDispatcher
lateinit var mainDispatcher: CoroutineDispatcher
@Inject lateinit var tunnelManager: TunnelManager @Inject
lateinit var tunnelManager: TunnelManager
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
instance = this instance = this
ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver()) ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver())
if (BuildConfig.DEBUG) { if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree()) Timber.plant(Timber.DebugTree())
StrictMode.setThreadPolicy( StrictMode.setThreadPolicy(
ThreadPolicy.Builder() ThreadPolicy.Builder()
.detectDiskReads() .detectDiskReads()
.detectDiskWrites() .detectDiskWrites()
.detectNetwork() .detectNetwork()
.penaltyLog() .penaltyLog()
.build() .build(),
) )
} else { } else {
Timber.plant(ReleaseTree()) Timber.plant(ReleaseTree())
} }
GoBackend.setAlwaysOnCallback { GoBackend.setAlwaysOnCallback {
applicationScope.launch { applicationScope.launch {
val settings = appDataRepository.settings.get() val settings = appDataRepository.settings.get()
if (settings.isAlwaysOnVpnEnabled) { if (settings.isAlwaysOnVpnEnabled) {
val tunnel = appDataRepository.getPrimaryOrFirstTunnel() val tunnel = appDataRepository.getPrimaryOrFirstTunnel()
tunnel?.let { tunnelManager.startTunnel(it) } tunnel?.let {
} else { tunnelManager.startTunnel(it)
Timber.w("Always-on VPN is not enabled in app settings") }
} } else {
} Timber.Forest.w("Always-on VPN is not enabled in app settings")
} }
}
}
ServiceWorker.start(this) ServiceWorker.start(this)
applicationScope.launch { applicationScope.launch {
appDataRepository.appState.getLocale()?.let { withContext(mainDispatcher) {
withContext(mainDispatcher) { LocaleUtil.changeLocale(it) } if (appDataRepository.appState.isLocalLogsEnabled() && !isRunningOnTv()) logReader.start()
} }
appDataRepository.appState.isLocalLogsEnabled().let { enabled -> if (!appDataRepository.settings.get().isKernelEnabled) {
if (enabled) logReader.start() tunnelManager.setBackendState(BackendState.SERVICE_ACTIVE, emptyList())
} }
} appDataRepository.appState.getLocale()?.let {
} withContext(mainDispatcher) {
LocaleUtil.changeLocale(it)
}
}
}
}
override fun onTerminate() { override fun onTerminate() {
applicationScope.launch { applicationScope.launch {
tunnelManager.setBackendState(BackendState.INACTIVE, emptyList()) tunnelManager.setBackendState(BackendState.SERVICE_ACTIVE, emptyList())
} }
super.onTerminate() super.onTerminate()
} }
class AppLifecycleObserver : DefaultLifecycleObserver { class AppLifecycleObserver : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) { override fun onStart(owner: LifecycleOwner) {
Timber.d("Application entered foreground") Timber.d("Application entered foreground")
foreground = true foreground = true
} }
override fun onPause(owner: LifecycleOwner) {
Timber.d("Application entered background")
foreground = false
}
}
override fun onPause(owner: LifecycleOwner) { companion object {
Timber.d("Application entered background") private var foreground = false
foreground = false
}
}
companion object { fun isForeground(): Boolean {
private var foreground = false return foreground
}
fun isForeground(): Boolean { lateinit var instance: WireGuardAutoTunnel
return foreground private set
} }
@Volatile private var lastActiveTunnels: List<Int> = emptyList()
@Synchronized
fun getLastActiveTunnels(): List<Int> {
return lastActiveTunnels
}
@Synchronized
fun setLastActiveTunnels(newTunnels: List<Int>) {
lastActiveTunnels = newTunnels
}
lateinit var instance: WireGuardAutoTunnel
private set
}
} }
@@ -3,40 +3,47 @@ package com.zaneschepke.wireguardautotunnel.core.broadcast
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.domain.repository.TunnelRepository
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class KernelReceiver : BroadcastReceiver() { class KernelReceiver : BroadcastReceiver() {
@Inject @ApplicationScope lateinit var applicationScope: CoroutineScope @Inject
@ApplicationScope
lateinit var applicationScope: CoroutineScope
@Inject lateinit var tunnelRepository: TunnelRepository @Inject
lateinit var tunnelRepository: TunnelRepository
@Inject lateinit var serviceManager: ServiceManager @Inject
lateinit var serviceManager: ServiceManager
@Inject lateinit var tunnelManager: TunnelManager @Inject
lateinit var tunnelManager: TunnelManager
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
val action = intent.action ?: return val action = intent.action ?: return
applicationScope.launch { applicationScope.launch {
if (action == REFRESH_TUNNELS_ACTION) { if (action == REFRESH_TUNNELS_ACTION) {
tunnelManager.runningTunnelNames().forEach { name -> tunnelManager.runningTunnelNames().forEach { name ->
val tunnel = tunnelRepository.findByTunnelName(name) val tunnel = tunnelRepository.findByTunnelName(name)
tunnel?.let { tunnelRepository.save(it.copy(isActive = true)) } tunnel?.let {
} tunnelRepository.save(it.copy(isActive = true))
serviceManager.updateTunnelTile() }
} }
} serviceManager.updateTunnelTile()
} }
}
}
companion object { companion object {
const val REFRESH_TUNNELS_ACTION = "com.wireguard.android.action.REFRESH_TUNNEL_STATES" const val REFRESH_TUNNELS_ACTION = "com.wireguard.android.action.REFRESH_TUNNEL_STATES"
} }
} }
@@ -4,42 +4,43 @@ import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class NotificationActionReceiver : BroadcastReceiver() { class NotificationActionReceiver : BroadcastReceiver() {
@Inject lateinit var serviceManager: ServiceManager @Inject
lateinit var serviceManager: ServiceManager
@Inject lateinit var tunnelManager: TunnelManager @Inject
lateinit var tunnelManager: TunnelManager
@Inject lateinit var tunnelRepository: TunnelRepository @Inject
lateinit var tunnelRepository: TunnelRepository
@Inject @ApplicationScope lateinit var applicationScope: CoroutineScope @Inject
@ApplicationScope
lateinit var applicationScope: CoroutineScope
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
applicationScope.launch { applicationScope.launch {
when (intent.action) { when (intent.action) {
NotificationAction.AUTO_TUNNEL_OFF.name -> serviceManager.stopAutoTunnel() NotificationAction.AUTO_TUNNEL_OFF.name -> serviceManager.stopAutoTunnel()
NotificationAction.TUNNEL_OFF.name -> { NotificationAction.TUNNEL_OFF.name -> {
val tunnelId = intent.getIntExtra(NotificationManager.EXTRA_ID, 0) val tunnelId = intent.getIntExtra(NotificationManager.EXTRA_ID, 0)
if (tunnelId == STOP_ALL_TUNNELS_ID) return@launch tunnelManager.stopTunnel() if (tunnelId == 0) return@launch tunnelManager.stopTunnel()
val tunnel = tunnelRepository.getById(tunnelId) val tunnel = tunnelRepository.getById(tunnelId)
tunnelManager.stopTunnel(tunnel) tunnelManager.stopTunnel(tunnel)
} }
} }
} }
} }
companion object {
const val STOP_ALL_TUNNELS_ID = 0
}
} }
@@ -1,96 +0,0 @@
package com.zaneschepke.wireguardautotunnel.core.broadcast
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.util.Constants
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import timber.log.Timber
@AndroidEntryPoint
class RemoteControlReceiver : BroadcastReceiver() {
@Inject @ApplicationScope lateinit var applicationScope: CoroutineScope
@Inject lateinit var appDataRepository: AppDataRepository
@Inject lateinit var serviceManager: ServiceManager
@Inject lateinit var tunnelManager: TunnelManager
enum class Action(private val suffix: String) {
START_TUNNEL("START_TUNNEL"),
STOP_TUNNEL("STOP_TUNNEL"),
START_AUTO_TUNNEL("START_AUTO_TUNNEL"),
STOP_AUTO_TUNNEL("STOP_AUTO_TUNNEL");
fun getFullAction(): String {
return "${Constants.BASE_PACKAGE}.$suffix"
}
companion object {
fun fromAction(action: String): Action? {
for (a in entries) {
if (a.getFullAction() == action) {
return a
}
}
return null
}
}
}
override fun onReceive(context: Context, intent: Intent) {
Timber.i("onReceive")
val action = intent.action ?: return
val appAction = Action.fromAction(action) ?: return Timber.w("Unknown action $action")
applicationScope.launch {
if (!appDataRepository.appState.isRemoteControlEnabled())
return@launch Timber.w("Remote control disabled")
val key =
appDataRepository.appState.getRemoteKey()
?: return@launch Timber.w("Remote control key missing")
if (key != intent.getStringExtra(EXTRA_KEY)?.trim())
return@launch Timber.w("Invalid remote control key")
when (appAction) {
Action.START_TUNNEL -> {
val tunnelName =
intent.getStringExtra(EXTRA_TUN_NAME) ?: return@launch startDefaultTunnel()
val tunnel =
appDataRepository.tunnels.findByTunnelName(tunnelName)
?: return@launch startDefaultTunnel()
tunnelManager.startTunnel(tunnel)
}
Action.STOP_TUNNEL -> {
val tunnelName =
intent.getStringExtra(EXTRA_TUN_NAME)
?: return@launch tunnelManager.stopTunnel()
val tunnel =
appDataRepository.tunnels.findByTunnelName(tunnelName)
?: return@launch tunnelManager.stopTunnel()
tunnelManager.stopTunnel(tunnel)
}
Action.START_AUTO_TUNNEL -> serviceManager.startAutoTunnel()
Action.STOP_AUTO_TUNNEL -> serviceManager.stopAutoTunnel()
}
}
}
private suspend fun startDefaultTunnel() {
appDataRepository.getPrimaryOrFirstTunnel()?.let { tunnel ->
tunnelManager.startTunnel(tunnel)
}
}
companion object {
const val EXTRA_TUN_NAME = "tunnelName"
const val EXTRA_KEY = "key"
}
}
@@ -3,53 +3,62 @@ package com.zaneschepke.wireguardautotunnel.core.broadcast
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.logcatter.LogReader import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class RestartReceiver : BroadcastReceiver() { class RestartReceiver : BroadcastReceiver() {
@Inject lateinit var appDataRepository: AppDataRepository @Inject
lateinit var appDataRepository: AppDataRepository
@Inject @ApplicationScope lateinit var applicationScope: CoroutineScope @Inject
@ApplicationScope
lateinit var applicationScope: CoroutineScope
@Inject lateinit var serviceManager: ServiceManager @Inject
lateinit var serviceManager: ServiceManager
@Inject lateinit var tunnelManager: TunnelManager @Inject
lateinit var tunnelManager: TunnelManager
@Inject lateinit var logReader: LogReader @Inject
@IoDispatcher
lateinit var ioDispatcher: CoroutineDispatcher
@Inject @IoDispatcher lateinit var ioDispatcher: CoroutineDispatcher override fun onReceive(context: Context, intent: Intent) {
val action = intent.action ?: return
if (action != Intent.ACTION_BOOT_COMPLETED &&
action != Intent.ACTION_MY_PACKAGE_REPLACED &&
action != "com.htc.intent.action.QUICKBOOT_POWERON"
) {
return
}
override fun onReceive(context: Context, intent: Intent) { Timber.d("RestartReceiver triggered with action: ${intent.action}")
Timber.d("RestartReceiver triggered with action: ${intent.action}") applicationScope.launch(ioDispatcher) {
serviceManager.updateTunnelTile() serviceManager.updateTunnelTile()
serviceManager.updateAutoTunnelTile() serviceManager.updateAutoTunnelTile()
applicationScope.launch(ioDispatcher) { val settings = appDataRepository.settings.get()
val settings = appDataRepository.settings.get() if (settings.isRestoreOnBootEnabled) {
if (settings.isRestoreOnBootEnabled) { if (settings.isAutoTunnelEnabled && !serviceManager.autoTunnelActive.value) {
if ( Timber.d("Starting auto-tunnel on boot/update")
settings.isAutoTunnelEnabled && serviceManager.autoTunnelService.value == null serviceManager.startAutoTunnel(true)
) { } else {
Timber.d("Starting auto-tunnel on boot/update") Timber.d("Restoring previous tunnel state")
serviceManager.startAutoTunnel() tunnelManager.restorePreviousState()
} else { }
Timber.d("Restoring previous tunnel state") } else {
tunnelManager.restorePreviousState() Timber.d("Restore on boot disabled, skipping")
} }
} else { }
Timber.d("Restore on boot disabled, skipping") }
}
if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) logReader.deleteAndClearLogs()
}
}
} }
@@ -4,47 +4,44 @@ import android.app.Notification
import android.app.NotificationManager import android.app.NotificationManager
import android.content.Context import android.content.Context
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification.NotificationChannels
import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction
import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification.NotificationChannels
import com.zaneschepke.wireguardautotunnel.util.StringValue import com.zaneschepke.wireguardautotunnel.util.StringValue
interface NotificationManager { interface NotificationManager {
val context: Context val context: Context
fun createNotification(
channel: NotificationChannels,
title: String = "",
actions: Collection<NotificationCompat.Action> = emptyList(),
description: String = "",
showTimestamp: Boolean = false,
importance: Int = NotificationManager.IMPORTANCE_HIGH,
onGoing: Boolean = true,
onlyAlertOnce: Boolean = true,
): Notification
fun createNotification( fun createNotification(
channel: NotificationChannels, channel: NotificationChannels,
title: String = "", title: StringValue,
actions: Collection<NotificationCompat.Action> = emptyList(), actions: Collection<NotificationCompat.Action> = emptyList(),
description: String = "", description: StringValue,
showTimestamp: Boolean = false, showTimestamp: Boolean = false,
importance: Int = NotificationManager.IMPORTANCE_HIGH, importance: Int = NotificationManager.IMPORTANCE_HIGH,
onGoing: Boolean = true, onGoing: Boolean = true,
onlyAlertOnce: Boolean = true, onlyAlertOnce: Boolean = true,
): Notification ): Notification
fun createNotification( fun createNotificationAction(notificationAction: NotificationAction, extraId: Int? = null): NotificationCompat.Action
channel: NotificationChannels,
title: StringValue,
actions: Collection<NotificationCompat.Action> = emptyList(),
description: StringValue,
showTimestamp: Boolean = false,
importance: Int = NotificationManager.IMPORTANCE_HIGH,
onGoing: Boolean = true,
onlyAlertOnce: Boolean = true,
): Notification
fun createNotificationAction( fun remove(notificationId: Int)
notificationAction: NotificationAction,
extraId: Int? = null,
): NotificationCompat.Action
fun remove(notificationId: Int) fun show(notificationId: Int, notification: Notification)
fun show(notificationId: Int, notification: Notification) companion object {
const val KERNEL_SERVICE_NOTIFICATION_ID = 123
companion object { const val AUTO_TUNNEL_NOTIFICATION_ID = 122
const val AUTO_TUNNEL_NOTIFICATION_ID = 122 const val VPN_NOTIFICATION_ID = 100
const val VPN_NOTIFICATION_ID = 100 const val EXTRA_ID = "id"
const val EXTRA_ID = "id" }
}
} }
@@ -12,165 +12,158 @@ import android.graphics.Color
import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat
import com.zaneschepke.wireguardautotunnel.MainActivity
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.core.broadcast.NotificationActionReceiver import com.zaneschepke.wireguardautotunnel.core.broadcast.NotificationActionReceiver
import com.zaneschepke.wireguardautotunnel.MainActivity
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager.Companion.EXTRA_ID import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager.Companion.EXTRA_ID
import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction
import com.zaneschepke.wireguardautotunnel.util.StringValue import com.zaneschepke.wireguardautotunnel.util.StringValue
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 override val context: Context) : class WireGuardNotification
com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager { @Inject
constructor(
@ApplicationContext override val context: Context,
) : com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager {
enum class NotificationChannels { enum class NotificationChannels {
VPN, VPN,
AUTO_TUNNEL, AUTO_TUNNEL,
} }
private val notificationManager = NotificationManagerCompat.from(context) private val notificationManager = NotificationManagerCompat.from(context)
override fun createNotification( override fun createNotification(
channel: NotificationChannels, channel: NotificationChannels,
title: String, title: String,
actions: Collection<NotificationCompat.Action>, actions: Collection<NotificationCompat.Action>,
description: String, description: String,
showTimestamp: Boolean, showTimestamp: Boolean,
importance: Int, importance: Int,
onGoing: Boolean, onGoing: Boolean,
onlyAlertOnce: Boolean, onlyAlertOnce: Boolean,
): Notification { ): Notification {
notificationManager.createNotificationChannel(channel.asChannel()) notificationManager.createNotificationChannel(channel.asChannel())
return channel return channel.asBuilder().apply {
.asBuilder() actions.forEach {
.apply { addAction(it)
actions.forEach { addAction(it) } }
setContentTitle(title) setContentTitle(title)
setContentIntent( setContentIntent(
PendingIntent.getActivity( PendingIntent.getActivity(
context, context,
0, 0,
Intent(context, MainActivity::class.java), Intent(context, MainActivity::class.java),
PendingIntent.FLAG_IMMUTABLE, PendingIntent.FLAG_IMMUTABLE,
) ),
) )
setContentText(description) setContentText(description)
setOnlyAlertOnce(onlyAlertOnce) setOnlyAlertOnce(onlyAlertOnce)
setOngoing(onGoing) setOngoing(onGoing)
setPriority(NotificationCompat.PRIORITY_HIGH) setPriority(NotificationCompat.PRIORITY_HIGH)
setShowWhen(showTimestamp) setShowWhen(showTimestamp)
setSmallIcon(R.drawable.ic_notification) setSmallIcon(R.drawable.ic_launcher)
} }.build()
.build() }
}
override fun createNotification( override fun createNotification(
channel: NotificationChannels, channel: NotificationChannels,
title: StringValue, title: StringValue,
actions: Collection<NotificationCompat.Action>, actions: Collection<NotificationCompat.Action>,
description: StringValue, description: StringValue,
showTimestamp: Boolean, showTimestamp: Boolean,
importance: Int, importance: Int,
onGoing: Boolean, onGoing: Boolean,
onlyAlertOnce: Boolean, onlyAlertOnce: Boolean,
): Notification { ): Notification {
return createNotification( return createNotification(
channel, channel,
title.asString(context), title.asString(context),
actions, actions,
description.asString(context), description.asString(context),
showTimestamp, showTimestamp,
importance, importance,
onGoing, onGoing,
onlyAlertOnce, onlyAlertOnce,
) )
} }
override fun createNotificationAction( override fun createNotificationAction(notificationAction: NotificationAction, extraId: Int?): NotificationCompat.Action {
notificationAction: NotificationAction, val pendingIntent = PendingIntent.getBroadcast(
extraId: Int?, context,
): NotificationCompat.Action { 0,
val pendingIntent = Intent(context, NotificationActionReceiver::class.java).apply {
PendingIntent.getBroadcast( action = notificationAction.name
context, if (extraId != null) putExtra(EXTRA_ID, extraId)
0, },
Intent(context, NotificationActionReceiver::class.java).apply { PendingIntent.FLAG_IMMUTABLE,
action = notificationAction.name )
if (extraId != null) putExtra(EXTRA_ID, extraId) return NotificationCompat.Action.Builder(
}, R.drawable.ic_launcher,
PendingIntent.FLAG_IMMUTABLE, notificationAction.title(context).uppercase(),
) pendingIntent,
return NotificationCompat.Action.Builder( ).build()
R.drawable.ic_notification, }
notificationAction.title(context).uppercase(),
pendingIntent,
)
.build()
}
override fun remove(notificationId: Int) { override fun remove(notificationId: Int) {
notificationManager.cancel(notificationId) notificationManager.cancel(notificationId)
} }
override fun show(notificationId: Int, notification: Notification) { override fun show(notificationId: Int, notification: Notification) {
with(notificationManager) { with(notificationManager) {
if ( if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.checkSelfPermission( return
context, }
Manifest.permission.POST_NOTIFICATIONS, notify(notificationId, notification)
) != PackageManager.PERMISSION_GRANTED }
) { }
return
}
notify(notificationId, notification)
}
}
private fun NotificationChannels.asBuilder(): NotificationCompat.Builder { private fun NotificationChannels.asBuilder(): NotificationCompat.Builder {
return when (this) { return when (this) {
NotificationChannels.AUTO_TUNNEL -> { NotificationChannels.AUTO_TUNNEL -> {
NotificationCompat.Builder( NotificationCompat.Builder(
context, context,
context.getString(R.string.auto_tunnel_channel_id), context.getString(R.string.auto_tunnel_channel_id),
) )
} }
NotificationChannels.VPN -> { NotificationChannels.VPN -> {
NotificationCompat.Builder(context, context.getString(R.string.vpn_channel_id)) NotificationCompat.Builder(
} context,
} context.getString(R.string.vpn_channel_id),
} )
}
}
}
private fun NotificationChannels.asChannel(): NotificationChannel { private fun NotificationChannels.asChannel(): NotificationChannel {
return when (this) { return when (this) {
NotificationChannels.VPN -> { NotificationChannels.VPN -> {
NotificationChannel( NotificationChannel(
context.getString(R.string.vpn_channel_id), context.getString(R.string.vpn_channel_id),
context.getString(R.string.vpn_channel_name), context.getString(R.string.vpn_channel_name),
NotificationManager.IMPORTANCE_HIGH, NotificationManager.IMPORTANCE_HIGH,
) ).apply {
.apply { description = context.getString(R.string.vpn_channel_description)
description = context.getString(R.string.vpn_channel_description) enableLights(true)
enableLights(true) lightColor = Color.WHITE
lightColor = Color.WHITE enableVibration(false)
enableVibration(false) vibrationPattern = longArrayOf(100, 200, 300)
vibrationPattern = longArrayOf(100, 200, 300) }
} }
} NotificationChannels.AUTO_TUNNEL -> {
NotificationChannels.AUTO_TUNNEL -> { NotificationChannel(
NotificationChannel( context.getString(R.string.auto_tunnel_channel_id),
context.getString(R.string.auto_tunnel_channel_id), context.getString(R.string.auto_tunnel_channel_name),
context.getString(R.string.auto_tunnel_channel_name), NotificationManager.IMPORTANCE_HIGH,
NotificationManager.IMPORTANCE_HIGH, ).apply {
) description = context.getString(R.string.auto_tunnel_channel_description)
.apply { enableLights(true)
description = context.getString(R.string.auto_tunnel_channel_description) lightColor = Color.WHITE
enableLights(true) enableVibration(false)
lightColor = Color.WHITE vibrationPattern = longArrayOf(100, 200, 300)
enableVibration(false) }
vibrationPattern = longArrayOf(100, 200, 300) }
} }
} }
}
}
} }
@@ -1,150 +1,142 @@
package com.zaneschepke.wireguardautotunnel.core.service package com.zaneschepke.wireguardautotunnel.core.service
import android.content.ComponentName import android.app.Service
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.ServiceConnection
import android.net.VpnService
import android.os.IBinder
import com.zaneschepke.wireguardautotunnel.core.service.autotunnel.AutoTunnelService import com.zaneschepke.wireguardautotunnel.core.service.autotunnel.AutoTunnelService
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.di.MainDispatcher import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
import jakarta.inject.Inject import jakarta.inject.Inject
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
class ServiceManager class ServiceManager @Inject constructor(
@Inject private val context: Context,
constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val context: Context, @ApplicationScope private val applicationScope: CoroutineScope,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, private val appDataRepository: AppDataRepository,
@ApplicationScope private val applicationScope: CoroutineScope,
@MainDispatcher private val mainDispatcher: CoroutineDispatcher,
private val appDataRepository: AppDataRepository,
) { ) {
private val autoTunnelMutex = Mutex() private val _autoTunnelActive = MutableStateFlow(false)
val autoTunnelActive = _autoTunnelActive.asStateFlow()
private val _tunnelService = MutableStateFlow<TunnelForegroundService?>(null) var autoTunnelService = CompletableDeferred<AutoTunnelService>()
private val _autoTunnelService = MutableStateFlow<AutoTunnelService?>(null) var backgroundService = CompletableDeferred<TunnelForegroundService>()
val autoTunnelService = _autoTunnelService.asStateFlow()
private val tunnelServiceConnection = private fun <T : Service> startService(cls: Class<T>, background: Boolean) {
object : ServiceConnection { runCatching {
override fun onServiceConnected(name: ComponentName, service: IBinder) { val intent = Intent(context, cls)
val binder = service as? TunnelForegroundService.LocalBinder if (background) {
_tunnelService.value = binder?.service context.startForegroundService(intent)
Timber.d("TunnelForegroundService connected") } else {
} context.startService(intent)
}
}.onFailure { Timber.e(it) }
}
override fun onServiceDisconnected(name: ComponentName) { fun startAutoTunnel(background: Boolean) {
_tunnelService.value = null applicationScope.launch(ioDispatcher) {
Timber.d("TunnelForegroundService disconnected") val settings = appDataRepository.settings.get()
} appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = true))
} if (autoTunnelService.isCompleted) {
_autoTunnelActive.update { true }
return@launch
}
runCatching {
autoTunnelService = CompletableDeferred()
startService(AutoTunnelService::class.java, background)
_autoTunnelActive.update { true }
}.onFailure {
Timber.e(it)
_autoTunnelActive.update { false }
}
}
updateAutoTunnelTile()
}
private val autoTunnelServiceConnection = fun startTunnelForegroundService(tunnelConf: TunnelConf) {
object : ServiceConnection { applicationScope.launch(ioDispatcher) {
override fun onServiceConnected(name: ComponentName, service: IBinder) { if (backgroundService.isCompleted) return@launch
val binder = service as? AutoTunnelService.LocalBinder runCatching {
_autoTunnelService.value = binder?.service backgroundService = CompletableDeferred()
Timber.d("AutoTunnelService connected") startService(TunnelForegroundService::class.java, true)
} val service = withTimeoutOrNull(SERVICE_START_TIMEOUT) { backgroundService.await() }
?: throw IllegalStateException("Background service start timed out")
service.start(tunnelConf)
}.onFailure {
Timber.e(it)
}
}
}
override fun onServiceDisconnected(name: ComponentName) { fun updateTunnelForegroundServiceNotification(tunnelConf: TunnelConf) {
_autoTunnelService.value = null applicationScope.launch(ioDispatcher) {
Timber.d("AutoTunnelService disconnected") if (!backgroundService.isCompleted) return@launch
} runCatching {
} val service = backgroundService.await()
service.start(tunnelConf)
}.onFailure {
Timber.e(it)
}
}
}
fun hasVpnPermission(): Boolean { fun stopTunnelForegroundService() {
return VpnService.prepare(context) == null applicationScope.launch(ioDispatcher) {
} if (!backgroundService.isCompleted) return@launch
runCatching {
val service = backgroundService.await()
service.stop()
backgroundService = CompletableDeferred()
}.onFailure {
Timber.e(it)
}
}
}
suspend fun startAutoTunnel() { fun toggleAutoTunnel(background: Boolean) {
autoTunnelMutex.withLock { applicationScope.launch(ioDispatcher) {
val settings = appDataRepository.settings.get() if (_autoTunnelActive.value) stopAutoTunnel() else startAutoTunnel(background)
appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = true)) }
if (_autoTunnelService.value != null) return }
withContext(ioDispatcher) {
val intent = Intent(context, AutoTunnelService::class.java)
context.startForegroundService(intent)
context.bindService(intent, autoTunnelServiceConnection, Context.BIND_AUTO_CREATE)
withContext(mainDispatcher) { updateAutoTunnelTile() }
}
}
}
suspend fun stopAutoTunnel() { fun updateAutoTunnelTile() {
autoTunnelMutex.withLock { context.requestAutoTunnelTileServiceUpdate()
val settings = appDataRepository.settings.get() }
appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = false))
if (_autoTunnelService.value == null) return
_autoTunnelService.value?.let { service ->
service.stop()
try {
context.unbindService(autoTunnelServiceConnection)
} finally {
_tunnelService.value = null
}
}
withContext(mainDispatcher) { updateAutoTunnelTile() }
}
}
suspend fun startTunnelForegroundService() { fun updateTunnelTile() {
if (_tunnelService.value != null) return context.requestTunnelTileServiceStateUpdate()
withContext(ioDispatcher) { }
applicationScope.launch(ioDispatcher) {
val intent = Intent(context, TunnelForegroundService::class.java)
context.startForegroundService(intent)
context.bindService(intent, tunnelServiceConnection, Context.BIND_AUTO_CREATE)
}
}
}
fun stopTunnelForegroundService() { fun stopAutoTunnel() {
_tunnelService.value?.let { service -> applicationScope.launch(ioDispatcher) {
service.stop() val settings = appDataRepository.settings.get()
try { appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = false))
context.unbindService(tunnelServiceConnection) if (!autoTunnelService.isCompleted) return@launch
} finally { runCatching {
_tunnelService.value = null val service = autoTunnelService.await()
} service.stop()
} _autoTunnelActive.update { false }
} autoTunnelService = CompletableDeferred()
updateAutoTunnelTile()
}.onFailure {
Timber.e(it)
}
}
}
fun toggleAutoTunnel() { companion object {
applicationScope.launch(ioDispatcher) { const val SERVICE_START_TIMEOUT = 5_000L
if (_autoTunnelService.value != null) stopAutoTunnel() else startAutoTunnel() }
}
}
fun updateAutoTunnelTile() {
context.requestAutoTunnelTileServiceUpdate()
}
fun updateTunnelTile() {
context.requestTunnelTileServiceStateUpdate()
}
fun handleTunnelServiceDestroy() {
_tunnelService.update { null }
}
fun handleAutoTunnelServiceDestroy() {
_autoTunnelService.update { null }
}
} }
@@ -2,327 +2,69 @@ package com.zaneschepke.wireguardautotunnel.core.service
import android.app.Notification import android.app.Notification
import android.content.Intent import android.content.Intent
import android.os.Binder
import android.os.IBinder import android.os.IBinder
import androidx.core.app.ServiceCompat import androidx.core.app.ServiceCompat
import androidx.lifecycle.LifecycleService import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.networkmonitor.NetworkStatus
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager
import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.extensions.distinctByKeys
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.CompletableDeferred
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import timber.log.Timber
@AndroidEntryPoint @AndroidEntryPoint
class TunnelForegroundService : LifecycleService() { class TunnelForegroundService : LifecycleService() {
@Inject lateinit var notificationManager: NotificationManager @Inject
lateinit var notificationManager: NotificationManager
@Inject lateinit var serviceManager: ServiceManager @Inject
lateinit var serviceManager: ServiceManager
@Inject lateinit var networkMonitor: NetworkMonitor override fun onCreate() {
super.onCreate()
serviceManager.backgroundService.complete(this)
}
@Inject @IoDispatcher lateinit var ioDispatcher: CoroutineDispatcher override fun onBind(intent: Intent): IBinder? {
super.onBind(intent)
return null
}
@Inject lateinit var tunnelRepo: TunnelRepository override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
serviceManager.backgroundService.complete(this)
return super.onStartCommand(intent, flags, startId)
}
@Inject lateinit var tunnelManager: TunnelManager fun start(tunnelConf: TunnelConf) {
ServiceCompat.startForeground(
this@TunnelForegroundService,
NotificationManager.KERNEL_SERVICE_NOTIFICATION_ID,
createNotification(tunnelConf),
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
}
private val isNetworkConnected = MutableStateFlow(true) fun stop() {
stopSelf()
}
private val tunnelJobs = ConcurrentHashMap<TunnelConf, Job>() override fun onDestroy() {
private val pingJobs = ConcurrentHashMap<TunnelConf, Job>() serviceManager.backgroundService = CompletableDeferred()
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
super.onDestroy()
}
private val jobsMutex = Mutex() private fun createNotification(tunnelConf: TunnelConf): Notification {
return notificationManager.createNotification(
class LocalBinder(val service: TunnelForegroundService) : Binder() WireGuardNotification.NotificationChannels.VPN,
title = "${getString(R.string.tunnel_running)} - ${tunnelConf.tunName}",
private val binder = LocalBinder(this) actions = listOf(
notificationManager.createNotificationAction(NotificationAction.TUNNEL_OFF, tunnelConf.id),
override fun onCreate() { ),
super.onCreate() )
ServiceCompat.startForeground( }
this@TunnelForegroundService,
NotificationManager.VPN_NOTIFICATION_ID,
onCreateNotification(),
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
}
override fun onBind(intent: Intent): IBinder {
super.onBind(intent)
return binder
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
ServiceCompat.startForeground(
this@TunnelForegroundService,
NotificationManager.VPN_NOTIFICATION_ID,
onCreateNotification(),
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
start()
return START_STICKY
}
fun start() =
lifecycleScope.launch(ioDispatcher) {
tunnelManager.activeTunnels.distinctByKeys().collect { activeTunnels ->
// No active tunnels and no jobs: nothing to do
if (activeTunnels.isEmpty() && tunnelJobs.isEmpty()) return@collect
// Synchronize jobs with active tunnels
synchronizeJobs(activeTunnels)
updateServiceNotification()
}
}
private suspend fun synchronizeJobs(activeTunnels: Map<TunnelConf, TunnelState>) {
jobsMutex.withLock {
// Stop jobs for tunnels that are no longer active
stopInactiveJobs(activeTunnels)
// Start jobs for new tunnels
startNewJobs(activeTunnels)
}
}
private fun stopInactiveJobs(activeTunnels: Map<TunnelConf, TunnelState>) {
// If no active tunnels, clear all jobs
if (activeTunnels.isEmpty()) {
clearAllJobs()
return
}
// Stop jobs for tunnels not in activeTunnels
val tunnelsToStop = tunnelJobs.keys - activeTunnels.keys
tunnelsToStop.forEach { tun -> stopTunnelJobs(tun) }
}
private fun clearAllJobs() {
tunnelJobs.forEach { (tun, job) ->
Timber.d("Stopping tunnel job for ${tun.tunName}")
job.cancel()
}
tunnelJobs.clear()
pingJobs.forEach { (tun, job) ->
if (isPingBounce(tun)) {
Timber.d("Preserving ping job for ${tun.tunName} due to PING bounce")
return@forEach
}
Timber.d("Stopping ping job for ${tun.tunName}")
job.cancel()
}
pingJobs.entries.removeIf { (tun, _) -> !isPingBounce(tun) }
}
private fun stopTunnelJobs(tun: TunnelConf) {
tunnelJobs.remove(tun)?.cancel()
Timber.d("Stopped tunnel job for ${tun.tunName}")
if (isPingBounce(tun))
return Timber.d("Preserving ${tun.tunName} ping job due to ping bounce")
pingJobs.remove(tun)?.cancel()
Timber.d("Stopped ping job for ${tun.tunName}")
}
private fun startNewJobs(activeTunnels: Map<TunnelConf, TunnelState>) {
val tunnelsToStart = activeTunnels.keys - tunnelJobs.keys
tunnelsToStart.forEach { tun ->
tunnelJobs[tun] = startTunnelJobs(tun)
Timber.d("Started tunnel job for ${tun.tunName}")
if (pingJobs[tun]?.isActive == true) {
Timber.d("Reusing active ping job for ${tun.tunName}")
} else {
pingJobs[tun]?.cancel() // Cancel any stale job
if (tun.isPingEnabled) {
if (tun.isStaticallyConfigured()) {
Timber.d("Skipping ping for statically configured tunnel")
} else {
pingJobs[tun] = startPingJob(tun)
Timber.d("Started ping job for ${tun.tunName}")
}
}
}
}
}
private fun isPingBounce(tun: TunnelConf): Boolean =
tunnelManager.bouncingTunnelIds[tun.id] == TunnelStatus.StopReason.PING
// TODO Would be cool to have this include kill switch
// TODO also we need to include errors
private fun updateServiceNotification() {
val notification =
when (tunnelJobs.size) {
0 -> onCreateNotification()
1 -> createTunnelNotification(tunnelJobs.keys.first())
else -> createTunnelsNotification()
}
ServiceCompat.startForeground(
this@TunnelForegroundService,
NotificationManager.VPN_NOTIFICATION_ID,
notification,
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
}
// use same scope so we can cancel all of these
private fun startTunnelJobs(tunnelConf: TunnelConf) =
lifecycleScope.launch(ioDispatcher) {
// monitor if we have internet connectivity
launch { startNetworkMonitorJob() }
// job to trigger stats emit on interval
launch { startTunnelStatsJob(tunnelConf) }
// monitor changes to the tunnel config
launch { startTunnelConfChangesJob(tunnelConf) }
}
private suspend fun startTunnelConfChangesJob(tunnelConf: TunnelConf) {
tunnelRepo.flow
.flowOn(ioDispatcher)
.map { storedTunnels -> storedTunnels.firstOrNull { it.id == tunnelConf.id } }
.filterNotNull()
// only emit when one of these 3 values change
.distinctUntilChanged { old, new -> old == new }
.collect { storedTunnel ->
if (tunnelConf != storedTunnel) {
Timber.d("Config changed for ${storedTunnel.tunName}, bouncing")
// let this complete, even after cancel
withContext(NonCancellable) {
tunnelManager.bounceTunnel(
storedTunnel,
TunnelStatus.StopReason.CONFIG_CHANGED,
)
}
}
}
}
private suspend fun startNetworkMonitorJob() {
networkMonitor.networkStatusFlow.flowOn(ioDispatcher).collectLatest { status ->
val isAvailable = status !is NetworkStatus.Disconnected
isNetworkConnected.value = isAvailable
Timber.d("Network available: $status")
}
}
private suspend fun startTunnelStatsJob(tunnel: TunnelConf) = coroutineScope {
while (isActive) {
tunnelManager.updateTunnelStatistics(tunnel)
delay(STATS_DELAY)
}
}
private fun startPingJob(tunnel: TunnelConf) =
lifecycleScope.launch(ioDispatcher) {
// delay for initial duration
delay(tunnel.pingInterval ?: Constants.PING_INTERVAL)
while (isActive) {
val shouldBounce = shouldBounceTunnel(tunnel)
val delayMs =
if (shouldBounce) {
// let this complete, even after cancel
withContext(NonCancellable) {
tunnelManager.bounceTunnel(tunnel, TunnelStatus.StopReason.PING)
}
tunnel.pingCooldown ?: Constants.PING_COOLDOWN
} else {
tunnel.pingInterval ?: Constants.PING_INTERVAL
}
delay(delayMs)
}
}
private suspend fun shouldBounceTunnel(tunnel: TunnelConf): Boolean {
if (!isNetworkConnected.value) {
Timber.d("Network disconnected, skipping ping for ${tunnel.tunName}")
return false
}
return runCatching { !tunnel.isTunnelPingable(ioDispatcher) }
.onFailure { e -> Timber.e(e, "Ping check failed for ${tunnel.tunName}") }
.getOrDefault(true)
}
fun stop() {
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
stopSelf()
}
override fun onDestroy() {
serviceManager.handleTunnelServiceDestroy()
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
super.onDestroy()
}
private fun createTunnelNotification(tunnelConf: TunnelConf): Notification {
return notificationManager.createNotification(
WireGuardNotification.NotificationChannels.VPN,
title = "${getString(R.string.tunnel_running)} - ${tunnelConf.tunName}",
actions =
listOf(
notificationManager.createNotificationAction(
NotificationAction.TUNNEL_OFF,
tunnelConf.id,
)
),
)
}
private fun createTunnelsNotification(): Notification {
return notificationManager.createNotification(
WireGuardNotification.NotificationChannels.VPN,
title = "${getString(R.string.tunnel_running)} - ${getString(R.string.multiple)}",
actions =
listOf(
notificationManager.createNotificationAction(NotificationAction.TUNNEL_OFF, 0)
),
)
}
private fun onCreateNotification(): Notification {
return notificationManager.createNotification(
WireGuardNotification.NotificationChannels.VPN,
title = getString(R.string.tunnel_starting),
)
}
// TODO add notification handling and optional log reading for restart on handshake failures
companion object {
const val STATS_DELAY = 1_000L
// ipv6 disabled or block on network
// Failed to send handshake initiation: write udp [::]"
// Failed to send data packets: write udp [::]
// Failed to send data packets: write udp 0.0.0.0:51820
// Handshake did not complete after 5 seconds, retrying
}
} }
@@ -1,7 +1,6 @@
package com.zaneschepke.wireguardautotunnel.core.service.autotunnel package com.zaneschepke.wireguardautotunnel.core.service.autotunnel
import android.content.Intent import android.content.Intent
import android.os.Binder
import android.os.IBinder import android.os.IBinder
import android.os.PowerManager import android.os.PowerManager
import androidx.core.app.ServiceCompat import androidx.core.app.ServiceCompat
@@ -15,8 +14,8 @@ import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotificati
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.di.MainImmediateDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction
import com.zaneschepke.wireguardautotunnel.domain.events.AutoTunnelEvent import com.zaneschepke.wireguardautotunnel.domain.events.AutoTunnelEvent
@@ -27,12 +26,10 @@ import com.zaneschepke.wireguardautotunnel.domain.state.NetworkState
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject import kotlinx.coroutines.CompletableDeferred
import javax.inject.Provider
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combine
@@ -44,235 +41,215 @@ import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
import javax.inject.Provider
@AndroidEntryPoint @AndroidEntryPoint
class AutoTunnelService : LifecycleService() { class AutoTunnelService : LifecycleService() {
@Inject lateinit var networkMonitor: NetworkMonitor @Inject
lateinit var networkMonitor: NetworkMonitor
@Inject lateinit var appDataRepository: Provider<AppDataRepository> @Inject
lateinit var appDataRepository: Provider<AppDataRepository>
@Inject lateinit var notificationManager: NotificationManager @Inject
lateinit var notificationManager: NotificationManager
@Inject @IoDispatcher lateinit var ioDispatcher: CoroutineDispatcher @Inject
@IoDispatcher
lateinit var ioDispatcher: CoroutineDispatcher
@Inject lateinit var serviceManager: ServiceManager @Inject
lateinit var serviceManager: ServiceManager
@Inject lateinit var tunnelManager: TunnelManager @Inject
@MainImmediateDispatcher
lateinit var mainImmediateDispatcher: CoroutineDispatcher
private val defaultState = AutoTunnelState() @Inject
lateinit var tunnelManager: TunnelManager
private val autoTunnelStateFlow = MutableStateFlow(defaultState) private val defaultState = AutoTunnelState()
private var wakeLock: PowerManager.WakeLock? = null private val autoTunnelStateFlow = MutableStateFlow(defaultState)
private var killSwitchJob: Job? = null private var wakeLock: PowerManager.WakeLock? = null
class LocalBinder(val service: AutoTunnelService) : Binder() override fun onCreate() {
super.onCreate()
serviceManager.autoTunnelService.complete(this)
lifecycleScope.launch(mainImmediateDispatcher) {
runCatching {
launchWatcherNotification()
}.onFailure {
Timber.e(it)
}
}
}
private val binder = LocalBinder(this) override fun onBind(intent: Intent): IBinder? {
super.onBind(intent)
return null
}
override fun onCreate() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onCreate() super.onStartCommand(intent, flags, startId)
launchWatcherNotification() Timber.d("onStartCommand executed with startId: $startId")
} serviceManager.autoTunnelService.complete(this)
start()
return START_STICKY
}
override fun onBind(intent: Intent): IBinder { fun start() {
super.onBind(intent) kotlin.runCatching {
return binder lifecycleScope.launch(mainImmediateDispatcher) {
} launchWatcherNotification()
initWakeLock()
}
startAutoTunnelJob()
startAutoTunnelStateJob()
startKillSwitchJob()
}.onFailure {
Timber.e(it)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { fun stop() {
super.onStartCommand(intent, flags, startId) wakeLock?.let { if (it.isHeld) it.release() }
Timber.d("onStartCommand executed with startId: $startId") stopSelf()
start() }
return START_STICKY
}
fun start() { override fun onDestroy() {
kotlin serviceManager.autoTunnelService = CompletableDeferred()
.runCatching { super.onDestroy()
launchWatcherNotification() }
initWakeLock()
startAutoTunnelJob()
startAutoTunnelStateJob()
killSwitchJob = startKillSwitchJob()
}
.onFailure { Timber.e(it) }
}
fun stop() { private fun launchWatcherNotification(description: String = getString(R.string.monitoring_state_changes)) {
wakeLock?.let { if (it.isHeld) it.release() } val notification =
stopSelf() notificationManager.createNotification(
} WireGuardNotification.NotificationChannels.AUTO_TUNNEL,
title = getString(R.string.auto_tunnel_title),
description = description,
actions = listOf(
notificationManager.createNotificationAction(NotificationAction.AUTO_TUNNEL_OFF),
),
)
ServiceCompat.startForeground(
this,
NotificationManager.AUTO_TUNNEL_NOTIFICATION_ID,
notification,
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
}
override fun onDestroy() { private fun initWakeLock() {
serviceManager.handleAutoTunnelServiceDestroy() wakeLock = (getSystemService(POWER_SERVICE) as PowerManager).run {
restoreVpnKillSwitch() val tag = this.javaClass.name
super.onDestroy() 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 restoreVpnKillSwitch() { private fun buildNetworkState(networkStatus: NetworkStatus): NetworkState {
with(autoTunnelStateFlow.value) { return with(autoTunnelStateFlow.value.networkState) {
if ( val wifiName = when (networkStatus) {
settings.isVpnKillSwitchEnabled && is NetworkStatus.Connected -> {
tunnelManager.getBackendState() != BackendState.KILL_SWITCH_ACTIVE networkStatus.wifiSsid
) { }
killSwitchJob?.cancel() else -> null
val allowedIps = }
if (settings.isLanOnKillSwitchEnabled) TunnelConf.LAN_BYPASS_ALLOWED_IPS copy(
else emptyList() isWifiConnected = networkStatus.wifiConnected,
tunnelManager.setBackendState(BackendState.KILL_SWITCH_ACTIVE, allowedIps) isMobileDataConnected = networkStatus.cellularConnected,
} isEthernetConnected = networkStatus.ethernetConnected,
} wifiName = wifiName,
} )
}
}
private fun launchWatcherNotification( @OptIn(ExperimentalCoroutinesApi::class)
description: String = getString(R.string.monitoring_state_changes) private fun startAutoTunnelStateJob() = lifecycleScope.launch(ioDispatcher) {
) { combine(
val notification = combineSettings(),
notificationManager.createNotification( appDataRepository.get().settings.flow
WireGuardNotification.NotificationChannels.AUTO_TUNNEL, .distinctUntilChanged { old, new -> old.isKernelEnabled == new.isKernelEnabled } // Only emit when isKernelEnabled changes
title = getString(R.string.auto_tunnel_title), .flatMapLatest {
description = description, networkMonitor.networkStatusFlow
actions = .flowOn(ioDispatcher)
listOf( .map { buildNetworkState(it) }
notificationManager.createNotificationAction( }
NotificationAction.AUTO_TUNNEL_OFF .distinctUntilChanged(),
) ) { double, networkState ->
), AutoTunnelState(
) tunnelManager.activeTunnels.value,
ServiceCompat.startForeground( networkState,
this, double.first,
NotificationManager.AUTO_TUNNEL_NOTIFICATION_ID, double.second,
notification, )
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID, }.collect { state ->
) autoTunnelStateFlow.update {
} it.copy(
activeTunnels = state.activeTunnels,
networkState = state.networkState,
settings = state.settings,
tunnels = state.tunnels,
)
}
}
}
private fun initWakeLock() { private fun combineSettings(): Flow<Pair<AppSettings, Tunnels>> {
wakeLock = return combine(
(getSystemService(POWER_SERVICE) as PowerManager).run { appDataRepository.get().settings.flow,
val tag = this.javaClass.name appDataRepository.get().tunnels.flow.map { tunnels ->
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply { // isActive is ignored for equality checks so user can manually toggle off tunnel with auto-tunnel
try { tunnels.map { it.copy(isActive = false) }
Timber.i("Initiating wakelock with 10 min timeout") },
acquire(Constants.BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT) ) { settings, tunnels ->
} finally { Pair(settings, tunnels)
release() }.distinctUntilChanged()
} }
}
}
}
private fun buildNetworkState(networkStatus: NetworkStatus): NetworkState { private fun startKillSwitchJob() = lifecycleScope.launch(ioDispatcher) {
return with(autoTunnelStateFlow.value.networkState) { autoTunnelStateFlow.collect {
val wifiName = if (it == defaultState) return@collect
when (networkStatus) { when (val event = it.asKillSwitchEvent()) {
is NetworkStatus.Connected -> { KillSwitchEvent.DoNothing -> Unit
networkStatus.wifiSsid is KillSwitchEvent.Start -> {
} Timber.d("Starting kill switch")
else -> null tunnelManager.setBackendState(BackendState.KILL_SWITCH_ACTIVE, event.allowedIps)
} }
copy( KillSwitchEvent.Stop -> {
isWifiConnected = networkStatus.wifiConnected, Timber.d("Stopping kill switch")
isMobileDataConnected = networkStatus.cellularConnected, tunnelManager.setBackendState(BackendState.SERVICE_ACTIVE, emptySet())
isEthernetConnected = networkStatus.ethernetConnected, }
wifiName = wifiName, }
) }
} }
}
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(FlowPreview::class)
private fun startAutoTunnelStateJob() = private fun startAutoTunnelJob() = lifecycleScope.launch(ioDispatcher) {
lifecycleScope.launch(ioDispatcher) { Timber.i("Starting auto-tunnel network event watcher")
combine( val settings = appDataRepository.get().settings.get()
combineSettings(), Timber.d("Starting with debounce delay of: ${settings.debounceDelaySeconds} seconds")
appDataRepository autoTunnelStateFlow.debounce(settings.debounceDelayMillis()).collect { watcherState ->
.get() if (watcherState == defaultState) return@collect
.settings Timber.d("New auto tunnel state emitted ${watcherState.networkState}")
.flow when (val event = watcherState.asAutoTunnelEvent()) {
.distinctUntilChanged { old, new -> is AutoTunnelEvent.Start -> (event.tunnelConf ?: appDataRepository.get().getPrimaryOrFirstTunnel())?.let {
old.isKernelEnabled == new.isKernelEnabled tunnelManager.startTunnel(it)
} // Only emit when isKernelEnabled changes }
.flatMapLatest { // TODO improve this to target specific tunnels to better support multi-tunnel
networkMonitor.networkStatusFlow.flowOn(ioDispatcher).map { is AutoTunnelEvent.Stop -> tunnelManager.stopTunnel()
buildNetworkState(it) AutoTunnelEvent.DoNothing -> Timber.i("Auto-tunneling: no condition met")
} }
} }
.distinctUntilChanged(), }
) { double, networkState ->
AutoTunnelState(
tunnelManager.activeTunnels.value,
networkState,
double.first,
double.second,
)
}
.collect { state ->
autoTunnelStateFlow.update {
it.copy(
activeTunnels = state.activeTunnels,
networkState = state.networkState,
settings = state.settings,
tunnels = state.tunnels,
)
}
}
}
private fun combineSettings(): Flow<Pair<AppSettings, Tunnels>> {
return combine(
appDataRepository.get().settings.flow,
appDataRepository.get().tunnels.flow.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()
}
private fun startKillSwitchJob() =
lifecycleScope.launch(ioDispatcher) {
autoTunnelStateFlow.collect {
if (it == defaultState) return@collect
when (val event = it.asKillSwitchEvent()) {
KillSwitchEvent.DoNothing -> Unit
is KillSwitchEvent.Start -> {
Timber.d("Starting kill switch")
tunnelManager.setBackendState(
BackendState.KILL_SWITCH_ACTIVE,
event.allowedIps,
)
}
KillSwitchEvent.Stop -> {
Timber.d("Stopping kill switch")
tunnelManager.setBackendState(BackendState.SERVICE_ACTIVE, emptySet())
}
}
}
}
@OptIn(FlowPreview::class)
private fun startAutoTunnelJob() =
lifecycleScope.launch(ioDispatcher) {
Timber.i("Starting auto-tunnel network event watcher")
val settings = appDataRepository.get().settings.get()
Timber.d("Starting with debounce delay of: ${settings.debounceDelaySeconds} seconds")
autoTunnelStateFlow.debounce(settings.debounceDelayMillis()).collect { watcherState ->
if (watcherState == defaultState) return@collect
Timber.d("New auto tunnel state emitted ${watcherState.networkState}")
when (val event = watcherState.asAutoTunnelEvent()) {
is AutoTunnelEvent.Start ->
(event.tunnelConf ?: appDataRepository.get().getPrimaryOrFirstTunnel())
?.let { tunnelManager.startTunnel(it) }
// TODO improve this to target specific tunnels to better support multi-tunnel
is AutoTunnelEvent.Stop -> tunnelManager.stopTunnel()
AutoTunnelEvent.DoNothing -> Timber.i("Auto-tunneling: no condition met")
}
}
}
} }
@@ -8,97 +8,100 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class AutoTunnelControlTile : TileService(), LifecycleOwner { class AutoTunnelControlTile : TileService(), LifecycleOwner {
@Inject lateinit var appDataRepository: AppDataRepository @Inject
lateinit var appDataRepository: AppDataRepository
@Inject lateinit var serviceManager: ServiceManager @Inject
lateinit var serviceManager: ServiceManager
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this) private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
} }
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
} }
override fun onStartListening() { override fun onStartListening() {
super.onStartListening() super.onStartListening()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START) Timber.d("Start listening called for auto tunnel tile")
Timber.d("Start listening called for auto tunnel tile") lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
lifecycleScope.launch { lifecycleScope.launch {
serviceManager.autoTunnelService.collect { serviceManager.autoTunnelActive.collect {
if (it != null) return@collect setActive() if (it) setActive() else setInactive()
setInactive() }
} }
} lifecycleScope.launch {
lifecycleScope.launch { appDataRepository.tunnels.flow.collect {
appDataRepository.tunnels.flow.collect { if (it.isEmpty()) {
if (it.isEmpty()) { setUnavailable()
setUnavailable() } else {
} if (qsTile.state == Tile.STATE_ACTIVE) setInactive()
} }
} }
} }
}
override fun onClick() { override fun onClick() {
super.onClick() super.onClick()
unlockAndRun { unlockAndRun {
lifecycleScope.launch { lifecycleScope.launch {
if (serviceManager.autoTunnelService.value != null) { if (serviceManager.autoTunnelActive.value) {
serviceManager.stopAutoTunnel() serviceManager.stopAutoTunnel()
setInactive() setInactive()
} else { } else {
serviceManager.startAutoTunnel() serviceManager.startAutoTunnel(true)
setActive() setActive()
} }
} }
} }
} }
private fun setActive() { private fun setActive() {
runCatching { runCatching {
qsTile.state = Tile.STATE_ACTIVE qsTile.state = Tile.STATE_ACTIVE
qsTile.updateTile() qsTile.updateTile()
} }
} }
private fun setInactive() { private fun setInactive() {
runCatching { runCatching {
qsTile.state = Tile.STATE_INACTIVE qsTile.state = Tile.STATE_INACTIVE
qsTile.updateTile() qsTile.updateTile()
} }
} }
/* This works around an annoying unsolved frameworks bug some people are hitting. */ /* This works around an annoying unsolved frameworks bug some people are hitting. */
override fun onBind(intent: Intent): IBinder? { override fun onBind(intent: Intent): IBinder? {
var ret: IBinder? = null var ret: IBinder? = null
try { try {
ret = super.onBind(intent) ret = super.onBind(intent)
} catch (_: Throwable) { } catch (_: Throwable) {
Timber.e("Failed to bind to TunnelControlTile") Timber.e("Failed to bind to TunnelControlTile")
} }
return ret return ret
} }
private fun setUnavailable() { private fun setUnavailable() {
runCatching { runCatching {
qsTile.state = Tile.STATE_UNAVAILABLE qsTile.state = Tile.STATE_UNAVAILABLE
qsTile.updateTile() qsTile.updateTile()
} }
} }
override val lifecycle: Lifecycle override val lifecycle: Lifecycle
get() = lifecycleRegistry get() = lifecycleRegistry
} }
@@ -10,175 +10,133 @@ import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class TunnelControlTile : TileService(), LifecycleOwner { class TunnelControlTile : TileService(), LifecycleOwner {
@Inject lateinit var appDataRepository: AppDataRepository @Inject
lateinit var appDataRepository: AppDataRepository
@Inject lateinit var serviceManager: ServiceManager @Inject
lateinit var serviceManager: ServiceManager
@Inject lateinit var tunnelManager: TunnelManager @Inject
lateinit var tunnelManager: TunnelManager
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this) private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
private var isCollecting = false private var isCollecting = false
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
} }
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
} }
override fun onStartListening() { override fun onStartListening() {
super.onStartListening() super.onStartListening()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START) lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
Timber.d("Start listening called for tunnel tile") Timber.d("Start listening called for tunnel tile")
if (isCollecting) return if (isCollecting) return
isCollecting = true isCollecting = true
lifecycleScope.launch { tunnelManager.activeTunnels.collect { updateTileState() } } lifecycleScope.launch {
} tunnelManager.activeTunnels.collect {
updateTileState()
}
}
}
private suspend fun updateTileState() { private fun updateTileState() = lifecycleScope.launch {
try { val tunnels = appDataRepository.tunnels.getAll()
val tunnels = appDataRepository.tunnels.getAll() if (tunnels.isEmpty()) return@launch setUnavailable()
if (tunnels.isEmpty()) { with(tunnelManager.activeTunnels.value) {
setUnavailable() if (isNotEmpty()) if (size == 1) {
return tunnels.firstOrNull { it.id == keys.first().id }?.let { return@launch updateTile(it.tunName, true) }
} } else {
return@launch updateTile(getString(R.string.multiple), true)
}
}
appDataRepository.getStartTunnelConfig()?.let {
updateTile(it.tunName, false)
}
}
val activeTunnels = override fun onClick() {
tunnelManager.activeTunnels.value.filter { it.value.status.isUpOrStarting() } super.onClick()
unlockAndRun {
lifecycleScope.launch {
if (tunnelManager.activeTunnels.value.isNotEmpty()) return@launch tunnelManager.stopTunnel()
appDataRepository.getStartTunnelConfig()?.let {
tunnelManager.startTunnel(it)
}
}
}
}
when { private fun setActive() {
activeTunnels.isNotEmpty() -> { runCatching {
val activeIds = activeTunnels.map { it.key.id } qsTile.state = Tile.STATE_ACTIVE
// TODO improvements would be needed to make this work well with toggling qsTile.updateTile()
// multiple tunnels }
// this would be better managed elsewhere }
WireGuardAutoTunnel.setLastActiveTunnels(activeIds)
updateTileForActiveTunnels(activeTunnels)
}
else -> updateTileForLastActiveTunnels()
}
} catch (e: Exception) {
setUnavailable()
}
}
private fun updateTileForActiveTunnels(activeTunnels: Map<TunnelConf, TunnelState>) { private fun setInactive() {
val tileName = runCatching {
when (activeTunnels.size) { qsTile.state = Tile.STATE_INACTIVE
1 -> activeTunnels.keys.first().tunName qsTile.updateTile()
else -> getString(R.string.multiple) }
} }
updateTile(tileName, true)
}
private suspend fun updateTileForLastActiveTunnels() { private fun setUnavailable() {
val lastActiveIds = WireGuardAutoTunnel.getLastActiveTunnels() runCatching {
when { qsTile.state = Tile.STATE_UNAVAILABLE
lastActiveIds.isEmpty() -> { setTileDescription("")
appDataRepository.getStartTunnelConfig()?.let { config -> qsTile.updateTile()
updateTile(config.tunName, false) }
} ?: setUnavailable() }
}
lastActiveIds.size > 1 -> updateTile(getString(R.string.multiple), false)
else -> {
val tunnelId = lastActiveIds.first()
appDataRepository.tunnels.getById(tunnelId)?.let { tunnel ->
updateTile(tunnel.tunName, false)
} ?: setUnavailable()
}
}
}
override fun onClick() { private fun setTileDescription(description: String) {
super.onClick() runCatching {
unlockAndRun { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
lifecycleScope.launch { qsTile.subtitle = description
if (tunnelManager.activeTunnels.value.isNotEmpty()) }
return@launch tunnelManager.stopTunnel() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val lastActive = WireGuardAutoTunnel.getLastActiveTunnels() qsTile.stateDescription = description
if (lastActive.isEmpty()) { }
appDataRepository.getStartTunnelConfig()?.let { tunnelManager.startTunnel(it) } qsTile.updateTile()
} else { }
lastActive.forEach { id -> }
appDataRepository.tunnels.getById(id)?.let { tunnelManager.startTunnel(it) }
}
}
}
}
}
private fun setActive() { /* This works around an annoying unsolved frameworks bug some people are hitting. */
runCatching { override fun onBind(intent: Intent): IBinder? {
qsTile.state = Tile.STATE_ACTIVE var ret: IBinder? = null
qsTile.updateTile() try {
} ret = super.onBind(intent)
} } catch (_: Throwable) {
Timber.e("Failed to bind to TunnelControlTile")
}
return ret
}
private fun setInactive() { private fun updateTile(name: String, active: Boolean) {
runCatching { runCatching {
qsTile.state = Tile.STATE_INACTIVE setTileDescription(name)
qsTile.updateTile() if (active) return setActive()
} setInactive()
} }.onFailure {
Timber.e(it)
private fun setUnavailable() { }
runCatching { }
qsTile.state = Tile.STATE_UNAVAILABLE override val lifecycle: Lifecycle
setTileDescription("") get() = lifecycleRegistry
qsTile.updateTile()
}
}
private fun setTileDescription(description: String) {
runCatching {
if (qsTile == null) return@runCatching
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
qsTile.subtitle = description
qsTile.stateDescription = description
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
qsTile.subtitle = description
}
qsTile.updateTile()
}
}
/* This works around an annoying unsolved frameworks bug some people are hitting. */
override fun onBind(intent: Intent): IBinder? {
var ret: IBinder? = null
try {
ret = super.onBind(intent)
} catch (_: Throwable) {
Timber.e("Failed to bind to TunnelControlTile")
}
return ret
}
private fun updateTile(name: String, active: Boolean) {
runCatching {
setTileDescription(name)
if (active) return setActive()
setInactive()
}
.onFailure { Timber.e(it) }
}
override val lifecycle: Lifecycle
get() = lifecycleRegistry
} }
@@ -10,83 +10,70 @@ import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
class DynamicShortcutManager( class DynamicShortcutManager(private val context: Context, @IoDispatcher private val ioDispatcher: CoroutineDispatcher) : ShortcutManager {
private val context: Context, override suspend fun addShortcuts() {
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, withContext(ioDispatcher) {
) : ShortcutManager { ShortcutManagerCompat.setDynamicShortcuts(context, createShortcuts())
override suspend fun addShortcuts() { }
withContext(ioDispatcher) { }
ShortcutManagerCompat.setDynamicShortcuts(context, createShortcuts())
}
}
override suspend fun removeShortcuts() { override suspend fun removeShortcuts() {
withContext(ioDispatcher) { withContext(ioDispatcher) {
ShortcutManagerCompat.removeDynamicShortcuts(context, createShortcuts().map { it.id }) ShortcutManagerCompat.removeDynamicShortcuts(context, createShortcuts().map { it.id })
} }
} }
private fun createShortcuts(): List<ShortcutInfoCompat> { private fun createShortcuts(): List<ShortcutInfoCompat> {
return listOf( return listOf(
buildShortcut( buildShortcut(
context.getString(R.string.vpn_off), context.getString(R.string.vpn_off),
context.getString(R.string.vpn_off), context.getString(R.string.vpn_off),
context.getString(R.string.vpn_off), context.getString(R.string.vpn_off),
intent = intent = Intent(context, ShortcutsActivity::class.java).apply {
Intent(context, ShortcutsActivity::class.java).apply { putExtra("className", "WireGuardTunnelService")
putExtra("className", "WireGuardTunnelService") action = ShortcutsActivity.Action.STOP.name
action = ShortcutsActivity.Action.STOP.name },
}, shortcutIcon = R.drawable.vpn_off,
shortcutIcon = R.drawable.vpn_off, ),
), buildShortcut(
buildShortcut( context.getString(R.string.vpn_on),
context.getString(R.string.vpn_on), context.getString(R.string.vpn_on),
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 {
intent = putExtra("className", "WireGuardTunnelService")
Intent(context, ShortcutsActivity::class.java).apply { action = ShortcutsActivity.Action.START.name
putExtra("className", "WireGuardTunnelService") },
action = ShortcutsActivity.Action.START.name shortcutIcon = R.drawable.vpn_on,
}, ),
shortcutIcon = R.drawable.vpn_on, buildShortcut(
), context.getString(R.string.start_auto),
buildShortcut( context.getString(R.string.start_auto),
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 {
context.getString(R.string.start_auto), putExtra("className", "WireGuardConnectivityWatcherService")
intent = action = ShortcutsActivity.Action.START.name
Intent(context, ShortcutsActivity::class.java).apply { },
putExtra("className", "WireGuardConnectivityWatcherService") shortcutIcon = R.drawable.auto_play,
action = ShortcutsActivity.Action.START.name ),
}, buildShortcut(
shortcutIcon = R.drawable.auto_play, context.getString(R.string.stop_auto),
), context.getString(R.string.stop_auto),
buildShortcut( context.getString(R.string.stop_auto),
context.getString(R.string.stop_auto), intent = Intent(context, ShortcutsActivity::class.java).apply {
context.getString(R.string.stop_auto), putExtra("className", "WireGuardConnectivityWatcherService")
context.getString(R.string.stop_auto), action = ShortcutsActivity.Action.STOP.name
intent = },
Intent(context, ShortcutsActivity::class.java).apply { shortcutIcon = R.drawable.auto_pause,
putExtra("className", "WireGuardConnectivityWatcherService") ),
action = ShortcutsActivity.Action.STOP.name )
}, }
shortcutIcon = R.drawable.auto_pause,
),
)
}
private fun buildShortcut( private fun buildShortcut(id: String, shortLabel: String, longLabel: String, intent: Intent, shortcutIcon: Int): ShortcutInfoCompat {
id: String, return ShortcutInfoCompat.Builder(context, id)
shortLabel: String, .setShortLabel(shortLabel)
longLabel: String, .setLongLabel(longLabel)
intent: Intent, .setIntent(intent)
shortcutIcon: Int, .setIcon(IconCompat.createWithResource(context, shortcutIcon))
): ShortcutInfoCompat { .build()
return ShortcutInfoCompat.Builder(context, id) }
.setShortLabel(shortLabel)
.setLongLabel(longLabel)
.setIntent(intent)
.setIcon(IconCompat.createWithResource(context, shortcutIcon))
.build()
}
} }
@@ -1,7 +1,6 @@
package com.zaneschepke.wireguardautotunnel.core.shortcut package com.zaneschepke.wireguardautotunnel.core.shortcut
interface ShortcutManager { interface ShortcutManager {
suspend fun addShortcuts() suspend fun addShortcuts()
suspend fun removeShortcuts()
suspend fun removeShortcuts()
} }
@@ -2,75 +2,76 @@ package com.zaneschepke.wireguardautotunnel.core.shortcut
import android.os.Bundle import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.service.autotunnel.AutoTunnelService import com.zaneschepke.wireguardautotunnel.core.service.autotunnel.AutoTunnelService
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelProvider import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelProvider
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
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
@AndroidEntryPoint @AndroidEntryPoint
class ShortcutsActivity : ComponentActivity() { class ShortcutsActivity : ComponentActivity() {
@Inject lateinit var appDataRepository: AppDataRepository @Inject
lateinit var appDataRepository: AppDataRepository
@Inject lateinit var serviceManager: ServiceManager @Inject
lateinit var serviceManager: ServiceManager
@Inject lateinit var tunnelManager: TunnelManager @Inject
lateinit var tunnelManager: TunnelManager
@Inject @ApplicationScope lateinit var applicationScope: CoroutineScope @Inject
@ApplicationScope
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.get() val settings = appDataRepository.settings.get()
if (settings.isShortcutsEnabled) { if (settings.isShortcutsEnabled) {
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) { when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
LEGACY_TUNNEL_SERVICE_NAME, LEGACY_TUNNEL_SERVICE_NAME, TunnelProvider::class.java.simpleName -> {
TunnelProvider::class.java.simpleName -> { val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY) Timber.d("Tunnel name extra: $tunnelName")
Timber.d("Tunnel name extra: $tunnelName") val tunnelConfig = tunnelName?.let {
val tunnelConfig = appDataRepository.tunnels.getAll()
tunnelName?.let { .firstOrNull { it.tunName == tunnelName }
appDataRepository.tunnels.getAll().firstOrNull { } ?: appDataRepository.getStartTunnelConfig()
it.tunName == tunnelName Timber.d("Shortcut action on name: ${tunnelConfig?.tunName}")
} tunnelConfig?.let {
} ?: appDataRepository.getStartTunnelConfig() when (intent.action) {
Timber.d("Shortcut action on name: ${tunnelConfig?.tunName}") Action.START.name -> tunnelManager.startTunnel(it)
tunnelConfig?.let { Action.STOP.name -> tunnelManager.stopTunnel()
when (intent.action) { else -> Unit
Action.START.name -> tunnelManager.startTunnel(it) }
Action.STOP.name -> tunnelManager.stopTunnel() }
else -> Unit }
} AutoTunnelService::class.java.simpleName, LEGACY_AUTO_TUNNEL_SERVICE_NAME -> {
} when (intent.action) {
} Action.START.name -> serviceManager.startAutoTunnel(true)
AutoTunnelService::class.java.simpleName, Action.STOP.name -> serviceManager.stopAutoTunnel()
LEGACY_AUTO_TUNNEL_SERVICE_NAME -> { }
when (intent.action) { }
Action.START.name -> serviceManager.startAutoTunnel() }
Action.STOP.name -> serviceManager.stopAutoTunnel() }
} }
} finish()
} }
}
}
finish()
}
enum class Action { enum class Action {
START, START,
STOP, STOP,
} }
companion object { companion object {
const val LEGACY_TUNNEL_SERVICE_NAME = "WireGuardTunnelService" const val LEGACY_TUNNEL_SERVICE_NAME = "WireGuardTunnelService"
const val LEGACY_AUTO_TUNNEL_SERVICE_NAME = "WireGuardConnectivityWatcherService" const val LEGACY_AUTO_TUNNEL_SERVICE_NAME = "WireGuardConnectivityWatcherService"
const val TUNNEL_NAME_EXTRA_KEY = "tunnelName" const val TUNNEL_NAME_EXTRA_KEY = "tunnelName"
const val CLASS_NAME_EXTRA_KEY = "className" const val CLASS_NAME_EXTRA_KEY = "className"
} }
} }
@@ -1,233 +1,259 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.wireguard.android.backend.BackendException
import com.wireguard.android.backend.Tunnel import com.wireguard.android.backend.Tunnel
import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.networkmonitor.NetworkStatus
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager
import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendError import com.zaneschepke.wireguardautotunnel.domain.enums.BackendError
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.StringValue
import com.zaneschepke.wireguardautotunnel.util.extensions.asTunnelState import com.zaneschepke.wireguardautotunnel.util.extensions.asTunnelState
import java.util.concurrent.ConcurrentHashMap import com.zaneschepke.wireguardautotunnel.util.extensions.cancelWithMessage
import kotlin.concurrent.thread import com.zaneschepke.wireguardautotunnel.util.extensions.toBackendError
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.* import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.sync.withLock
import timber.log.Timber import timber.log.Timber
import java.util.concurrent.ConcurrentHashMap
abstract class BaseTunnel( abstract class BaseTunnel(
@ApplicationScope private val applicationScope: CoroutineScope, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val appDataRepository: AppDataRepository, @ApplicationScope private val applicationScope: CoroutineScope,
private val serviceManager: ServiceManager, private val networkMonitor: NetworkMonitor,
private val appDataRepository: AppDataRepository,
private val serviceManager: ServiceManager,
private val notificationManager: NotificationManager,
) : TunnelProvider { ) : TunnelProvider {
private val _errorEvents = companion object {
MutableSharedFlow<Pair<TunnelConf, BackendError>>(replay = 0, extraBufferCapacity = 1) const val CHECK_INTERVAL = 1000L
override val errorEvents = _errorEvents.asSharedFlow() }
private val activeTuns = MutableStateFlow<Map<TunnelConf, TunnelState>>(emptyMap()) protected val activeTuns = MutableStateFlow<Map<TunnelConf, TunnelState>>(emptyMap())
private val tunThreads = ConcurrentHashMap<Int, Thread>() override val activeTunnels = activeTuns.asStateFlow()
override val activeTunnels = activeTuns.asStateFlow()
private val tunMutex = Mutex() private val tunnelJobs = ConcurrentHashMap<Int, MutableList<Job>>()
private val tunStatusMutex = Mutex()
private val bounceTunnelMutex = Mutex()
override val bouncingTunnelIds = ConcurrentHashMap<Int, TunnelStatus.StopReason>() protected val mutex = Mutex()
private val isNetworkConnected = MutableStateFlow(true)
abstract suspend fun startBackend(tunnel: TunnelConf) init {
applicationScope.launch(ioDispatcher) {
launch { monitorNetworkStatus() }
launch { monitorTunnelConfigChanges() }
}
}
abstract fun stopBackend(tunnel: TunnelConf) private fun startTunnelJobs(tunnel: TunnelConf): Job {
return applicationScope.launch(ioDispatcher) {
val jobs = mutableListOf<Job>()
jobs += launch { updateTunnelStatistics(tunnel) }
if (tunnel.isPingEnabled) jobs += launch { monitorTunnelPing(tunnel) }
jobs.forEach { it.join() }
}
}
override fun hasVpnPermission(): Boolean { private suspend fun updateTunnelStatistics(tunnel: TunnelConf) {
return serviceManager.hasVpnPermission() while (true) {
} runCatching {
val stats = getStatistics(tunnel)
updateTunnelState(tunnel, stats = stats)
}.onFailure { e ->
Timber.e(e, "Failed to update stats for ${tunnel.tunName}")
}
delay(CHECK_INTERVAL)
}
}
protected suspend fun updateTunnelStatus( private suspend fun monitorTunnelPing(tunnel: TunnelConf) {
tunnelConf: TunnelConf, while (true) {
status: TunnelStatus? = null, runCatching {
stats: TunnelStatistics? = null, if (isNetworkConnected.value && tunnel.isActive) {
) { val pingSuccess = tunnel.isTunnelPingable(ioDispatcher)
tunStatusMutex.withLock { if (!pingSuccess) bounceTunnel(tunnel)
activeTuns.update { currentTuns -> }
val originalConf = currentTuns.getKeyById(tunnelConf.id) ?: tunnelConf }.onFailure { e ->
val existingState = currentTuns.getValueById(tunnelConf.id) ?: TunnelState() Timber.e(e, "Ping failed for ${tunnel.tunName}")
val newState = status ?: existingState.status }
if (newState == TunnelStatus.Down) { delay(tunnel.pingInterval ?: Constants.PING_INTERVAL)
Timber.d("Removing tunnel ${tunnelConf.id} from activeTunnels as state is DOWN") }
cleanUpTunThread(tunnelConf) }
currentTuns - originalConf
} else if (existingState.status == newState && stats == null) {
Timber.d("Skipping redundant state update for ${tunnelConf.id}: $newState")
currentTuns
} else {
val updated =
existingState.copy(
status = newState,
statistics = stats ?: existingState.statistics,
)
currentTuns + (originalConf to updated)
}
}
}
}
private suspend fun stopActiveTunnels() { protected fun handleBackendThrowable(throwable: Throwable) {
activeTunnels.value.forEach { (config, state) -> val backendError = when (throwable) {
if (state.status.isUpOrStarting()) { is BackendException -> throwable.toBackendError()
stopTunnel(config) is org.amnezia.awg.backend.BackendException -> throwable.toBackendError()
} else -> BackendError.Unknown
} }
} val message = when (backendError) {
BackendError.Config -> StringValue.StringResource(R.string.start_failed_config)
BackendError.DNS -> StringValue.StringResource(R.string.dns_error)
BackendError.Unauthorized -> StringValue.StringResource(R.string.unauthorized)
BackendError.Unknown -> StringValue.StringResource(R.string.unknown_error)
}
if (WireGuardAutoTunnel.isForeground()) {
SnackbarController.showMessage(message)
} else {
notificationManager.show(
NotificationManager.VPN_NOTIFICATION_ID,
notificationManager.createNotification(
WireGuardNotification.NotificationChannels.VPN,
title = StringValue.StringResource(R.string.tunne_start_failed_title),
description = message,
),
)
}
}
private fun configureTunnelCallbacks(tunnelConf: TunnelConf) { protected fun updateTunnelState(tunnelConf: TunnelConf, state: TunnelStatus? = null, stats: TunnelStatistics? = null) {
Timber.d("Configuring TunnelConf instance: ${tunnelConf.hashCode()}") applicationScope.launch(ioDispatcher) {
tunnelConf.setStateChangeCallback { state -> mutex.withLock {
applicationScope.launch { activeTuns.update { current ->
Timber.d( val originalConf = current.getKeyById(tunnelConf.id) ?: tunnelConf
"State change callback triggered for tunnel ${tunnelConf.id}: ${tunnelConf.tunName} with state $state at ${System.currentTimeMillis()}" val existingState = current.getValueById(tunnelConf.id) ?: TunnelState()
) val newState = state ?: existingState.state
when (state) { if (newState == TunnelStatus.DOWN) {
is Tunnel.State -> updateTunnelStatus(tunnelConf, state.asTunnelState()) // Remove tunnel from activeTunnels when it goes DOWN
is org.amnezia.awg.backend.Tunnel.State -> Timber.d("Removing tunnel ${tunnelConf.id} from activeTunnels as state is DOWN")
updateTunnelStatus(tunnelConf, state.asTunnelState()) current - originalConf
} } else if (existingState.state == newState && stats == null) {
handleServiceStateOnChange() Timber.d("Skipping redundant state update for ${tunnelConf.id}: $newState")
} current
serviceManager.updateTunnelTile() } else {
} val updated = existingState.copy(
} state = newState,
statistics = stats ?: existingState.statistics,
)
current + (originalConf to updated)
}
}
}
}
}
override suspend fun updateTunnelStatistics(tunnel: TunnelConf) { protected suspend fun configureTunnel(tunnelConf: TunnelConf) {
val stats = getStatistics(tunnel) // setup state change callback
updateTunnelStatus(tunnel, null, stats) tunnelConf.setStateChangeCallback { state ->
} Timber.d("State change callback triggered for tunnel ${tunnelConf.id}: ${tunnelConf.tunName} with state $state at ${System.currentTimeMillis()}")
when (state) {
is Tunnel.State -> updateTunnelState(tunnelConf, state.asTunnelState())
is org.amnezia.awg.backend.Tunnel.State -> updateTunnelState(tunnelConf, state.asTunnelState())
}
applicationScope.launch(ioDispatcher) { serviceManager.updateTunnelTile() }
}
override suspend fun startTunnel(tunnelConf: TunnelConf) { activeTuns.update { current ->
if (activeTuns.exists(tunnelConf.id) || tunThreads.containsKey(tunnelConf.id)) return current.filter { it.key != tunnelConf } + (tunnelConf to TunnelState())
if (this@BaseTunnel is UserspaceTunnel) stopActiveTunnels() }
tunMutex.withLock { }
tunThreads[tunnelConf.id] = thread {
runBlocking {
try {
Timber.d("Starting tunnel ${tunnelConf.id}...")
startTunnelInner(tunnelConf)
Timber.d("Started complete for tunnel ${tunnelConf.name}...")
} catch (e: InterruptedException) {
Timber.w(
"Tunnel start has been interrupted as ${tunnelConf.name} failed to start"
)
}
}
}
}
}
private suspend fun startTunnelInner(tunnelConf: TunnelConf) { protected suspend fun onStartSuccess(tunnelConf: TunnelConf) {
configureTunnelCallbacks(tunnelConf) val tunnelCopy = tunnelConf.copyWithCallback(isActive = true)
Timber.d("Starting backend for tunnel ${tunnelConf.id}...")
try {
startBackend(tunnelConf)
updateTunnelStatus(tunnelConf, TunnelStatus.Up)
Timber.d("Started for tun ${tunnelConf.id}...")
saveTunnelActiveState(tunnelConf, true)
serviceManager.startTunnelForegroundService()
} catch (e: BackendError) {
Timber.e(e, "Failed to start backend for ${tunnelConf.name}")
_errorEvents.emit(tunnelConf to e)
updateTunnelStatus(tunnelConf, TunnelStatus.Down)
}
}
private suspend fun saveTunnelActiveState(tunnelConf: TunnelConf, active: Boolean) { // start service
val tunnelCopy = tunnelConf.copyWithCallback(isActive = active) if (activeTuns.value.isEmpty()) {
appDataRepository.tunnels.save(tunnelCopy) serviceManager.startTunnelForegroundService(tunnelCopy)
} } else {
serviceManager.updateTunnelForegroundServiceNotification(tunnelCopy)
}
// save active
appDataRepository.tunnels.save(tunnelCopy)
// start tunnel jobs
tunnelJobs[tunnelCopy.id] = mutableListOf(startTunnelJobs(tunnelConf))
}
override suspend fun stopTunnel(tunnelConf: TunnelConf?, reason: TunnelStatus.StopReason) { override fun startTunnel(tunnelConf: TunnelConf) {
if (tunnelConf == null) return stopActiveTunnels() throw NotImplementedError("Must be implemented by subclass")
tunMutex.withLock { }
if (activeTuns.isStarting(tunnelConf.id))
return handleStuckStartingTunnelShutdown(tunnelConf)
updateTunnelStatus(tunnelConf, TunnelStatus.Stopping(reason))
stopTunnelInner(tunnelConf)
}
}
private suspend fun stopTunnelInner(tunnelConf: TunnelConf) { override fun stopTunnel(tunnelConf: TunnelConf?) {
try { tunnelConf?.let {
val tunnel = activeTuns.findTunnel(tunnelConf.id) ?: return applicationScope.launch(ioDispatcher) {
stopBackend(tunnel) mutex.withLock {
saveTunnelActiveState(tunnelConf, false) removeActiveTunnel(tunnelConf)
removeActiveTunnel(tunnel) tunnelJobs[tunnelConf.id]?.forEach { it.cancelWithMessage("Cancel tunnel job") }
} catch (e: BackendError) { tunnelJobs.remove(tunnelConf.id)
Timber.e(e, "Failed to stop tunnel ${tunnelConf.id}") val lockedConf = it.copyWithCallback(isActive = false)
_errorEvents.emit(tunnelConf to e) appDataRepository.tunnels.save(lockedConf)
updateTunnelStatus(tunnelConf, TunnelStatus.Down)
}
}
private fun handleServiceStateOnChange() { // TODO improve to handle multiple tunnels
if (activeTuns.value.isEmpty() && bouncingTunnelIds.isEmpty()) if (activeTuns.value.isEmpty()) {
serviceManager.stopTunnelForegroundService() Timber.d("No tunnels active, stopping background service")
} serviceManager.stopTunnelForegroundService()
} else {
Timber.d("Other tunnels still active, updating service notification")
val nextActive = activeTuns.value.keys.firstOrNull()
if (nextActive != null) {
Timber.d("Next active tunnel: ${nextActive.id}")
serviceManager.updateTunnelForegroundServiceNotification(nextActive)
}
}
}
}
}
}
private suspend fun handleStuckStartingTunnelShutdown(tunnel: TunnelConf) { private fun removeActiveTunnel(tunnelConf: TunnelConf) {
Timber.d("Stuck in starting state so shutting down tunnel thread for tunnel ${tunnel.name}") activeTuns.update { current ->
try { current.toMutableMap().apply { remove(tunnelConf) }
tunThreads[tunnel.id]?.let { }
if (it.state != Thread.State.TERMINATED) { }
it.interrupt()
} else {
Timber.d("Thread already terminated")
}
}
} catch (e: Exception) {
Timber.e(e, "Failed to stop tunnel thread for ${tunnel.name}")
} finally {
updateTunnelStatus(tunnel, TunnelStatus.Down)
}
}
private fun cleanUpTunThread(tunnel: TunnelConf) { override suspend fun bounceTunnel(tunnelConf: TunnelConf) {
Timber.d("Removing thread for ${tunnel.name}") stopTunnel(tunnelConf)
tunThreads -= tunnel.id delay(1000)
} startTunnel(tunnelConf)
}
private fun removeActiveTunnel(tunnelConf: TunnelConf) { private suspend fun monitorNetworkStatus() {
activeTuns.update { current -> current.toMutableMap().apply { remove(tunnelConf) } } networkMonitor.networkStatusFlow
} .flowOn(ioDispatcher)
.collectLatest { status ->
val isAvailable = status !is NetworkStatus.Disconnected
isNetworkConnected.value = isAvailable
Timber.d("Network status: $isAvailable")
}
}
override suspend fun bounceTunnel(tunnelConf: TunnelConf, reason: TunnelStatus.StopReason) { private suspend fun monitorTunnelConfigChanges() {
bounceTunnelMutex.withLock { appDataRepository.tunnels.flow.collectLatest { storedTunnels ->
Timber.i( mutex.withLock {
"Bounce tunnel ${tunnelConf.name} for reason: $reason, current bouncing: ${bouncingTunnelIds.size}" storedTunnels.forEach { stored ->
) val current = activeTuns.value.keys.find { it.id == stored.id }
bouncingTunnelIds[tunnelConf.id] = reason if (current != null && !current.isQuickConfigMatching(stored)) {
try { Timber.d("Config changed for ${stored.id}, bouncing")
stopTunnel(tunnelConf, reason) bounceTunnel(stored)
delay(BOUNCE_DELAY) }
startTunnel(tunnelConf) }
} finally { }
bouncingTunnelIds.remove(tunnelConf.id) }
handleServiceStateOnChange() }
Timber.d(
"Cleared bounce state for ${tunnelConf.name}, remaining: ${bouncingTunnelIds.size}"
)
}
}
}
override suspend fun runningTunnelNames(): Set<String> = override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? {
activeTuns.value.keys.map { it.tunName }.toSet() throw NotImplementedError("Must be implemented by subclass")
}
companion object { override suspend fun runningTunnelNames(): Set<String> = activeTuns.value.keys.map { it.tunName }.toSet()
const val BOUNCE_DELAY = 300L
}
} }
@@ -1,50 +1,25 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import kotlinx.coroutines.flow.MutableStateFlow
fun Map<TunnelConf, TunnelState>.allDown(): Boolean { fun Map<TunnelConf, TunnelState>.allDown(): Boolean {
return this.all { it.value.status.isDown() } return this.all { it.value.state.isDown() }
} }
fun Map<TunnelConf, TunnelState>.hasActive(): Boolean { fun Map<TunnelConf, TunnelState>.hasActive(): Boolean {
return this.any { it.value.status.isUp() } return this.any { it.value.state.isUp() }
} }
fun Map<TunnelConf, TunnelState>.getValueById(id: Int): TunnelState? { fun Map<TunnelConf, TunnelState>.getValueById(id: Int): TunnelState? {
val key = this.keys.find { it.id == id } val key = this.keys.find { it.id == id }
return key?.let { this@getValueById[it] } return key?.let { this@getValueById[it] }
} }
fun Map<TunnelConf, TunnelState>.getKeyById(id: Int): TunnelConf? { fun Map<TunnelConf, TunnelState>.getKeyById(id: Int): TunnelConf? {
return this.keys.find { it.id == id } return this.keys.find { it.id == id }
} }
fun Map<TunnelConf, TunnelState>.isUp(tunnelConf: TunnelConf): Boolean { fun Map<TunnelConf, TunnelState>.isUp(tunnelConf: TunnelConf): Boolean {
return this.getValueById(tunnelConf.id)?.status?.isUp() ?: false return this.getValueById(tunnelConf.id)?.state?.isUp() ?: false
}
fun MutableStateFlow<Map<TunnelConf, TunnelState>>.exists(id: Int): Boolean {
return this.value.any { it.key.id == id }
}
fun MutableStateFlow<Map<TunnelConf, TunnelState>>.isUp(id: Int): Boolean {
return this.value.any { it.key.id == id && it.value.status == TunnelStatus.Up }
}
fun MutableStateFlow<Map<TunnelConf, TunnelState>>.isStarting(id: Int): Boolean {
return this.value.any { it.key.id == id && it.value.status == TunnelStatus.Starting }
}
fun MutableStateFlow<Map<TunnelConf, TunnelState>>.findTunnel(id: Int): TunnelConf? {
return this.value.keys.find { it.id == id }
}
private val URL_PATTERN =
Regex("""^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}:[0-9]{1,5}$""")
fun String.isUrl(): Boolean {
return URL_PATTERN.matches(this)
} }
@@ -1,66 +1,100 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.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 import com.wireguard.android.backend.Tunnel
import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import com.zaneschepke.wireguardautotunnel.domain.state.WireGuardStatistics import com.zaneschepke.wireguardautotunnel.domain.state.WireGuardStatistics
import com.zaneschepke.wireguardautotunnel.util.extensions.toBackendError import com.zaneschepke.wireguardautotunnel.util.extensions.asTunnelState
import javax.inject.Inject import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.withLock
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
class KernelTunnel class KernelTunnel @Inject constructor(
@Inject @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
constructor( @ApplicationScope private val applicationScope: CoroutineScope,
@ApplicationScope private val applicationScope: CoroutineScope, serviceManager: ServiceManager,
serviceManager: ServiceManager, appDataRepository: AppDataRepository,
appDataRepository: AppDataRepository, notificationManager: NotificationManager,
private val backend: Backend, private val backend: Backend,
) : BaseTunnel(applicationScope, appDataRepository, serviceManager) { networkMonitor: NetworkMonitor,
) : BaseTunnel(ioDispatcher, applicationScope, networkMonitor, appDataRepository, serviceManager, notificationManager) {
override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? { override fun startTunnel(tunnelConf: TunnelConf) {
return try { Timber.i("Starting tunnel ${tunnelConf.id} kernel")
WireGuardStatistics(backend.getStatistics(tunnelConf)) applicationScope.launch(ioDispatcher) {
} catch (e: Exception) { runCatching {
Timber.e(e) // tunnel already active
null if (activeTuns.value.any { it.key.id == tunnelConf.id }) return@launch
}
}
override suspend fun startBackend(tunnel: TunnelConf) { mutex.withLock {
try { updateTunnelState(tunnelConf, TunnelStatus.STARTING)
updateTunnelStatus(tunnel, TunnelStatus.Starting)
backend.setState(tunnel, Tunnel.State.UP, tunnel.toWgConfig())
} catch (e: BackendException) {
throw e.toBackendError()
}
}
override fun stopBackend(tunnel: TunnelConf) { // configure state callback and add to tunnels
Timber.i("Stopping tunnel ${tunnel.id} kernel") configureTunnel(tunnelConf)
try {
backend.setState(tunnel, Tunnel.State.DOWN, tunnel.toWgConfig())
} catch (e: BackendException) {
throw e.toBackendError()
}
}
override fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) { updateTunnelState(tunnelConf, backend.setState(tunnelConf, Tunnel.State.UP, tunnelConf.toWgConfig()).asTunnelState())
Timber.w("Not yet implemented for kernel")
}
override fun getBackendState(): BackendState { // run some actions after start success
return BackendState.INACTIVE onStartSuccess(tunnelConf)
} }
}.onFailure { exception ->
Timber.e(exception, "Failed to start tunnel ${tunnelConf.id} kernel")
stopTunnel(tunnelConf)
handleBackendThrowable(exception)
}.onSuccess {
Timber.i("Tunnel ${tunnelConf.id} started successfully")
}
}
}
override suspend fun runningTunnelNames(): Set<String> { override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? {
return backend.runningTunnelNames return try {
} WireGuardStatistics(backend.getStatistics(tunnelConf))
} catch (e: Exception) {
Timber.e(e)
null
}
}
override fun stopTunnel(tunnelConf: TunnelConf?) {
applicationScope.launch(ioDispatcher) {
runCatching {
val originalTunnel = activeTuns.value.keys.find { it.id == tunnelConf?.id }
if (originalTunnel != null) {
Timber.i("Stopping tunnel ${originalTunnel.id} kernel")
mutex.withLock {
updateTunnelState(originalTunnel, backend.setState(originalTunnel, Tunnel.State.DOWN, originalTunnel.toWgConfig()).asTunnelState())
super.stopTunnel(originalTunnel)
}
} else {
Timber.w("Tunnel not found in startedTunnels, stopping all tunnels")
activeTuns.value.keys.forEach { config ->
stopTunnel(config)
}
}
}.onFailure { e ->
Timber.e(e, "Failed to stop tunnel ${tunnelConf?.id}")
}
}
}
override suspend fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) {
Timber.w("Not yet implemented for kernel")
}
override suspend fun runningTunnelNames(): Set<String> {
return backend.runningTunnelNames
}
} }
@@ -5,121 +5,93 @@ import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.di.Kernel import com.zaneschepke.wireguardautotunnel.di.Kernel
import com.zaneschepke.wireguardautotunnel.di.Userspace import com.zaneschepke.wireguardautotunnel.di.Userspace
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendError
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.plus import kotlinx.coroutines.plus
import javax.inject.Inject
class TunnelManager class TunnelManager @Inject constructor(
@Inject @Kernel private val kernelTunnel: TunnelProvider,
constructor( @Userspace private val userspaceTunnel: TunnelProvider,
@Kernel private val kernelTunnel: TunnelProvider, private val appDataRepository: AppDataRepository,
@Userspace private val userspaceTunnel: TunnelProvider, @ApplicationScope private val applicationScope: CoroutineScope,
private val appDataRepository: AppDataRepository, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
@ApplicationScope private val applicationScope: CoroutineScope,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : TunnelProvider { ) : TunnelProvider {
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
private val tunnelProviderFlow = private val tunnelProviderFlow = appDataRepository.settings.flow
appDataRepository.settings.flow .filterNotNull()
.filterNotNull() .flatMapLatest { settings ->
.flatMapLatest { settings -> MutableStateFlow(if (settings.isKernelEnabled) kernelTunnel else userspaceTunnel)
MutableStateFlow(if (settings.isKernelEnabled) kernelTunnel else userspaceTunnel) }
} .stateIn(
.stateIn( scope = applicationScope.plus(ioDispatcher),
scope = applicationScope.plus(ioDispatcher), started = SharingStarted.Eagerly,
started = SharingStarted.Eagerly, initialValue = userspaceTunnel,
initialValue = userspaceTunnel, )
)
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
override val activeTunnels = override val activeTunnels = appDataRepository.settings.flow
appDataRepository.settings.flow .filterNotNull()
.filterNotNull() .flatMapLatest { settings ->
.flatMapLatest { settings -> if (settings.isKernelEnabled) {
if (settings.isKernelEnabled) { kernelTunnel.activeTunnels
kernelTunnel.activeTunnels } else {
} else { userspaceTunnel.activeTunnels
userspaceTunnel.activeTunnels }
} }
} .stateIn(
.stateIn( scope = applicationScope.plus(ioDispatcher),
scope = applicationScope.plus(ioDispatcher), started = SharingStarted.Eagerly,
started = SharingStarted.Eagerly, initialValue = emptyMap(),
initialValue = emptyMap(), )
)
override val errorEvents: SharedFlow<Pair<TunnelConf, BackendError>> override fun startTunnel(tunnelConf: TunnelConf) {
get() = tunnelProviderFlow.value.errorEvents tunnelProviderFlow.value.startTunnel(tunnelConf)
}
override val bouncingTunnelIds: ConcurrentHashMap<Int, TunnelStatus.StopReason> = override fun stopTunnel(tunnelConf: TunnelConf?) {
tunnelProviderFlow.value.bouncingTunnelIds tunnelProviderFlow.value.stopTunnel(tunnelConf)
}
override fun hasVpnPermission(): Boolean { override suspend fun bounceTunnel(tunnelConf: TunnelConf) {
return userspaceTunnel.hasVpnPermission() tunnelProviderFlow.value.bounceTunnel(tunnelConf)
} }
override suspend fun updateTunnelStatistics(tunnel: TunnelConf) { override suspend fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) {
tunnelProviderFlow.value.updateTunnelStatistics(tunnel) tunnelProviderFlow.value.setBackendState(backendState, allowedIps)
} }
override suspend fun startTunnel(tunnelConf: TunnelConf) { override suspend fun runningTunnelNames(): Set<String> {
tunnelProviderFlow.value.startTunnel(tunnelConf) return tunnelProviderFlow.value.runningTunnelNames()
} }
override suspend fun stopTunnel(tunnelConf: TunnelConf?, reason: TunnelStatus.StopReason) { override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? {
tunnelProviderFlow.value.stopTunnel(tunnelConf, reason) return tunnelProviderFlow.value.getStatistics(tunnelConf)
} }
override suspend fun bounceTunnel(tunnelConf: TunnelConf, reason: TunnelStatus.StopReason) { fun restorePreviousState() = applicationScope.launch(ioDispatcher) {
tunnelProviderFlow.value.bounceTunnel(tunnelConf, reason) val settings = appDataRepository.settings.get()
} if (settings.isRestoreOnBootEnabled) {
val previouslyActiveTuns = appDataRepository.tunnels.getActive()
override fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) { val tunsToStart = previouslyActiveTuns.filterNot { tun -> activeTunnels.value.any { tun.id == it.key.id } }
tunnelProviderFlow.value.setBackendState(backendState, allowedIps) if (settings.isKernelEnabled) {
} return@launch tunsToStart.forEach {
startTunnel(it)
override fun getBackendState(): BackendState { }
return tunnelProviderFlow.value.getBackendState() } else {
} tunsToStart.firstOrNull()?.let { startTunnel(it) }
}
override suspend fun runningTunnelNames(): Set<String> { }
return tunnelProviderFlow.value.runningTunnelNames() }
}
override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? {
return tunnelProviderFlow.value.getStatistics(tunnelConf)
}
fun restorePreviousState() =
applicationScope.launch(ioDispatcher) {
val settings = appDataRepository.settings.get()
if (settings.isRestoreOnBootEnabled) {
val previouslyActiveTuns = appDataRepository.tunnels.getActive()
val tunsToStart =
previouslyActiveTuns.filterNot { tun ->
activeTunnels.value.any { tun.id == it.key.id }
}
if (settings.isKernelEnabled) {
return@launch tunsToStart.forEach { startTunnel(it) }
} else {
tunsToStart.firstOrNull()?.let { startTunnel(it) }
}
}
}
} }
@@ -1,58 +1,17 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendError
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
interface TunnelProvider { interface TunnelProvider {
/** Starts the specified tunnel configuration. */ fun startTunnel(tunnelConf: TunnelConf)
suspend fun startTunnel(tunnelConf: TunnelConf) fun stopTunnel(tunnelConf: TunnelConf? = null)
suspend fun bounceTunnel(tunnelConf: TunnelConf)
/** suspend fun setBackendState(backendState: BackendState, allowedIps: Collection<String>)
* Stops the specified tunnel, or all tunnels if none is provided. suspend fun runningTunnelNames(): Set<String>
* fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics?
* @param tunnelConf The tunnel to stop, or null to stop all active tunnels. val activeTunnels: StateFlow<Map<TunnelConf, TunnelState>>
* @param reason The reason for stopping, defaults to USER for manual stops. Callers should
* override with specific reasons (e.g., PING, CONFIG_CHANGED) when applicable.
*/
suspend fun stopTunnel(
tunnelConf: TunnelConf? = null,
reason: TunnelStatus.StopReason = TunnelStatus.StopReason.USER,
)
/**
* Bounces (stops and restarts) the specified tunnel.
*
* @param tunnelConf The tunnel to bounce.
* @param reason The reason for bouncing, defaults to USER for manual actions. Callers should
* override with specific reasons (e.g., PING, CONFIG_CHANGED) when applicable.
*/
suspend fun bounceTunnel(
tunnelConf: TunnelConf,
reason: TunnelStatus.StopReason = TunnelStatus.StopReason.USER,
)
fun setBackendState(backendState: BackendState, allowedIps: Collection<String>)
fun getBackendState(): BackendState
suspend fun runningTunnelNames(): Set<String>
fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics?
val activeTunnels: StateFlow<Map<TunnelConf, TunnelState>>
val errorEvents: SharedFlow<Pair<TunnelConf, BackendError>>
val bouncingTunnelIds: ConcurrentHashMap<Int, TunnelStatus.StopReason>
fun hasVpnPermission(): Boolean
suspend fun updateTunnelStatistics(tunnel: TunnelConf)
} }
@@ -1,7 +1,10 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
@@ -9,100 +12,104 @@ import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.AmneziaStatistics import com.zaneschepke.wireguardautotunnel.domain.state.AmneziaStatistics
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import com.zaneschepke.wireguardautotunnel.util.extensions.asAmBackendState import com.zaneschepke.wireguardautotunnel.util.extensions.asAmBackendState
import com.zaneschepke.wireguardautotunnel.util.extensions.asBackendState import com.zaneschepke.wireguardautotunnel.util.extensions.asTunnelState
import com.zaneschepke.wireguardautotunnel.util.extensions.toBackendError import kotlinx.coroutines.CoroutineDispatcher
import javax.inject.Inject
import kotlin.jvm.optionals.getOrNull
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.withLock
import org.amnezia.awg.backend.Backend import org.amnezia.awg.backend.Backend
import org.amnezia.awg.backend.BackendException
import org.amnezia.awg.backend.Tunnel import org.amnezia.awg.backend.Tunnel
import org.amnezia.awg.config.Config
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
class UserspaceTunnel class UserspaceTunnel @Inject constructor(
@Inject @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
constructor( @ApplicationScope private val applicationScope: CoroutineScope,
@ApplicationScope private val applicationScope: CoroutineScope, serviceManager: ServiceManager,
val serviceManager: ServiceManager, appDataRepository: AppDataRepository,
val appDataRepository: AppDataRepository, notificationManager: NotificationManager,
private val backend: Backend, private val backend: Backend,
) : BaseTunnel(applicationScope, appDataRepository, serviceManager) { networkMonitor: NetworkMonitor,
) : BaseTunnel(ioDispatcher, applicationScope, networkMonitor, appDataRepository, serviceManager, notificationManager) {
private var previousBackendState: Pair<BackendState, Boolean>? = null override fun startTunnel(tunnelConf: TunnelConf) {
Timber.i("Starting tunnel ${tunnelConf.id} userspace")
applicationScope.launch(ioDispatcher) {
runCatching {
// tunnel already active
if (activeTuns.value.any { it.key.id == tunnelConf.id }) return@launch
override suspend fun startBackend(tunnel: TunnelConf) { // stop any active tunnels that aren't this one, userspace only
try { stopActiveTunnels()
updateTunnelStatus(tunnel, TunnelStatus.Starting)
val amConfig = tunnel.toAmConfig()
handleVpnKillSwitchWithDomainEndpoints(amConfig)
backend.setState(tunnel, Tunnel.State.UP, amConfig)
} catch (e: BackendException) {
Timber.e(e, "Failed to start up backend for tunnel ${tunnel.name}")
throw e.toBackendError()
}
}
override fun stopBackend(tunnel: TunnelConf) { mutex.withLock {
Timber.i("Stopping tunnel ${tunnel.name} userspace") updateTunnelState(tunnelConf, TunnelStatus.STARTING)
try {
backend.setState(tunnel, Tunnel.State.DOWN, tunnel.toAmConfig())
} catch (e: BackendException) {
Timber.e(e, "Failed to stop tunnel ${tunnel.id}")
throw e.toBackendError()
} finally {
handlePreviouslyEnabledVpnKillSwitch()
}
}
// stop vpn kill switch if we need to resolve DNS for peer endpoints // configure state callback and add to tunnels
private suspend fun handleVpnKillSwitchWithDomainEndpoints(config: Config) { configureTunnel(tunnelConf)
if (
config.peers.any { it.endpoint.getOrNull()?.toString()?.isUrl() == true } &&
backend.backendState.asBackendState() == BackendState.KILL_SWITCH_ACTIVE
) {
val bypassLan = appDataRepository.settings.get().isLanOnKillSwitchEnabled
previousBackendState = Pair(BackendState.KILL_SWITCH_ACTIVE, bypassLan)
setBackendState(BackendState.SERVICE_ACTIVE, emptyList())
}
}
// restore vpn kill switch if needed updateTunnelState(tunnelConf, backend.setState(tunnelConf, Tunnel.State.UP, tunnelConf.toAmConfig()).asTunnelState())
private fun handlePreviouslyEnabledVpnKillSwitch() {
// let auto tunnel handle this if it is active
if (serviceManager.autoTunnelService.value == null) {
previousBackendState?.let { (state, lanEnabled) ->
Timber.d("Restoring kill switch configuration")
val lan = if (lanEnabled) TunnelConf.LAN_BYPASS_ALLOWED_IPS else emptyList()
backend.setBackendState(state.asAmBackendState(), lan)
}
}
previousBackendState = null
}
override fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) { // run some actions after start success
Timber.d("Setting backend state: $backendState with allowedIps: $allowedIps") onStartSuccess(tunnelConf)
try { }
backend.setBackendState(backendState.asAmBackendState(), allowedIps) }.onFailure { exception ->
} catch (e: BackendException) { Timber.e(exception, "Failed to start tunnel ${tunnelConf.id} userspace")
throw e.toBackendError() stopTunnel(tunnelConf)
} handleBackendThrowable(exception)
} }.onSuccess {
Timber.i("Tunnel ${tunnelConf.id} started successfully")
}
}
}
override fun getBackendState(): BackendState { private suspend fun stopActiveTunnels() {
return backend.backendState.asBackendState() activeTunnels.value.forEach { (config, state) ->
} if (state.state.isUp()) {
stopTunnel(config)
delay(300)
}
}
}
override suspend fun runningTunnelNames(): Set<String> { override fun stopTunnel(tunnelConf: TunnelConf?) {
return backend.runningTunnelNames applicationScope.launch(ioDispatcher) {
} runCatching {
val originalTunnel = activeTuns.value.keys.find { it.id == tunnelConf?.id }
if (originalTunnel != null) {
Timber.i("Stopping tunnel ${originalTunnel.id} userspace")
mutex.withLock {
updateTunnelState(originalTunnel, backend.setState(originalTunnel, Tunnel.State.DOWN, originalTunnel.toAmConfig()).asTunnelState())
super.stopTunnel(originalTunnel)
}
} else {
Timber.w("Tunnel not found in startedTunnels, stopping all tunnels")
activeTuns.value.keys.forEach { config ->
stopTunnel(config)
}
}
}.onFailure { e ->
Timber.e(e, "Failed to stop tunnel ${tunnelConf?.id}")
}
}
}
override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? { override suspend fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) {
return try { Timber.d("Setting backend state: $backendState with allowedIps: $allowedIps")
AmneziaStatistics(backend.getStatistics(tunnelConf)) backend.setBackendState(backendState.asAmBackendState(), allowedIps)
} catch (e: Exception) { }
Timber.e(e, "Failed to get stats for ${tunnelConf.tunName}")
null override suspend fun runningTunnelNames(): Set<String> {
} return backend.runningTunnelNames
} }
override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? {
return try {
AmneziaStatistics(backend.getStatistics(tunnelConf))
} catch (e: Exception) {
Timber.e(e, "Failed to get stats for ${tunnelConf.tunName}")
null
}
}
} }
@@ -13,55 +13,48 @@ import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import dagger.assisted.Assisted import dagger.assisted.Assisted
import dagger.assisted.AssistedInject import dagger.assisted.AssistedInject
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
import java.util.concurrent.TimeUnit
@HiltWorker @HiltWorker
class ServiceWorker class ServiceWorker @AssistedInject constructor(
@AssistedInject @Assisted private val context: Context,
constructor( @Assisted private val params: WorkerParameters,
@Assisted private val context: Context, private val serviceManager: ServiceManager,
@Assisted private val params: WorkerParameters, private val appDataRepository: AppDataRepository,
private val serviceManager: ServiceManager, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val appDataRepository: AppDataRepository, private val tunnelManager: TunnelManager,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val tunnelManager: TunnelManager,
) : CoroutineWorker(context, params) { ) : CoroutineWorker(context, params) {
companion object { companion object {
private const val TAG = "service_worker" private const val TAG = "service_worker"
fun stop(context: Context) { fun stop(context: Context) {
WorkManager.getInstance(context).cancelAllWorkByTag(TAG) WorkManager.getInstance(context).cancelAllWorkByTag(TAG)
} }
fun start(context: Context) { fun start(context: Context) {
val periodicWorkRequest = val periodicWorkRequest = PeriodicWorkRequestBuilder<ServiceWorker>(
PeriodicWorkRequestBuilder<ServiceWorker>( repeatInterval = 15,
repeatInterval = 15, repeatIntervalTimeUnit = TimeUnit.MINUTES,
repeatIntervalTimeUnit = TimeUnit.MINUTES, ).build()
) WorkManager.getInstance(context)
.build() .enqueueUniquePeriodicWork(
WorkManager.getInstance(context) TAG,
.enqueueUniquePeriodicWork( ExistingPeriodicWorkPolicy.KEEP,
TAG, periodicWorkRequest,
ExistingPeriodicWorkPolicy.KEEP, )
periodicWorkRequest, }
) }
}
}
override suspend fun doWork(): Result = override suspend fun doWork(): Result = withContext(ioDispatcher) {
withContext(ioDispatcher) { Timber.i("Service worker started")
Timber.i("Service worker started") with(appDataRepository.settings.get()) {
with(appDataRepository.settings.get()) { if (isAutoTunnelEnabled && !serviceManager.autoTunnelActive.value) return@with serviceManager.startAutoTunnel(true)
if (isAutoTunnelEnabled && serviceManager.autoTunnelService.value == null) if (tunnelManager.activeTunnels.value.isEmpty()) tunnelManager.restorePreviousState()
return@with serviceManager.startAutoTunnel() }
if (tunnelManager.activeTunnels.value.isEmpty()) Result.success()
tunnelManager.restorePreviousState() }
}
Result.success()
}
} }
@@ -12,38 +12,79 @@ import com.zaneschepke.wireguardautotunnel.data.model.Settings
import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
@Database( @Database(
entities = [Settings::class, TunnelConfig::class], entities = [Settings::class, TunnelConfig::class],
version = 16, version = 16,
autoMigrations = autoMigrations =
[ [
AutoMigration(from = 1, to = 2), AutoMigration(from = 1, to = 2),
AutoMigration(from = 2, to = 3), AutoMigration(from = 2, to = 3),
AutoMigration(from = 3, to = 4), AutoMigration(
AutoMigration(from = 4, to = 5), from = 3,
AutoMigration(from = 5, to = 6), to = 4,
AutoMigration(from = 6, to = 7, spec = RemoveLegacySettingColumnsMigration::class), ),
AutoMigration(7, 8), AutoMigration(
AutoMigration(8, 9), from = 4,
AutoMigration(9, 10), to = 5,
AutoMigration(from = 10, to = 11, spec = RemoveTunnelPauseMigration::class), ),
AutoMigration(from = 11, to = 12), AutoMigration(
AutoMigration(from = 12, to = 13), from = 5,
AutoMigration(from = 13, to = 14), to = 6,
AutoMigration(from = 14, to = 15), ),
AutoMigration(from = 15, to = 16), AutoMigration(
], from = 6,
exportSchema = true, to = 7,
spec = RemoveLegacySettingColumnsMigration::class,
),
AutoMigration(7, 8),
AutoMigration(8, 9),
AutoMigration(9, 10),
AutoMigration(
from = 10,
to = 11,
spec = RemoveTunnelPauseMigration::class,
),
AutoMigration(
from = 11,
to = 12,
),
AutoMigration(
from = 12,
to = 13,
),
AutoMigration(
from = 13,
to = 14,
),
AutoMigration(
from = 14,
to = 15,
),
AutoMigration(
from = 15,
to = 16,
),
],
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(tableName = "Settings", columnName = "default_tunnel") @DeleteColumn(
@DeleteColumn(tableName = "Settings", columnName = "is_battery_saver_enabled") tableName = "Settings",
columnName = "default_tunnel",
)
@DeleteColumn(
tableName = "Settings",
columnName = "is_battery_saver_enabled",
)
class RemoveLegacySettingColumnsMigration : AutoMigrationSpec class RemoveLegacySettingColumnsMigration : AutoMigrationSpec
@DeleteColumn(tableName = "Settings", columnName = "is_auto_tunnel_paused") @DeleteColumn(
tableName = "Settings",
columnName = "is_auto_tunnel_paused",
)
class RemoveTunnelPauseMigration : AutoMigrationSpec class RemoveTunnelPauseMigration : AutoMigrationSpec
@@ -7,7 +7,6 @@ import androidx.datastore.preferences.core.edit
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.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import java.io.IOException
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
@@ -16,77 +15,80 @@ import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
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 locationDisclosureShown = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN") val locationDisclosureShown = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
val batteryDisableShown = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN") val batteryDisableShown = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
val pinLockEnabled = booleanPreferencesKey("PIN_LOCK_ENABLED") val currentSSID = stringPreferencesKey("CURRENT_SSID")
val expandedTunnelIds = stringPreferencesKey("EXPANDED_TUNNEL_IDS") val pinLockEnabled = booleanPreferencesKey("PIN_LOCK_ENABLED")
val isLocalLogsEnabled = booleanPreferencesKey("LOCAL_LOGS_ENABLED") val tunnelStatsExpanded = booleanPreferencesKey("TUNNEL_STATS_EXPANDED")
val locale = stringPreferencesKey("LOCALE") val isLocalLogsEnabled = booleanPreferencesKey("LOCAL_LOGS_ENABLED")
val theme = stringPreferencesKey("THEME") val locale = stringPreferencesKey("LOCALE")
val isRemoteControlEnabled = booleanPreferencesKey("IS_REMOTE_CONTROL_ENABLED") val theme = stringPreferencesKey("THEME")
val remoteKey = stringPreferencesKey("REMOTE_KEY") }
}
// preferences // preferences
private val preferencesKey = "preferences" private val preferencesKey = "preferences"
private val Context.dataStore by preferencesDataStore(name = preferencesKey) private val Context.dataStore by
preferencesDataStore(
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.Forest.e(e) Timber.Forest.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.Forest.e(e) Timber.Forest.e(e)
} catch (e: Exception) { } catch (e: Exception) {
Timber.Forest.e(e) Timber.Forest.e(e)
} }
} }
} }
suspend fun <T> removeFromDataStore(key: Preferences.Key<T>) { suspend fun <T> removeFromDataStore(key: Preferences.Key<T>) {
withContext(ioDispatcher) { withContext(ioDispatcher) {
try { try {
context.dataStore.edit { it.remove(key) } context.dataStore.edit { it.remove(key) }
} catch (e: IOException) { } catch (e: IOException) {
Timber.Forest.e(e) Timber.Forest.e(e)
} catch (e: Exception) { } catch (e: Exception) {
Timber.Forest.e(e) Timber.Forest.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.Forest.e(e) Timber.Forest.e(e)
null null
} }
} }
} }
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking { fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking {
context.dataStore.data.map { it[key] }.first() context.dataStore.data.map { it[key] }.first()
} }
val preferencesFlow: Flow<Preferences?> = context.dataStore.data.flowOn(ioDispatcher) val preferencesFlow: Flow<Preferences?> = context.dataStore.data.flowOn(ioDispatcher)
} }
@@ -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) = override fun onCreate(db: SupportSQLiteDatabase) = db.run {
db.run { // 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()
} }
} }
} }
@@ -1,23 +1,24 @@
package com.zaneschepke.wireguardautotunnel.data package com.zaneschepke.wireguardautotunnel.data
import androidx.room.TypeConverter import androidx.room.TypeConverter
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,8 +1,8 @@
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,
@@ -24,14 +24,12 @@ object Queries {
'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,19 +10,27 @@ import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface SettingsDao { interface SettingsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun save(t: Settings) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun save(t: Settings)
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun saveAll(t: List<Settings>) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun saveAll(t: List<Settings>)
@Query("SELECT * FROM settings WHERE id=:id") suspend fun getById(id: Long): Settings? @Query("SELECT * FROM settings WHERE id=:id")
suspend fun getById(id: Long): Settings?
@Query("SELECT * FROM settings") suspend fun getAll(): List<Settings> @Query("SELECT * FROM settings")
suspend fun getAll(): List<Settings>
@Query("SELECT * FROM settings LIMIT 1") fun getSettingsFlow(): Flow<Settings> @Query("SELECT * FROM settings LIMIT 1")
fun getSettingsFlow(): Flow<Settings>
@Query("SELECT * FROM settings") fun getAllFlow(): Flow<MutableList<Settings>> @Query("SELECT * FROM settings")
fun getAllFlow(): Flow<MutableList<Settings>>
@Delete suspend fun delete(t: Settings) @Delete
suspend fun delete(t: Settings)
@Query("SELECT COUNT('id') FROM settings") suspend fun count(): Long @Query("SELECT COUNT('id') FROM settings")
suspend fun count(): Long
} }
@@ -11,40 +11,48 @@ import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface TunnelConfigDao { interface TunnelConfigDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun save(t: TunnelConfig) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun save(t: TunnelConfig)
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun saveAll(t: TunnelConfigs) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun saveAll(t: TunnelConfigs)
@Query("SELECT * FROM TunnelConfig WHERE id=:id") suspend fun getById(id: Long): TunnelConfig? @Query("SELECT * FROM TunnelConfig WHERE id=:id")
suspend fun getById(id: Long): TunnelConfig?
@Query("SELECT * FROM TunnelConfig WHERE name=:name") @Query("SELECT * FROM TunnelConfig WHERE name=:name")
suspend fun getByName(name: String): TunnelConfig? suspend fun getByName(name: String): TunnelConfig?
@Query("SELECT * FROM TunnelConfig WHERE is_Active=1") suspend fun getActive(): TunnelConfigs @Query("SELECT * FROM TunnelConfig WHERE is_Active=1")
suspend fun getActive(): TunnelConfigs
@Query("SELECT * FROM TunnelConfig") suspend fun getAll(): TunnelConfigs @Query("SELECT * FROM TunnelConfig")
suspend fun getAll(): TunnelConfigs
@Delete suspend fun delete(t: TunnelConfig) @Delete
suspend fun delete(t: TunnelConfig)
@Query("SELECT COUNT('id') FROM TunnelConfig") suspend fun count(): Long @Query("SELECT COUNT('id') FROM TunnelConfig")
suspend fun count(): Long
@Query("SELECT * FROM TunnelConfig WHERE tunnel_networks LIKE '%' || :name || '%'") @Query("SELECT * FROM TunnelConfig WHERE tunnel_networks LIKE '%' || :name || '%'")
suspend fun findByTunnelNetworkName(name: String): TunnelConfigs suspend fun findByTunnelNetworkName(name: String): TunnelConfigs
@Query("UPDATE TunnelConfig SET is_primary_tunnel = 0 WHERE is_primary_tunnel =1") @Query("UPDATE TunnelConfig SET is_primary_tunnel = 0 WHERE is_primary_tunnel =1")
suspend fun resetPrimaryTunnel() suspend fun resetPrimaryTunnel()
@Query("UPDATE TunnelConfig SET is_mobile_data_tunnel = 0 WHERE is_mobile_data_tunnel =1") @Query("UPDATE TunnelConfig SET is_mobile_data_tunnel = 0 WHERE is_mobile_data_tunnel =1")
suspend fun resetMobileDataTunnel() suspend fun resetMobileDataTunnel()
@Query("UPDATE TunnelConfig SET is_ethernet_tunnel = 0 WHERE is_ethernet_tunnel =1") @Query("UPDATE TunnelConfig SET is_ethernet_tunnel = 0 WHERE is_ethernet_tunnel =1")
suspend fun resetEthernetTunnel() suspend fun resetEthernetTunnel()
@Query("SELECT * FROM TUNNELCONFIG WHERE is_primary_tunnel=1") @Query("SELECT * FROM TUNNELCONFIG WHERE is_primary_tunnel=1")
suspend fun findByPrimary(): TunnelConfigs suspend fun findByPrimary(): TunnelConfigs
@Query("SELECT * FROM TUNNELCONFIG WHERE is_mobile_data_tunnel=1") @Query("SELECT * FROM TUNNELCONFIG WHERE is_mobile_data_tunnel=1")
suspend fun findByMobileDataTunnel(): TunnelConfigs suspend fun findByMobileDataTunnel(): TunnelConfigs
@Query("SELECT * FROM tunnelconfig") fun getAllFlow(): Flow<MutableList<TunnelConfig>> @Query("SELECT * FROM tunnelconfig")
fun getAllFlow(): Flow<MutableList<TunnelConfig>>
} }
@@ -1,10 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Asset(
val name: String,
@SerialName("browser_download_url") val browserDownloadUrl: String,
)
@@ -4,51 +4,43 @@ import com.zaneschepke.wireguardautotunnel.domain.entity.AppState
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme 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 isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT, val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
val expandedTunnelIds: List<Int> = emptyList(), val isTunnelStatsExpanded: Boolean = IS_TUNNEL_STATS_EXPANDED,
val isLocalLogsEnabled: Boolean = IS_LOGS_ENABLED_DEFAULT, val isLocalLogsEnabled: Boolean = IS_LOGS_ENABLED_DEFAULT,
val isRemoteControlEnabled: Boolean = IS_REMOTE_CONTROL_ENABLED, val locale: String? = null,
val remoteKey: String? = null, val theme: Theme = Theme.AUTOMATIC,
val locale: String? = null,
val theme: Theme = Theme.AUTOMATIC,
) { ) {
fun toAppState(): AppState = fun toAppState(): AppState = AppState(
AppState( isLocationDisclosureShown,
isLocationDisclosureShown, isBatteryOptimizationDisableShown,
isBatteryOptimizationDisableShown, isPinLockEnabled,
isPinLockEnabled, isTunnelStatsExpanded,
expandedTunnelIds, isLocationDisclosureShown,
isLocalLogsEnabled, locale,
isRemoteControlEnabled, theme,
remoteKey, )
locale,
theme,
)
companion object { companion object {
fun from(appState: AppState): GeneralState { fun from(appState: AppState): GeneralState {
return with(appState) { return with(appState) {
GeneralState( GeneralState(
isLocationDisclosureShown, isLocationDisclosureShown,
isBatteryOptimizationDisableShown, isBatteryOptimizationDisableShown,
isPinLockEnabled, isPinLockEnabled,
expandedTunnelIds, isTunnelStatsExpanded,
isLocalLogsEnabled, isLocationDisclosureShown,
isRemoteControlEnabled, locale,
remoteKey, theme,
locale, )
theme, }
) }
} const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
} const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
const val PIN_LOCK_ENABLED_DEFAULT = false
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false const val IS_TUNNEL_STATS_EXPANDED = false
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false const val IS_LOGS_ENABLED_DEFAULT = false
const val PIN_LOCK_ENABLED_DEFAULT = false }
const val IS_LOGS_ENABLED_DEFAULT = false
const val IS_REMOTE_CONTROL_ENABLED = false
}
} }
@@ -1,24 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.model
import com.zaneschepke.wireguardautotunnel.domain.entity.AppUpdate
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GitHubRelease(
@SerialName("tag_name") val tagName: String,
val name: String?,
val body: String?,
val assets: List<Asset>,
) {
fun toAppUpdate(): AppUpdate {
val apkAsset = assets.firstOrNull { it.name.endsWith(".apk") }
return AppUpdate(
version = tagName.removePrefix("v"),
title = name ?: "Update $tagName",
releaseNotes = body ?: "No release notes provided",
apkUrl = apkAsset?.browserDownloadUrl,
apkFileName = apkAsset?.name,
)
}
}
@@ -7,100 +7,112 @@ import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings
@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(name = "is_shortcuts_enabled", defaultValue = "false") @ColumnInfo(
val isShortcutsEnabled: Boolean = false, name = "is_shortcuts_enabled",
@ColumnInfo(name = "is_tunnel_on_wifi_enabled", defaultValue = "false") defaultValue = "false",
val isTunnelOnWifiEnabled: Boolean = false, )
@ColumnInfo(name = "is_kernel_enabled", defaultValue = "false") val isShortcutsEnabled: Boolean = false,
val isKernelEnabled: Boolean = false, @ColumnInfo(
@ColumnInfo(name = "is_restore_on_boot_enabled", defaultValue = "false") name = "is_tunnel_on_wifi_enabled",
val isRestoreOnBootEnabled: Boolean = false, defaultValue = "false",
@ColumnInfo(name = "is_multi_tunnel_enabled", defaultValue = "false") )
val isMultiTunnelEnabled: Boolean = false, val isTunnelOnWifiEnabled: Boolean = false,
@ColumnInfo(name = "is_ping_enabled", defaultValue = "false") @ColumnInfo(
val isPingEnabled: Boolean = false, name = "is_kernel_enabled",
@ColumnInfo(name = "is_amnezia_enabled", defaultValue = "false") defaultValue = "false",
val isAmneziaEnabled: Boolean = false, )
@ColumnInfo(name = "is_wildcards_enabled", defaultValue = "false") val isKernelEnabled: Boolean = false,
val isWildcardsEnabled: Boolean = false, @ColumnInfo(
@ColumnInfo(name = "is_wifi_by_shell_enabled", defaultValue = "false") name = "is_restore_on_boot_enabled",
val isWifiNameByShellEnabled: Boolean = false, defaultValue = "false",
@ColumnInfo(name = "is_stop_on_no_internet_enabled", defaultValue = "false") )
val isStopOnNoInternetEnabled: Boolean = false, val isRestoreOnBootEnabled: Boolean = false,
@ColumnInfo(name = "is_vpn_kill_switch_enabled", defaultValue = "false") @ColumnInfo(
val isVpnKillSwitchEnabled: Boolean = false, name = "is_multi_tunnel_enabled",
@ColumnInfo(name = "is_kernel_kill_switch_enabled", defaultValue = "false") defaultValue = "false",
val isKernelKillSwitchEnabled: Boolean = false, )
@ColumnInfo(name = "is_lan_on_kill_switch_enabled", defaultValue = "false") val isMultiTunnelEnabled: Boolean = false,
val isLanOnKillSwitchEnabled: Boolean = false, @ColumnInfo(
@ColumnInfo(name = "debounce_delay_seconds", defaultValue = "3") name = "is_ping_enabled",
val debounceDelaySeconds: Int = 3, defaultValue = "false",
@ColumnInfo(name = "is_disable_kill_switch_on_trusted_enabled", defaultValue = "false") )
val isDisableKillSwitchOnTrustedEnabled: Boolean = false, val isPingEnabled: Boolean = false,
@ColumnInfo(
name = "is_amnezia_enabled",
defaultValue = "false",
)
val isAmneziaEnabled: Boolean = false,
@ColumnInfo(
name = "is_wildcards_enabled",
defaultValue = "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,
@ColumnInfo(
name = "debounce_delay_seconds",
defaultValue = "3",
)
val debounceDelaySeconds: Int = 3,
@ColumnInfo(
name = "is_disable_kill_switch_on_trusted_enabled",
defaultValue = "false",
)
val isDisableKillSwitchOnTrustedEnabled: Boolean = false,
) { ) {
fun toAppSettings(): AppSettings { fun toAppSettings(): AppSettings {
return AppSettings( return AppSettings(
id, id, isAutoTunnelEnabled, isTunnelOnMobileDataEnabled, trustedNetworkSSIDs, isAlwaysOnVpnEnabled, isTunnelOnEthernetEnabled,
isAutoTunnelEnabled, isShortcutsEnabled, isTunnelOnWifiEnabled, isKernelEnabled, isRestoreOnBootEnabled, isMultiTunnelEnabled, isPingEnabled,
isTunnelOnMobileDataEnabled, isAmneziaEnabled, isWildcardsEnabled, isWifiNameByShellEnabled, isStopOnNoInternetEnabled, isVpnKillSwitchEnabled,
trustedNetworkSSIDs, isKernelKillSwitchEnabled, isLanOnKillSwitchEnabled, debounceDelaySeconds, isDisableKillSwitchOnTrustedEnabled,
isAlwaysOnVpnEnabled, )
isTunnelOnEthernetEnabled, }
isShortcutsEnabled,
isTunnelOnWifiEnabled,
isKernelEnabled,
isRestoreOnBootEnabled,
isMultiTunnelEnabled,
isPingEnabled,
isAmneziaEnabled,
isWildcardsEnabled,
isWifiNameByShellEnabled,
isStopOnNoInternetEnabled,
isVpnKillSwitchEnabled,
isKernelKillSwitchEnabled,
isLanOnKillSwitchEnabled,
debounceDelaySeconds,
isDisableKillSwitchOnTrustedEnabled,
)
}
companion object { companion object {
fun from(appSettings: AppSettings): Settings { fun from(appSettings: AppSettings): Settings {
return with(appSettings) { return with(appSettings) {
Settings( Settings(
id, id, isAutoTunnelEnabled, isTunnelOnMobileDataEnabled, trustedNetworkSSIDs.toMutableList(), isAlwaysOnVpnEnabled,
isAutoTunnelEnabled, isTunnelOnEthernetEnabled, isShortcutsEnabled, isTunnelOnWifiEnabled, isKernelEnabled, isRestoreOnBootEnabled,
isTunnelOnMobileDataEnabled, isMultiTunnelEnabled, isPingEnabled, isAmneziaEnabled, isWildcardsEnabled, isWifiNameByShellEnabled,
trustedNetworkSSIDs.toMutableList(), isStopOnNoInternetEnabled, isVpnKillSwitchEnabled, isKernelKillSwitchEnabled, isLanOnKillSwitchEnabled,
isAlwaysOnVpnEnabled, debounceDelaySeconds, isDisableKillSwitchOnTrustedEnabled,
isTunnelOnEthernetEnabled, )
isShortcutsEnabled, }
isTunnelOnWifiEnabled, }
isKernelEnabled, }
isRestoreOnBootEnabled,
isMultiTunnelEnabled,
isPingEnabled,
isAmneziaEnabled,
isWildcardsEnabled,
isWifiNameByShellEnabled,
isStopOnNoInternetEnabled,
isVpnKillSwitchEnabled,
isKernelKillSwitchEnabled,
isLanOnKillSwitchEnabled,
debounceDelaySeconds,
isDisableKillSwitchOnTrustedEnabled,
)
}
}
}
} }
@@ -8,70 +8,86 @@ import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
@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(name = "tunnel_networks", defaultValue = "") @ColumnInfo(
val tunnelNetworks: MutableList<String> = mutableListOf(), name = "tunnel_networks",
@ColumnInfo(name = "is_mobile_data_tunnel", defaultValue = "false") defaultValue = "",
val isMobileDataTunnel: Boolean = false, )
@ColumnInfo(name = "is_primary_tunnel", defaultValue = "false") val tunnelNetworks: MutableList<String> = mutableListOf(),
val isPrimaryTunnel: Boolean = false, @ColumnInfo(
@ColumnInfo(name = "am_quick", defaultValue = "") val amQuick: String = AM_QUICK_DEFAULT, name = "is_mobile_data_tunnel",
@ColumnInfo(name = "is_Active", defaultValue = "false") val isActive: Boolean = false, defaultValue = "false",
@ColumnInfo(name = "is_ping_enabled", defaultValue = "false") )
val isPingEnabled: Boolean = false, val isMobileDataTunnel: Boolean = false,
@ColumnInfo(name = "ping_interval", defaultValue = "null") val pingInterval: Long? = null, @ColumnInfo(
@ColumnInfo(name = "ping_cooldown", defaultValue = "null") val pingCooldown: Long? = null, name = "is_primary_tunnel",
@ColumnInfo(name = "ping_ip", defaultValue = "null") var pingIp: String? = null, defaultValue = "false",
@ColumnInfo(name = "is_ethernet_tunnel", defaultValue = "false") )
var isEthernetTunnel: Boolean = false, val isPrimaryTunnel: Boolean = false,
@ColumnInfo(name = "is_ipv4_preferred", defaultValue = "true") @ColumnInfo(
var isIpv4Preferred: Boolean = true, name = "am_quick",
defaultValue = "",
)
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,
@ColumnInfo(
name = "is_ipv4_preferred",
defaultValue = "true",
)
var isIpv4Preferred: Boolean = true,
) { ) {
fun toTunnel(): TunnelConf { fun toTunnel(): TunnelConf {
return TunnelConf( return TunnelConf(
id, id, name, wgQuick, tunnelNetworks, isMobileDataTunnel,
name, isPrimaryTunnel, amQuick, isActive, isPingEnabled, pingInterval,
wgQuick, pingCooldown, pingIp, isEthernetTunnel, isIpv4Preferred,
tunnelNetworks, )
isMobileDataTunnel, }
isPrimaryTunnel,
amQuick,
isActive,
isPingEnabled,
pingInterval,
pingCooldown,
pingIp,
isEthernetTunnel,
isIpv4Preferred,
)
}
companion object { companion object {
const val AM_QUICK_DEFAULT = "" const val AM_QUICK_DEFAULT = ""
fun from(tunnelConf: TunnelConf): TunnelConfig { fun from(tunnelConf: TunnelConf): TunnelConfig {
return with(tunnelConf) { return with(tunnelConf) {
return TunnelConfig( return TunnelConfig(
id, id, tunName, wgQuick, tunnelNetworks.toMutableList(), isMobileDataTunnel,
tunName, isPrimaryTunnel, amQuick, isActive, isPingEnabled, pingInterval,
wgQuick, pingCooldown, pingIp, isEthernetTunnel, isIpv4Preferred,
tunnelNetworks.toMutableList(), )
isMobileDataTunnel, }
isPrimaryTunnel, }
amQuick, }
isActive,
isPingEnabled,
pingInterval,
pingCooldown,
pingIp,
isEthernetTunnel,
isIpv4Preferred,
)
}
}
}
} }
@@ -1,9 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.network
import com.zaneschepke.wireguardautotunnel.data.model.GitHubRelease
interface GitHubApi {
suspend fun getLatestRelease(owner: String, repo: String): Result<GitHubRelease>
suspend fun getNightlyRelease(owner: String, repo: String): Result<GitHubRelease>
}
@@ -1,28 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.network
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
object KtorClient {
fun create(): HttpClient {
return HttpClient(OkHttp) {
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
isLenient = true
}
)
}
install(HttpTimeout) {
requestTimeoutMillis = 15000
connectTimeoutMillis = 15000
socketTimeoutMillis = 15000
}
}
}
}
@@ -1,56 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.network
import com.zaneschepke.wireguardautotunnel.data.model.GitHubRelease
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.request.get
import io.ktor.http.HttpStatusCode
class KtorGitHubApi(private val client: HttpClient) : GitHubApi {
override suspend fun getLatestRelease(owner: String, repo: String): Result<GitHubRelease> {
return try {
val response: GitHubRelease =
client.get("https://api.github.com/repos/$owner/$repo/releases/latest").body()
Result.success(response)
} catch (e: ClientRequestException) {
when (e.response.status) {
HttpStatusCode.Forbidden -> Result.failure(Exception("Rate limit exceeded"))
HttpStatusCode.NotFound ->
Result.failure(Exception("Repository or release not found"))
else -> Result.failure(e)
}
} catch (e: Exception) {
Result.failure(e)
}
}
override suspend fun getNightlyRelease(owner: String, repo: String): Result<GitHubRelease> {
return try {
// Fetch all releases
val releases: List<GitHubRelease> =
client.get("https://api.github.com/repos/$owner/$repo/releases").body()
// Find the first release with "nightly" in the tag_name (case-insensitive)
val nightlyRelease =
releases.firstOrNull { release ->
release.tagName.contains("nightly", ignoreCase = true)
}
if (nightlyRelease != null) {
Result.success(nightlyRelease)
} else {
Result.failure(Exception("No release with 'nightly' tag found"))
}
} catch (e: ClientRequestException) {
when (e.response.status) {
HttpStatusCode.Forbidden -> Result.failure(Exception("Rate limit exceeded"))
HttpStatusCode.NotFound ->
Result.failure(Exception("Repository or release not found"))
else -> Result.failure(e)
}
} catch (e: Exception) {
Result.failure(e)
}
}
}
@@ -1,28 +1,28 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import javax.inject.Inject import javax.inject.Inject
class AppDataRoomRepository class AppDataRoomRepository
@Inject @Inject
constructor( constructor(
override val settings: AppSettingRepository, override val settings: AppSettingRepository,
override val tunnels: TunnelRepository, override val tunnels: TunnelRepository,
override val appState: AppStateRepository, override val appState: AppStateRepository,
) : AppDataRepository { ) : AppDataRepository {
override suspend fun getPrimaryOrFirstTunnel(): TunnelConf? { override suspend fun getPrimaryOrFirstTunnel(): TunnelConf? {
return tunnels.findPrimary().firstOrNull() ?: tunnels.getAll().firstOrNull() return tunnels.findPrimary().firstOrNull() ?: tunnels.getAll().firstOrNull()
} }
override suspend fun getStartTunnelConfig(): TunnelConf? { override suspend fun getStartTunnelConfig(): TunnelConf? {
tunnels.getActive().let { tunnels.getActive().let {
if (it.isNotEmpty()) return it.first() if (it.isNotEmpty()) return it.first()
return getPrimaryOrFirstTunnel() return getPrimaryOrFirstTunnel()
} }
} }
} }
@@ -1,157 +1,106 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.DataStoreManager import com.zaneschepke.wireguardautotunnel.data.DataStoreManager
import com.zaneschepke.wireguardautotunnel.data.model.GeneralState
import com.zaneschepke.wireguardautotunnel.domain.entity.AppState
import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.data.model.GeneralState
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme 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.locationDisclosureShown) 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.locationDisclosureShown, shown) dataStoreManager.saveToDataStore(DataStoreManager.locationDisclosureShown, shown)
} }
override suspend fun isPinLockEnabled(): Boolean { override suspend fun isPinLockEnabled(): Boolean {
return dataStoreManager.getFromStore(DataStoreManager.pinLockEnabled) 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.pinLockEnabled, enabled) dataStoreManager.saveToDataStore(DataStoreManager.pinLockEnabled, enabled)
} }
override suspend fun isBatteryOptimizationDisableShown(): Boolean { override suspend fun isBatteryOptimizationDisableShown(): Boolean {
return dataStoreManager.getFromStore(DataStoreManager.batteryDisableShown) 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.batteryDisableShown, shown) dataStoreManager.saveToDataStore(DataStoreManager.batteryDisableShown, shown)
} }
override suspend fun setTunnelExpanded(id: Int) { override suspend fun isTunnelStatsExpanded(): Boolean {
val ids = return dataStoreManager.getFromStore(DataStoreManager.tunnelStatsExpanded)
dataStoreManager ?: GeneralState.IS_TUNNEL_STATS_EXPANDED
.getFromStore(DataStoreManager.expandedTunnelIds) }
?.split(",")
?.mapNotNull { it.toIntOrNull() } ?: emptyList()
if (ids.contains(id)) return override suspend fun setTunnelStatsExpanded(expanded: Boolean) {
dataStoreManager.saveToDataStore(DataStoreManager.tunnelStatsExpanded, expanded)
}
val updatedList = ids.toMutableList().apply { add(id) } override suspend fun setTheme(theme: Theme) {
dataStoreManager.saveToDataStore( dataStoreManager.saveToDataStore(DataStoreManager.theme, theme.name)
DataStoreManager.expandedTunnelIds, }
updatedList.joinToString(","),
)
}
override suspend fun removeTunnelExpanded(id: Int) { override suspend fun getTheme(): Theme {
val ids = return dataStoreManager.getFromStore(DataStoreManager.theme)?.let {
dataStoreManager try {
.getFromStore(DataStoreManager.expandedTunnelIds) Theme.valueOf(it)
?.split(",") } catch (_: IllegalArgumentException) {
?.mapNotNull { it.toIntOrNull() } ?: emptyList() Theme.AUTOMATIC
}
} ?: Theme.AUTOMATIC
}
if (ids.isEmpty() || !ids.contains(id)) return override suspend fun isLocalLogsEnabled(): Boolean {
return dataStoreManager.getFromStore(DataStoreManager.isLocalLogsEnabled) ?: GeneralState.IS_LOGS_ENABLED_DEFAULT
}
val updatedList = ids.toMutableList().apply { remove(id) } override suspend fun setLocalLogsEnabled(enabled: Boolean) {
dataStoreManager.saveToDataStore( dataStoreManager.saveToDataStore(DataStoreManager.isLocalLogsEnabled, enabled)
DataStoreManager.expandedTunnelIds, }
updatedList.joinToString(","),
)
}
override suspend fun setTheme(theme: Theme) { override suspend fun setLocale(localeTag: String) {
dataStoreManager.saveToDataStore(DataStoreManager.theme, theme.name) dataStoreManager.saveToDataStore(DataStoreManager.locale, localeTag)
} }
override suspend fun getTheme(): Theme { override suspend fun getLocale(): String? {
return dataStoreManager.getFromStore(DataStoreManager.theme)?.let { return dataStoreManager.getFromStore(DataStoreManager.locale)
try { }
Theme.valueOf(it)
} catch (_: IllegalArgumentException) {
Theme.AUTOMATIC
}
} ?: Theme.AUTOMATIC
}
override suspend fun isLocalLogsEnabled(): Boolean { override val flow: Flow<GeneralState> =
return dataStoreManager.getFromStore(DataStoreManager.isLocalLogsEnabled) dataStoreManager.preferencesFlow.map { prefs ->
?: GeneralState.IS_LOGS_ENABLED_DEFAULT prefs?.let { pref ->
} try {
GeneralState(
override suspend fun setLocalLogsEnabled(enabled: Boolean) { isLocationDisclosureShown =
dataStoreManager.saveToDataStore(DataStoreManager.isLocalLogsEnabled, enabled) pref[DataStoreManager.locationDisclosureShown]
} ?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
isBatteryOptimizationDisableShown =
override suspend fun setLocale(localeTag: String) { pref[DataStoreManager.batteryDisableShown]
dataStoreManager.saveToDataStore(DataStoreManager.locale, localeTag) ?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
} isPinLockEnabled =
pref[DataStoreManager.pinLockEnabled]
override suspend fun getLocale(): String? { ?: GeneralState.PIN_LOCK_ENABLED_DEFAULT,
return dataStoreManager.getFromStore(DataStoreManager.locale) isTunnelStatsExpanded = pref[DataStoreManager.tunnelStatsExpanded] ?: GeneralState.IS_TUNNEL_STATS_EXPANDED,
} isLocalLogsEnabled = pref[DataStoreManager.isLocalLogsEnabled] ?: GeneralState.IS_LOGS_ENABLED_DEFAULT,
locale = pref[DataStoreManager.locale],
override suspend fun setIsRemoteControlEnabled(enabled: Boolean) { theme = getTheme(),
dataStoreManager.saveToDataStore(DataStoreManager.isRemoteControlEnabled, enabled) )
} } catch (e: IllegalArgumentException) {
Timber.e(e)
override suspend fun isRemoteControlEnabled(): Boolean { GeneralState()
return dataStoreManager.getFromStore(DataStoreManager.isRemoteControlEnabled) }
?: GeneralState.IS_REMOTE_CONTROL_ENABLED } ?: GeneralState()
} }
override suspend fun setRemoteKey(key: String) {
dataStoreManager.saveToDataStore(DataStoreManager.remoteKey, key)
}
override suspend fun getRemoteKey(): String? {
return dataStoreManager.getFromStore(DataStoreManager.remoteKey)
}
override val flow: Flow<AppState> =
dataStoreManager.preferencesFlow
.map { prefs ->
prefs?.let { pref ->
try {
GeneralState(
isLocationDisclosureShown =
pref[DataStoreManager.locationDisclosureShown]
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
isBatteryOptimizationDisableShown =
pref[DataStoreManager.batteryDisableShown]
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
isPinLockEnabled =
pref[DataStoreManager.pinLockEnabled]
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT,
expandedTunnelIds =
pref[DataStoreManager.expandedTunnelIds]?.split(",")?.mapNotNull {
it.toIntOrNull()
} ?: emptyList(),
isLocalLogsEnabled =
pref[DataStoreManager.isLocalLogsEnabled]
?: GeneralState.IS_LOGS_ENABLED_DEFAULT,
isRemoteControlEnabled =
pref[DataStoreManager.isRemoteControlEnabled]
?: GeneralState.IS_REMOTE_CONTROL_ENABLED,
remoteKey = pref[DataStoreManager.remoteKey],
locale = pref[DataStoreManager.locale],
theme = getTheme(),
)
} catch (e: IllegalArgumentException) {
Timber.e(e)
GeneralState()
}
} ?: GeneralState()
}
.map { it.toAppState() }
} }
@@ -1,98 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.repository
import android.content.Context
import com.zaneschepke.wireguardautotunnel.BuildConfig
import com.zaneschepke.wireguardautotunnel.data.network.GitHubApi
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.AppUpdate
import com.zaneschepke.wireguardautotunnel.domain.repository.UpdateRepository
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.contentLength
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.readAvailable
import java.io.File
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import timber.log.Timber
class GitHubUpdateRepository(
private val gitHubApi: GitHubApi,
private val httpClient: HttpClient,
private val githubOwner: String,
private val githubRepo: String,
private val context: Context,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : UpdateRepository {
override suspend fun checkForUpdate(currentVersion: String): Result<AppUpdate?> =
withContext(ioDispatcher) {
Timber.i("Checking for update")
val release =
if (BuildConfig.VERSION_NAME.contains("nightly")) {
gitHubApi.getNightlyRelease(githubOwner, githubRepo)
} else {
gitHubApi.getLatestRelease(githubOwner, githubRepo)
}
release.map { release ->
val apkAsset =
release.assets.find { asset ->
asset.name.startsWith("wgtunnel-full-v") && asset.name.endsWith(".apk")
}
val newVersion =
apkAsset?.name?.removePrefix("wgtunnel-full-v")?.removeSuffix(".apk")
?: return@map null
Timber.i("Latest version: $newVersion, current version: $currentVersion")
if (NumberUtils.compareVersions(newVersion, currentVersion) > 0) {
release.toAppUpdate()
} else {
null
}
}
}
override suspend fun downloadApk(
apkUrl: String,
fileName: String,
onProgress: (Float) -> Unit,
): Result<File> =
withContext(ioDispatcher) {
try {
// clean up old files
context.getExternalFilesDir(null)?.listFiles()?.forEach { file ->
if (file.extension == "apk") file.delete()
}
val response: HttpResponse = httpClient.get(apkUrl)
val apkFile = File(context.getExternalFilesDir(null), fileName)
val channel: ByteReadChannel = response.bodyAsChannel()
val totalBytes: Long = response.contentLength() ?: -1L
var bytesCopied = 0L
apkFile.outputStream().use { output ->
val buffer = ByteArray(8 * 1024)
while (!channel.isClosedForRead) {
val bytesRead = channel.readAvailable(buffer)
if (bytesRead <= 0) break
output.write(buffer, 0, bytesRead)
bytesCopied += bytesRead
if (totalBytes > 0) {
val progress = bytesCopied.toFloat() / totalBytes
onProgress(progress.coerceIn(0f, 1f))
}
}
}
Result.success(apkFile)
} catch (e: Exception) {
Result.failure(e)
}
}
}
@@ -1,30 +1,31 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao
import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository
import com.zaneschepke.wireguardautotunnel.data.model.Settings import com.zaneschepke.wireguardautotunnel.data.model.Settings
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
class RoomSettingsRepository( class RoomSettingsRepository(
private val settingsDoa: SettingsDao, private val settingsDoa: SettingsDao,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : AppSettingRepository { ) : AppSettingRepository {
override suspend fun save(appSettings: AppSettings) { override suspend fun save(appSettings: AppSettings) {
withContext(ioDispatcher) { settingsDoa.save(Settings.from(appSettings)) } withContext(ioDispatcher) {
} settingsDoa.save(Settings.from(appSettings))
}
}
override val flow = override val flow = settingsDoa.getSettingsFlow().flowOn(ioDispatcher).map { it.toAppSettings() }
settingsDoa.getSettingsFlow().flowOn(ioDispatcher).map { it.toAppSettings() }
override suspend fun get(): AppSettings { override suspend fun get(): AppSettings {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
(settingsDoa.getAll().firstOrNull() ?: Settings()).toAppSettings() (settingsDoa.getAll().firstOrNull() ?: Settings()).toAppSettings()
} }
} }
} }
@@ -1,10 +1,10 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
@@ -12,81 +12,96 @@ import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
class RoomTunnelRepository( class RoomTunnelRepository(
private val tunnelConfigDao: TunnelConfigDao, private val tunnelConfigDao: TunnelConfigDao,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : TunnelRepository { ) : TunnelRepository {
override val flow = override val flow = tunnelConfigDao.getAllFlow().flowOn(ioDispatcher).map { it.map { it.toTunnel() } }
tunnelConfigDao.getAllFlow().flowOn(ioDispatcher).map { it.map { it.toTunnel() } }
override suspend fun getAll(): Tunnels { override suspend fun getAll(): Tunnels {
return withContext(ioDispatcher) { tunnelConfigDao.getAll().map { it.toTunnel() } } return withContext(ioDispatcher) {
} tunnelConfigDao.getAll().map { it.toTunnel() }
}
}
override suspend fun save(tunnelConf: TunnelConf) { override suspend fun save(tunnelConf: TunnelConf) {
withContext(ioDispatcher) { tunnelConfigDao.save(TunnelConfig.from(tunnelConf)) } withContext(ioDispatcher) {
} tunnelConfigDao.save(TunnelConfig.from(tunnelConf))
}
}
override suspend fun saveAll(tunnelConfList: List<TunnelConf>) { override suspend fun updatePrimaryTunnel(tunnelConf: TunnelConf?) {
withContext(ioDispatcher) { withContext(ioDispatcher) {
tunnelConfigDao.saveAll(tunnelConfList.map(TunnelConfig::from)) tunnelConfigDao.resetPrimaryTunnel()
} tunnelConf?.let {
} save(
it.copy(
isPrimaryTunnel = true,
),
)
}
}
}
override suspend fun updatePrimaryTunnel(tunnelConf: TunnelConf?) { override suspend fun updateMobileDataTunnel(tunnelConf: TunnelConf?) {
withContext(ioDispatcher) { withContext(ioDispatcher) {
tunnelConfigDao.resetPrimaryTunnel() tunnelConfigDao.resetMobileDataTunnel()
tunnelConf?.let { save(it.copy(isPrimaryTunnel = true)) } tunnelConf?.let {
} save(
} it.copy(
isMobileDataTunnel = true,
),
)
}
}
}
override suspend fun updateMobileDataTunnel(tunnelConf: TunnelConf?) { override suspend fun updateEthernetTunnel(tunnelConf: TunnelConf?) {
withContext(ioDispatcher) { withContext(ioDispatcher) {
tunnelConfigDao.resetMobileDataTunnel() tunnelConfigDao.resetEthernetTunnel()
tunnelConf?.let { save(it.copy(isMobileDataTunnel = true)) } tunnelConf?.let {
} save(
} it.copy(
isEthernetTunnel = true,
),
)
}
}
}
override suspend fun updateEthernetTunnel(tunnelConf: TunnelConf?) { override suspend fun delete(tunnelConf: TunnelConf) {
withContext(ioDispatcher) { withContext(ioDispatcher) {
tunnelConfigDao.resetEthernetTunnel() tunnelConfigDao.delete(TunnelConfig.from(tunnelConf))
tunnelConf?.let { save(it.copy(isEthernetTunnel = true)) } }
} }
}
override suspend fun delete(tunnelConf: TunnelConf) { override suspend fun getById(id: Int): TunnelConf? {
withContext(ioDispatcher) { tunnelConfigDao.delete(TunnelConfig.from(tunnelConf)) } return withContext(ioDispatcher) { tunnelConfigDao.getById(id.toLong())?.toTunnel() }
} }
override suspend fun getById(id: Int): TunnelConf? { override suspend fun getActive(): Tunnels {
return withContext(ioDispatcher) { tunnelConfigDao.getById(id.toLong())?.toTunnel() } return withContext(ioDispatcher) {
} tunnelConfigDao.getActive().map { it.toTunnel() }
}
}
override suspend fun getActive(): Tunnels { override suspend fun count(): Int {
return withContext(ioDispatcher) { tunnelConfigDao.getActive().map { it.toTunnel() } } return withContext(ioDispatcher) { tunnelConfigDao.count().toInt() }
} }
override suspend fun count(): Int { override suspend fun findByTunnelName(name: String): TunnelConf? {
return withContext(ioDispatcher) { tunnelConfigDao.count().toInt() } return withContext(ioDispatcher) { tunnelConfigDao.getByName(name)?.toTunnel() }
} }
override suspend fun findByTunnelName(name: String): TunnelConf? { override suspend fun findByTunnelNetworksName(name: String): Tunnels {
return withContext(ioDispatcher) { tunnelConfigDao.getByName(name)?.toTunnel() } return withContext(ioDispatcher) { tunnelConfigDao.findByTunnelNetworkName(name).map { it.toTunnel() } }
} }
override suspend fun findByTunnelNetworksName(name: String): Tunnels { override suspend fun findByMobileDataTunnel(): Tunnels {
return withContext(ioDispatcher) { return withContext(ioDispatcher) { tunnelConfigDao.findByMobileDataTunnel().map { it.toTunnel() } }
tunnelConfigDao.findByTunnelNetworkName(name).map { it.toTunnel() } }
}
}
override suspend fun findByMobileDataTunnel(): Tunnels { override suspend fun findPrimary(): Tunnels {
return withContext(ioDispatcher) { return withContext(ioDispatcher) { tunnelConfigDao.findByPrimary().map { it.toTunnel() } }
tunnelConfigDao.findByMobileDataTunnel().map { it.toTunnel() } }
}
}
override suspend fun findPrimary(): Tunnels {
return withContext(ioDispatcher) { tunnelConfigDao.findByPrimary().map { it.toTunnel() } }
}
} }
@@ -12,39 +12,35 @@ import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import javax.inject.Singleton
@Module @Module
@InstallIn(SingletonComponent::class) @InstallIn(SingletonComponent::class)
class AppModule { class AppModule {
@Singleton @Singleton
@ApplicationScope @ApplicationScope
@Provides @Provides
fun providesApplicationScope( fun providesApplicationScope(@DefaultDispatcher defaultDispatcher: CoroutineDispatcher): CoroutineScope =
@DefaultDispatcher defaultDispatcher: CoroutineDispatcher CoroutineScope(SupervisorJob() + defaultDispatcher)
): CoroutineScope = CoroutineScope(SupervisorJob() + defaultDispatcher)
@Singleton @Singleton
@Provides @Provides
fun provideLogCollect(@ApplicationContext context: Context): LogReader { fun provideLogCollect(@ApplicationContext context: Context): LogReader {
return LogcatReader.init(storageDir = context.filesDir.absolutePath) return LogcatReader.init(storageDir = context.filesDir.absolutePath)
} }
@Singleton @Singleton
@Provides @Provides
fun provideNotificationService(@ApplicationContext context: Context): NotificationManager { fun provideNotificationService(@ApplicationContext context: Context): NotificationManager {
return WireGuardNotification(context) return WireGuardNotification(context)
} }
@Singleton @Singleton
@Provides @Provides
fun provideShortcutManager( fun provideShortcutManager(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): ShortcutManager {
@ApplicationContext context: Context, return DynamicShortcutManager(context, ioDispatcher)
@IoDispatcher ioDispatcher: CoroutineDispatcher, }
): ShortcutManager {
return DynamicShortcutManager(context, ioDispatcher)
}
} }
@@ -2,10 +2,18 @@ package com.zaneschepke.wireguardautotunnel.di
import javax.inject.Qualifier import javax.inject.Qualifier
@Qualifier @Retention(AnnotationRetention.BINARY) annotation class TunnelShell @Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class TunnelShell
@Qualifier @Retention(AnnotationRetention.BINARY) annotation class AppShell @Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class AppShell
@Qualifier @Retention(AnnotationRetention.BINARY) annotation class Kernel @Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class Kernel
@Qualifier @Retention(AnnotationRetention.BINARY) annotation class Userspace @Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class Userspace
@@ -2,14 +2,26 @@ package com.zaneschepke.wireguardautotunnel.di
import javax.inject.Qualifier import javax.inject.Qualifier
@Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class DefaultDispatcher @Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class DefaultDispatcher
@Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class IoDispatcher @Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class IoDispatcher
@Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class MainDispatcher @Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class MainDispatcher
@Retention(AnnotationRetention.BINARY) @Qualifier annotation class MainImmediateDispatcher @Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class MainImmediateDispatcher
@Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class ApplicationScope @Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ApplicationScope
@Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class ServiceScope @Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ServiceScope
@@ -10,15 +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 @Provides fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO @IoDispatcher
@Provides
fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
@MainDispatcher @Provides fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main @MainDispatcher
@Provides
fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main
@MainImmediateDispatcher @MainImmediateDispatcher
@Provides @Provides
fun providesMainImmediateDispatcher(): CoroutineDispatcher = Dispatchers.Main.immediate fun providesMainImmediateDispatcher(): CoroutineDispatcher = Dispatchers.Main.immediate
} }
@@ -4,130 +4,85 @@ import android.content.Context
import androidx.room.Room import androidx.room.Room
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.data.AppDatabase import com.zaneschepke.wireguardautotunnel.data.AppDatabase
import com.zaneschepke.wireguardautotunnel.data.DataStoreManager
import com.zaneschepke.wireguardautotunnel.data.DatabaseCallback import com.zaneschepke.wireguardautotunnel.data.DatabaseCallback
import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao
import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao
import com.zaneschepke.wireguardautotunnel.data.network.GitHubApi import com.zaneschepke.wireguardautotunnel.data.DataStoreManager
import com.zaneschepke.wireguardautotunnel.data.network.KtorClient import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.data.network.KtorGitHubApi
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRoomRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRoomRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.data.repository.DataStoreAppStateRepository import com.zaneschepke.wireguardautotunnel.data.repository.DataStoreAppStateRepository
import com.zaneschepke.wireguardautotunnel.data.repository.GitHubUpdateRepository
import com.zaneschepke.wireguardautotunnel.data.repository.RoomSettingsRepository import com.zaneschepke.wireguardautotunnel.data.repository.RoomSettingsRepository
import com.zaneschepke.wireguardautotunnel.data.repository.RoomTunnelRepository import com.zaneschepke.wireguardautotunnel.data.repository.RoomTunnelRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.UpdateRepository
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent import dagger.hilt.components.SingletonComponent
import io.ktor.client.HttpClient
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
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(true) .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( fun provideTunnelConfigRepository(tunnelConfigDao: TunnelConfigDao, @IoDispatcher ioDispatcher: CoroutineDispatcher): TunnelRepository {
tunnelConfigDao: TunnelConfigDao, return RoomTunnelRepository(tunnelConfigDao, ioDispatcher)
@IoDispatcher ioDispatcher: CoroutineDispatcher, }
): TunnelRepository {
return RoomTunnelRepository(tunnelConfigDao, ioDispatcher)
}
@Singleton @Singleton
@Provides @Provides
fun provideSettingsRepository( fun provideSettingsRepository(settingsDao: SettingsDao, @IoDispatcher ioDispatcher: CoroutineDispatcher): AppSettingRepository {
settingsDao: SettingsDao, return RoomSettingsRepository(settingsDao, ioDispatcher)
@IoDispatcher ioDispatcher: CoroutineDispatcher, }
): AppSettingRepository {
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 @Provides
@Singleton @Singleton
fun provideGeneralStateRepository(dataStoreManager: DataStoreManager): AppStateRepository { fun provideGeneralStateRepository(dataStoreManager: DataStoreManager): AppStateRepository {
return DataStoreAppStateRepository(dataStoreManager) return DataStoreAppStateRepository(dataStoreManager)
} }
@Provides @Provides
@Singleton @Singleton
fun provideAppDataRepository( fun provideAppDataRepository(
settingsRepository: AppSettingRepository, settingsRepository: AppSettingRepository,
tunnelRepository: TunnelRepository, tunnelRepository: TunnelRepository,
appStateRepository: AppStateRepository, appStateRepository: AppStateRepository,
): AppDataRepository { ): AppDataRepository {
return AppDataRoomRepository(settingsRepository, tunnelRepository, appStateRepository) return AppDataRoomRepository(settingsRepository, tunnelRepository, appStateRepository)
} }
@Provides
@Singleton
fun provideHttpClient(): HttpClient {
return KtorClient.create()
}
@Provides
@Singleton
fun provideGitHubApi(client: HttpClient): GitHubApi {
return KtorGitHubApi(client)
}
@Provides
@Singleton
fun provideUpdateRepository(
gitHubApi: GitHubApi,
client: HttpClient,
@IoDispatcher ioDispatcher: CoroutineDispatcher,
@ApplicationContext context: Context,
): UpdateRepository {
return GitHubUpdateRepository(
gitHubApi,
client,
"wgtunnel",
"wgtunnel",
context,
ioDispatcher,
)
}
} }
@@ -6,6 +6,7 @@ import com.wireguard.android.util.RootShell
import com.wireguard.android.util.ToolsInstaller import com.wireguard.android.util.ToolsInstaller
import com.zaneschepke.networkmonitor.AndroidNetworkMonitor import com.zaneschepke.networkmonitor.AndroidNetworkMonitor
import com.zaneschepke.networkmonitor.NetworkMonitor import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.KernelTunnel import com.zaneschepke.wireguardautotunnel.core.tunnel.KernelTunnel
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
@@ -18,121 +19,102 @@ import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import org.amnezia.awg.backend.Backend import org.amnezia.awg.backend.Backend
import org.amnezia.awg.backend.GoBackend import org.amnezia.awg.backend.GoBackend
import org.amnezia.awg.backend.RootTunnelActionHandler import org.amnezia.awg.backend.RootTunnelActionHandler
import javax.inject.Singleton
@Module @Module
@InstallIn(SingletonComponent::class) @InstallIn(SingletonComponent::class)
class TunnelModule { class TunnelModule {
@Provides @Provides
@Singleton @Singleton
@TunnelShell @TunnelShell
fun provideTunnelRootShell(@ApplicationContext context: Context): RootShell { fun provideTunnelRootShell(@ApplicationContext context: Context): RootShell {
return RootShell(context) return RootShell(context)
} }
@Provides @Provides
@Singleton @Singleton
@AppShell @AppShell
fun provideAppRootShell(@ApplicationContext context: Context): RootShell { fun provideAppRootShell(@ApplicationContext context: Context): RootShell {
return RootShell(context) return RootShell(context)
} }
@Provides @Provides
@Singleton @Singleton
fun provideAmneziaBackend(@ApplicationContext context: Context): Backend { fun provideAmneziaBackend(@ApplicationContext context: Context): Backend {
return GoBackend(context, RootTunnelActionHandler(org.amnezia.awg.util.RootShell(context))) return GoBackend(context, RootTunnelActionHandler(org.amnezia.awg.util.RootShell(context)))
} }
@Provides @Provides
@Singleton @Singleton
fun provideKernelBackend( fun provideKernelBackend(@ApplicationContext context: Context, @TunnelShell shell: RootShell): com.wireguard.android.backend.Backend {
@ApplicationContext context: Context, return WgQuickBackend(context, shell, ToolsInstaller(context, shell), com.wireguard.android.backend.RootTunnelActionHandler(shell)).also {
@TunnelShell shell: RootShell, it.setMultipleTunnels(true)
): com.wireguard.android.backend.Backend { }
return WgQuickBackend( }
context,
shell,
ToolsInstaller(context, shell),
com.wireguard.android.backend.RootTunnelActionHandler(shell),
)
.also { it.setMultipleTunnels(true) }
}
@Provides @Provides
@Singleton @Singleton
@Kernel @Kernel
fun provideKernelProvider( fun provideKernelProvider(
@ApplicationScope applicationScope: CoroutineScope, @IoDispatcher ioDispatcher: CoroutineDispatcher,
serviceManager: ServiceManager, @ApplicationScope applicationScope: CoroutineScope,
appDataRepository: AppDataRepository, serviceManager: ServiceManager,
backend: com.wireguard.android.backend.Backend, appDataRepository: AppDataRepository,
): TunnelProvider { networkMonitor: NetworkMonitor,
return KernelTunnel(applicationScope, serviceManager, appDataRepository, backend) notificationManager: NotificationManager,
} backend: com.wireguard.android.backend.Backend,
): TunnelProvider {
return KernelTunnel(ioDispatcher, applicationScope, serviceManager, appDataRepository, notificationManager, backend, networkMonitor)
}
@Provides @Provides
@Singleton @Singleton
@Userspace @Userspace
fun provideUserspaceProvider( fun provideUserspaceProvider(
@ApplicationScope applicationScope: CoroutineScope, @IoDispatcher ioDispatcher: CoroutineDispatcher,
serviceManager: ServiceManager, @ApplicationScope applicationScope: CoroutineScope,
appDataRepository: AppDataRepository, serviceManager: ServiceManager,
backend: Backend, appDataRepository: AppDataRepository,
): TunnelProvider { notificationManager: NotificationManager,
return UserspaceTunnel(applicationScope, serviceManager, appDataRepository, backend) networkMonitor: NetworkMonitor,
} backend: Backend,
): TunnelProvider {
return UserspaceTunnel(ioDispatcher, applicationScope, serviceManager, appDataRepository, notificationManager, backend, networkMonitor)
}
@Provides @Provides
@Singleton @Singleton
fun provideTunnelManager( fun provideTunnelManager(
@Kernel kernelTunnel: TunnelProvider, @Kernel kernelTunnel: TunnelProvider,
@Userspace userspaceTunnel: TunnelProvider, @Userspace userspaceTunnel: TunnelProvider,
appDataRepository: AppDataRepository, appDataRepository: AppDataRepository,
@IoDispatcher ioDispatcher: CoroutineDispatcher, @IoDispatcher ioDispatcher: CoroutineDispatcher,
@ApplicationScope applicationScope: CoroutineScope, @ApplicationScope applicationScope: CoroutineScope,
): TunnelManager { ): TunnelManager {
return TunnelManager( return TunnelManager(kernelTunnel, userspaceTunnel, appDataRepository, applicationScope, ioDispatcher)
kernelTunnel, }
userspaceTunnel,
appDataRepository,
applicationScope,
ioDispatcher,
)
}
@Provides @Provides
@Singleton @Singleton
fun provideNetworkMonitor( fun provideNetworkMonitor(@ApplicationContext context: Context, settingsRepository: AppSettingRepository): NetworkMonitor {
@ApplicationContext context: Context, return AndroidNetworkMonitor(context) { runBlocking { settingsRepository.get().isWifiNameByShellEnabled } }
settingsRepository: AppSettingRepository, }
): NetworkMonitor {
return AndroidNetworkMonitor(context) {
runBlocking { settingsRepository.get().isWifiNameByShellEnabled }
}
}
@Singleton @Singleton
@Provides @Provides
fun provideServiceManager( fun provideServiceManager(
@ApplicationContext context: Context, @ApplicationContext context: Context,
@IoDispatcher ioDispatcher: CoroutineDispatcher, @IoDispatcher ioDispatcher: CoroutineDispatcher,
@MainDispatcher mainCoroutineDispatcher: CoroutineDispatcher, @ApplicationScope applicationScope: CoroutineScope,
@ApplicationScope applicationScope: CoroutineScope, appDataRepository: AppDataRepository,
appDataRepository: AppDataRepository, ): ServiceManager {
): ServiceManager { return ServiceManager(context, ioDispatcher, applicationScope, appDataRepository)
return ServiceManager( }
context,
ioDispatcher,
applicationScope,
mainCoroutineDispatcher,
appDataRepository,
)
}
} }
@@ -13,12 +13,9 @@ import kotlinx.coroutines.CoroutineDispatcher
@Module @Module
@InstallIn(ViewModelComponent::class) @InstallIn(ViewModelComponent::class)
class ViewModelModule { class ViewModelModule {
@ViewModelScoped @ViewModelScoped
@Provides @Provides
fun provideFileUtils( fun provideFileUtils(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): FileUtils {
@ApplicationContext context: Context, return FileUtils(context, ioDispatcher)
@IoDispatcher ioDispatcher: CoroutineDispatcher, }
): FileUtils {
return FileUtils(context, ioDispatcher)
}
} }
@@ -1,29 +1,29 @@
package com.zaneschepke.wireguardautotunnel.domain.entity package com.zaneschepke.wireguardautotunnel.domain.entity
data class AppSettings( data class AppSettings(
val id: Int = 0, val id: Int = 0,
val isAutoTunnelEnabled: Boolean = false, val isAutoTunnelEnabled: Boolean = false,
val isTunnelOnMobileDataEnabled: Boolean = false, val isTunnelOnMobileDataEnabled: Boolean = false,
val trustedNetworkSSIDs: List<String> = emptyList(), val trustedNetworkSSIDs: List<String> = emptyList(),
val isAlwaysOnVpnEnabled: Boolean = false, val isAlwaysOnVpnEnabled: Boolean = false,
val isTunnelOnEthernetEnabled: Boolean = false, val isTunnelOnEthernetEnabled: Boolean = false,
val isShortcutsEnabled: Boolean = false, val isShortcutsEnabled: Boolean = false,
val isTunnelOnWifiEnabled: Boolean = false, val isTunnelOnWifiEnabled: Boolean = false,
val isKernelEnabled: Boolean = false, val isKernelEnabled: Boolean = false,
val isRestoreOnBootEnabled: Boolean = false, val isRestoreOnBootEnabled: Boolean = false,
val isMultiTunnelEnabled: Boolean = false, val isMultiTunnelEnabled: Boolean = false,
val isPingEnabled: Boolean = false, val isPingEnabled: Boolean = false,
val isAmneziaEnabled: Boolean = false, val isAmneziaEnabled: Boolean = false,
val isWildcardsEnabled: Boolean = false, val isWildcardsEnabled: Boolean = false,
val isWifiNameByShellEnabled: Boolean = false, val isWifiNameByShellEnabled: Boolean = false,
val isStopOnNoInternetEnabled: Boolean = false, val isStopOnNoInternetEnabled: Boolean = false,
val isVpnKillSwitchEnabled: Boolean = false, val isVpnKillSwitchEnabled: Boolean = false,
val isKernelKillSwitchEnabled: Boolean = false, val isKernelKillSwitchEnabled: Boolean = false,
val isLanOnKillSwitchEnabled: Boolean = false, val isLanOnKillSwitchEnabled: Boolean = false,
val debounceDelaySeconds: Int = 3, val debounceDelaySeconds: Int = 3,
val isDisableKillSwitchOnTrustedEnabled: Boolean = false, val isDisableKillSwitchOnTrustedEnabled: Boolean = false,
) { ) {
fun debounceDelayMillis(): Long { fun debounceDelayMillis(): Long {
return debounceDelaySeconds * 1000L return debounceDelaySeconds * 1000L
} }
} }
@@ -3,13 +3,11 @@ package com.zaneschepke.wireguardautotunnel.domain.entity
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
data class AppState( data class AppState(
val isLocationDisclosureShown: Boolean, val isLocationDisclosureShown: Boolean,
val isBatteryOptimizationDisableShown: Boolean, val isBatteryOptimizationDisableShown: Boolean,
val isPinLockEnabled: Boolean, val isPinLockEnabled: Boolean,
val expandedTunnelIds: List<Int>, val isTunnelStatsExpanded: Boolean,
val isLocalLogsEnabled: Boolean, val isLocalLogsEnabled: Boolean,
val isRemoteControlEnabled: Boolean, val locale: String?,
val remoteKey: String?, val theme: Theme,
val locale: String?,
val theme: Theme,
) )
@@ -1,9 +0,0 @@
package com.zaneschepke.wireguardautotunnel.domain.entity
data class AppUpdate(
val version: String,
val title: String,
val releaseNotes: String,
val apkUrl: String?,
val apkFileName: String?,
)
@@ -3,214 +3,166 @@ package com.zaneschepke.wireguardautotunnel.domain.entity
import com.wireguard.android.backend.Tunnel import com.wireguard.android.backend.Tunnel
import com.wireguard.config.Config import com.wireguard.config.Config
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.extensions.* import com.zaneschepke.wireguardautotunnel.util.extensions.isReachable
import com.zaneschepke.wireguardautotunnel.util.extensions.toWgQuickString
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.InputStream import java.io.InputStream
import java.net.InetAddress import java.net.InetAddress
import java.nio.charset.StandardCharsets
import kotlin.coroutines.CoroutineContext import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
import java.nio.charset.StandardCharsets
data class TunnelConf( data class TunnelConf(
val id: Int = 0, val id: Int = 0,
val tunName: String, val tunName: String,
val wgQuick: String, val wgQuick: String,
val tunnelNetworks: List<String> = emptyList(), val tunnelNetworks: List<String> = emptyList(),
val isMobileDataTunnel: Boolean = false, val isMobileDataTunnel: Boolean = false,
val isPrimaryTunnel: Boolean = false, val isPrimaryTunnel: Boolean = false,
val amQuick: String, val amQuick: String,
val isActive: Boolean = false, val isActive: Boolean = false,
val isPingEnabled: Boolean = false, val isPingEnabled: Boolean = false,
val pingInterval: Long? = null, val pingInterval: Long? = null,
val pingCooldown: Long? = null, val pingCooldown: Long? = null,
val pingIp: String? = null, val pingIp: String? = null,
val isEthernetTunnel: Boolean = false, val isEthernetTunnel: Boolean = false,
val isIpv4Preferred: Boolean = true, val isIpv4Preferred: Boolean = true,
@Transient private var stateChangeCallback: ((Any) -> Unit)? = null, @Transient
private var stateChangeCallback: ((Any) -> Unit)? = null,
) : Tunnel, org.amnezia.awg.backend.Tunnel { ) : Tunnel, org.amnezia.awg.backend.Tunnel {
fun setStateChangeCallback(callback: (Any) -> Unit) { private val callbackMutex = Mutex()
stateChangeCallback = callback
}
override fun equals(other: Any?): Boolean { suspend fun setStateChangeCallback(callback: (Any) -> Unit) {
if (this === other) return true callbackMutex.withLock {
if (other !is TunnelConf) return false stateChangeCallback = callback
return id == other.id && }
tunName == other.tunName && }
wgQuick == other.wgQuick &&
amQuick == other.amQuick &&
isPrimaryTunnel == other.isPrimaryTunnel &&
isMobileDataTunnel == other.isMobileDataTunnel &&
isEthernetTunnel == other.isEthernetTunnel &&
isPingEnabled == other.isPingEnabled &&
pingIp == other.pingIp &&
pingCooldown == other.pingCooldown &&
pingInterval == other.pingInterval &&
tunnelNetworks == other.tunnelNetworks &&
isIpv4Preferred == other.isIpv4Preferred
}
override fun hashCode(): Int { fun copyWithCallback(
var result = id id: Int = this.id,
result = 31 * result + tunName.hashCode() tunName: String = this.tunName,
result = 31 * result + wgQuick.hashCode() wgQuick: String = this.wgQuick,
result = 31 * result + amQuick.hashCode() tunnelNetworks: List<String> = this.tunnelNetworks,
return result isMobileDataTunnel: Boolean = this.isMobileDataTunnel,
} isPrimaryTunnel: Boolean = this.isPrimaryTunnel,
amQuick: String = this.amQuick,
isActive: Boolean = this.isActive,
isPingEnabled: Boolean = this.isPingEnabled,
pingInterval: Long? = this.pingInterval,
pingCooldown: Long? = this.pingCooldown,
pingIp: String? = this.pingIp,
isEthernetTunnel: Boolean = this.isEthernetTunnel,
isIpv4Preferred: Boolean = this.isIpv4Preferred,
): TunnelConf {
return TunnelConf(
id, tunName, wgQuick, tunnelNetworks, isMobileDataTunnel, isPrimaryTunnel,
amQuick, isActive, isPingEnabled, pingInterval, pingCooldown, pingIp,
isEthernetTunnel, isIpv4Preferred,
).apply {
stateChangeCallback = this@TunnelConf.stateChangeCallback
}
}
fun isStaticallyConfigured(): Boolean { fun toAmConfig(): org.amnezia.awg.config.Config {
return toAmConfig().peers.all { it.endpoint.get().host.isValidIpv4orIpv6Address() } return configFromAmQuick(amQuick.ifBlank { wgQuick })
} }
fun copyWithCallback( fun toWgConfig(): Config {
id: Int = this.id, return configFromWgQuick(wgQuick)
tunName: String = this.tunName, }
wgQuick: String = this.wgQuick,
tunnelNetworks: List<String> = this.tunnelNetworks,
isMobileDataTunnel: Boolean = this.isMobileDataTunnel,
isPrimaryTunnel: Boolean = this.isPrimaryTunnel,
amQuick: String = this.amQuick,
isActive: Boolean = this.isActive,
isPingEnabled: Boolean = this.isPingEnabled,
pingInterval: Long? = this.pingInterval,
pingCooldown: Long? = this.pingCooldown,
pingIp: String? = this.pingIp,
isEthernetTunnel: Boolean = this.isEthernetTunnel,
isIpv4Preferred: Boolean = this.isIpv4Preferred,
): TunnelConf {
return TunnelConf(
id,
tunName,
wgQuick,
tunnelNetworks,
isMobileDataTunnel,
isPrimaryTunnel,
amQuick,
isActive,
isPingEnabled,
pingInterval,
pingCooldown,
pingIp,
isEthernetTunnel,
isIpv4Preferred,
)
.apply { stateChangeCallback = this@TunnelConf.stateChangeCallback }
}
fun toAmConfig(): org.amnezia.awg.config.Config { override fun getName(): String = tunName
return configFromAmQuick(amQuick.ifBlank { wgQuick })
}
fun toWgConfig(): Config { override fun isIpv4ResolutionPreferred(): Boolean = isIpv4Preferred
return configFromWgQuick(wgQuick)
}
override fun getName(): String = tunName override fun onStateChange(newState: org.amnezia.awg.backend.Tunnel.State) {
Timber.d("onStateChange called for tunnel $id: $tunName with state $newState")
runBlocking {
callbackMutex.withLock {
if (stateChangeCallback != null) {
Timber.d("Invoking stateChangeCallback for tunnel $id: $tunName with state $newState")
stateChangeCallback?.invoke(newState)
} else {
Timber.w("No stateChangeCallback set for tunnel $id: $tunName")
}
}
}
}
override fun isIpv4ResolutionPreferred(): Boolean = isIpv4Preferred override fun onStateChange(newState: Tunnel.State) {
Timber.d("onStateChange called for tunnel $id: $tunName with state $newState")
runBlocking {
callbackMutex.withLock {
if (stateChangeCallback != null) {
Timber.d("Invoking stateChangeCallback for tunnel $id: $tunName with state $newState")
stateChangeCallback?.invoke(newState)
} else {
Timber.w("No stateChangeCallback set for tunnel $id: $tunName")
}
}
}
}
override fun onStateChange(newState: org.amnezia.awg.backend.Tunnel.State) { fun isQuickConfigMatching(updatedConf: TunnelConf): Boolean {
stateChangeCallback?.invoke(newState) return updatedConf.wgQuick == wgQuick || updatedConf.amQuick == amQuick
} }
override fun onStateChange(newState: Tunnel.State) { fun isPingConfigMatching(updatedConf: TunnelConf): Boolean {
stateChangeCallback?.invoke(newState) return updatedConf.isPingEnabled == isPingEnabled &&
} pingIp == updatedConf.pingIp &&
updatedConf.pingCooldown == pingCooldown &&
updatedConf.pingInterval == pingInterval
}
fun generateUniqueName(tunnelNames: List<String>): String { suspend fun isTunnelPingable(context: CoroutineContext): Boolean {
var tunnelName = this.tunName return withContext(context) {
var num = 1 val config = toWgConfig()
while (tunnelNames.any { it == tunnelName }) { if (pingIp != null) {
tunnelName = return@withContext InetAddress.getByName(pingIp)
if (!tunnelName.hasNumberInParentheses()) { .isReachable(Constants.PING_TIMEOUT.toInt())
"$name($num)" }
} else { config.peers.map { peer ->
val pair = tunnelName.extractNameAndNumber() peer.isReachable(isIpv4Preferred)
"${pair?.first}($num)" }.all { true }
} }
num++ }
}
return tunnelName
}
suspend fun isTunnelPingable(context: CoroutineContext): Boolean { companion object {
return withContext(context) { fun configFromWgQuick(wgQuick: String): Config {
val config = toWgConfig() val inputStream: InputStream = wgQuick.byteInputStream()
if (pingIp != null) { return inputStream.bufferedReader(StandardCharsets.UTF_8).use {
return@withContext InetAddress.getByName(pingIp) Config.parse(it)
.isReachable(Constants.PING_TIMEOUT.toInt()) }
.also { Timber.i("Ping reachable $pingIp: $it") } }
}
config.peers
.map { peer -> peer.isReachable() }
.all { true }
.also { Timber.i("Ping of all peers reachable: $it") }
}
}
companion object { fun configFromAmQuick(amQuick: String): org.amnezia.awg.config.Config {
fun configFromWgQuick(wgQuick: String): Config { val inputStream: InputStream = amQuick.byteInputStream()
val inputStream: InputStream = wgQuick.byteInputStream() return inputStream.bufferedReader(StandardCharsets.UTF_8).use {
return inputStream.bufferedReader(StandardCharsets.UTF_8).use { Config.parse(it) } org.amnezia.awg.config.Config.parse(it)
} }
}
fun configFromAmQuick(amQuick: String): org.amnezia.awg.config.Config { fun tunnelConfigFromAmConfig(config: org.amnezia.awg.config.Config, name: String): TunnelConf {
val inputStream: InputStream = amQuick.byteInputStream() val amQuick = config.toAwgQuickString(true)
return inputStream.bufferedReader(StandardCharsets.UTF_8).use { val wgQuick = config.toWgQuickString()
org.amnezia.awg.config.Config.parse(it) return TunnelConf(tunName = name, wgQuick = wgQuick, amQuick = amQuick)
} }
}
fun tunnelConfigFromAmConfig( private const val IPV6_ALL_NETWORKS = "::/0"
config: org.amnezia.awg.config.Config, private const val IPV4_ALL_NETWORKS = "0.0.0.0/0"
name: String? = null, val ALL_IPS = listOf(IPV4_ALL_NETWORKS, IPV6_ALL_NETWORKS)
): TunnelConf { private val IPV4_PUBLIC_NETWORKS = listOf(
val amQuick = config.toAwgQuickString(true) "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",
val wgQuick = config.toWgQuickString() "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",
return TunnelConf( "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",
tunName = name ?: config.defaultName(), "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",
wgQuick = wgQuick, "192.170.0.0/15", "192.172.0.0/14", "192.176.0.0/12", "192.192.0.0/10",
amQuick = amQuick, "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",
) )
} val LAN_BYPASS_ALLOWED_IPS = listOf(IPV6_ALL_NETWORKS) + IPV4_PUBLIC_NETWORKS
}
private const val IPV6_ALL_NETWORKS = "::/0"
private const val IPV4_ALL_NETWORKS = "0.0.0.0/0"
val ALL_IPS = listOf(IPV4_ALL_NETWORKS, IPV6_ALL_NETWORKS)
private val IPV4_PUBLIC_NETWORKS =
listOf(
"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",
)
val LAN_BYPASS_ALLOWED_IPS = listOf(IPV6_ALL_NETWORKS) + IPV4_PUBLIC_NETWORKS
}
} }
@@ -1,33 +1,8 @@
package com.zaneschepke.wireguardautotunnel.domain.enums package com.zaneschepke.wireguardautotunnel.domain.enums
import com.zaneschepke.wireguardautotunnel.R sealed class BackendError() {
data object DNS : BackendError()
sealed class BackendError : Exception() { data object Unauthorized : BackendError()
data object DNS : BackendError() data object Config : BackendError()
data object Unknown : BackendError()
data object Unauthorized : BackendError()
data object Config : BackendError()
data object KernelModuleName : BackendError()
data object InvalidConfig : BackendError()
data object NotAuthorized : BackendError()
data object ServiceNotRunning : BackendError()
data object Unknown : BackendError()
fun toStringRes() =
when (this) {
Config -> R.string.config_error
DNS -> R.string.dns_resolve_error
InvalidConfig -> R.string.invalid_config_error
KernelModuleName -> R.string.kernel_name_error
NotAuthorized,
Unauthorized -> R.string.auth_error
ServiceNotRunning -> R.string.service_running_error
Unknown -> R.string.unknown_error
}
} }
@@ -1,7 +1,7 @@
package com.zaneschepke.wireguardautotunnel.domain.enums package com.zaneschepke.wireguardautotunnel.domain.enums
enum class BackendState { enum class BackendState {
KILL_SWITCH_ACTIVE, KILL_SWITCH_ACTIVE,
SERVICE_ACTIVE, SERVICE_ACTIVE,
INACTIVE, INACTIVE,
} }
@@ -1,6 +1,6 @@
package com.zaneschepke.wireguardautotunnel.domain.enums package com.zaneschepke.wireguardautotunnel.domain.enums
enum class ConfigType { enum class ConfigType {
AM, AMNEZIA,
WG, WG,
} }
@@ -1,16 +1,17 @@
package com.zaneschepke.wireguardautotunnel.domain.enums package com.zaneschepke.wireguardautotunnel.domain.enums
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
} }
} }
@@ -4,13 +4,14 @@ import android.content.Context
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
enum class NotificationAction { enum class NotificationAction {
TUNNEL_OFF, TUNNEL_OFF,
AUTO_TUNNEL_OFF; AUTO_TUNNEL_OFF,
;
fun title(context: Context): String { fun title(context: Context): String {
return when (this) { return when (this) {
TUNNEL_OFF -> context.getString(R.string.stop) TUNNEL_OFF -> context.getString(R.string.stop)
AUTO_TUNNEL_OFF -> context.getString(R.string.stop) AUTO_TUNNEL_OFF -> context.getString(R.string.stop)
} }
} }
} }
@@ -1,34 +1,17 @@
package com.zaneschepke.wireguardautotunnel.domain.enums package com.zaneschepke.wireguardautotunnel.domain.enums
sealed class TunnelStatus { enum class TunnelStatus {
UP,
DOWN,
STARTING,
STOPPING,
;
data object Up : TunnelStatus() fun isDown(): Boolean {
return this == DOWN
}
data object Down : TunnelStatus() fun isUp(): Boolean {
return this == UP
data class Stopping(val reason: StopReason) : TunnelStatus() }
data object Starting : TunnelStatus()
enum class StopReason {
USER,
PING,
CONFIG_CHANGED,
}
fun isDown(): Boolean {
return this == Down
}
fun isUp(): Boolean {
return this == Up
}
fun isUpOrStarting(): Boolean {
return this == Up || this == Starting
}
fun isDownOrStopping(): Boolean {
return this == Down || this is Stopping
}
} }
@@ -3,9 +3,7 @@ package com.zaneschepke.wireguardautotunnel.domain.events
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
sealed class AutoTunnelEvent { sealed class AutoTunnelEvent {
data class Start(val tunnelConf: TunnelConf? = null) : AutoTunnelEvent() data class Start(val tunnelConf: TunnelConf? = null) : AutoTunnelEvent()
data object Stop : AutoTunnelEvent()
data object Stop : AutoTunnelEvent() data object DoNothing : AutoTunnelEvent()
data object DoNothing : AutoTunnelEvent()
} }
@@ -1,9 +1,7 @@
package com.zaneschepke.wireguardautotunnel.domain.events package com.zaneschepke.wireguardautotunnel.domain.events
sealed class KillSwitchEvent { sealed class KillSwitchEvent {
data class Start(val allowedIps: List<String>) : KillSwitchEvent() data class Start(val allowedIps: List<String>) : KillSwitchEvent()
data object Stop : KillSwitchEvent()
data object Stop : KillSwitchEvent() data object DoNothing : KillSwitchEvent()
data object DoNothing : KillSwitchEvent()
} }
@@ -3,11 +3,11 @@ package com.zaneschepke.wireguardautotunnel.domain.repository
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
interface AppDataRepository { interface AppDataRepository {
suspend fun getPrimaryOrFirstTunnel(): TunnelConf? suspend fun getPrimaryOrFirstTunnel(): TunnelConf?
suspend fun getStartTunnelConfig(): TunnelConf? suspend fun getStartTunnelConfig(): TunnelConf?
val settings: AppSettingRepository val settings: AppSettingRepository
val tunnels: TunnelRepository val tunnels: TunnelRepository
val appState: AppStateRepository val appState: AppStateRepository
} }
@@ -4,9 +4,7 @@ import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface AppSettingRepository { interface AppSettingRepository {
suspend fun save(appSettings: AppSettings) suspend fun save(appSettings: AppSettings)
val flow: Flow<AppSettings>
val flow: Flow<AppSettings> suspend fun get(): AppSettings
suspend fun get(): AppSettings
} }
@@ -1,45 +1,37 @@
package com.zaneschepke.wireguardautotunnel.domain.repository package com.zaneschepke.wireguardautotunnel.domain.repository
import com.zaneschepke.wireguardautotunnel.domain.entity.AppState import com.zaneschepke.wireguardautotunnel.data.model.GeneralState
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme 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 setLocationDisclosureShown(shown: Boolean)
suspend fun isPinLockEnabled(): Boolean suspend fun isPinLockEnabled(): Boolean
suspend fun setPinLockEnabled(enabled: Boolean) suspend fun setPinLockEnabled(enabled: Boolean)
suspend fun isBatteryOptimizationDisableShown(): Boolean suspend fun isBatteryOptimizationDisableShown(): Boolean
suspend fun setBatteryOptimizationDisableShown(shown: Boolean) suspend fun setBatteryOptimizationDisableShown(shown: Boolean)
suspend fun setTunnelExpanded(id: Int) suspend fun isTunnelStatsExpanded(): Boolean
suspend fun removeTunnelExpanded(id: Int) suspend fun setTunnelStatsExpanded(expanded: Boolean)
suspend fun setTheme(theme: Theme) suspend fun setTheme(theme: Theme)
suspend fun getTheme(): Theme suspend fun getTheme(): Theme
suspend fun isLocalLogsEnabled(): Boolean suspend fun isLocalLogsEnabled(): Boolean
suspend fun setLocalLogsEnabled(enabled: Boolean) suspend fun setLocalLogsEnabled(enabled: Boolean)
suspend fun setLocale(localeTag: String) suspend fun setLocale(localeTag: String)
suspend fun getLocale(): String? suspend fun getLocale(): String?
suspend fun setIsRemoteControlEnabled(enabled: Boolean) val flow: Flow<GeneralState>
suspend fun isRemoteControlEnabled(): Boolean
suspend fun setRemoteKey(key: String)
suspend fun getRemoteKey(): String?
val flow: Flow<AppState>
} }
@@ -5,33 +5,31 @@ import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface TunnelRepository { interface TunnelRepository {
val flow: Flow<List<TunnelConf>> val flow: Flow<List<TunnelConf>>
suspend fun getAll(): Tunnels suspend fun getAll(): Tunnels
suspend fun save(tunnelConf: TunnelConf) suspend fun save(tunnelConf: TunnelConf)
suspend fun saveAll(tunnelConfList: List<TunnelConf>) suspend fun updatePrimaryTunnel(tunnelConf: TunnelConf?)
suspend fun updatePrimaryTunnel(tunnelConf: TunnelConf?) suspend fun updateMobileDataTunnel(tunnelConf: TunnelConf?)
suspend fun updateMobileDataTunnel(tunnelConf: TunnelConf?) suspend fun updateEthernetTunnel(tunnelConf: TunnelConf?)
suspend fun updateEthernetTunnel(tunnelConf: TunnelConf?) suspend fun delete(tunnelConf: TunnelConf)
suspend fun delete(tunnelConf: TunnelConf) suspend fun getById(id: Int): TunnelConf?
suspend fun getById(id: Int): TunnelConf? suspend fun getActive(): Tunnels
suspend fun getActive(): Tunnels suspend fun count(): Int
suspend fun count(): Int suspend fun findByTunnelName(name: String): TunnelConf?
suspend fun findByTunnelName(name: String): TunnelConf? suspend fun findByTunnelNetworksName(name: String): Tunnels
suspend fun findByTunnelNetworksName(name: String): Tunnels suspend fun findByMobileDataTunnel(): Tunnels
suspend fun findByMobileDataTunnel(): Tunnels suspend fun findPrimary(): Tunnels
suspend fun findPrimary(): Tunnels
} }
@@ -1,14 +0,0 @@
package com.zaneschepke.wireguardautotunnel.domain.repository
import com.zaneschepke.wireguardautotunnel.domain.entity.AppUpdate
import java.io.File
interface UpdateRepository {
suspend fun checkForUpdate(currentVersion: String): Result<AppUpdate?>
suspend fun downloadApk(
apkUrl: String,
fileName: String,
onProgress: (Float) -> Unit,
): Result<File>
}
@@ -4,32 +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,
resolvedEndpoint = stats.resolvedEndpoint, )
) }
} }
}
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()
} }
} }
@@ -3,196 +3,157 @@ package com.zaneschepke.wireguardautotunnel.domain.state
import com.zaneschepke.wireguardautotunnel.core.tunnel.allDown import com.zaneschepke.wireguardautotunnel.core.tunnel.allDown
import com.zaneschepke.wireguardautotunnel.core.tunnel.hasActive import com.zaneschepke.wireguardautotunnel.core.tunnel.hasActive
import com.zaneschepke.wireguardautotunnel.core.tunnel.isUp import com.zaneschepke.wireguardautotunnel.core.tunnel.isUp
import com.zaneschepke.wireguardautotunnel.domain.events.KillSwitchEvent
import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.events.AutoTunnelEvent import com.zaneschepke.wireguardautotunnel.domain.events.AutoTunnelEvent
import com.zaneschepke.wireguardautotunnel.domain.events.KillSwitchEvent
import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList
data class AutoTunnelState( data class AutoTunnelState(
val activeTunnels: Map<TunnelConf, TunnelState> = emptyMap(), val activeTunnels: Map<TunnelConf, TunnelState> = emptyMap(),
val networkState: NetworkState = NetworkState(), val networkState: NetworkState = NetworkState(),
val settings: AppSettings = AppSettings(), val settings: AppSettings = AppSettings(),
val tunnels: List<TunnelConf> = emptyList(), val tunnels: List<TunnelConf> = emptyList(),
) { ) {
private fun isMobileDataActive(): Boolean { private fun isMobileDataActive(): Boolean {
return !networkState.isEthernetConnected && return !networkState.isEthernetConnected && !networkState.isWifiConnected && networkState.isMobileDataConnected
!networkState.isWifiConnected && }
networkState.isMobileDataConnected
}
private fun isMobileTunnelDataChangeNeeded(): Boolean { private fun isMobileTunnelDataChangeNeeded(): Boolean {
val preferredTunnel = preferredMobileDataTunnel() val preferredTunnel = preferredMobileDataTunnel()
return preferredTunnel != null && return preferredTunnel != null &&
activeTunnels.isNotEmpty() && activeTunnels.isNotEmpty() && !activeTunnels.isUp(preferredTunnel)
!activeTunnels.isUp(preferredTunnel) }
}
private fun isEthernetTunnelChangeNeeded(): Boolean { private fun isEthernetTunnelChangeNeeded(): Boolean {
val preferredTunnel = preferredEthernetTunnel() val preferredTunnel = preferredEthernetTunnel()
return preferredTunnel != null && return preferredTunnel != null && activeTunnels.isNotEmpty() && !activeTunnels.isUp(preferredTunnel)
activeTunnels.isNotEmpty() && }
!activeTunnels.isUp(preferredTunnel)
}
private fun preferredMobileDataTunnel(): TunnelConf? { private fun preferredMobileDataTunnel(): TunnelConf? {
return tunnels.firstOrNull { it.isMobileDataTunnel } return tunnels.firstOrNull { it.isMobileDataTunnel } ?: tunnels.firstOrNull { it.isPrimaryTunnel }
?: tunnels.firstOrNull { it.isPrimaryTunnel } }
}
private fun preferredEthernetTunnel(): TunnelConf? { private fun preferredEthernetTunnel(): TunnelConf? {
return tunnels.firstOrNull { it.isEthernetTunnel } return tunnels.firstOrNull { it.isEthernetTunnel } ?: tunnels.firstOrNull { it.isPrimaryTunnel }
?: tunnels.firstOrNull { it.isPrimaryTunnel } }
}
private fun preferredWifiTunnel(): TunnelConf? { private fun preferredWifiTunnel(): TunnelConf? {
return getTunnelWithMatchingTunnelNetwork() ?: tunnels.firstOrNull { it.isPrimaryTunnel } return getTunnelWithMatchingTunnelNetwork() ?: tunnels.firstOrNull { it.isPrimaryTunnel }
} }
private fun isWifiActive(): Boolean { private fun isWifiActive(): Boolean {
return !networkState.isEthernetConnected && networkState.isWifiConnected return !networkState.isEthernetConnected && networkState.isWifiConnected
} }
private fun startOnEthernet(): Boolean { private fun startOnEthernet(): Boolean {
return networkState.isEthernetConnected && return networkState.isEthernetConnected && settings.isTunnelOnEthernetEnabled && activeTunnels.allDown()
settings.isTunnelOnEthernetEnabled && }
activeTunnels.allDown()
}
private fun stopOnEthernet(): Boolean { private fun stopOnEthernet(): Boolean {
return networkState.isEthernetConnected && return networkState.isEthernetConnected && !settings.isTunnelOnEthernetEnabled && activeTunnels.hasActive()
!settings.isTunnelOnEthernetEnabled && }
activeTunnels.hasActive()
}
// TODO test removed kill switch state check // TODO test removed kill switch state check
private fun stopKillSwitchOnTrusted(): Boolean { private fun stopKillSwitchOnTrusted(): Boolean {
return networkState.isWifiConnected && return networkState.isWifiConnected && settings.isVpnKillSwitchEnabled && settings.isDisableKillSwitchOnTrustedEnabled && isCurrentSSIDTrusted()
settings.isVpnKillSwitchEnabled && }
settings.isDisableKillSwitchOnTrustedEnabled &&
isCurrentSSIDTrusted()
}
// TODO test, removed kill switch state check // TODO test, removed kill switch state check
private fun startKillSwitch(): Boolean { private fun startKillSwitch(): Boolean {
return settings.isVpnKillSwitchEnabled && return settings.isVpnKillSwitchEnabled && (!settings.isDisableKillSwitchOnTrustedEnabled || !isCurrentSSIDTrusted())
(!settings.isDisableKillSwitchOnTrustedEnabled || !isCurrentSSIDTrusted()) }
}
private fun isNoConnectivity(): Boolean { private fun isNoConnectivity(): Boolean {
return !networkState.isEthernetConnected && return !networkState.isEthernetConnected && !networkState.isWifiConnected && !networkState.isMobileDataConnected
!networkState.isWifiConnected && }
!networkState.isMobileDataConnected
}
private fun stopOnMobileData(): Boolean { private fun stopOnMobileData(): Boolean {
return isMobileDataActive() && return isMobileDataActive() && !settings.isTunnelOnMobileDataEnabled && activeTunnels.hasActive()
!settings.isTunnelOnMobileDataEnabled && }
activeTunnels.hasActive()
}
private fun startOnMobileData(): Boolean { private fun startOnMobileData(): Boolean {
return isMobileDataActive() && return isMobileDataActive() && settings.isTunnelOnMobileDataEnabled && activeTunnels.allDown()
settings.isTunnelOnMobileDataEnabled && }
activeTunnels.allDown()
}
private fun changeOnMobileData(): Boolean { private fun changeOnMobileData(): Boolean {
return isMobileDataActive() && return isMobileDataActive() && settings.isTunnelOnMobileDataEnabled && isMobileTunnelDataChangeNeeded()
settings.isTunnelOnMobileDataEnabled && }
isMobileTunnelDataChangeNeeded()
}
private fun changeOnEthernet(): Boolean { private fun changeOnEthernet(): Boolean {
return networkState.isEthernetConnected && return networkState.isEthernetConnected && settings.isTunnelOnEthernetEnabled && isEthernetTunnelChangeNeeded()
settings.isTunnelOnEthernetEnabled && }
isEthernetTunnelChangeNeeded()
}
private fun stopOnWifi(): Boolean { private fun stopOnWifi(): Boolean {
return isWifiActive() && !settings.isTunnelOnWifiEnabled && activeTunnels.hasActive() return isWifiActive() && !settings.isTunnelOnWifiEnabled && activeTunnels.hasActive()
} }
private fun stopOnTrustedWifi(): Boolean { private fun stopOnTrustedWifi(): Boolean {
return isWifiActive() && return isWifiActive() && settings.isTunnelOnWifiEnabled && activeTunnels.hasActive() && isCurrentSSIDTrusted()
settings.isTunnelOnWifiEnabled && }
activeTunnels.hasActive() &&
isCurrentSSIDTrusted()
}
private fun startOnUntrustedWifi(): Boolean { private fun startOnUntrustedWifi(): Boolean {
return isWifiActive() && return isWifiActive() && settings.isTunnelOnWifiEnabled && activeTunnels.allDown() && !isCurrentSSIDTrusted()
settings.isTunnelOnWifiEnabled && }
activeTunnels.allDown() &&
!isCurrentSSIDTrusted()
}
private fun changeOnUntrustedWifi(): Boolean { private fun changeOnUntrustedWifi(): Boolean {
return isWifiActive() && return isWifiActive() && settings.isTunnelOnWifiEnabled && activeTunnels.hasActive() && !isCurrentSSIDTrusted() && !isWifiTunnelPreferred()
settings.isTunnelOnWifiEnabled && }
activeTunnels.hasActive() &&
!isCurrentSSIDTrusted() &&
!isWifiTunnelPreferred()
}
private fun isWifiTunnelPreferred(): Boolean { private fun isWifiTunnelPreferred(): Boolean {
val preferred = preferredWifiTunnel() val preferred = preferredWifiTunnel()
return preferred?.let { activeTunnels.isUp(it) } ?: true return preferred?.let { activeTunnels.isUp(it) } ?: true
} }
fun asAutoTunnelEvent(): AutoTunnelEvent { fun asAutoTunnelEvent(): AutoTunnelEvent {
return when { return when {
// ethernet scenarios // ethernet scenarios
stopOnEthernet() -> AutoTunnelEvent.Stop stopOnEthernet() -> AutoTunnelEvent.Stop
startOnEthernet() || changeOnEthernet() -> startOnEthernet() || changeOnEthernet() -> AutoTunnelEvent.Start(preferredEthernetTunnel())
AutoTunnelEvent.Start(preferredEthernetTunnel()) // mobile data scenarios
// mobile data scenarios stopOnMobileData() -> AutoTunnelEvent.Stop
stopOnMobileData() -> AutoTunnelEvent.Stop startOnMobileData() || changeOnMobileData() -> AutoTunnelEvent.Start(preferredMobileDataTunnel())
startOnMobileData() || changeOnMobileData() -> // wifi scenarios
AutoTunnelEvent.Start(preferredMobileDataTunnel()) stopOnWifi() -> AutoTunnelEvent.Stop
// wifi scenarios stopOnTrustedWifi() -> AutoTunnelEvent.Stop
stopOnWifi() -> AutoTunnelEvent.Stop startOnUntrustedWifi() || changeOnUntrustedWifi() -> AutoTunnelEvent.Start(preferredWifiTunnel())
stopOnTrustedWifi() -> AutoTunnelEvent.Stop // no connectivity
startOnUntrustedWifi() || changeOnUntrustedWifi() -> isNoConnectivity() && settings.isStopOnNoInternetEnabled -> AutoTunnelEvent.Stop
AutoTunnelEvent.Start(preferredWifiTunnel()) else -> AutoTunnelEvent.DoNothing
// no connectivity }
isNoConnectivity() && settings.isStopOnNoInternetEnabled -> AutoTunnelEvent.Stop }
else -> AutoTunnelEvent.DoNothing
}
}
fun asKillSwitchEvent(): KillSwitchEvent { fun asKillSwitchEvent(): KillSwitchEvent {
return when { return when {
stopKillSwitchOnTrusted() -> KillSwitchEvent.Stop stopKillSwitchOnTrusted() -> KillSwitchEvent.Stop
startKillSwitch() -> { startKillSwitch() -> {
val allowedIps = val allowedIps = if (settings.isLanOnKillSwitchEnabled) TunnelConf.LAN_BYPASS_ALLOWED_IPS else emptyList()
if (settings.isLanOnKillSwitchEnabled) TunnelConf.LAN_BYPASS_ALLOWED_IPS KillSwitchEvent.Start(allowedIps)
else emptyList() }
KillSwitchEvent.Start(allowedIps) else -> KillSwitchEvent.DoNothing
} }
else -> KillSwitchEvent.DoNothing }
}
}
private fun isCurrentSSIDTrusted(): Boolean { private fun isCurrentSSIDTrusted(): Boolean {
return networkState.wifiName?.let { hasTrustedWifiName(it) } == true return networkState.wifiName?.let {
} hasTrustedWifiName(it)
} == true
}
private fun hasTrustedWifiName( private fun hasTrustedWifiName(wifiName: String, wifiNames: List<String> = settings.trustedNetworkSSIDs): Boolean {
wifiName: String, return if (settings.isWildcardsEnabled) {
wifiNames: List<String> = settings.trustedNetworkSSIDs, wifiNames.isMatchingToWildcardList(wifiName)
): Boolean { } else {
return if (settings.isWildcardsEnabled) { wifiNames.contains(wifiName)
wifiNames.isMatchingToWildcardList(wifiName) }
} else { }
wifiNames.contains(wifiName)
}
}
private fun getTunnelWithMatchingTunnelNetwork(): TunnelConf? { private fun getTunnelWithMatchingTunnelNetwork(): TunnelConf? {
return networkState.wifiName?.let { wifiName -> return networkState.wifiName?.let { wifiName ->
tunnels.firstOrNull { hasTrustedWifiName(wifiName, it.tunnelNetworks) } tunnels.firstOrNull {
} hasTrustedWifiName(wifiName, it.tunnelNetworks)
} }
}
}
} }
@@ -1,9 +1,9 @@
package com.zaneschepke.wireguardautotunnel.domain.state package com.zaneschepke.wireguardautotunnel.domain.state
data class ConnectivityState( data class ConnectivityState(
val wifiAvailable: Boolean, val wifiAvailable: Boolean,
val ethernetAvailable: Boolean, val ethernetAvailable: Boolean,
val cellularAvailable: Boolean, val cellularAvailable: Boolean,
) { ) {
val allOffline = !wifiAvailable && !ethernetAvailable && !cellularAvailable val allOffline = !wifiAvailable && !ethernetAvailable && !cellularAvailable
} }
@@ -1,12 +1,12 @@
package com.zaneschepke.wireguardautotunnel.domain.state package com.zaneschepke.wireguardautotunnel.domain.state
data class NetworkState( data class NetworkState(
val isWifiConnected: Boolean = false, val isWifiConnected: Boolean = false,
val isMobileDataConnected: Boolean = false, val isMobileDataConnected: Boolean = false,
val isEthernetConnected: Boolean = false, val isEthernetConnected: Boolean = false,
val wifiName: String? = null, val wifiName: String? = null,
) { ) {
fun hasNoCapabilities(): Boolean { fun hasNoCapabilities(): Boolean {
return !isWifiConnected && !isMobileDataConnected && !isEthernetConnected return !isWifiConnected && !isMobileDataConnected && !isEthernetConnected
} }
} }
@@ -4,7 +4,7 @@ import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
data class TunnelState( data class TunnelState(
val status: TunnelStatus = TunnelStatus.Down, val state: TunnelStatus = TunnelStatus.DOWN,
val backendState: BackendState = BackendState.INACTIVE, val backendState: BackendState = BackendState.INACTIVE,
val statistics: TunnelStatistics? = null, val statistics: TunnelStatistics? = null,
) )
@@ -3,21 +3,16 @@ package com.zaneschepke.wireguardautotunnel.domain.state
import org.amnezia.awg.crypto.Key import org.amnezia.awg.crypto.Key
abstract class TunnelStatistics { abstract class TunnelStatistics {
@JvmRecord @JvmRecord
data class PeerStats( data class PeerStats(val rxBytes: Long, val txBytes: Long, val latestHandshakeEpochMillis: Long)
val rxBytes: Long,
val txBytes: Long,
val latestHandshakeEpochMillis: Long,
val resolvedEndpoint: String,
)
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
} }
@@ -4,32 +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,
resolvedEndpoint = peerStats.resolvedEndpoint, )
) }
} }
}
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 { Key.fromBase64(it.toBase64()) }.toTypedArray() return statistics.peers().map {
} Key.fromBase64(it.toBase64())
}.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()
} }
} }
@@ -3,44 +3,62 @@ package com.zaneschepke.wireguardautotunnel.ui
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
sealed class Route { sealed class Route {
@Serializable data object Support : Route() @Serializable
data object Support : Route()
@Serializable data object Settings : Route() @Serializable
data object Settings : Route()
@Serializable data object SettingsAdvanced : Route() @Serializable
data object AutoTunnel : Route()
@Serializable data object AutoTunnel : Route() @Serializable
data object AutoTunnelAdvanced : Route()
@Serializable data object AutoTunnelAdvanced : Route() @Serializable
data object LocationDisclosure : Route()
@Serializable data object LocationDisclosure : Route() @Serializable
data object Appearance : Route()
@Serializable data object Appearance : Route() @Serializable
data object Display : Route()
@Serializable data object Display : Route() @Serializable
data object KillSwitch : Route()
@Serializable data object KillSwitch : Route() @Serializable
data object Language : Route()
@Serializable data object Language : Route() @Serializable
data object Main : Route()
@Serializable data object Main : Route() @Serializable
data class TunnelOptions(
val id: Int,
) : Route()
@Serializable data class TunnelOptions(val id: Int) : Route() @Serializable
data object Lock : Route()
@Serializable data object Lock : Route() @Serializable
data object Scanner : Route()
@Serializable data object License : Route() @Serializable
data class Config(
val id: Int,
) : Route()
@Serializable data class Config(val id: Int) : Route() @Serializable
data class SplitTunnel(
val id: Int,
) : Route()
@Serializable @Serializable
data class SplitTunnel(val id: Int) : Route() { data class TunnelAutoTunnel(
companion object { val id: Int,
const val KEY_ID = "id" ) : Route()
}
}
@Serializable data class TunnelAutoTunnel(val id: Int) : Route() @Serializable
data object Logs : Route()
@Serializable data object Logs : Route()
} }
@@ -0,0 +1,37 @@
package com.zaneschepke.wireguardautotunnel.ui.common
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
@Composable
fun ClickableIconButton(onClick: () -> Unit, onIconClick: () -> Unit, text: String, icon: ImageVector, enabled: Boolean = true) {
TextButton(
onClick = onClick,
enabled = enabled,
) {
Text(text, Modifier.weight(1f, false), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary)
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
Icon(
imageVector = icon,
contentDescription = icon.name,
modifier =
Modifier
.size(ButtonDefaults.IconSize)
.weight(1f, false)
.clickable {
if (enabled) {
onIconClick()
}
},
)
}
}
@@ -1,56 +0,0 @@
package com.zaneschepke.wireguardautotunnel.ui.common
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.zaneschepke.wireguardautotunnel.R
@Composable
fun <T> DropdownSelector(
currentValue: T,
options: List<T>,
onValueSelected: (T) -> Unit,
modifier: Modifier = Modifier,
label: @Composable (() -> Unit)? = null,
isExpanded: Boolean = false,
onDismiss: () -> Unit = {},
) {
Row(
horizontalArrangement = Arrangement.spacedBy(5.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (label != null) label()
Text(text = currentValue.toString(), style = MaterialTheme.typography.bodyMedium)
Icon(Icons.Default.ArrowDropDown, contentDescription = stringResource(R.string.dropdown))
}
DropdownMenu(
modifier = modifier.height(250.dp),
scrollState = rememberScrollState(),
containerColor = MaterialTheme.colorScheme.surface,
expanded = isExpanded,
onDismissRequest = onDismiss,
) {
options.forEach { option ->
DropdownMenuItem(
text = { Text(text = option.toString()) },
onClick = {
onValueSelected(option)
onDismiss() // Close dropdown after selection
},
)
}
}
}
@@ -2,89 +2,70 @@ package com.zaneschepke.wireguardautotunnel.ui.common
import androidx.compose.animation.animateContentSize import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.indication import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.* 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.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.ripple
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.zaneschepke.wireguardautotunnel.ui.navigation.LocalIsAndroidTV
@OptIn(ExperimentalFoundationApi::class) @OptIn(ExperimentalFoundationApi::class)
@Composable @Composable
fun ExpandingRowListItem( fun ExpandingRowListItem(
leading: @Composable () -> Unit, leading: @Composable () -> Unit,
text: String, text: String,
onHold: () -> Unit, onHold: () -> Unit = {},
onClick: () -> Unit, onClick: () -> Unit,
onDoubleClick: () -> Unit, trailing: @Composable () -> Unit,
trailing: @Composable () -> Unit, isExpanded: Boolean,
isSelected: Boolean, expanded: @Composable () -> Unit = {},
expanded: (@Composable () -> Unit)?,
) { ) {
val isTv = LocalIsAndroidTV.current Box(
val haptic = LocalHapticFeedback.current modifier =
val interactionSource = remember { MutableInteractionSource() } Modifier
.animateContentSize()
Box( .clip(RoundedCornerShape(30.dp))
modifier = .combinedClickable(
Modifier.animateContentSize() onClick = { onClick() },
.clip(RoundedCornerShape(8.dp)) onLongClick = { onHold() },
.background( ),
if (isSelected) MaterialTheme.colorScheme.primary.copy(alpha = 0.1f) ) {
else Color.Transparent Column {
) Row(
.then( modifier =
if (!isTv) { Modifier
Modifier.combinedClickable( .fillMaxWidth()
interactionSource = interactionSource, .padding(horizontal = 15.dp),
indication = ripple(), verticalAlignment = Alignment.CenterVertically,
onClick = onClick, horizontalArrangement = Arrangement.SpaceBetween,
onLongClick = { ) {
haptic.performHapticFeedback(HapticFeedbackType.LongPress) Row(
onHold() verticalAlignment = Alignment.CenterVertically,
}, horizontalArrangement = Arrangement.spacedBy(15.dp),
onDoubleClick = onDoubleClick, modifier = Modifier.fillMaxWidth(13 / 20f),
) ) {
} else Modifier leading()
) Text(
) { text,
Column { maxLines = 1,
Row( overflow = TextOverflow.Ellipsis,
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp), style = MaterialTheme.typography.labelLarge,
verticalAlignment = Alignment.CenterVertically, color = MaterialTheme.colorScheme.onBackground,
horizontalArrangement = Arrangement.SpaceBetween, )
) { }
Row( trailing()
verticalAlignment = Alignment.CenterVertically, }
horizontalArrangement = Arrangement.spacedBy(16.dp), if (isExpanded) expanded()
modifier = Modifier.fillMaxWidth(13 / 20f), }
) { }
leading()
Text(
text,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onBackground,
)
}
trailing()
}
expanded?.invoke()
}
}
} }
@@ -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
}
}
@@ -0,0 +1,82 @@
package com.zaneschepke.wireguardautotunnel.ui.common
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Clear
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import com.zaneschepke.wireguardautotunnel.R
@Composable
fun SearchBar(onQuery: (queryString: String) -> Unit) {
// Immediately update and keep track of query from text field changes.
var query: String by rememberSaveable { mutableStateOf("") }
var showClearIcon by rememberSaveable { mutableStateOf(false) }
if (query.isEmpty()) {
showClearIcon = false
} else if (query.isNotEmpty()) {
showClearIcon = true
}
TextField(
value = query,
onValueChange = { onQueryChanged ->
// If user makes changes to text, immediately updated it.
query = onQueryChanged
onQuery(onQueryChanged)
},
leadingIcon = {
val icon = Icons.Rounded.Search
Icon(
imageVector = icon,
tint = MaterialTheme.colorScheme.onBackground,
contentDescription = icon.name,
)
},
trailingIcon = {
if (showClearIcon) {
IconButton(onClick = { query = "" }) {
val icon = Icons.Rounded.Clear
Icon(
imageVector = icon,
tint = MaterialTheme.colorScheme.onBackground,
contentDescription = icon.name,
)
}
}
},
maxLines = 1,
colors =
TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
disabledContainerColor = Color.Transparent,
),
placeholder = { Text(text = stringResource(R.string.hint_search_packages)) },
textStyle = MaterialTheme.typography.bodySmall,
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
modifier =
Modifier
.fillMaxWidth()
.background(color = MaterialTheme.colorScheme.background, shape = RectangleShape),
)
}
@@ -1,16 +0,0 @@
package com.zaneschepke.wireguardautotunnel.ui.common
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun SectionDivider() {
HorizontalDivider(
color = MaterialTheme.colorScheme.outline.copy(0.30f),
modifier = Modifier.padding(horizontal = 12.dp),
)
}

Some files were not shown because too many files have changed in this diff Show More