Compare commits

..

1 Commits

Author SHA1 Message Date
Zane Schepke 701e611e50 feat: auto-tunneling flexibility 2024-03-29 23:53:41 -04:00
272 changed files with 6675 additions and 11053 deletions
+10 -22
View File
@@ -1,14 +1,8 @@
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}] [{*.kt,*.kts}]
indent_style = space
insert_final_newline = true
max_line_length = 100
indent_size = 4
ij_continuation_indent_size = 4 ij_continuation_indent_size = 4
ij_java_names_count_to_use_import_on_demand = 9999 ij_java_names_count_to_use_import_on_demand = 9999
ij_kotlin_align_in_columns_case_branch = false ij_kotlin_align_in_columns_case_branch = false
@@ -17,6 +11,8 @@ ij_kotlin_align_multiline_extends_list = false
ij_kotlin_align_multiline_method_parentheses = false ij_kotlin_align_multiline_method_parentheses = false
ij_kotlin_align_multiline_parameters = true ij_kotlin_align_multiline_parameters = true
ij_kotlin_align_multiline_parameters_in_calls = false ij_kotlin_align_multiline_parameters_in_calls = false
ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true
ij_kotlin_assignment_wrap = normal ij_kotlin_assignment_wrap = normal
ij_kotlin_blank_lines_after_class_header = 0 ij_kotlin_blank_lines_after_class_header = 0
ij_kotlin_blank_lines_around_block_when_branches = 0 ij_kotlin_blank_lines_around_block_when_branches = 0
@@ -24,7 +20,10 @@ ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_
ij_kotlin_block_comment_at_first_column = true ij_kotlin_block_comment_at_first_column = true
ij_kotlin_call_parameters_new_line_after_left_paren = true ij_kotlin_call_parameters_new_line_after_left_paren = true
ij_kotlin_call_parameters_right_paren_on_new_line = false ij_kotlin_call_parameters_right_paren_on_new_line = false
ij_kotlin_call_parameters_wrap = on_every_item
ij_kotlin_catch_on_new_line = false ij_kotlin_catch_on_new_line = false
ij_kotlin_class_annotation_wrap = split_into_lines
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
ij_kotlin_continuation_indent_for_chained_calls = true ij_kotlin_continuation_indent_for_chained_calls = true
ij_kotlin_continuation_indent_for_expression_bodies = true ij_kotlin_continuation_indent_for_expression_bodies = true
ij_kotlin_continuation_indent_in_argument_lists = true ij_kotlin_continuation_indent_in_argument_lists = true
@@ -53,6 +52,7 @@ ij_kotlin_method_annotation_wrap = split_into_lines
ij_kotlin_method_call_chain_wrap = normal ij_kotlin_method_call_chain_wrap = normal
ij_kotlin_method_parameters_new_line_after_left_paren = true ij_kotlin_method_parameters_new_line_after_left_paren = true
ij_kotlin_method_parameters_right_paren_on_new_line = true ij_kotlin_method_parameters_right_paren_on_new_line = true
ij_kotlin_method_parameters_wrap = on_every_item
ij_kotlin_name_count_to_use_star_import = 9999 ij_kotlin_name_count_to_use_star_import = 9999
ij_kotlin_name_count_to_use_star_import_for_members = 9999 ij_kotlin_name_count_to_use_star_import_for_members = 9999
ij_kotlin_parameter_annotation_wrap = off ij_kotlin_parameter_annotation_wrap = off
@@ -83,15 +83,3 @@ ij_kotlin_while_on_new_line = false
ij_kotlin_wrap_elvis_expressions = 1 ij_kotlin_wrap_elvis_expressions = 1
ij_kotlin_wrap_expression_body_functions = 1 ij_kotlin_wrap_expression_body_functions = 1
ij_kotlin_wrap_first_method_in_call_chain = false ij_kotlin_wrap_first_method_in_call_chain = false
#compose
ktlint_standard_filename = disabled
ktlint_standard_no-wildcard-imports = disabled
ktlint_standard_function-naming = disabled
ktlint_standard_property-naming = disabled
ktlint_standard_package-naming = disabled
ktlint_function_naming_ignore_when_annotated_with = Composable
ktlint_code_style = android_studio
ktlint_standard_import-ordering = disabled
ktlint_standard_package-naming = disabled
ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true
-22
View File
@@ -1,22 +0,0 @@
# Contributor Code of Conduct
## Pledge
We as individuals involved in this project, pledge to participate in this
community in a respectful, constructive, and civil manner as we work towards a common goal
of delivering free, open source, and value adding software for all.
## Standard
The standard for this community is the Golden Rule.
> “Do unto others as you would have them do unto you.”
## Scope
This Code of Conduct applies to all spaces related to WG Tunnel.
## Incidents or Concerns
For any incidents or concerns, reach out to Zane at
<support@zaneschepke.com>.
-23
View File
@@ -1,23 +0,0 @@
name: ci-android
on:
workflow_dispatch:
pull_request:
jobs:
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Run ktlint
run: ./gradlew ktlintCheck
-20
View File
@@ -1,20 +0,0 @@
name: Issue Updates Workflow
on:
issues:
types: [ opened, closed, reopened ]
jobs:
build:
name: Build
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 }}"
+99
View File
@@ -0,0 +1,99 @@
# name of the workflow
name: Android CI Tag Deployment (Pre-release)
on:
workflow_dispatch:
push:
tags:
- '*.*.*-**'
jobs:
build:
name: Build Signed APK
runs-on: ubuntu-latest
env:
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
KEY_STORE_FILE: 'android_keystore.jks'
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
GH_USER: ${{ secrets.GH_USER }}
GH_TOKEN: ${{ secrets.GH_TOKEN }}
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
# Here we need to decode keystore.jks from base64 string and place it
# in the folder specified in the release signing configuration
- name: Decode Keystore
id: decode_keystore
uses: timheuer/base64-to-file@v1.2
with:
fileName: ${{ env.KEY_STORE_FILE }}
fileDir: ${{ env.KEY_STORE_LOCATION }}
encodedString: ${{ secrets.KEYSTORE }}
# create keystore path for gradle to read
- name: Create keystore path env var
run: |
store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }}
echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV
- name: Create service_account.json
id: createServiceAccount
run: echo '${{ secrets.SERVICE_ACCOUNT_JSON }}' > service_account.json
# Build and sign APK ("-x test" argument is used to skip tests)
# add fdroid flavor for apk upload
- name: Build Fdroid Release APK
run: ./gradlew :app:assembleFdroidRelease -x test
# get fdroid flavor release apk path
- name: Get apk path
id: apk-path
run: echo "path=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_OUTPUT
- name: Get version code
run: |
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
# Save the APK after the Build job is complete to publish it as a Github release in the next job
- name: Upload APK
uses: actions/upload-artifact@v4.3.1
with:
name: wgtunnel
path: ${{ steps.apk-path.outputs.path }}
- name: Download APK from build
uses: actions/download-artifact@v4
with:
name: wgtunnel
- name: Create Release with Fastlane changelog notes
id: create_release
uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# fix hardcode changelog file name
body_path: ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt
tag_name: ${{ github.ref_name }}
name: ${{ github.ref_name }}
draft: false
prerelease: true
files: ${{ github.workspace }}/${{ steps.apk-path.outputs.path }}
- name: Deploy with fastlane
uses: ruby/setup-ruby@v1
with:
ruby-version: '3.2' # Not needed with a .ruby-version file
bundler-cache: true
- name: Distribute app to Beta track 🚀
run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane beta)
-21
View File
@@ -1,21 +0,0 @@
name: Release Updates Workflow
on:
release:
types: [ published ]
jobs:
build:
name: Build
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 }}"
+19 -150
View File
@@ -1,40 +1,17 @@
name: release-android # name of the workflow
name: Android CI Tag Deployment (Release)
on: on:
schedule:
- cron: "4 3 * * *"
workflow_dispatch: workflow_dispatch:
inputs: push:
track: tags:
type: choice - '*.*.*'
description: "Google play release track" - '!*.*.*-**'
options:
- none
- internal
- alpha
- beta
- production
default: alpha
required: true
release_type:
type: choice
description: "GitHub release type"
options:
- none
- prerelease
- nightly
- release
default: release
required: true
tag_name:
description: "Tag name for release"
required: false
default: nightly
jobs: jobs:
build: build:
name: Build Signed APK name: Build Signed APK
if: ${{ inputs.release_type != 'none' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
@@ -44,9 +21,7 @@ jobs:
KEY_STORE_FILE: 'android_keystore.jks' KEY_STORE_FILE: 'android_keystore.jks'
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/ KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
GH_USER: ${{ secrets.GH_USER }} GH_USER: ${{ secrets.GH_USER }}
# GH needed for gh cli
GH_TOKEN: ${{ secrets.GH_TOKEN }} GH_TOKEN: ${{ secrets.GH_TOKEN }}
GH_REPO: ${{ github.repository }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -59,10 +34,6 @@ jobs:
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x gradlew run: chmod +x gradlew
- name: Install system dependencies
run: |
sudo apt update && sudo apt install -y gh apksigner
# Here we need to decode keystore.jks from base64 string and place it # Here we need to decode keystore.jks from base64 string and place it
# in the folder specified in the release signing configuration # in the folder specified in the release signing configuration
- name: Decode Keystore - name: Decode Keystore
@@ -86,151 +57,49 @@ jobs:
# Build and sign APK ("-x test" argument is used to skip tests) # Build and sign APK ("-x test" argument is used to skip tests)
# add fdroid flavor for apk upload # add fdroid flavor for apk upload
- name: Build Fdroid Release APK - name: Build Fdroid Release APK
if: ${{ inputs.release_type != '' && inputs.release_type == 'release' }}
run: ./gradlew :app:assembleFdroidRelease -x test run: ./gradlew :app:assembleFdroidRelease -x test
- name: Build Fdroid Prerelease APK # get fdroid flavor release apk path
if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }} - name: Get apk path
run: ./gradlew :app:assembleFdroidPrerelease -x test id: apk-path
run: echo "path=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_OUTPUT
- name: Build Fdroid Nightly APK
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
run: ./gradlew :app:assembleFdroidNightly -x test
- if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/nightly/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
- if: ${{ inputs.release_type != '' && inputs.release_type == 'release' }}
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
- if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }}
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/prerelease/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
- name: Get version code - name: Get version code
if: ${{ inputs.release_type == 'release' }}
run: | run: |
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n') version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
# Save the APK after the Build job is complete to publish it as a Github release in the next job # Save the APK after the Build job is complete to publish it as a Github release in the next job
- name: Upload APK - name: Upload APK
uses: actions/upload-artifact@v4.3.5 uses: actions/upload-artifact@v4.3.1
with: with:
name: wgtunnel name: wgtunnel
path: ${{ env.APK_PATH }} path: ${{ steps.apk-path.outputs.path }}
- name: Download APK from build - name: Download APK from build
uses: actions/download-artifact@v4 uses: actions/download-artifact@v4
with: with:
name: wgtunnel name: wgtunnel
- name: Repository Dispatch for my F-Droid repo - name: Repository Dispatch for my F-Droid repo
uses: peter-evans/repository-dispatch@v3 uses: peter-evans/repository-dispatch@v3
if: ${{ inputs.release_type == 'release' }}
with: with:
token: ${{ secrets.PAT }} token: ${{ secrets.PAT }}
repository: zaneschepke/fdroid repository: zaneschepke/fdroid
event-type: fdroid-update event-type: fdroid-update
# Setup TAG_NAME, which is used as a general "name"
- if: github.event_name == 'workflow_dispatch'
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
- if: github.event_name == 'schedule'
run: echo "TAG_NAME=nightly" >> $GITHUB_ENV
- name: Set version release notes
if: ${{ inputs.release_type == 'release' }}
run: |
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
echo "$RELEASE_NOTES" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
- name: On nightly release notes
if: ${{ contains(env.TAG_NAME, 'nightly') }}
run: |
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
gh release delete nightly --yes || true
- name: On prerelease release notes
if: ${{ inputs.release_type == 'prerelease' }}
run: |
echo "RELEASE_NOTES=Testing version of app for specific feature." >> $GITHUB_ENV
gh release delete ${{ github.event.inputs.tag_name }} --yes || true
- name: Get checksum
id: checksum
run: echo "checksum=$(apksigner verify -print-certs ${{ env.APK_PATH }} | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT
- name: Create Release with Fastlane changelog notes - name: Create Release with Fastlane changelog notes
id: create_release id: create_release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
body: | body_path: ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt
${{ env.RELEASE_NOTES }} tag_name: ${{ github.ref_name }}
name: ${{ github.ref_name }}
SHA256 fingerprint:
```${{ steps.checksum.outputs.checksum }}```
tag_name: ${{ env.TAG_NAME }}
name: ${{ env.TAG_NAME }}
draft: false draft: false
prerelease: ${{ inputs.release_type == 'prerelease' || inputs.release_type == '' || inputs.release_type == 'nightly' }} prerelease: false
make_latest: ${{ inputs.release_type == 'release' }} files: ${{ github.workspace }}/${{ steps.apk-path.outputs.path }}
files: ${{ github.workspace }}/${{ env.APK_PATH }}
publish-play:
if: ${{ inputs.track != 'none' && inputs.track != '' }}
name: Publish to Google Play
runs-on: ubuntu-latest
env:
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
KEY_STORE_FILE: 'android_keystore.jks'
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
GH_USER: ${{ secrets.GH_USER }}
GH_TOKEN: ${{ secrets.GH_TOKEN }}
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
# Here we need to decode keystore.jks from base64 string and place it
# in the folder specified in the release signing configuration
- name: Decode Keystore
id: decode_keystore
uses: timheuer/base64-to-file@v1.2
with:
fileName: ${{ env.KEY_STORE_FILE }}
fileDir: ${{ env.KEY_STORE_LOCATION }}
encodedString: ${{ secrets.KEYSTORE }}
# create keystore path for gradle to read
- name: Create keystore path env var
run: |
store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }}
echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV
- name: Create service_account.json
id: createServiceAccount
run: echo '${{ secrets.SERVICE_ACCOUNT_JSON }}' > service_account.json
- name: Deploy with fastlane - name: Deploy with fastlane
uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1
with: with:
ruby-version: '3.2' # Not needed with a .ruby-version file ruby-version: '3.2' # Not needed with a .ruby-version file
bundler-cache: true bundler-cache: true
- name: Distribute app to Prod track 🚀 - 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 production)
+12 -39
View File
@@ -4,9 +4,8 @@ WG Tunnel
<div align="center"> <div align="center">
[![Discord](https://img.shields.io/badge/Discord-%235865F2.svg?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/rbRRNh6H7V) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![X Community](https://img.shields.io/badge/X-000000?style=for-the-badge&logo=x&logoColor=white)](https://twitter.com/i/communities/1780655267685736818) [![Discord Chat](https://img.shields.io/discord/1108285024631001111.svg)](https://discord.gg/rbRRNh6H7V)
[![Telegram](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/wgtunnel)
</div> </div>
@@ -22,8 +21,7 @@ WG Tunnel
<div align="left"> <div align="left">
This is an alternative Android Application for [WireGuard](https://www.wireguard.com/) This is an alternative Android Application for [WireGuard](https://www.wireguard.com/) with added
and [AmneziaWG](https://docs.amnezia.org/documentation/amnezia-wg/) with added
features. Built using the [wireguard-android](https://github.com/WireGuard/wireguard-android) features. Built using the [wireguard-android](https://github.com/WireGuard/wireguard-android)
library and [Jetpack Compose](https://developer.android.com/jetpack/compose), this application was library and [Jetpack Compose](https://developer.android.com/jetpack/compose), this application was
inspired by the official [WireGuard Android](https://github.com/WireGuard/wireguard-android) app. inspired by the official [WireGuard Android](https://github.com/WireGuard/wireguard-android) app.
@@ -51,42 +49,24 @@ and on while on different networks. This app was created to offer a free solutio
## Features ## Features
* Add tunnels via .conf file, zip, manual entry, or QR code * Add tunnels via .conf file, zip, manual entry, or QR code
* Auto connect to tunnels based on Wi-Fi SSID, ethernet, or mobile data * Auto connect to VPN based on Wi-Fi SSID, ethernet, or mobile data
* Split tunneling by application with search * Split tunneling by application with search
* WireGuard support for kernel and userspace modes * WireGuard support for kernel and userspace modes
* Amnezia support for userspace mode for DPI/censorship protection
* Always-On VPN support * Always-On VPN support
* Export Amnezia and WireGuard tunnels to zip * Export tunnels to zip
* Quick tile support for tunnel toggling, auto-tunneling * Quick tile support for VPN toggling
* Static shortcuts support for tunnel toggling, auto-tunneling * Static shortcuts support for primary tunnel for automation integration
* Intent automation support for all tunnels * Intent automation support for all tunnels
* Automatic auto-tunneling service restart after reboot * Automatic service restart after reboot
* Automatic tunnel restart after reboot
* Battery preservation measures * Battery preservation measures
* Restart tunnel on ping failure (beta)
## Fdroid ## Docs (WIP)
Want updates faster? Basic documentation of the feature and behaviors of this app can be
found [here](https://zaneschepke.com/wgtunnel-docs/overview.html).
Check out my personal [fdroid repository](https://github.com/zaneschepke/fdroid) to get updates the
moment they are released.
## Docs
Information about features, behaviors, and answers to common questions can be found in the
app [documentation](https://zaneschepke.com/wgtunnel-docs/overview.html).
The repository for these docs can be found [here](https://github.com/zaneschepke/wgtunnel-docs). The repository for these docs can be found [here](https://github.com/zaneschepke/wgtunnel-docs).
## Translation
This app is using [Weblate](https://weblate.org) to assist with translations.
Help translate WG Tunnel into your language
at [Hosted Weblate](https://hosted.weblate.org/engage/wg-tunnel/).\
[![Translation status](https://hosted.weblate.org/widgets/wg-tunnel/-/multi-auto.svg)](https://hosted.weblate.org/engage/wg-tunnel/)
## Building ## Building
``` ```
@@ -100,11 +80,4 @@ And then build the app:
$ ./gradlew assembleDebug $ ./gradlew assembleDebug
``` ```
## Contributing </span>
Any contributions in the form of feedback, issues, code, or translations are welcome and much
appreciated!
Please read
the [code of conduct](https://github.com/zaneschepke/wgtunnel?tab=coc-ov-file#contributor-code-of-conduct)
before contributing.
-5
View File
@@ -1,5 +0,0 @@
# Security Policy
## Reporting a Vulnerability
Please report security issues to `support@zaneschepke.com`
+175 -175
View File
@@ -1,209 +1,209 @@
import java.util.Properties
plugins { plugins {
alias(libs.plugins.android.application) alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.android)
alias(libs.plugins.hilt.android) alias(libs.plugins.hilt.android)
alias(libs.plugins.kotlinxSerialization) alias(libs.plugins.kotlinxSerialization)
alias(libs.plugins.ksp) alias(libs.plugins.ksp)
alias(libs.plugins.compose.compiler)
alias(libs.plugins.grgit)
} }
android { android {
namespace = Constants.APP_ID namespace = Constants.APP_ID
compileSdk = Constants.TARGET_SDK compileSdk = Constants.TARGET_SDK
androidResources { defaultConfig {
generateLocaleConfig = true applicationId = Constants.APP_ID
} minSdk = Constants.MIN_SDK
targetSdk = Constants.TARGET_SDK
versionCode = Constants.VERSION_CODE
versionName = Constants.VERSION_NAME
defaultConfig { ksp { arg("room.schemaLocation", "$projectDir/schemas") }
applicationId = Constants.APP_ID
minSdk = Constants.MIN_SDK
targetSdk = Constants.TARGET_SDK
versionCode = determineVersionCode()
versionName = determineVersionName()
ksp { arg("room.schemaLocation", "$projectDir/schemas") } sourceSets {
getByName("debug").assets.srcDirs(files("$projectDir/schemas")) // Room
}
sourceSets { resourceConfigurations.addAll(listOf("en"))
getByName("debug").assets.srcDirs(files("$projectDir/schemas")) // Room
}
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 = getStoreFile() val properties =
storePassword = getSigningProperty(Constants.STORE_PASS_VAR) Properties().apply {
keyAlias = getSigningProperty(Constants.KEY_ALIAS_VAR) // created local file for signing details
keyPassword = getSigningProperty(Constants.KEY_PASS_VAR) try {
} load(file("signing.properties").reader())
} } catch (_: Exception) {
load(file("signing_template.properties").reader())
}
}
buildTypes { // try to get secrets from env first for pipeline build, then properties file for local
// don't strip // build
packaging.jniLibs.keepDebugSymbols.addAll( storeFile =
listOf("libwg-go.so", "libwg-quick.so", "libwg.so"), file(
) System.getenv()
.getOrDefault(
Constants.KEY_STORE_PATH_VAR,
properties.getProperty(Constants.KEY_STORE_PATH_VAR),
),
)
storePassword =
System.getenv()
.getOrDefault(
Constants.STORE_PASS_VAR,
properties.getProperty(Constants.STORE_PASS_VAR),
)
keyAlias =
System.getenv()
.getOrDefault(
Constants.KEY_ALIAS_VAR,
properties.getProperty(Constants.KEY_ALIAS_VAR),
)
keyPassword =
System.getenv()
.getOrDefault(
Constants.KEY_PASS_VAR,
properties.getProperty(Constants.KEY_PASS_VAR),
)
}
}
release { buildTypes {
isDebuggable = false // don't strip
isMinifyEnabled = true packaging.jniLibs.keepDebugSymbols.addAll(
isShrinkResources = true listOf("libwg-go.so", "libwg-quick.so", "libwg.so"),
proguardFiles( )
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro",
)
signingConfig = signingConfigs.getByName(Constants.RELEASE)
}
debug { isDebuggable = true }
create(Constants.PRERELEASE) { applicationVariants.all {
initWith(buildTypes.getByName(Constants.RELEASE)) val variant = this
} variant.outputs
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
create(Constants.NIGHTLY) { .forEach { output ->
initWith(buildTypes.getByName(Constants.RELEASE)) val outputFileName =
} "${Constants.APP_NAME}-${variant.flavorName}-${variant.buildType.name}-${variant.versionName}.apk"
output.outputFileName = outputFileName
applicationVariants.all { }
val variant = this }
variant.outputs release {
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl } isDebuggable = false
.forEach { output -> isMinifyEnabled = true
val outputFileName = isShrinkResources = true
"${Constants.APP_NAME}-${variant.flavorName}-" + proguardFiles(
"${variant.buildType.name}-${variant.versionName}.apk" getDefaultProguardFile("proguard-android-optimize.txt"),
output.outputFileName = outputFileName "proguard-rules.pro",
} )
} signingConfig = signingConfigs.getByName(Constants.RELEASE)
} }
flavorDimensions.add(Constants.TYPE) debug { isDebuggable = true }
productFlavors { }
create("fdroid") { flavorDimensions.add(Constants.TYPE)
dimension = Constants.TYPE productFlavors {
proguardFile("fdroid-rules.pro") create("fdroid") {
} dimension = Constants.TYPE
create("general") { proguardFile("fdroid-rules.pro")
dimension = Constants.TYPE }
} create("general") {
} dimension = Constants.TYPE
compileOptions { if (BuildHelper.isReleaseBuild(gradle) && BuildHelper.isGeneralFlavor(gradle)) {
sourceCompatibility = JavaVersion.VERSION_17 //any plugins general specific
targetCompatibility = JavaVersion.VERSION_17 }
isCoreLibraryDesugaringEnabled = true }
} }
kotlinOptions { jvmTarget = Constants.JVM_TARGET } compileOptions {
buildFeatures { sourceCompatibility = JavaVersion.VERSION_17
compose = true targetCompatibility = JavaVersion.VERSION_17
buildConfig = true isCoreLibraryDesugaringEnabled = true
} }
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } } kotlinOptions { jvmTarget = Constants.JVM_TARGET }
buildFeatures {
compose = true
buildConfig = true
}
composeOptions { kotlinCompilerExtensionVersion = Constants.COMPOSE_COMPILER_EXTENSION_VERSION }
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
} }
val generalImplementation by configurations val generalImplementation by configurations
dependencies { dependencies {
implementation(project(":logcatter")) implementation(project(":logcatter"))
implementation(libs.androidx.core.ktx) implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.lifecycle.runtime.ktx)
// helpers for implementing LifecycleOwner in a Service
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)
// helpers for implementing LifecycleOwner in a Service // test
implementation(libs.androidx.lifecycle.service) testImplementation(libs.junit)
implementation(libs.androidx.activity.compose) testImplementation(libs.androidx.junit)
implementation(platform(libs.androidx.compose.bom)) androidTestImplementation(libs.androidx.junit)
implementation(libs.androidx.compose.ui) androidTestImplementation(libs.androidx.espresso.core)
implementation(libs.androidx.compose.ui.graphics) androidTestImplementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui.tooling.preview) androidTestImplementation(libs.androidx.compose.ui.test)
implementation(libs.androidx.material3) androidTestImplementation(libs.androidx.room.testing)
implementation(libs.androidx.appcompat) debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.androidx.compose.manifest)
// test // get tunnel lib from github packages or mavenLocal
testImplementation(libs.junit) implementation(libs.tunnel)
testImplementation(libs.androidx.junit) coreLibraryDesugaring(libs.desugar.jdk.libs)
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)
// get tunnel lib from github packages or mavenLocal // logging
implementation(libs.tunnel) implementation(libs.timber)
implementation(libs.amneziawg.android)
coreLibraryDesugaring(libs.desugar.jdk.libs)
// logging
implementation(libs.timber)
// compose navigation // compose navigation
implementation(libs.androidx.navigation.compose) implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.hilt.navigation.compose) implementation(libs.androidx.hilt.navigation.compose)
implementation(libs.zaneschepke.multifab) // hilt
implementation(libs.hilt.android)
ksp(libs.hilt.android.compiler)
// hilt // accompanist
implementation(libs.hilt.android) implementation(libs.accompanist.permissions)
ksp(libs.hilt.android.compiler) implementation(libs.accompanist.flowlayout)
implementation(libs.accompanist.drawablepainter)
// accompanist // storage
implementation(libs.accompanist.permissions) implementation(libs.androidx.room.runtime)
implementation(libs.accompanist.flowlayout) ksp(libs.androidx.room.compiler)
implementation(libs.accompanist.drawablepainter) implementation(libs.androidx.room.ktx)
implementation(libs.androidx.datastore.preferences)
// storage // lifecycle
implementation(libs.androidx.room.runtime) implementation(libs.lifecycle.runtime.compose)
ksp(libs.androidx.room.compiler) implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.room.ktx) implementation(libs.androidx.lifecycle.process)
implementation(libs.androidx.datastore.preferences)
// lifecycle // icons
implementation(libs.lifecycle.runtime.compose) implementation(libs.material.icons.extended)
implementation(libs.androidx.lifecycle.runtime.ktx) // serialization
implementation(libs.androidx.lifecycle.process) implementation(libs.kotlinx.serialization.json)
// icons // barcode scanning
implementation(libs.material.icons.extended) implementation(libs.zxing.android.embedded)
// serialization implementation(libs.zxing.core)
implementation(libs.kotlinx.serialization.json)
// barcode scanning // bio
implementation(libs.zxing.android.embedded) implementation(libs.androidx.biometric.ktx)
implementation(libs.pin.lock.compose)
// bio // shortcuts
implementation(libs.androidx.biometric.ktx) implementation(libs.androidx.core)
implementation(libs.pin.lock.compose) implementation(libs.androidx.core.google.shortcuts)
// shortcuts
implementation(libs.androidx.core)
implementation(libs.androidx.core.google.shortcuts)
// splash
implementation(libs.androidx.core.splashscreen)
}
fun determineVersionCode(): Int {
return with(getBuildTaskName().lowercase()) {
when {
contains(Constants.NIGHTLY) -> Constants.VERSION_CODE + Constants.NIGHTLY_CODE
contains(Constants.PRERELEASE) -> Constants.VERSION_CODE + Constants.PRERELEASE_CODE
else -> Constants.VERSION_CODE
}
}
}
fun determineVersionName(): String {
return with(getBuildTaskName().lowercase()) {
when {
contains(Constants.NIGHTLY) || contains(Constants.PRERELEASE) ->
Constants.VERSION_NAME +
"-${grgitService.service.get().grgit.head().abbreviatedId}"
else -> Constants.VERSION_NAME
}
}
} }
+2
View File
@@ -22,3 +22,5 @@
-keepclassmembers class * extends androidx.datastore.preferences.protobuf.GeneratedMessageLite { -keepclassmembers class * extends androidx.datastore.preferences.protobuf.GeneratedMessageLite {
<fields>; <fields>;
} }
@@ -1,190 +0,0 @@
{
"formatVersion": 1,
"database": {
"version": 8,
"identityHash": "b4d4a7c489f6b2f0d3aa4fa6f37b4935",
"entities": [
{
"tableName": "Settings",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_auto_tunnel_paused` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isAutoTunnelEnabled",
"columnName": "is_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnMobileDataEnabled",
"columnName": "is_tunnel_on_mobile_data_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trustedNetworkSSIDs",
"columnName": "trusted_network_ssids",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isAlwaysOnVpnEnabled",
"columnName": "is_always_on_vpn_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnEthernetEnabled",
"columnName": "is_tunnel_on_ethernet_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isShortcutsEnabled",
"columnName": "is_shortcuts_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnWifiEnabled",
"columnName": "is_tunnel_on_wifi_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isKernelEnabled",
"columnName": "is_kernel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isRestoreOnBootEnabled",
"columnName": "is_restore_on_boot_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isMultiTunnelEnabled",
"columnName": "is_multi_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isAutoTunnelPaused",
"columnName": "is_auto_tunnel_paused",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPingEnabled",
"columnName": "is_ping_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isAmneziaEnabled",
"columnName": "is_amnezia_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "TunnelConfig",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '')",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wgQuick",
"columnName": "wg_quick",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "tunnelNetworks",
"columnName": "tunnel_networks",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isMobileDataTunnel",
"columnName": "is_mobile_data_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPrimaryTunnel",
"columnName": "is_primary_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "amQuick",
"columnName": "am_quick",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_TunnelConfig_name",
"unique": true,
"columnNames": [
"name"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
}
],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'b4d4a7c489f6b2f0d3aa4fa6f37b4935')"
]
}
}
@@ -13,10 +13,10 @@ import org.junit.runner.RunWith
*/ */
@RunWith(AndroidJUnit4::class) @RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest { class ExampleInstrumentedTest {
@Test @Test
fun useAppContext() { fun useAppContext() {
// Context of the app under test. // Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.zaneschepke.wireguardautotunnel", appContext.packageName) assertEquals("com.zaneschepke.wireguardautotunnel", appContext.packageName)
} }
} }
@@ -12,33 +12,33 @@ import java.io.IOException
@RunWith(AndroidJUnit4::class) @RunWith(AndroidJUnit4::class)
class MigrationTest { class MigrationTest {
private val dbName = "migration-test" private val dbName = "migration-test"
@get:Rule @get:Rule
val helper: MigrationTestHelper = val helper: MigrationTestHelper =
MigrationTestHelper( MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(), InstrumentationRegistry.getInstrumentation(),
AppDatabase::class.java, AppDatabase::class.java,
) )
@Test @Test
@Throws(IOException::class) @Throws(IOException::class)
fun migrate6To7() { fun migrate6To7() {
helper.createDatabase(dbName, 6).apply { helper.createDatabase(dbName, 6).apply {
// Database has schema version 1. Insert some data using SQL queries. // Database has schema version 1. Insert some data using SQL queries.
// You can't use DAO classes because they expect the latest schema. // You can't use DAO classes because they expect the latest schema.
execSQL(Queries.createDefaultSettings()) execSQL(Queries.createDefaultSettings())
execSQL( execSQL(
Queries.createTunnelConfig(), Queries.createTunnelConfig(),
) )
// Prepare for the next version. // Prepare for the next version.
close() close()
} }
// Re-open the database with version 2 and provide // Re-open the database with version 2 and provide
// MIGRATION_1_2 as the migration process. // MIGRATION_1_2 as the migration process.
helper.runMigrationsAndValidate(dbName, 7, true) helper.runMigrationsAndValidate(dbName, 7, true)
// MigrationTestHelper automatically verifies the schema changes, // MigrationTestHelper automatically verifies the schema changes,
// but you need to validate that the data was migrated properly. // but you need to validate that the data was migrated properly.
} }
} }
+13 -18
View File
@@ -51,8 +51,8 @@
</queries> </queries>
<application <application
android:name=".WireGuardAutoTunnel" android:name=".WireGuardAutoTunnel"
android:allowBackup="false" android:allowBackup="true"
android:banner="@drawable/ic_banner" android:banner="@mipmap/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"
@@ -60,17 +60,18 @@
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.AppSplashScreen" android:theme="@style/Theme.WireguardAutoTunnel"
tools:targetApi="tiramisu"> tools:targetApi="tiramisu">
<activity <activity
android:name=".ui.SplashActivity" android:name=".ui.MainActivity"
android:exported="true" android:exported="true"
android:theme="@style/Theme.AppSplashScreen"> android:theme="@style/Theme.WireguardAutoTunnel">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" /> <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" /> <action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
</intent-filter> </intent-filter>
<meta-data <meta-data
@@ -78,23 +79,17 @@
android:resource="@xml/shortcuts" /> android:resource="@xml/shortcuts" />
</activity> </activity>
<activity <activity
android:name=".ui.MainActivity" android:name=".ui.CaptureActivityPortrait"
android:exported="true" android:screenOrientation="fullSensor"
android:theme="@style/Theme.WireguardAutoTunnel"> android:stateNotNeeded="true"
</activity> android:theme="@style/zxing_CaptureTheme"
<activity android:windowSoftInputMode="stateAlwaysHidden"
android:name="com.journeyapps.barcodescanner.CaptureActivity" tools:ignore="DiscouragedApi" />
android:screenOrientation="portrait"
tools:replace="screenOrientation" />
<activity <activity
android:name=".service.shortcut.ShortcutsActivity" android:name=".service.shortcut.ShortcutsActivity"
android:enabled="true" android:enabled="true"
android:exported="true" android:exported="true"
android:noHistory="true" android:finishOnTaskLaunch="true"
android:excludeFromRecents="true"
android:finishOnTaskLaunch="true"
android:launchMode="singleInstance"
android:theme="@android:style/Theme.NoDisplay" /> android:theme="@android:style/Theme.NoDisplay" />
<service <service
@@ -2,56 +2,45 @@ package com.zaneschepke.wireguardautotunnel
import android.app.Application import android.app.Application
import android.content.ComponentName import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy
import android.service.quicksettings.TileService import android.service.quicksettings.TileService
import com.zaneschepke.wireguardautotunnel.service.tile.AutoTunnelControlTile import com.zaneschepke.wireguardautotunnel.service.tile.AutoTunnelControlTile
import com.zaneschepke.wireguardautotunnel.service.tile.TunnelControlTile import com.zaneschepke.wireguardautotunnel.service.tile.TunnelControlTile
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
import dagger.hilt.android.HiltAndroidApp import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber import timber.log.Timber
import xyz.teamgravity.pin_lock_compose.PinManager
@HiltAndroidApp @HiltAndroidApp
class WireGuardAutoTunnel : Application() { class WireGuardAutoTunnel : Application() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
instance = this instance = this
if (BuildConfig.DEBUG) { if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree()) else Timber.plant(ReleaseTree())
Timber.plant(Timber.DebugTree()) PinManager.initialize(this)
StrictMode.setThreadPolicy( }
ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build(),
)
} else {
Timber.plant(ReleaseTree())
}
}
companion object { companion object {
lateinit var instance: WireGuardAutoTunnel lateinit var instance: WireGuardAutoTunnel
private set private set
fun isRunningOnAndroidTv(): Boolean { fun isRunningOnAndroidTv(): Boolean {
return instance.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK) return instance.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
} }
fun requestTunnelTileServiceStateUpdate() { fun requestTunnelTileServiceStateUpdate(context: Context) {
TileService.requestListeningState( TileService.requestListeningState(
instance, context,
ComponentName(instance, TunnelControlTile::class.java), ComponentName(instance, TunnelControlTile::class.java),
) )
} }
fun requestAutoTunnelTileServiceUpdate() { fun requestAutoTunnelTileServiceUpdate(context: Context) {
TileService.requestListeningState( TileService.requestListeningState(
instance, context,
ComponentName(instance, AutoTunnelControlTile::class.java), ComponentName(instance, AutoTunnelControlTile::class.java),
) )
} }
} }
} }
@@ -6,50 +6,49 @@ import androidx.room.DeleteColumn
import androidx.room.RoomDatabase import androidx.room.RoomDatabase
import androidx.room.TypeConverters import androidx.room.TypeConverters
import androidx.room.migration.AutoMigrationSpec import androidx.room.migration.AutoMigrationSpec
import com.zaneschepke.wireguardautotunnel.data.domain.Settings import com.zaneschepke.wireguardautotunnel.data.model.Settings
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
@Database( @Database(
entities = [Settings::class, TunnelConfig::class], entities = [Settings::class, TunnelConfig::class],
version = 8, version = 7,
autoMigrations = autoMigrations =
[ [
AutoMigration(from = 1, to = 2), AutoMigration(from = 1, to = 2),
AutoMigration(from = 2, to = 3), AutoMigration(from = 2, to = 3),
AutoMigration( AutoMigration(
from = 3, from = 3,
to = 4, to = 4,
), ),
AutoMigration( AutoMigration(
from = 4, from = 4,
to = 5, to = 5,
), ),
AutoMigration( AutoMigration(
from = 5, from = 5,
to = 6, to = 6,
), ),
AutoMigration( AutoMigration(
from = 6, from = 6,
to = 7, to = 7,
spec = RemoveLegacySettingColumnsMigration::class, spec = RemoveLegacySettingColumnsMigration::class,
), ),
AutoMigration(7, 8), ],
], exportSchema = true,
exportSchema = true,
) )
@TypeConverters(DatabaseListConverters::class) @TypeConverters(DatabaseListConverters::class)
abstract class AppDatabase : RoomDatabase() { abstract class AppDatabase : RoomDatabase() {
abstract fun settingDao(): SettingsDao abstract fun settingDao(): SettingsDao
abstract fun tunnelConfigDoa(): TunnelConfigDao abstract fun tunnelConfigDoa(): TunnelConfigDao
} }
@DeleteColumn( @DeleteColumn(
tableName = "Settings", tableName = "Settings",
columnName = "default_tunnel", columnName = "default_tunnel",
) )
@DeleteColumn( @DeleteColumn(
tableName = "Settings", tableName = "Settings",
columnName = "is_battery_saver_enabled", columnName = "is_battery_saver_enabled",
) )
class RemoveLegacySettingColumnsMigration : AutoMigrationSpec class RemoveLegacySettingColumnsMigration : AutoMigrationSpec
@@ -5,17 +5,17 @@ import androidx.sqlite.db.SupportSQLiteDatabase
import timber.log.Timber import timber.log.Timber
class DatabaseCallback : RoomDatabase.Callback() { class DatabaseCallback : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) = db.run { override fun onCreate(db: SupportSQLiteDatabase) = db.run {
// Notice non-ui thread is here // Notice non-ui thread is here
beginTransaction() beginTransaction()
try { try {
execSQL(Queries.createDefaultSettings()) execSQL(Queries.createDefaultSettings())
Timber.i("Bootstrapping settings data") Timber.i("Bootstrapping settings data")
setTransactionSuccessful() setTransactionSuccessful()
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e) Timber.e(e)
} finally { } finally {
endTransaction() endTransaction()
} }
} }
} }
@@ -5,20 +5,20 @@ import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
class DatabaseListConverters { class DatabaseListConverters {
@TypeConverter @TypeConverter
fun listToString(value: MutableList<String>): String { fun listToString(value: MutableList<String>): String {
return Json.encodeToString(value) return Json.encodeToString(value)
} }
@TypeConverter @TypeConverter
fun stringToList(value: String): MutableList<String> { fun stringToList(value: String): MutableList<String> {
if (value.isBlank() || value.isEmpty()) return mutableListOf() if (value.isBlank() || value.isEmpty()) return mutableListOf()
return try { return try {
Json.decodeFromString<MutableList<String>>(value) Json.decodeFromString<MutableList<String>>(value)
} catch (e: Exception) { } catch (e: Exception) {
val list = value.split(",").toMutableList() val list = value.split(",").toMutableList()
val json = listToString(list) val json = listToString(list)
Json.decodeFromString<MutableList<String>>(json) Json.decodeFromString<MutableList<String>>(json)
} }
} }
} }
@@ -1,35 +1,35 @@
package com.zaneschepke.wireguardautotunnel.data package com.zaneschepke.wireguardautotunnel.data
object Queries { object Queries {
fun createDefaultSettings(): String { fun createDefaultSettings(): String {
return """ return """
INSERT INTO Settings (is_tunnel_enabled, INSERT INTO Settings (is_tunnel_enabled,
is_tunnel_on_mobile_data_enabled, is_tunnel_on_mobile_data_enabled,
trusted_network_ssids, trusted_network_ssids,
is_always_on_vpn_enabled, is_always_on_vpn_enabled,
is_tunnel_on_ethernet_enabled, is_tunnel_on_ethernet_enabled,
is_shortcuts_enabled, is_shortcuts_enabled,
is_tunnel_on_wifi_enabled, is_tunnel_on_wifi_enabled,
is_kernel_enabled, is_kernel_enabled,
is_restore_on_boot_enabled, is_restore_on_boot_enabled,
is_multi_tunnel_enabled) is_multi_tunnel_enabled)
VALUES VALUES
('false', ('false',
'false', 'false',
'sampleSSID1,sampleSSID2', 'sampleSSID1,sampleSSID2',
'false', 'false',
'false', 'false',
'false', 'false',
'false', 'false',
'false', 'false',
'false', 'false',
'false') 'false')
""".trimIndent() """.trimIndent()
} }
fun createTunnelConfig(): String { fun createTunnelConfig(): String {
return """ return """
INSERT INTO TunnelConfig (name, wg_quick) VALUES ('test', 'test') INSERT INTO TunnelConfig (name, wg_quick) VALUES ('test', 'test')
""".trimIndent() """.trimIndent()
} }
} }
@@ -5,32 +5,32 @@ import androidx.room.Delete
import androidx.room.Insert import androidx.room.Insert
import androidx.room.OnConflictStrategy import androidx.room.OnConflictStrategy
import androidx.room.Query import androidx.room.Query
import com.zaneschepke.wireguardautotunnel.data.domain.Settings import com.zaneschepke.wireguardautotunnel.data.model.Settings
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface SettingsDao { interface SettingsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun save(t: Settings) suspend fun save(t: Settings)
@Insert(onConflict = OnConflictStrategy.REPLACE) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun saveAll(t: List<Settings>) suspend fun saveAll(t: List<Settings>)
@Query("SELECT * FROM settings WHERE id=:id") @Query("SELECT * FROM settings WHERE id=:id")
suspend fun getById(id: Long): Settings? suspend fun getById(id: Long): Settings?
@Query("SELECT * FROM settings") @Query("SELECT * FROM settings")
suspend fun getAll(): List<Settings> suspend fun getAll(): List<Settings>
@Query("SELECT * FROM settings LIMIT 1") @Query("SELECT * FROM settings LIMIT 1")
fun getSettingsFlow(): Flow<Settings> fun getSettingsFlow(): Flow<Settings>
@Query("SELECT * FROM settings") @Query("SELECT * FROM settings")
fun getAllFlow(): Flow<MutableList<Settings>> fun getAllFlow(): Flow<MutableList<Settings>>
@Delete @Delete
suspend fun delete(t: Settings) suspend fun delete(t: Settings)
@Query("SELECT COUNT('id') FROM settings") @Query("SELECT COUNT('id') FROM settings")
suspend fun count(): Long suspend fun count(): Long
} }
@@ -5,48 +5,45 @@ import androidx.room.Delete
import androidx.room.Insert import androidx.room.Insert
import androidx.room.OnConflictStrategy import androidx.room.OnConflictStrategy
import androidx.room.Query import androidx.room.Query
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface TunnelConfigDao { interface TunnelConfigDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun save(t: TunnelConfig) suspend fun save(t: TunnelConfig)
@Insert(onConflict = OnConflictStrategy.REPLACE) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun saveAll(t: TunnelConfigs) suspend fun saveAll(t: TunnelConfigs)
@Query("SELECT * FROM TunnelConfig WHERE id=:id") @Query("SELECT * FROM TunnelConfig WHERE id=:id")
suspend fun getById(id: Long): TunnelConfig? suspend fun getById(id: Long): TunnelConfig?
@Query("SELECT * FROM TunnelConfig WHERE name=:name") @Query("SELECT * FROM TunnelConfig")
suspend fun getByName(name: String): TunnelConfig? suspend fun getAll(): TunnelConfigs
@Query("SELECT * FROM TunnelConfig") @Delete
suspend fun getAll(): TunnelConfigs suspend fun delete(t: TunnelConfig)
@Delete @Query("SELECT COUNT('id') FROM TunnelConfig")
suspend fun delete(t: TunnelConfig) suspend fun count(): Long
@Query("SELECT COUNT('id') FROM TunnelConfig") @Query("SELECT * FROM TunnelConfig WHERE tunnel_networks LIKE '%' || :name || '%'")
suspend fun count(): Long suspend fun findByTunnelNetworkName(name: String): TunnelConfigs
@Query("SELECT * FROM TunnelConfig WHERE tunnel_networks LIKE '%' || :name || '%'") @Query("UPDATE TunnelConfig SET is_primary_tunnel = 0 WHERE is_primary_tunnel =1")
suspend fun findByTunnelNetworkName(name: String): TunnelConfigs fun resetPrimaryTunnel()
@Query("UPDATE TunnelConfig SET is_primary_tunnel = 0 WHERE is_primary_tunnel =1") @Query("UPDATE TunnelConfig SET is_mobile_data_tunnel = 0 WHERE is_mobile_data_tunnel =1")
suspend fun resetPrimaryTunnel() fun resetMobileDataTunnel()
@Query("UPDATE TunnelConfig SET is_mobile_data_tunnel = 0 WHERE is_mobile_data_tunnel =1") @Query("SELECT * FROM TUNNELCONFIG WHERE is_primary_tunnel=1")
suspend fun resetMobileDataTunnel() suspend fun findByPrimary(): TunnelConfigs
@Query("SELECT * FROM TUNNELCONFIG WHERE is_primary_tunnel=1") @Query("SELECT * FROM TUNNELCONFIG WHERE is_mobile_data_tunnel=1")
suspend fun findByPrimary(): TunnelConfigs suspend fun findByMobileDataTunnel(): TunnelConfigs
@Query("SELECT * FROM TUNNELCONFIG WHERE is_mobile_data_tunnel=1") @Query("SELECT * FROM tunnelconfig")
suspend fun findByMobileDataTunnel(): TunnelConfigs fun getAllFlow(): Flow<MutableList<TunnelConfig>>
@Query("SELECT * FROM tunnelconfig")
fun getAllFlow(): Flow<MutableList<TunnelConfig>>
} }
@@ -7,75 +7,64 @@ import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore import androidx.datastore.preferences.preferencesDataStore
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
import java.io.IOException import java.io.IOException
class DataStoreManager( class DataStoreManager(private val context: Context) {
private val context: Context, companion object {
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
) { val BATTERY_OPTIMIZE_DISABLE_SHOWN = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
companion object { val TUNNEL_RUNNING_FROM_MANUAL_START =
val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN") booleanPreferencesKey("TUNNEL_RUNNING_FROM_MANUAL_START")
val BATTERY_OPTIMIZE_DISABLE_SHOWN = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN") val ACTIVE_TUNNEL = intPreferencesKey("ACTIVE_TUNNEL")
val TUNNEL_RUNNING_FROM_MANUAL_START = val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
booleanPreferencesKey("TUNNEL_RUNNING_FROM_MANUAL_START") }
val ACTIVE_TUNNEL = intPreferencesKey("ACTIVE_TUNNEL")
val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
val IS_PIN_LOCK_ENABLED = booleanPreferencesKey("PIN_LOCK_ENABLED")
}
// preferences // preferences
private val preferencesKey = "preferences" private val preferencesKey = "preferences"
private val Context.dataStore by private val Context.dataStore by
preferencesDataStore( preferencesDataStore(
name = preferencesKey, name = preferencesKey,
) )
suspend fun init() { suspend fun init() {
withContext(ioDispatcher) { try {
try { context.dataStore.data.first()
context.dataStore.data.first() } catch (e: IOException) {
} catch (e: IOException) { Timber.e(e)
Timber.e(e) }
} }
}
}
suspend fun <T> saveToDataStore(key: Preferences.Key<T>, value: T) { suspend fun <T> saveToDataStore(key: Preferences.Key<T>, value: T) {
withContext(ioDispatcher) { try {
try { context.dataStore.edit { it[key] = value }
context.dataStore.edit { it[key] = value } } catch (e: IOException) {
} catch (e: IOException) { Timber.e(e)
Timber.e(e) } catch (e: Exception) {
} catch (e: Exception) { Timber.e(e)
Timber.e(e) }
} }
}
}
fun <T> getFromStoreFlow(key: Preferences.Key<T>) = context.dataStore.data.map { it[key] }
suspend fun <T> getFromStore(key: Preferences.Key<T>): T? { fun <T> getFromStoreFlow(key: Preferences.Key<T>) = context.dataStore.data.map { it[key] }
return withContext(ioDispatcher) {
try {
context.dataStore.data.map { it[key] }.first()
} catch (e: IOException) {
Timber.e(e)
null
}
}
}
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking { suspend fun <T> getFromStore(key: Preferences.Key<T>): T? {
context.dataStore.data.map { it[key] }.first() return try {
} context.dataStore.data.map { it[key] }.first()
} catch (e: IOException) {
Timber.e(e)
null
}
}
val preferencesFlow: Flow<Preferences?> = context.dataStore.data
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking {
context.dataStore.data.map { it[key] }.first()
}
val preferencesFlow: Flow<Preferences?> = context.dataStore.data
} }
@@ -1,16 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.domain
data class GeneralState(
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
val isTunnelRunningFromManualStart: Boolean = TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
val activeTunnelId: Int? = null,
) {
companion object {
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
const val TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT = false
const val PIN_LOCK_ENABLED_DEFAULT = false
}
}
@@ -1,58 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.domain
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Settings(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "is_tunnel_enabled") val isAutoTunnelEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_mobile_data_enabled")
val isTunnelOnMobileDataEnabled: Boolean = false,
@ColumnInfo(name = "trusted_network_ssids")
val trustedNetworkSSIDs: MutableList<String> = mutableListOf(),
@ColumnInfo(name = "is_always_on_vpn_enabled") val isAlwaysOnVpnEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_ethernet_enabled")
val isTunnelOnEthernetEnabled: Boolean = false,
@ColumnInfo(
name = "is_shortcuts_enabled",
defaultValue = "false",
)
val isShortcutsEnabled: Boolean = false,
@ColumnInfo(
name = "is_tunnel_on_wifi_enabled",
defaultValue = "false",
)
val isTunnelOnWifiEnabled: Boolean = false,
@ColumnInfo(
name = "is_kernel_enabled",
defaultValue = "false",
)
val isKernelEnabled: Boolean = false,
@ColumnInfo(
name = "is_restore_on_boot_enabled",
defaultValue = "false",
)
val isRestoreOnBootEnabled: Boolean = false,
@ColumnInfo(
name = "is_multi_tunnel_enabled",
defaultValue = "false",
)
val isMultiTunnelEnabled: Boolean = false,
@ColumnInfo(
name = "is_auto_tunnel_paused",
defaultValue = "false",
)
val isAutoTunnelPaused: Boolean = false,
@ColumnInfo(
name = "is_ping_enabled",
defaultValue = "false",
)
val isPingEnabled: Boolean = false,
@ColumnInfo(
name = "is_amnezia_enabled",
defaultValue = "false",
)
val isAmneziaEnabled: Boolean = false,
)
@@ -1,53 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.domain
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.wireguard.config.Config
import java.io.InputStream
@Entity(indices = [Index(value = ["name"], unique = true)])
data class TunnelConfig(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "wg_quick") val wgQuick: String,
@ColumnInfo(
name = "tunnel_networks",
defaultValue = "",
)
val tunnelNetworks: MutableList<String> = mutableListOf(),
@ColumnInfo(
name = "is_mobile_data_tunnel",
defaultValue = "false",
)
val isMobileDataTunnel: Boolean = false,
@ColumnInfo(
name = "is_primary_tunnel",
defaultValue = "false",
)
val isPrimaryTunnel: Boolean = false,
@ColumnInfo(
name = "am_quick",
defaultValue = "",
)
val amQuick: String = AM_QUICK_DEFAULT,
) {
companion object {
fun configFromWgQuick(wgQuick: String): Config {
val inputStream: InputStream = wgQuick.byteInputStream()
return inputStream.bufferedReader(Charsets.UTF_8).use {
Config.parse(it)
}
}
fun configFromAmQuick(amQuick: String): org.amnezia.awg.config.Config {
val inputStream: InputStream = amQuick.byteInputStream()
return inputStream.bufferedReader(Charsets.UTF_8).use {
org.amnezia.awg.config.Config.parse(it)
}
}
const val AM_QUICK_DEFAULT = ""
}
}
@@ -0,0 +1,14 @@
package com.zaneschepke.wireguardautotunnel.data.model
data class GeneralState(
val locationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
val batteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
val tunnelRunningFromManualStart: Boolean = TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
val activeTunnelId: Int? = null
) {
companion object {
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
const val TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT = false
}
}
@@ -0,0 +1,53 @@
package com.zaneschepke.wireguardautotunnel.data.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Settings(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "is_tunnel_enabled") val isAutoTunnelEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_mobile_data_enabled")
val isTunnelOnMobileDataEnabled: Boolean = false,
@ColumnInfo(name = "trusted_network_ssids")
val trustedNetworkSSIDs: MutableList<String> = mutableListOf(),
@ColumnInfo(name = "is_always_on_vpn_enabled") val isAlwaysOnVpnEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_ethernet_enabled")
val isTunnelOnEthernetEnabled: Boolean = false,
@ColumnInfo(
name = "is_shortcuts_enabled",
defaultValue = "false",
)
val isShortcutsEnabled: Boolean = false,
@ColumnInfo(
name = "is_tunnel_on_wifi_enabled",
defaultValue = "false",
)
val isTunnelOnWifiEnabled: Boolean = false,
@ColumnInfo(
name = "is_kernel_enabled",
defaultValue = "false",
)
val isKernelEnabled: Boolean = false,
@ColumnInfo(
name = "is_restore_on_boot_enabled",
defaultValue = "false",
)
val isRestoreOnBootEnabled: Boolean = false,
@ColumnInfo(
name = "is_multi_tunnel_enabled",
defaultValue = "false",
)
val isMultiTunnelEnabled: Boolean = false,
@ColumnInfo(
name = "is_auto_tunnel_paused",
defaultValue = "false",
)
val isAutoTunnelPaused: Boolean = false,
@ColumnInfo(
name = "is_ping_enabled",
defaultValue = "false",
)
val isPingEnabled: Boolean = false,
)
@@ -0,0 +1,38 @@
package com.zaneschepke.wireguardautotunnel.data.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.wireguard.config.Config
import java.io.InputStream
@Entity(indices = [Index(value = ["name"], unique = true)])
data class TunnelConfig(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "wg_quick") val wgQuick: String,
@ColumnInfo(
name = "tunnel_networks",
defaultValue = "",
)
val tunnelNetworks: MutableList<String> = mutableListOf(),
@ColumnInfo(
name = "is_mobile_data_tunnel",
defaultValue = "false",
)
val isMobileDataTunnel: Boolean = false,
@ColumnInfo(
name = "is_primary_tunnel",
defaultValue = "false",
)
val isPrimaryTunnel: Boolean = false,
) {
companion object {
fun configFromQuick(wgQuick: String): Config {
val inputStream: InputStream = wgQuick.byteInputStream()
val reader = inputStream.bufferedReader(Charsets.UTF_8)
return Config.parse(reader)
}
}
}
@@ -1,15 +1,14 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
interface AppDataRepository { interface AppDataRepository {
suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? suspend fun getPrimaryOrFirstTunnel(): TunnelConfig?
suspend fun getStartTunnelConfig(): TunnelConfig?
suspend fun getStartTunnelConfig(): TunnelConfig? suspend fun toggleWatcherServicePause()
suspend fun toggleWatcherServicePause() val settings: SettingsRepository
val tunnels: TunnelConfigRepository
val settings: SettingsRepository val appState: AppStateRepository
val tunnels: TunnelConfigRepository
val appState: AppStateRepository
} }
@@ -1,38 +1,34 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import javax.inject.Inject import javax.inject.Inject
class AppDataRoomRepository class AppDataRoomRepository @Inject constructor(
@Inject override val settings: SettingsRepository,
constructor( override val tunnels: TunnelConfigRepository,
override val settings: SettingsRepository, override val appState: AppStateRepository
override val tunnels: TunnelConfigRepository,
override val appState: AppStateRepository,
) : AppDataRepository { ) : AppDataRepository {
override suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? { override suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? {
return tunnels.findPrimary().firstOrNull() ?: tunnels.getAll().firstOrNull() return tunnels.findPrimary().firstOrNull() ?: tunnels.getAll().firstOrNull()
} }
override suspend fun getStartTunnelConfig(): TunnelConfig? { override suspend fun getStartTunnelConfig(): TunnelConfig? {
return if (appState.isTunnelRunningFromManualStart()) { return if (appState.isTunnelRunningFromManualStart()) {
appState.getActiveTunnelId()?.let { appState.getActiveTunnelId()?.let {
tunnels.getById(it) tunnels.getById(it)
} }
} else { } else null
null }
}
}
override suspend fun toggleWatcherServicePause() { override suspend fun toggleWatcherServicePause() {
val settings = settings.getSettings() val settings = settings.getSettings()
if (settings.isAutoTunnelEnabled) { if (settings.isAutoTunnelEnabled) {
val pauseAutoTunnel = !settings.isAutoTunnelPaused val pauseAutoTunnel = !settings.isAutoTunnelPaused
this.settings.save( this.settings.save(
settings.copy( settings.copy(
isAutoTunnelPaused = pauseAutoTunnel, isAutoTunnelPaused = pauseAutoTunnel,
), ),
) )
} }
} }
} }
@@ -1,32 +1,26 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState import com.zaneschepke.wireguardautotunnel.data.model.GeneralState
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 isBatteryOptimizationDisableShown(): Boolean
suspend fun setBatteryOptimizationDisableShown(shown: Boolean)
suspend fun isPinLockEnabled(): Boolean suspend fun isTunnelRunningFromManualStart(): Boolean
suspend fun setTunnelRunningFromManualStart(id: Int)
suspend fun setPinLockEnabled(enabled: Boolean) suspend fun setManualStop()
suspend fun isBatteryOptimizationDisableShown(): Boolean suspend fun getActiveTunnelId(): Int?
suspend fun setBatteryOptimizationDisableShown(shown: Boolean) suspend fun getCurrentSsid(): String?
suspend fun isTunnelRunningFromManualStart(): Boolean suspend fun setCurrentSsid(ssid: String)
suspend fun setTunnelRunningFromManualStart(id: Int) val generalStateFlow: Flow<GeneralState>
suspend fun setManualStop()
suspend fun getActiveTunnelId(): Int?
suspend fun getCurrentSsid(): String?
suspend fun setCurrentSsid(ssid: String)
val generalStateFlow: Flow<GeneralState>
} }
@@ -1,96 +1,81 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState import com.zaneschepke.wireguardautotunnel.data.model.GeneralState
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(private val dataStoreManager: DataStoreManager) :
AppStateRepository { AppStateRepository {
override suspend fun isLocationDisclosureShown(): Boolean { override suspend fun isLocationDisclosureShown(): Boolean {
return dataStoreManager.getFromStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN) return dataStoreManager.getFromStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN)
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT ?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT
} }
override suspend fun setLocationDisclosureShown(shown: Boolean) { override suspend fun setLocationDisclosureShown(shown: Boolean) {
dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown) dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown)
} }
override suspend fun isPinLockEnabled(): Boolean { override suspend fun isBatteryOptimizationDisableShown(): Boolean {
return dataStoreManager.getFromStore(DataStoreManager.IS_PIN_LOCK_ENABLED) return dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN)
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT ?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
} }
override suspend fun setPinLockEnabled(enabled: Boolean) { override suspend fun setBatteryOptimizationDisableShown(shown: Boolean) {
dataStoreManager.saveToDataStore(DataStoreManager.IS_PIN_LOCK_ENABLED, enabled) dataStoreManager.saveToDataStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN, shown)
} }
override suspend fun isBatteryOptimizationDisableShown(): Boolean { override suspend fun isTunnelRunningFromManualStart(): Boolean {
return dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN) return dataStoreManager.getFromStore(DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START)
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT ?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT
} }
override suspend fun setBatteryOptimizationDisableShown(shown: Boolean) { override suspend fun setTunnelRunningFromManualStart(id: Int) {
dataStoreManager.saveToDataStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN, shown) setTunnelRunningFromManualStart(true)
} setActiveTunnelId(id)
}
override suspend fun isTunnelRunningFromManualStart(): Boolean { override suspend fun setManualStop() {
return dataStoreManager.getFromStore(DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START) setTunnelRunningFromManualStart(false)
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT }
}
override suspend fun setTunnelRunningFromManualStart(id: Int) { private suspend fun setTunnelRunningFromManualStart(running: Boolean) {
setTunnelRunningFromManualStart(true) dataStoreManager.saveToDataStore(DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START, running)
setActiveTunnelId(id) }
}
override suspend fun setManualStop() { override suspend fun getActiveTunnelId(): Int? {
setTunnelRunningFromManualStart(false) return dataStoreManager.getFromStore(DataStoreManager.ACTIVE_TUNNEL)
} }
private suspend fun setTunnelRunningFromManualStart(running: Boolean) { private suspend fun setActiveTunnelId(id: Int) {
dataStoreManager.saveToDataStore(DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START, running) dataStoreManager.saveToDataStore(DataStoreManager.ACTIVE_TUNNEL, id)
} }
override suspend fun getActiveTunnelId(): Int? { override suspend fun getCurrentSsid(): String? {
return dataStoreManager.getFromStore(DataStoreManager.ACTIVE_TUNNEL) return dataStoreManager.getFromStore(DataStoreManager.CURRENT_SSID)
} }
private suspend fun setActiveTunnelId(id: Int) { override suspend fun setCurrentSsid(ssid: String) {
dataStoreManager.saveToDataStore(DataStoreManager.ACTIVE_TUNNEL, id) dataStoreManager.saveToDataStore(DataStoreManager.CURRENT_SSID, ssid)
} }
override suspend fun getCurrentSsid(): String? { override val generalStateFlow: Flow<GeneralState> =
return dataStoreManager.getFromStore(DataStoreManager.CURRENT_SSID) dataStoreManager.preferencesFlow.map { prefs ->
} prefs?.let { pref ->
try {
override suspend fun setCurrentSsid(ssid: String) { GeneralState(
dataStoreManager.saveToDataStore(DataStoreManager.CURRENT_SSID, ssid) locationDisclosureShown = pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
} ?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
batteryOptimizationDisableShown = pref[DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN]
override val generalStateFlow: Flow<GeneralState> = ?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
dataStoreManager.preferencesFlow.map { prefs -> tunnelRunningFromManualStart = pref[DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START]
prefs?.let { pref -> ?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
try { )
GeneralState( } catch (e: IllegalArgumentException) {
isLocationDisclosureShown = Timber.e(e)
pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN] GeneralState()
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT, }
isBatteryOptimizationDisableShown = } ?: GeneralState()
pref[DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN] }
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
isTunnelRunningFromManualStart =
pref[DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START]
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
isPinLockEnabled =
pref[DataStoreManager.IS_PIN_LOCK_ENABLED]
?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
)
} catch (e: IllegalArgumentException) {
Timber.e(e)
GeneralState()
}
} ?: GeneralState()
}
} }
@@ -1,23 +1,24 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.SettingsDao import com.zaneschepke.wireguardautotunnel.data.SettingsDao
import com.zaneschepke.wireguardautotunnel.data.domain.Settings import com.zaneschepke.wireguardautotunnel.data.model.Settings
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
class RoomSettingsRepository(private val settingsDoa: SettingsDao) : SettingsRepository { class RoomSettingsRepository(private val settingsDoa: SettingsDao) : SettingsRepository {
override suspend fun save(settings: Settings) {
settingsDoa.save(settings)
}
override fun getSettingsFlow(): Flow<Settings> { override suspend fun save(settings: Settings) {
return settingsDoa.getSettingsFlow() settingsDoa.save(settings)
} }
override suspend fun getSettings(): Settings { override fun getSettingsFlow(): Flow<Settings> {
return settingsDoa.getAll().firstOrNull() ?: Settings() return settingsDoa.getSettingsFlow()
} }
override suspend fun getAll(): List<Settings> { override suspend fun getSettings(): Settings {
return settingsDoa.getAll() return settingsDoa.getAll().firstOrNull() ?: Settings()
} }
override suspend fun getAll(): List<Settings> {
return settingsDoa.getAll()
}
} }
@@ -1,71 +1,68 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) : class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
TunnelConfigRepository { TunnelConfigRepository {
override fun getTunnelConfigsFlow(): Flow<TunnelConfigs> { override fun getTunnelConfigsFlow(): Flow<TunnelConfigs> {
return tunnelConfigDao.getAllFlow() return tunnelConfigDao.getAllFlow()
} }
override suspend fun getAll(): TunnelConfigs { override suspend fun getAll(): TunnelConfigs {
return tunnelConfigDao.getAll() return tunnelConfigDao.getAll()
} }
override suspend fun save(tunnelConfig: TunnelConfig) { override suspend fun save(tunnelConfig: TunnelConfig) {
tunnelConfigDao.save(tunnelConfig) tunnelConfigDao.save(tunnelConfig)
} }
override suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?) { override suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?) {
tunnelConfigDao.resetPrimaryTunnel() tunnelConfigDao.resetPrimaryTunnel()
tunnelConfig?.let { tunnelConfig?.let {
save( save(
it.copy( it.copy(
isPrimaryTunnel = true, isPrimaryTunnel = true,
), ),
) )
} }
}
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) { }
tunnelConfigDao.resetMobileDataTunnel()
tunnelConfig?.let {
save(
it.copy(
isMobileDataTunnel = true,
),
)
}
}
override suspend fun delete(tunnelConfig: TunnelConfig) { override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
tunnelConfigDao.delete(tunnelConfig) tunnelConfigDao.resetMobileDataTunnel()
} tunnelConfig?.let {
save(
it.copy(
isMobileDataTunnel = true,
),
)
}
}
override suspend fun getById(id: Int): TunnelConfig? { override suspend fun delete(tunnelConfig: TunnelConfig) {
return tunnelConfigDao.getById(id.toLong()) tunnelConfigDao.delete(tunnelConfig)
} }
override suspend fun count(): Int { override suspend fun getById(id: Int): TunnelConfig? {
return tunnelConfigDao.count().toInt() return tunnelConfigDao.getById(id.toLong())
} }
override suspend fun findByTunnelName(name: String): TunnelConfig? { override suspend fun count(): Int {
return tunnelConfigDao.getByName(name) return tunnelConfigDao.count().toInt()
} }
override suspend fun findByTunnelNetworksName(name: String): TunnelConfigs { override suspend fun findByTunnelNetworksName(name: String): TunnelConfigs {
return tunnelConfigDao.findByTunnelNetworkName(name) return tunnelConfigDao.findByTunnelNetworkName(name)
} }
override suspend fun findByMobileDataTunnel(): TunnelConfigs { override suspend fun findByMobileDataTunnel(): TunnelConfigs {
return tunnelConfigDao.findByMobileDataTunnel() return tunnelConfigDao.findByMobileDataTunnel()
} }
override suspend fun findPrimary(): TunnelConfigs { override suspend fun findPrimary(): TunnelConfigs {
return tunnelConfigDao.findByPrimary() return tunnelConfigDao.findByPrimary()
} }
} }
@@ -1,14 +1,14 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.domain.Settings import com.zaneschepke.wireguardautotunnel.data.model.Settings
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface SettingsRepository { interface SettingsRepository {
suspend fun save(settings: Settings) suspend fun save(settings: Settings)
fun getSettingsFlow(): Flow<Settings> fun getSettingsFlow(): Flow<Settings>
suspend fun getSettings(): Settings suspend fun getSettings(): Settings
suspend fun getAll(): List<Settings> suspend fun getAll(): List<Settings>
} }
@@ -1,31 +1,30 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface TunnelConfigRepository { interface TunnelConfigRepository {
fun getTunnelConfigsFlow(): Flow<TunnelConfigs>
suspend fun getAll(): TunnelConfigs fun getTunnelConfigsFlow(): Flow<TunnelConfigs>
suspend fun save(tunnelConfig: TunnelConfig) suspend fun getAll(): TunnelConfigs
suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?) suspend fun save(tunnelConfig: TunnelConfig)
suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) suspend fun updatePrimaryTunnel(tunnelConfig: TunnelConfig?)
suspend fun delete(tunnelConfig: TunnelConfig) suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?)
suspend fun getById(id: Int): TunnelConfig? suspend fun delete(tunnelConfig: TunnelConfig)
suspend fun count(): Int suspend fun getById(id: Int): TunnelConfig?
suspend fun findByTunnelName(name: String): TunnelConfig? suspend fun count(): Int
suspend fun findByTunnelNetworksName(name: String): TunnelConfigs suspend fun findByTunnelNetworksName(name: String): TunnelConfigs
suspend fun findByMobileDataTunnel(): TunnelConfigs suspend fun findByMobileDataTunnel(): TunnelConfigs
suspend fun findPrimary(): TunnelConfigs suspend fun findPrimary(): TunnelConfigs
} }
@@ -1,30 +0,0 @@
package com.zaneschepke.wireguardautotunnel.module
import android.content.Context
import com.zaneschepke.logcatter.LocalLogCollector
import com.zaneschepke.logcatter.LogcatUtil
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
@Singleton
@ApplicationScope
@Provides
fun providesApplicationScope(@DefaultDispatcher defaultDispatcher: CoroutineDispatcher): CoroutineScope =
CoroutineScope(SupervisorJob() + defaultDispatcher)
@Singleton
@Provides
fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector {
return LogcatUtil.init(context = context)
}
}
@@ -1,27 +0,0 @@
package com.zaneschepke.wireguardautotunnel.module
import javax.inject.Qualifier
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class DefaultDispatcher
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class IoDispatcher
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class MainDispatcher
@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class MainImmediateDispatcher
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ApplicationScope
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ServiceScope
@@ -1,28 +0,0 @@
package com.zaneschepke.wireguardautotunnel.module
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
@Module
@InstallIn(SingletonComponent::class)
object CoroutinesDispatchersModule {
@DefaultDispatcher
@Provides
fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
@IoDispatcher
@Provides
fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
@MainDispatcher
@Provides
fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main
@MainImmediateDispatcher
@Provides
fun providesMainImmediateDispatcher(): CoroutineDispatcher = Dispatchers.Main.immediate
}
@@ -0,0 +1,30 @@
package com.zaneschepke.wireguardautotunnel.module
import android.content.Context
import androidx.room.Room
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.data.AppDatabase
import com.zaneschepke.wireguardautotunnel.data.DatabaseCallback
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class DatabaseModule {
@Provides
@Singleton
fun provideDatabase(@ApplicationContext context: Context): AppDatabase {
return Room.databaseBuilder(
context,
AppDatabase::class.java,
context.getString(R.string.db_name),
)
.fallbackToDestructiveMigration()
.addCallback(DatabaseCallback())
.build()
}
}
@@ -0,0 +1,7 @@
package com.zaneschepke.wireguardautotunnel.module
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class Kernel
@@ -1,10 +1,7 @@
package com.zaneschepke.wireguardautotunnel.module package com.zaneschepke.wireguardautotunnel.module
import android.content.Context import android.content.Context
import androidx.room.Room
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.data.AppDatabase import com.zaneschepke.wireguardautotunnel.data.AppDatabase
import com.zaneschepke.wireguardautotunnel.data.DatabaseCallback
import com.zaneschepke.wireguardautotunnel.data.SettingsDao import com.zaneschepke.wireguardautotunnel.data.SettingsDao
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
@@ -21,68 +18,56 @@ import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import javax.inject.Singleton import javax.inject.Singleton
@Module @Module
@InstallIn(SingletonComponent::class) @InstallIn(SingletonComponent::class)
class RepositoryModule { class RepositoryModule {
@Provides @Singleton
@Singleton @Provides
fun provideDatabase(@ApplicationContext context: Context): AppDatabase { fun provideSettingsDoa(appDatabase: AppDatabase): SettingsDao {
return Room.databaseBuilder( return appDatabase.settingDao()
context, }
AppDatabase::class.java,
context.getString(R.string.db_name),
)
.fallbackToDestructiveMigration()
.addCallback(DatabaseCallback())
.build()
}
@Singleton @Singleton
@Provides @Provides
fun provideSettingsDoa(appDatabase: AppDatabase): SettingsDao { fun provideTunnelConfigDoa(appDatabase: AppDatabase): TunnelConfigDao {
return appDatabase.settingDao() return appDatabase.tunnelConfigDoa()
} }
@Singleton @Singleton
@Provides @Provides
fun provideTunnelConfigDoa(appDatabase: AppDatabase): TunnelConfigDao { fun provideTunnelConfigRepository(tunnelConfigDao: TunnelConfigDao): TunnelConfigRepository {
return appDatabase.tunnelConfigDoa() return RoomTunnelConfigRepository(tunnelConfigDao)
} }
@Singleton @Singleton
@Provides @Provides
fun provideTunnelConfigRepository(tunnelConfigDao: TunnelConfigDao): TunnelConfigRepository { fun provideSettingsRepository(settingsDao: SettingsDao): SettingsRepository {
return RoomTunnelConfigRepository(tunnelConfigDao) return RoomSettingsRepository(settingsDao)
} }
@Singleton @Singleton
@Provides @Provides
fun provideSettingsRepository(settingsDao: SettingsDao): SettingsRepository { fun providePreferencesDataStore(@ApplicationContext context: Context): DataStoreManager {
return RoomSettingsRepository(settingsDao) return DataStoreManager(context)
} }
@Singleton @Provides
@Provides @Singleton
fun providePreferencesDataStore(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): DataStoreManager { fun provideGeneralStateRepository(dataStoreManager: DataStoreManager): AppStateRepository {
return DataStoreManager(context, ioDispatcher) return DataStoreAppStateRepository(dataStoreManager)
} }
@Provides
@Singleton
fun provideAppDataRepository(
settingsRepository: SettingsRepository,
tunnelConfigRepository: TunnelConfigRepository,
appStateRepository: AppStateRepository
): AppDataRepository {
return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository)
}
@Provides
@Singleton
fun provideGeneralStateRepository(dataStoreManager: DataStoreManager): AppStateRepository {
return DataStoreAppStateRepository(dataStoreManager)
}
@Provides
@Singleton
fun provideAppDataRepository(
settingsRepository: SettingsRepository,
tunnelConfigRepository: TunnelConfigRepository,
appStateRepository: AppStateRepository,
): AppDataRepository {
return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository)
}
} }
@@ -15,19 +15,25 @@ import dagger.hilt.android.scopes.ServiceScoped
@Module @Module
@InstallIn(ServiceComponent::class) @InstallIn(ServiceComponent::class)
abstract class ServiceModule { abstract class ServiceModule {
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideNotificationService(wireGuardNotification: WireGuardNotification): NotificationService abstract fun provideNotificationService(
wireGuardNotification: WireGuardNotification
): NotificationService
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideWifiService(wifiService: WifiService): NetworkService<WifiService> abstract fun provideWifiService(wifiService: WifiService): NetworkService<WifiService>
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideMobileDataService(mobileDataService: MobileDataService): NetworkService<MobileDataService> abstract fun provideMobileDataService(
mobileDataService: MobileDataService
): NetworkService<MobileDataService>
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideEthernetService(ethernetService: EthernetService): NetworkService<EthernetService> abstract fun provideEthernetService(
ethernetService: EthernetService
): NetworkService<EthernetService>
} }
@@ -15,63 +15,44 @@ import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import javax.inject.Provider
import javax.inject.Singleton import javax.inject.Singleton
@Module @Module
@InstallIn(SingletonComponent::class) @InstallIn(SingletonComponent::class)
class TunnelModule { class TunnelModule {
@Provides @Provides
@Singleton @Singleton
fun provideRootShell(@ApplicationContext context: Context): RootShell { fun provideRootShell(@ApplicationContext context: Context): RootShell {
return RootShell(context) return RootShell(context)
} }
@Provides @Provides
@Singleton @Singleton
@Userspace @Userspace
fun provideUserspaceBackend(@ApplicationContext context: Context): Backend { fun provideUserspaceBackend(@ApplicationContext context: Context): Backend {
return GoBackend(context) return GoBackend(context)
} }
@Provides @Provides
@Singleton @Singleton
@Kernel @Kernel
fun provideKernelBackend(@ApplicationContext context: Context, rootShell: RootShell): Backend { fun provideKernelBackend(@ApplicationContext context: Context, rootShell: RootShell): Backend {
return WgQuickBackend(context, rootShell, ToolsInstaller(context, rootShell)) return WgQuickBackend(context, rootShell, ToolsInstaller(context, rootShell))
} }
@Provides @Provides
@Singleton @Singleton
fun provideAmneziaBackend(@ApplicationContext context: Context): org.amnezia.awg.backend.Backend { fun provideVpnService(
return org.amnezia.awg.backend.GoBackend(context) @Userspace userspaceBackend: Backend,
} @Kernel kernelBackend: Backend,
appDataRepository: AppDataRepository
): VpnService {
return WireGuardTunnel(userspaceBackend, kernelBackend, appDataRepository)
}
@Provides @Provides
@Singleton @Singleton
fun provideVpnService( fun provideServiceManager(appDataRepository: AppDataRepository): ServiceManager {
amneziaBackend: Provider<org.amnezia.awg.backend.Backend>, return ServiceManager(appDataRepository)
@Userspace userspaceBackend: Provider<Backend>, }
@Kernel kernelBackend: Provider<Backend>,
appDataRepository: AppDataRepository,
@ApplicationScope applicationScope: CoroutineScope,
@IoDispatcher ioDispatcher: CoroutineDispatcher,
): VpnService {
return WireGuardTunnel(
amneziaBackend,
userspaceBackend,
kernelBackend,
appDataRepository,
applicationScope,
ioDispatcher,
)
}
@Provides
@Singleton
fun provideServiceManager(appDataRepository: AppDataRepository, @IoDispatcher ioDispatcher: CoroutineDispatcher): ServiceManager {
return ServiceManager(appDataRepository, ioDispatcher)
}
} }
@@ -2,10 +2,6 @@ package com.zaneschepke.wireguardautotunnel.module
import javax.inject.Qualifier import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class Kernel
@Qualifier @Qualifier
@Retention(AnnotationRetention.BINARY) @Retention(AnnotationRetention.BINARY)
annotation class Userspace annotation class Userspace
@@ -1,21 +0,0 @@
package com.zaneschepke.wireguardautotunnel.module
import android.content.Context
import com.zaneschepke.wireguardautotunnel.util.FileUtils
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.CoroutineDispatcher
@Module
@InstallIn(ViewModelComponent::class)
class ViewModelModule {
@ViewModelScoped
@Provides
fun provideFileUtils(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): FileUtils {
return FileUtils(context, ioDispatcher)
}
}
@@ -4,52 +4,42 @@ import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.util.goAsync
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class BootReceiver : BroadcastReceiver() { class BootReceiver : BroadcastReceiver() {
@Inject
lateinit var appDataRepository: AppDataRepository
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var appDataRepository: AppDataRepository
@Inject @Inject
@ApplicationScope lateinit var serviceManager: ServiceManager
lateinit var applicationScope: CoroutineScope
override fun onReceive(context: Context?, intent: Intent?) { override fun onReceive(context: Context?, intent: Intent?) = goAsync {
if (Intent.ACTION_BOOT_COMPLETED != intent?.action) return if (Intent.ACTION_BOOT_COMPLETED != intent?.action) return@goAsync
context?.run { context?.run {
applicationScope.launch { val settings = appDataRepository.settings.getSettings()
val settings = appDataRepository.settings.getSettings() if (settings.isAutoTunnelEnabled) {
if (settings.isRestoreOnBootEnabled) { Timber.i("Starting watcher service from boot")
if (settings.isAutoTunnelEnabled) { serviceManager.startWatcherServiceForeground(context)
Timber.i("Starting watcher service from boot") }
serviceManager.startWatcherServiceForeground(context) if (appDataRepository.appState.isTunnelRunningFromManualStart()) {
} appDataRepository.appState.getActiveTunnelId()?.let {
if (appDataRepository.appState.isTunnelRunningFromManualStart()) { Timber.i("Starting tunnel that was active before reboot")
appDataRepository.appState.getActiveTunnelId()?.let { serviceManager.startVpnServiceForeground(
Timber.i("Starting tunnel that was active before reboot") context,
serviceManager.startVpnServiceForeground( appDataRepository.tunnels.getById(it)?.id,
context, )
appDataRepository.tunnels.getById(it)?.id, }
) }
return@launch if (settings.isAlwaysOnVpnEnabled) {
} Timber.i("Starting vpn service from boot AOVPN")
} serviceManager.startVpnServiceForeground(context)
if (settings.isAlwaysOnVpnEnabled) { }
Timber.i("Starting vpn service from boot AOVPN") }
serviceManager.startVpnServiceForeground(context) }
}
}
}
}
}
} }
@@ -4,41 +4,33 @@ import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.goAsync
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class NotificationActionReceiver : BroadcastReceiver() { class NotificationActionReceiver : BroadcastReceiver() {
@Inject @Inject
lateinit var settingsRepository: SettingsRepository lateinit var settingsRepository: SettingsRepository
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var serviceManager: ServiceManager
@Inject override fun onReceive(context: Context, intent: Intent?) = goAsync {
@ApplicationScope try {
lateinit var applicationScope: CoroutineScope //TODO fix for manual start changes when enabled
serviceManager.stopVpnService(context)
override fun onReceive(context: Context, intent: Intent?) { delay(Constants.TOGGLE_TUNNEL_DELAY)
applicationScope.launch { serviceManager.startVpnServiceForeground(context)
try { } catch (e: Exception) {
// TODO fix for manual start changes when enabled Timber.e(e)
serviceManager.stopVpnServiceForeground(context) } finally {
delay(Constants.TOGGLE_TUNNEL_DELAY) cancel()
serviceManager.startVpnServiceForeground(context) }
} catch (e: Exception) { }
Timber.e(e)
} finally {
cancel()
}
}
}
} }
@@ -1,8 +1,7 @@
package com.zaneschepke.wireguardautotunnel.service.foreground package com.zaneschepke.wireguardautotunnel.service.foreground
enum class Action { enum class Action {
START, START,
START_FOREGROUND, START_FOREGROUND,
STOP, STOP
STOP_FOREGROUND,
} }
@@ -8,50 +8,59 @@ import com.zaneschepke.wireguardautotunnel.util.Constants
import timber.log.Timber import timber.log.Timber
open class ForegroundService : LifecycleService() { open class ForegroundService : LifecycleService() {
private var isServiceStarted = false private var isServiceStarted = false
override fun onBind(intent: Intent): IBinder? { override fun onBind(intent: Intent): IBinder? {
super.onBind(intent) super.onBind(intent)
// We don't provide binding, so return null // We don't provide binding, so return null
return null return null
} }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId) super.onStartCommand(intent, flags, startId)
Timber.d("onStartCommand executed with startId: $startId") Timber.d("onStartCommand executed with startId: $startId")
if (intent != null) { if (intent != null) {
val action = intent.action val action = intent.action
when (action) { when (action) {
Action.START.name, Action.START.name,
Action.START_FOREGROUND.name, Action.START_FOREGROUND.name -> startService(intent.extras)
-> startService(intent.extras)
Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService() Action.STOP.name -> stopService(intent.extras)
Constants.ALWAYS_ON_VPN_ACTION -> { Constants.ALWAYS_ON_VPN_ACTION -> {
Timber.i("Always-on VPN starting service") Timber.i("Always-on VPN starting service")
startService(intent.extras) startService(intent.extras)
} }
else -> Timber.d("This should never happen. No action in the received intent") else -> Timber.d("This should never happen. No action in the received intent")
} }
} else { } else {
Timber.d( Timber.d(
"with a null intent. It has been probably restarted by the system.", "with a null intent. It has been probably restarted by the system.",
) )
} }
return START_STICKY // by returning this we make sure the service is restarted if the system kills the service
} return START_STICKY
}
protected open fun startService(extras: Bundle?) { override fun onDestroy() {
if (isServiceStarted) return super.onDestroy()
Timber.d("Starting ${this.javaClass.simpleName}") Timber.d("The service has been destroyed")
isServiceStarted = true }
}
protected open fun stopService() { protected open fun startService(extras: Bundle?) {
Timber.d("Stopping ${this.javaClass.simpleName}") if (isServiceStarted) return
stopForeground(STOP_FOREGROUND_REMOVE) Timber.d("Starting ${this.javaClass.simpleName}")
stopSelf() isServiceStarted = true
isServiceStarted = false }
}
protected open fun stopService(extras: Bundle?) {
Timber.d("Stopping ${this.javaClass.simpleName}")
try {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
} catch (e: Exception) {
Timber.e(e)
}
isServiceStarted = false
}
} }
@@ -4,114 +4,111 @@ import android.app.Service
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
class ServiceManager( class ServiceManager(private val appDataRepository: AppDataRepository) {
private val appDataRepository: AppDataRepository,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) {
private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) {
val intent =
Intent(context, cls).also {
it.action = action.name
extras?.forEach { (k, v) -> it.putExtra(k, v) }
}
intent.component?.javaClass
try {
when (action) {
Action.START_FOREGROUND, Action.STOP_FOREGROUND ->
context.startForegroundService(
intent,
)
Action.START, Action.STOP -> context.startService(intent) private fun <T : Service> actionOnService(
} action: Action,
} catch (e: Exception) { context: Context,
Timber.e(e.message) cls: Class<T>,
} extras: Map<String, Int>? = null
} ) {
val intent =
Intent(context, cls).also {
it.action = action.name
extras?.forEach { (k, v) -> it.putExtra(k, v) }
}
intent.component?.javaClass
try {
when (action) {
Action.START_FOREGROUND -> {
context.startForegroundService(intent)
}
suspend fun startVpnService(context: Context, tunnelId: Int? = null, isManualStart: Boolean = false) { Action.START -> {
if (isManualStart) onManualStart(tunnelId) context.startService(intent)
actionOnService( }
Action.START,
context,
WireGuardTunnelService::class.java,
tunnelId?.let { mapOf(Constants.TUNNEL_EXTRA_KEY to it) },
)
}
suspend fun stopVpnServiceForeground(context: Context, isManualStop: Boolean = false) { Action.STOP -> context.startService(intent)
withContext(ioDispatcher) { }
if (isManualStop) onManualStop() } catch (e: Exception) {
Timber.i("Stopping vpn service") Timber.e(e.message)
actionOnService( }
Action.STOP_FOREGROUND, }
context,
WireGuardTunnelService::class.java,
)
}
}
suspend fun stopVpnService(context: Context, isManualStop: Boolean = false) { suspend fun startVpnService(
withContext(ioDispatcher) { context: Context,
if (isManualStop) onManualStop() tunnelId: Int? = null,
Timber.i("Stopping vpn service") isManualStart: Boolean = false
actionOnService( ) {
Action.STOP, if (isManualStart) onManualStart(tunnelId)
context, actionOnService(
WireGuardTunnelService::class.java, Action.START,
) context,
} WireGuardTunnelService::class.java,
} tunnelId?.let { mapOf(Constants.TUNNEL_EXTRA_KEY to it) },
)
}
private suspend fun onManualStop() { suspend fun stopVpnService(context: Context, isManualStop: Boolean = false) {
appDataRepository.appState.setManualStop() if (isManualStop) onManualStop()
} Timber.d("Stopping vpn service action")
actionOnService(
Action.STOP,
context,
WireGuardTunnelService::class.java,
)
}
private suspend fun onManualStart(tunnelId: Int?) { private suspend fun onManualStop() {
tunnelId?.let { appDataRepository.appState.setManualStop()
appDataRepository.appState.setTunnelRunningFromManualStart(it) }
}
}
suspend fun startVpnServiceForeground(context: Context, tunnelId: Int? = null, isManualStart: Boolean = false) { private suspend fun onManualStart(tunnelId: Int?) {
withContext(ioDispatcher) { tunnelId?.let {
if (isManualStart) onManualStart(tunnelId) appDataRepository.appState.setTunnelRunningFromManualStart(it)
actionOnService( }
Action.START_FOREGROUND, }
context,
WireGuardTunnelService::class.java,
tunnelId?.let { mapOf(Constants.TUNNEL_EXTRA_KEY to it) },
)
}
}
fun startWatcherServiceForeground(context: Context) { suspend fun startVpnServiceForeground(
actionOnService( context: Context,
Action.START_FOREGROUND, tunnelId: Int? = null,
context, isManualStart: Boolean = false
WireGuardConnectivityWatcherService::class.java, ) {
) if (isManualStart) onManualStart(tunnelId)
} actionOnService(
Action.START_FOREGROUND,
context,
WireGuardTunnelService::class.java,
tunnelId?.let { mapOf(Constants.TUNNEL_EXTRA_KEY to it) },
)
}
fun startWatcherService(context: Context) { fun startWatcherServiceForeground(
actionOnService( context: Context,
Action.START, ) {
context, actionOnService(
WireGuardConnectivityWatcherService::class.java, Action.START_FOREGROUND,
) context,
} WireGuardConnectivityWatcherService::class.java,
)
}
fun stopWatcherService(context: Context) { fun startWatcherService(context: Context) {
actionOnService( actionOnService(
Action.STOP, Action.START,
context, context,
WireGuardConnectivityWatcherService::class.java, WireGuardConnectivityWatcherService::class.java,
) )
} }
fun stopWatcherService(context: Context) {
actionOnService(
Action.STOP,
context,
WireGuardConnectivityWatcherService::class.java,
)
}
} }
@@ -0,0 +1,6 @@
package com.zaneschepke.wireguardautotunnel.service.foreground
enum class ServiceState {
STARTED,
STOPPED,
}
@@ -1,73 +1,84 @@
package com.zaneschepke.wireguardautotunnel.service.foreground package com.zaneschepke.wireguardautotunnel.service.foreground
import com.zaneschepke.wireguardautotunnel.data.domain.Settings import com.wireguard.android.backend.Tunnel
import com.zaneschepke.wireguardautotunnel.data.model.Settings
import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
data class WatcherState( data class WatcherState(
val isWifiConnected: Boolean = false, val isWifiConnected: Boolean = false,
val isEthernetConnected: Boolean = false, val config: TunnelConfig? = null,
val isMobileDataConnected: Boolean = false, val vpnStatus: Tunnel.State = Tunnel.State.DOWN,
val currentNetworkSSID: String = "", val isEthernetConnected: Boolean = false,
val settings: Settings = Settings(), val isMobileDataConnected: Boolean = false,
val currentNetworkSSID: String = "",
val settings: Settings = Settings()
) { ) {
fun isEthernetConditionMet(): Boolean {
return (
isEthernetConnected &&
settings.isTunnelOnEthernetEnabled
)
}
fun isMobileDataConditionMet(): Boolean { private fun isVpnConnected() = vpnStatus == Tunnel.State.UP
return ( fun isEthernetConditionMet(): Boolean {
!isEthernetConnected && return (isEthernetConnected &&
settings.isTunnelOnMobileDataEnabled && settings.isTunnelOnEthernetEnabled &&
!isWifiConnected && !isVpnConnected())
isMobileDataConnected }
)
}
fun isTunnelOffOnMobileDataConditionMet(): Boolean { fun isMobileDataConditionMet(): Boolean {
return ( return (!isEthernetConnected &&
!isEthernetConnected && settings.isTunnelOnMobileDataEnabled &&
!settings.isTunnelOnMobileDataEnabled && !isWifiConnected &&
isMobileDataConnected && isMobileDataConnected &&
!isWifiConnected !isVpnConnected())
) }
}
fun isUntrustedWifiConditionMet(): Boolean { fun isTunnelNotMobileDataPreferredConditionMet(): Boolean {
return ( return (!isEthernetConnected &&
!isEthernetConnected && settings.isTunnelOnMobileDataEnabled &&
isWifiConnected && !isWifiConnected &&
!settings.trustedNetworkSSIDs.contains(currentNetworkSSID) && isMobileDataConnected &&
settings.isTunnelOnWifiEnabled config?.isMobileDataTunnel == false && isVpnConnected())
) }
}
fun isTrustedWifiConditionMet(): Boolean { fun isTunnelOffOnMobileDataConditionMet(): Boolean {
return ( return (!isEthernetConnected &&
!isEthernetConnected && !settings.isTunnelOnMobileDataEnabled &&
( isMobileDataConnected &&
isWifiConnected && !isWifiConnected &&
settings.trustedNetworkSSIDs.contains(currentNetworkSSID) isVpnConnected())
) }
)
}
fun isTunnelOffOnWifiConditionMet(): Boolean { fun isUntrustedWifiConditionMet(): Boolean {
return ( return (!isEthernetConnected &&
!isEthernetConnected && isWifiConnected &&
( !settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
isWifiConnected && settings.isTunnelOnWifiEnabled
!settings.isTunnelOnWifiEnabled && !isVpnConnected())
) }
)
}
fun isTunnelOffOnNoConnectivityMet(): Boolean { fun isTunnelNotWifiNamePreferredMet(ssid: String): Boolean {
return ( return (!isEthernetConnected &&
!isEthernetConnected && isWifiConnected &&
!isWifiConnected && !settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
!isMobileDataConnected settings.isTunnelOnWifiEnabled && config?.tunnelNetworks?.contains(ssid) == false && isVpnConnected())
) }
}
fun isTrustedWifiConditionMet(): Boolean {
return (!isEthernetConnected &&
(isWifiConnected &&
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)) &&
(isVpnConnected()))
}
fun isTunnelOffOnWifiConditionMet(): Boolean {
return (!isEthernetConnected &&
(isWifiConnected &&
!settings.isTunnelOnWifiEnabled &&
(isVpnConnected())))
}
fun isTunnelOffOnNoConnectivityMet(): Boolean {
return (!isEthernetConnected &&
!isWifiConnected &&
!isMobileDataConnected &&
(isVpnConnected()))
}
} }
@@ -5,470 +5,421 @@ import android.os.Bundle
import android.os.PowerManager import android.os.PowerManager
import androidx.core.app.ServiceCompat import androidx.core.app.ServiceCompat
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.wireguard.android.backend.Tunnel
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
import com.zaneschepke.wireguardautotunnel.service.network.EthernetService import com.zaneschepke.wireguardautotunnel.service.network.EthernetService
import com.zaneschepke.wireguardautotunnel.service.network.MobileDataService import com.zaneschepke.wireguardautotunnel.service.network.MobileDataService
import com.zaneschepke.wireguardautotunnel.service.network.NetworkService import com.zaneschepke.wireguardautotunnel.service.network.NetworkService
import com.zaneschepke.wireguardautotunnel.service.network.NetworkStatus import com.zaneschepke.wireguardautotunnel.service.network.NetworkStatus
import com.zaneschepke.wireguardautotunnel.service.network.WifiService import com.zaneschepke.wireguardautotunnel.service.network.WifiService
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
import java.net.InetAddress import java.net.InetAddress
import javax.inject.Inject import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class WireGuardConnectivityWatcherService : ForegroundService() { class WireGuardConnectivityWatcherService : ForegroundService() {
private val foregroundId = 122 private val foregroundId = 122
@Inject @Inject
lateinit var wifiService: NetworkService<WifiService> lateinit var wifiService: NetworkService<WifiService>
@Inject @Inject
lateinit var mobileDataService: NetworkService<MobileDataService> lateinit var mobileDataService: NetworkService<MobileDataService>
@Inject @Inject
lateinit var ethernetService: NetworkService<EthernetService> lateinit var ethernetService: NetworkService<EthernetService>
@Inject @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@Inject @Inject
lateinit var notificationService: NotificationService lateinit var notificationService: NotificationService
@Inject @Inject
lateinit var vpnService: VpnService lateinit var vpnService: VpnService
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var serviceManager: ServiceManager
@Inject private val networkEventsFlow = MutableStateFlow(WatcherState())
@IoDispatcher
lateinit var ioDispatcher: CoroutineDispatcher
@Inject private lateinit var watcherJob: Job
@MainImmediateDispatcher
lateinit var mainImmediateDispatcher: CoroutineDispatcher
private val networkEventsFlow = MutableStateFlow(WatcherState()) private var wakeLock: PowerManager.WakeLock? = null
private val tag = this.javaClass.name
private var watcherJob: Job? = null override fun onCreate() {
super.onCreate()
lifecycleScope.launch(Dispatchers.Main) {
try {
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
launchWatcherPausedNotification()
} else launchWatcherNotification()
} catch (e: Exception) {
Timber.e("Failed to start watcher service, not enough permissions")
}
}
}
private var wakeLock: PowerManager.WakeLock? = null override fun startService(extras: Bundle?) {
private val tag = this.javaClass.name super.startService(extras)
try {
// we need this lock so our service gets not affected by Doze Mode
lifecycleScope.launch { initWakeLock() }
cancelWatcherJob()
startWatcherJob()
} catch (e: Exception) {
Timber.e("Failed to launch watcher service, no permissions")
}
}
override fun onCreate() { override fun stopService(extras: Bundle?) {
super.onCreate() super.stopService(extras)
lifecycleScope.launch(mainImmediateDispatcher) { wakeLock?.let {
try { if (it.isHeld) {
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) { it.release()
launchWatcherPausedNotification() }
} else { }
launchWatcherNotification() cancelWatcherJob()
} stopSelf()
} catch (e: Exception) { }
Timber.e("Failed to start watcher service, not enough permissions")
}
}
}
override fun startService(extras: Bundle?) { private fun launchWatcherNotification(
super.startService(extras) description: String = getString(R.string.watcher_notification_text_active)
try { ) {
// we need this lock so our service gets not affected by Doze Mode val notification =
lifecycleScope.launch { initWakeLock() } notificationService.createNotification(
cancelWatcherJob() channelId = getString(R.string.watcher_channel_id),
startWatcherJob() channelName = getString(R.string.watcher_channel_name),
} catch (e: Exception) { title = getString(R.string.auto_tunnel_title),
Timber.e("Failed to launch watcher service, no permissions") description = description,
} )
} ServiceCompat.startForeground(
this,
foregroundId,
notification,
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
}
override fun stopService() { private fun launchWatcherPausedNotification() {
super.stopService() launchWatcherNotification(getString(R.string.watcher_notification_text_paused))
wakeLock?.let { }
if (it.isHeld) {
it.release()
}
}
cancelWatcherJob()
stopSelf()
}
private fun launchWatcherNotification(description: String = getString(R.string.watcher_notification_text_active)) { private fun initWakeLock() {
val notification = wakeLock =
notificationService.createNotification( (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
channelId = getString(R.string.watcher_channel_id), newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply {
channelName = getString(R.string.watcher_channel_name), try {
title = getString(R.string.auto_tunnel_title), Timber.i("Initiating wakelock with 10 min timeout")
description = description, acquire(Constants.BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT)
) } finally {
ServiceCompat.startForeground( release()
this, }
foregroundId, }
notification, }
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID, }
)
}
private fun launchWatcherPausedNotification() { private fun cancelWatcherJob() {
launchWatcherNotification(getString(R.string.watcher_notification_text_paused)) if (this::watcherJob.isInitialized) {
} watcherJob.cancel()
}
}
private fun initWakeLock() { private fun startWatcherJob() {
wakeLock = watcherJob =
(getSystemService(Context.POWER_SERVICE) as PowerManager).run { lifecycleScope.launch(Dispatchers.IO) {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply { val setting = appDataRepository.settings.getSettings()
try { launch {
Timber.i("Initiating wakelock with 10 min timeout") Timber.i("Starting wifi watcher")
acquire(Constants.BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT) watchForWifiConnectivityChanges()
} finally { }
release() if (setting.isTunnelOnMobileDataEnabled) {
} launch {
} Timber.i("Starting mobile data watcher")
} watchForMobileDataConnectivityChanges()
} }
}
if (setting.isTunnelOnEthernetEnabled) {
launch {
Timber.i("Starting ethernet data watcher")
watchForEthernetConnectivityChanges()
}
}
launch {
Timber.i("Starting vpn state watcher")
watchForVpnConnectivityChanges()
}
launch {
Timber.i("Starting settings watcher")
watchForSettingsChanges()
}
if (setting.isPingEnabled) {
launch {
Timber.i("Starting ping watcher")
watchForPingFailure()
}
}
launch {
Timber.i("Starting management watcher")
manageVpn()
}
private fun cancelWatcherJob() { }
try { }
watcherJob?.cancel()
} catch (e: CancellationException) {
Timber.i("Watcher job cancelled")
}
}
private fun startWatcherJob() { private suspend fun watchForMobileDataConnectivityChanges() {
watcherJob = mobileDataService.networkStatus.collect {
lifecycleScope.launch { when (it) {
val setting = appDataRepository.settings.getSettings() is NetworkStatus.Available -> {
launch { Timber.i("Gained Mobile data connection")
Timber.i("Starting wifi watcher") networkEventsFlow.value =
watchForWifiConnectivityChanges() networkEventsFlow.value.copy(
} isMobileDataConnected = true,
if (setting.isTunnelOnMobileDataEnabled) { )
launch { }
Timber.i("Starting mobile data watcher")
watchForMobileDataConnectivityChanges()
}
}
if (setting.isTunnelOnEthernetEnabled) {
launch {
Timber.i("Starting ethernet data watcher")
watchForEthernetConnectivityChanges()
}
}
launch {
Timber.i("Starting settings watcher")
watchForSettingsChanges()
}
if (setting.isPingEnabled) {
launch {
Timber.i("Starting ping watcher")
watchForPingFailure()
}
}
launch {
Timber.i("Starting management watcher")
manageVpn()
}
}
}
private suspend fun watchForMobileDataConnectivityChanges() { is NetworkStatus.CapabilitiesChanged -> {
withContext(ioDispatcher) { networkEventsFlow.value =
mobileDataService.networkStatus.collect { status -> networkEventsFlow.value.copy(
when (status) { isMobileDataConnected = true,
is NetworkStatus.Available -> { )
Timber.i("Gained Mobile data connection") Timber.i("Mobile data capabilities changed")
networkEventsFlow.update { }
it.copy(
isMobileDataConnected = true,
)
}
}
is NetworkStatus.CapabilitiesChanged -> { is NetworkStatus.Unavailable -> {
networkEventsFlow.update { networkEventsFlow.value =
it.copy( networkEventsFlow.value.copy(
isMobileDataConnected = true, isMobileDataConnected = false,
) )
} Timber.i("Lost mobile data connection")
Timber.i("Mobile data capabilities changed") }
} }
}
}
is NetworkStatus.Unavailable -> { private suspend fun watchForPingFailure() {
networkEventsFlow.update { try {
it.copy( do {
isMobileDataConnected = false, if (vpnService.vpnState.value.status == Tunnel.State.UP) {
) val tunnelConfig = vpnService.vpnState.value.tunnelConfig
} tunnelConfig?.let {
Timber.i("Lost mobile data connection") val config = TunnelConfig.configFromQuick(it.wgQuick)
} val results = config.peers.map { peer ->
} val host = if (peer.endpoint.isPresent &&
} peer.endpoint.get().resolved.isPresent)
} peer.endpoint.get().resolved.get().host
} else Constants.BACKUP_PING_HOST
Timber.i("Checking reachability of: $host")
val reachable = InetAddress.getByName(host)
.isReachable(Constants.PING_TIMEOUT.toInt())
Timber.i("Result: reachable - $reachable")
reachable
}
if (results.contains(false)) {
Timber.i("Restarting VPN for ping failure")
serviceManager.stopVpnService(this)
delay(Constants.VPN_RESTART_DELAY)
serviceManager.startVpnServiceForeground(this)
delay(Constants.PING_COOLDOWN)
}
}
}
delay(Constants.PING_INTERVAL)
} while (true)
} catch (e: Exception) {
Timber.e(e)
}
}
private suspend fun watchForPingFailure() { private suspend fun watchForSettingsChanges() {
val context = this appDataRepository.settings.getSettingsFlow().collect {
withContext(ioDispatcher) { if (networkEventsFlow.value.settings.isAutoTunnelPaused != it.isAutoTunnelPaused) {
try { when (it.isAutoTunnelPaused) {
do { true -> launchWatcherPausedNotification()
if (vpnService.vpnState.value.status == TunnelState.UP) { false -> launchWatcherNotification()
val tunnelConfig = vpnService.vpnState.value.tunnelConfig }
tunnelConfig?.let { }
val config = TunnelConfig.configFromWgQuick(it.wgQuick) networkEventsFlow.value =
val results = networkEventsFlow.value.copy(
config.peers.map { peer -> settings = it,
val host = )
if (peer.endpoint.isPresent && }
peer.endpoint.get().resolved.isPresent }
) {
peer.endpoint.get().resolved.get().host
} else {
Constants.DEFAULT_PING_IP
}
Timber.i("Checking reachability of: $host")
val reachable =
InetAddress.getByName(host)
.isReachable(Constants.PING_TIMEOUT.toInt())
Timber.i("Result: reachable - $reachable")
reachable
}
if (results.contains(false)) {
Timber.i("Restarting VPN for ping failure")
serviceManager.stopVpnServiceForeground(context)
delay(Constants.VPN_RESTART_DELAY)
serviceManager.startVpnServiceForeground(context, it.id)
delay(Constants.PING_COOLDOWN)
}
}
}
delay(Constants.PING_INTERVAL)
} while (true)
} catch (e: Exception) {
Timber.e(e)
}
}
}
private suspend fun watchForSettingsChanges() { private suspend fun watchForVpnConnectivityChanges() {
appDataRepository.settings.getSettingsFlow().collect { settings -> vpnService.vpnState.collect {
if (networkEventsFlow.value.settings.isAutoTunnelPaused networkEventsFlow.value =
!= settings.isAutoTunnelPaused networkEventsFlow.value.copy(
) { vpnStatus = it.status,
when (settings.isAutoTunnelPaused) { config = it.tunnelConfig,
true -> launchWatcherPausedNotification() )
false -> launchWatcherNotification() }
} }
}
networkEventsFlow.update {
it.copy(
settings = settings,
)
}
}
}
private suspend fun watchForEthernetConnectivityChanges() { private suspend fun watchForEthernetConnectivityChanges() {
withContext(ioDispatcher) { ethernetService.networkStatus.collect {
ethernetService.networkStatus.collect { status -> when (it) {
when (status) { is NetworkStatus.Available -> {
is NetworkStatus.Available -> { Timber.i("Gained Ethernet connection")
Timber.i("Gained Ethernet connection") networkEventsFlow.value =
networkEventsFlow.update { networkEventsFlow.value.copy(
it.copy( isEthernetConnected = true,
isEthernetConnected = true, )
) }
}
}
is NetworkStatus.CapabilitiesChanged -> { is NetworkStatus.CapabilitiesChanged -> {
Timber.i("Ethernet capabilities changed") Timber.i("Ethernet capabilities changed")
networkEventsFlow.update { networkEventsFlow.value =
it.copy( networkEventsFlow.value.copy(
isEthernetConnected = true, isEthernetConnected = true,
) )
} }
}
is NetworkStatus.Unavailable -> { is NetworkStatus.Unavailable -> {
networkEventsFlow.update { networkEventsFlow.value =
it.copy( networkEventsFlow.value.copy(
isEthernetConnected = false, isEthernetConnected = false,
) )
} Timber.i("Lost Ethernet connection")
Timber.i("Lost Ethernet connection") }
} }
} }
} }
}
}
private suspend fun watchForWifiConnectivityChanges() { private suspend fun watchForWifiConnectivityChanges() {
withContext(ioDispatcher) { wifiService.networkStatus.collect {
wifiService.networkStatus.collect { status -> when (it) {
when (status) { is NetworkStatus.Available -> {
is NetworkStatus.Available -> { Timber.i("Gained Wi-Fi connection")
Timber.i("Gained Wi-Fi connection") networkEventsFlow.value =
networkEventsFlow.update { networkEventsFlow.value.copy(
it.copy( isWifiConnected = true,
isWifiConnected = true, )
) }
}
}
is NetworkStatus.CapabilitiesChanged -> { is NetworkStatus.CapabilitiesChanged -> {
Timber.i("Wifi capabilities changed") Timber.i("Wifi capabilities changed")
networkEventsFlow.update { networkEventsFlow.value =
it.copy( networkEventsFlow.value.copy(
isWifiConnected = true, isWifiConnected = true,
) )
} val ssid = wifiService.getNetworkName(it.networkCapabilities)
val ssid = wifiService.getNetworkName(status.networkCapabilities) ssid?.let {
ssid?.let { name -> Timber.i("Detected SSID: $ssid")
if (name.contains(Constants.UNREADABLE_SSID)) { appDataRepository.appState.setCurrentSsid(ssid)
Timber.w("SSID unreadable: missing permissions") networkEventsFlow.value =
} else { networkEventsFlow.value.copy(
Timber.i("Detected valid SSID") currentNetworkSSID = ssid,
} )
appDataRepository.appState.setCurrentSsid(name) } ?: Timber.w("Failed to read ssid")
networkEventsFlow.update { }
it.copy(
currentNetworkSSID = name,
)
}
} ?: Timber.w("Failed to read ssid")
}
is NetworkStatus.Unavailable -> { is NetworkStatus.Unavailable -> {
networkEventsFlow.update { networkEventsFlow.value =
it.copy( networkEventsFlow.value.copy(
isWifiConnected = false, isWifiConnected = false,
) )
} Timber.i("Lost Wi-Fi connection")
Timber.i("Lost Wi-Fi connection") }
} }
} }
} }
}
}
private suspend fun getMobileDataTunnel(): TunnelConfig? { private suspend fun getMobileDataTunnel(): TunnelConfig? {
return appDataRepository.tunnels.findByMobileDataTunnel().firstOrNull() return appDataRepository.tunnels.findByMobileDataTunnel().firstOrNull()
} }
private suspend fun getSsidTunnel(ssid: String): TunnelConfig? { private suspend fun getSsidTunnel(ssid: String): TunnelConfig? {
return appDataRepository.tunnels.findByTunnelNetworksName(ssid).firstOrNull() return appDataRepository.tunnels.findByTunnelNetworksName(ssid).firstOrNull()
} }
private fun isTunnelDown(): Boolean { private suspend fun manageVpn() {
return vpnService.vpnState.value.status == TunnelState.DOWN networkEventsFlow.collectLatest { watcherState ->
} val autoTunnel = "Auto-tunnel watcher"
if (!watcherState.settings.isAutoTunnelPaused) {
//delay for rapid network state changes and then collect latest
delay(Constants.WATCHER_COLLECTION_DELAY)
when {
watcherState.isEthernetConditionMet() -> {
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
serviceManager.startVpnServiceForeground(this)
}
private suspend fun manageVpn() { watcherState.isMobileDataConditionMet() -> {
val context = this Timber.i("$autoTunnel - tunnel on on mobile data condition met")
withContext(ioDispatcher) { serviceManager.startVpnServiceForeground(this, getMobileDataTunnel()?.id)
networkEventsFlow.collectLatest { watcherState -> }
val autoTunnel = "Auto-tunnel watcher"
if (!watcherState.settings.isAutoTunnelPaused) {
// delay for rapid network state changes and then collect latest
delay(Constants.WATCHER_COLLECTION_DELAY)
val tunnelConfig = vpnService.vpnState.value.tunnelConfig
when {
watcherState.isEthernetConditionMet() -> {
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
if (isTunnelDown()) serviceManager.startVpnServiceForeground(context)
}
watcherState.isMobileDataConditionMet() -> { watcherState.isTunnelNotMobileDataPreferredConditionMet() -> {
Timber.i("$autoTunnel - tunnel on mobile data condition met") getMobileDataTunnel()?.let {
val mobileDataTunnel = getMobileDataTunnel() Timber.i("$autoTunnel - tunnel connected on mobile data is not preferred condition met, switching to preferred")
val tunnel = serviceManager.startVpnServiceForeground(
mobileDataTunnel ?: appDataRepository.getPrimaryOrFirstTunnel() this,
if (isTunnelDown() || tunnelConfig?.isMobileDataTunnel == false) { getMobileDataTunnel()?.id,
serviceManager.startVpnServiceForeground( )
context, }
tunnel?.id, }
)
}
}
watcherState.isTunnelOffOnMobileDataConditionMet() -> { watcherState.isTunnelOffOnMobileDataConditionMet() -> {
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off") Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context) serviceManager.stopVpnService(this)
} }
watcherState.isUntrustedWifiConditionMet() -> { watcherState.isTunnelNotWifiNamePreferredMet(watcherState.currentNetworkSSID) -> {
if (tunnelConfig?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false || Timber.i("$autoTunnel - tunnel on ssid not associated with current tunnel condition met")
tunnelConfig == null getSsidTunnel(watcherState.currentNetworkSSID)?.let {
) { Timber.i("Found tunnel associated with this SSID, bringing tunnel up")
Timber.i( serviceManager.startVpnServiceForeground(this, it.id)
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met", } ?: suspend {
) Timber.i("No tunnel associated with this SSID, using defaults")
getSsidTunnel(watcherState.currentNetworkSSID)?.let { if (appDataRepository.getPrimaryOrFirstTunnel()?.name != vpnService.name) {
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}") serviceManager.startVpnServiceForeground(this)
if (isTunnelDown() || tunnelConfig?.id != it.id) { }
serviceManager.startVpnServiceForeground( }.invoke()
context, }
it.id,
)
}
} ?: suspend {
Timber.i("No tunnel associated with this SSID, using defaults")
val default = appDataRepository.getPrimaryOrFirstTunnel()
if (default?.name != vpnService.name) {
default?.let {
serviceManager.startVpnServiceForeground(context, it.id)
}
}
}.invoke()
}
}
watcherState.isTrustedWifiConditionMet() -> { watcherState.isUntrustedWifiConditionMet() -> {
Timber.i( Timber.i("$autoTunnel - tunnel on untrusted wifi condition met")
"$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off", serviceManager.startVpnServiceForeground(
) this,
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context) getSsidTunnel(watcherState.currentNetworkSSID)?.id,
} )
}
watcherState.isTunnelOffOnWifiConditionMet() -> { watcherState.isTrustedWifiConditionMet() -> {
Timber.i( Timber.i("$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off")
"$autoTunnel - tunnel off on wifi condition met, turning vpn off", serviceManager.stopVpnService(this)
) }
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
}
watcherState.isTunnelOffOnNoConnectivityMet() -> { watcherState.isTunnelOffOnWifiConditionMet() -> {
Timber.i( Timber.i("$autoTunnel - tunnel off on wifi condition met, turning vpn off")
"$autoTunnel - tunnel off on no connectivity met, turning vpn off", serviceManager.stopVpnService(this)
) }
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
}
else -> { watcherState.isTunnelOffOnNoConnectivityMet() -> {
Timber.i("$autoTunnel - no condition met") Timber.i("$autoTunnel - tunnel off on no connectivity met, turning vpn off")
} serviceManager.stopVpnService(this)
} }
}
} else -> {
} Timber.i("$autoTunnel - no condition met")
} }
}
}
}
}
} }
@@ -5,194 +5,180 @@ import android.content.Intent
import android.os.Bundle import android.os.Bundle
import androidx.core.app.ServiceCompat import androidx.core.app.ServiceCompat
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.wireguard.android.backend.Tunnel
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
import com.zaneschepke.wireguardautotunnel.receiver.NotificationActionReceiver import com.zaneschepke.wireguardautotunnel.receiver.NotificationActionReceiver
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.handshakeStatus import com.zaneschepke.wireguardautotunnel.util.handshakeStatus
import com.zaneschepke.wireguardautotunnel.util.mapPeerStats import com.zaneschepke.wireguardautotunnel.util.mapPeerStats
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class WireGuardTunnelService : ForegroundService() { class WireGuardTunnelService : ForegroundService() {
private val foregroundId = 123 private val foregroundId = 123
@Inject @Inject
lateinit var vpnService: VpnService lateinit var vpnService: VpnService
@Inject @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@Inject @Inject
lateinit var notificationService: NotificationService lateinit var notificationService: NotificationService
@Inject private lateinit var job: Job
@MainImmediateDispatcher
lateinit var mainImmediateDispatcher: CoroutineDispatcher
@Inject private var didShowConnected = false
@IoDispatcher
lateinit var ioDispatcher: CoroutineDispatcher
private var job: Job? = null override fun onCreate() {
super.onCreate()
lifecycleScope.launch(Dispatchers.Main) {
//TODO fix this to not launch if AOVPN
if (appDataRepository.tunnels.count() != 0) {
launchVpnNotification()
}
}
}
private var didShowConnected = false override fun startService(extras: Bundle?) {
super.startService(extras)
cancelJob()
job =
lifecycleScope.launch(Dispatchers.IO) {
launch {
val tunnelId = extras?.getInt(Constants.TUNNEL_EXTRA_KEY)
if (vpnService.getState() == Tunnel.State.UP) {
vpnService.stopTunnel()
}
vpnService.startTunnel(
tunnelId?.let {
appDataRepository.tunnels.getById(it)
},
)
}
launch {
handshakeNotifications()
}
}
}
override fun onCreate() { //TODO improve tunnel notifications
super.onCreate() private suspend fun handshakeNotifications() {
lifecycleScope.launch(mainImmediateDispatcher) { var tunnelName: String? = null
// TODO fix this to not launch if AOVPN vpnService.vpnState.collect { state ->
if (appDataRepository.tunnels.count() != 0) { state.statistics
launchVpnNotification() ?.mapPeerStats()
} ?.map { it.value?.handshakeStatus() }
} .let { statuses ->
} when {
statuses?.all { it == HandshakeStatus.HEALTHY } == true -> {
if (!didShowConnected) {
delay(Constants.VPN_CONNECTED_NOTIFICATION_DELAY)
tunnelName = state.tunnelConfig?.name
launchVpnNotification(
getString(R.string.tunnel_start_title),
"${getString(R.string.tunnel_start_text)} - $tunnelName",
)
didShowConnected = true
}
}
override fun startService(extras: Bundle?) { statuses?.any { it == HandshakeStatus.STALE } == true -> {}
super.startService(extras) statuses?.all { it == HandshakeStatus.NOT_STARTED } ==
cancelJob() true -> {
job = }
lifecycleScope.launch {
launch {
val tunnelId = extras?.getInt(Constants.TUNNEL_EXTRA_KEY)
if (vpnService.getState() == TunnelState.UP) {
vpnService.stopTunnel()
}
vpnService.startTunnel(
tunnelId?.let {
appDataRepository.tunnels.getById(it)
},
)
}
launch {
handshakeNotifications()
}
}
}
// TODO improve tunnel notifications else -> {}
private suspend fun handshakeNotifications() { }
withContext(ioDispatcher) { }
var tunnelName: String? = null if (state.status == Tunnel.State.UP && state.tunnelConfig?.name != tunnelName) {
vpnService.vpnState.collect { state -> tunnelName = state.tunnelConfig?.name
state.statistics launchVpnNotification(
?.mapPeerStats() getString(R.string.tunnel_start_title),
?.map { it.value?.handshakeStatus() } "${getString(R.string.tunnel_start_text)} - $tunnelName",
.let { statuses -> )
when { }
statuses?.all { it == HandshakeStatus.HEALTHY } == true -> { }
if (!didShowConnected) { }
delay(Constants.VPN_CONNECTED_NOTIFICATION_DELAY)
tunnelName = state.tunnelConfig?.name
launchVpnNotification(
getString(R.string.tunnel_start_title),
"${getString(R.string.tunnel_start_text)} - $tunnelName",
)
didShowConnected = true
}
}
statuses?.any { it == HandshakeStatus.STALE } == true -> {} private fun launchAlwaysOnDisabledNotification() {
statuses?.all { it == HandshakeStatus.NOT_STARTED } == launchVpnNotification(
true -> { title = this.getString(R.string.vpn_connection_failed),
} description = this.getString(R.string.always_on_disabled),
)
}
else -> {} override fun stopService(extras: Bundle?) {
} super.stopService(extras)
} lifecycleScope.launch(Dispatchers.IO) {
if (state.status == TunnelState.UP && state.tunnelConfig?.name != tunnelName) { vpnService.stopTunnel()
tunnelName = state.tunnelConfig?.name didShowConnected = false
launchVpnNotification( }
getString(R.string.tunnel_start_title), cancelJob()
"${getString(R.string.tunnel_start_text)} - $tunnelName", stopSelf()
) }
}
}
}
}
private fun launchAlwaysOnDisabledNotification() { private fun launchVpnNotification(
launchVpnNotification( title: String = getString(R.string.vpn_starting),
title = this.getString(R.string.vpn_connection_failed), description: String = getString(R.string.attempt_connection)
description = this.getString(R.string.always_on_disabled), ) {
) val notification =
} notificationService.createNotification(
channelId = getString(R.string.vpn_channel_id),
channelName = getString(R.string.vpn_channel_name),
title = title,
onGoing = false,
vibration = false,
showTimestamp = true,
description = description,
)
ServiceCompat.startForeground(
this,
foregroundId,
notification,
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
}
override fun stopService() { private fun launchVpnConnectionFailedNotification(message: String) {
super.stopService() val notification =
lifecycleScope.launch { notificationService.createNotification(
vpnService.stopTunnel() channelId = getString(R.string.vpn_channel_id),
didShowConnected = false channelName = getString(R.string.vpn_channel_name),
} action =
cancelJob() PendingIntent.getBroadcast(
stopSelf() this,
} 0,
Intent(this, NotificationActionReceiver::class.java),
PendingIntent.FLAG_IMMUTABLE,
),
actionText = getString(R.string.restart),
title = getString(R.string.vpn_connection_failed),
onGoing = false,
vibration = true,
showTimestamp = true,
description = message,
)
ServiceCompat.startForeground(
this,
foregroundId,
notification,
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
}
private fun launchVpnNotification(title: String = getString(R.string.vpn_starting), description: String = getString(R.string.attempt_connection)) { private fun cancelJob() {
val notification = if (this::job.isInitialized) {
notificationService.createNotification( job.cancel()
channelId = getString(R.string.vpn_channel_id), }
channelName = getString(R.string.vpn_channel_name), }
title = title,
onGoing = false,
vibration = false,
showTimestamp = true,
description = description,
)
ServiceCompat.startForeground(
this,
foregroundId,
notification,
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
}
private fun launchVpnConnectionFailedNotification(message: String) {
val notification =
notificationService.createNotification(
channelId = getString(R.string.vpn_channel_id),
channelName = getString(R.string.vpn_channel_name),
action =
PendingIntent.getBroadcast(
this,
0,
Intent(this, NotificationActionReceiver::class.java),
PendingIntent.FLAG_IMMUTABLE,
),
actionText = getString(R.string.restart),
title = getString(R.string.vpn_connection_failed),
onGoing = false,
vibration = true,
showTimestamp = true,
description = message,
)
ServiceCompat.startForeground(
this,
foregroundId,
notification,
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
)
}
private fun cancelJob() {
try {
job?.cancel()
} catch (e: CancellationException) {
Timber.i("Tunnel job cancelled")
}
}
} }
@@ -15,113 +15,118 @@ import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
abstract class BaseNetworkService<T : BaseNetworkService<T>>( abstract class BaseNetworkService<T : BaseNetworkService<T>>(
val context: Context, val context: Context,
networkCapability: Int, networkCapability: Int
) : NetworkService<T> { ) : NetworkService<T> {
private val connectivityManager = private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val wifiManager = private val wifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
override val networkStatus = override val networkStatus = callbackFlow {
callbackFlow { val networkStatusCallback =
val networkStatusCallback = when (Build.VERSION.SDK_INT) {
when (Build.VERSION.SDK_INT) { in Build.VERSION_CODES.S..Int.MAX_VALUE -> {
in Build.VERSION_CODES.S..Int.MAX_VALUE -> { object :
object : ConnectivityManager.NetworkCallback(
ConnectivityManager.NetworkCallback( FLAG_INCLUDE_LOCATION_INFO,
FLAG_INCLUDE_LOCATION_INFO, ) {
) { override fun onAvailable(network: Network) {
override fun onAvailable(network: Network) { trySend(NetworkStatus.Available(network))
trySend(NetworkStatus.Available(network)) }
}
override fun onLost(network: Network) { override fun onLost(network: Network) {
trySend(NetworkStatus.Unavailable(network)) trySend(NetworkStatus.Unavailable(network))
} }
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) { override fun onCapabilitiesChanged(
trySend( network: Network,
NetworkStatus.CapabilitiesChanged( networkCapabilities: NetworkCapabilities
network, ) {
networkCapabilities, trySend(
), NetworkStatus.CapabilitiesChanged(
) network,
} networkCapabilities,
} ),
} )
}
}
}
else -> { else -> {
object : ConnectivityManager.NetworkCallback() { object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) { override fun onAvailable(network: Network) {
trySend(NetworkStatus.Available(network)) trySend(NetworkStatus.Available(network))
} }
override fun onLost(network: Network) { override fun onLost(network: Network) {
trySend(NetworkStatus.Unavailable(network)) trySend(NetworkStatus.Unavailable(network))
} }
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) { override fun onCapabilitiesChanged(
trySend( network: Network,
NetworkStatus.CapabilitiesChanged( networkCapabilities: NetworkCapabilities
network, ) {
networkCapabilities, trySend(
), NetworkStatus.CapabilitiesChanged(
) network,
} networkCapabilities,
} ),
} )
} }
val request = }
NetworkRequest.Builder() }
.addTransportType(networkCapability) }
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) val request =
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) NetworkRequest.Builder()
.build() .addTransportType(networkCapability)
connectivityManager.registerNetworkCallback(request, networkStatusCallback) .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
.build()
connectivityManager.registerNetworkCallback(request, networkStatusCallback)
awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) } awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) }
} }
override fun getNetworkName(networkCapabilities: NetworkCapabilities): String? { override fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
var ssid: String? = getWifiNameFromCapabilities(networkCapabilities) var ssid: String? = getWifiNameFromCapabilities(networkCapabilities)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
val info = wifiManager.connectionInfo val info = wifiManager.connectionInfo
if (info.supplicantState === SupplicantState.COMPLETED) { if (info.supplicantState === SupplicantState.COMPLETED) {
ssid = info.ssid ssid = info.ssid
} }
} }
return ssid?.trim('"') return ssid?.trim('"')
} }
companion object { companion object {
private fun getWifiNameFromCapabilities(networkCapabilities: NetworkCapabilities): String? { private fun getWifiNameFromCapabilities(networkCapabilities: NetworkCapabilities): String? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val info: WifiInfo val info: WifiInfo
if (networkCapabilities.transportInfo is WifiInfo) { if (networkCapabilities.transportInfo is WifiInfo) {
info = networkCapabilities.transportInfo as WifiInfo info = networkCapabilities.transportInfo as WifiInfo
return info.ssid return info.ssid
} }
} }
return null return null
} }
} }
} }
inline fun <Result> Flow<NetworkStatus>.map( inline fun <Result> Flow<NetworkStatus>.map(
crossinline onUnavailable: suspend (network: Network) -> Result, crossinline onUnavailable: suspend (network: Network) -> Result,
crossinline onAvailable: suspend (network: Network) -> Result, crossinline onAvailable: suspend (network: Network) -> Result,
crossinline onCapabilitiesChanged: crossinline onCapabilitiesChanged:
suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result, suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result
): Flow<Result> = map { status -> ): Flow<Result> = map { status ->
when (status) { when (status) {
is NetworkStatus.Unavailable -> onUnavailable(status.network) is NetworkStatus.Unavailable -> onUnavailable(status.network)
is NetworkStatus.Available -> onAvailable(status.network) is NetworkStatus.Available -> onAvailable(status.network)
is NetworkStatus.CapabilitiesChanged -> is NetworkStatus.CapabilitiesChanged ->
onCapabilitiesChanged( onCapabilitiesChanged(
status.network, status.network,
status.networkCapabilities, status.networkCapabilities,
) )
} }
} }
@@ -5,9 +5,5 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class EthernetService class EthernetService @Inject constructor(@ApplicationContext context: Context) :
@Inject BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET)
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET)
@@ -5,9 +5,5 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class MobileDataService class MobileDataService @Inject constructor(@ApplicationContext context: Context) :
@Inject BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR)
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR)
@@ -4,7 +4,7 @@ import android.net.NetworkCapabilities
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface NetworkService<T> { interface NetworkService<T> {
fun getNetworkName(networkCapabilities: NetworkCapabilities): String? fun getNetworkName(networkCapabilities: NetworkCapabilities): String?
val networkStatus: Flow<NetworkStatus> val networkStatus: Flow<NetworkStatus>
} }
@@ -4,10 +4,10 @@ import android.net.Network
import android.net.NetworkCapabilities import android.net.NetworkCapabilities
sealed class NetworkStatus { sealed class NetworkStatus {
class Available(val network: Network) : NetworkStatus() class Available(val network: Network) : NetworkStatus()
class Unavailable(val network: Network) : NetworkStatus() class Unavailable(val network: Network) : NetworkStatus()
class CapabilitiesChanged(val network: Network, val networkCapabilities: NetworkCapabilities) : class CapabilitiesChanged(val network: Network, val networkCapabilities: NetworkCapabilities) :
NetworkStatus() NetworkStatus()
} }
@@ -5,9 +5,5 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class WifiService class WifiService @Inject constructor(@ApplicationContext context: Context) :
@Inject BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI)
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI)
@@ -5,18 +5,18 @@ import android.app.NotificationManager
import android.app.PendingIntent import android.app.PendingIntent
interface NotificationService { interface NotificationService {
fun createNotification( fun createNotification(
channelId: String, channelId: String,
channelName: String, channelName: String,
title: String = "", title: String = "",
action: PendingIntent? = null, action: PendingIntent? = null,
actionText: String? = null, actionText: String? = null,
description: String, description: String,
showTimestamp: Boolean = false, showTimestamp: Boolean = false,
importance: Int = NotificationManager.IMPORTANCE_HIGH, importance: Int = NotificationManager.IMPORTANCE_HIGH,
vibration: Boolean = false, vibration: Boolean = false,
onGoing: Boolean = true, onGoing: Boolean = true,
lights: Boolean = true, lights: Boolean = true,
onlyAlertOnce: Boolean = true, onlyAlertOnce: Boolean = true,
): Notification ): Notification
} }
@@ -9,97 +9,93 @@ import android.content.Intent
import android.graphics.Color import android.graphics.Color
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.ui.SplashActivity import com.zaneschepke.wireguardautotunnel.ui.MainActivity
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class WireGuardNotification class WireGuardNotification @Inject constructor(@ApplicationContext private val context: Context) :
@Inject NotificationService {
constructor( private val notificationManager =
@ApplicationContext private val context: Context, context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
) :
NotificationService {
private val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
private val watcherBuilder: NotificationCompat.Builder = private val watcherBuilder: NotificationCompat.Builder =
NotificationCompat.Builder( NotificationCompat.Builder(
context, context,
context.getString(R.string.watcher_channel_id), context.getString(R.string.watcher_channel_id),
) )
private val tunnelBuilder: NotificationCompat.Builder = private val tunnelBuilder: NotificationCompat.Builder =
NotificationCompat.Builder( NotificationCompat.Builder(
context, context,
context.getString(R.string.vpn_channel_id), context.getString(R.string.vpn_channel_id),
) )
override fun createNotification( override fun createNotification(
channelId: String, channelId: String,
channelName: String, channelName: String,
title: String, title: String,
action: PendingIntent?, action: PendingIntent?,
actionText: String?, actionText: String?,
description: String, description: String,
showTimestamp: Boolean, showTimestamp: Boolean,
importance: Int, importance: Int,
vibration: Boolean, vibration: Boolean,
onGoing: Boolean, onGoing: Boolean,
lights: Boolean, lights: Boolean,
onlyAlertOnce: Boolean, onlyAlertOnce: Boolean,
): Notification { ): Notification {
val channel = val channel =
NotificationChannel( NotificationChannel(
channelId, channelId,
channelName, channelName,
importance, importance,
) )
.let { .let {
it.description = title it.description = title
it.enableLights(lights) it.enableLights(lights)
it.lightColor = Color.RED it.lightColor = Color.RED
it.enableVibration(vibration) it.enableVibration(vibration)
it.vibrationPattern = longArrayOf(100, 200, 300) it.vibrationPattern = longArrayOf(100, 200, 300)
it it
} }
notificationManager.createNotificationChannel(channel) notificationManager.createNotificationChannel(channel)
val pendingIntent: PendingIntent = val pendingIntent: PendingIntent =
Intent(context, SplashActivity::class.java).let { notificationIntent -> Intent(context, MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity( PendingIntent.getActivity(
context, context,
0, 0,
notificationIntent, notificationIntent,
PendingIntent.FLAG_IMMUTABLE, PendingIntent.FLAG_IMMUTABLE,
) )
} }
val builder = val builder =
when (channelId) { when (channelId) {
context.getString(R.string.watcher_channel_id) -> watcherBuilder context.getString(R.string.watcher_channel_id) -> watcherBuilder
context.getString(R.string.vpn_channel_id) -> tunnelBuilder context.getString(R.string.vpn_channel_id) -> tunnelBuilder
else -> { else -> {
NotificationCompat.Builder( NotificationCompat.Builder(
context, context,
channelId, channelId,
) )
} }
} }
return builder.let { return builder.let {
if (action != null && actionText != null) { if (action != null && actionText != null) {
it.addAction( it.addAction(
NotificationCompat.Action.Builder(0, actionText, action).build(), NotificationCompat.Action.Builder(0, actionText, action).build(),
) )
it.setAutoCancel(true) it.setAutoCancel(true)
} }
it.setContentTitle(title) it.setContentTitle(title)
.setContentText(description) .setContentText(description)
.setOnlyAlertOnce(onlyAlertOnce) .setOnlyAlertOnce(onlyAlertOnce)
.setContentIntent(pendingIntent) .setContentIntent(pendingIntent)
.setOngoing(onGoing) .setOngoing(onGoing)
.setPriority(NotificationCompat.PRIORITY_HIGH) .setPriority(NotificationCompat.PRIORITY_HIGH)
.setShowWhen(showTimestamp) .setShowWhen(showTimestamp)
.setSmallIcon(R.drawable.ic_launcher) .setSmallIcon(R.drawable.ic_launcher)
.build() .build()
} }
} }
} }
@@ -2,84 +2,74 @@ package com.zaneschepke.wireguardautotunnel.service.shortcut
import android.os.Bundle import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.lifecycle.lifecycleScope
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import com.zaneschepke.wireguardautotunnel.service.foreground.Action import com.zaneschepke.wireguardautotunnel.service.foreground.Action
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardConnectivityWatcherService import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardConnectivityWatcherService
import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardTunnelService import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardTunnelService
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class ShortcutsActivity : ComponentActivity() { class ShortcutsActivity : ComponentActivity() {
@Inject
lateinit var appDataRepository: AppDataRepository
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var appDataRepository: AppDataRepository
@Inject @Inject
@ApplicationScope lateinit var serviceManager: ServiceManager
lateinit var applicationScope: CoroutineScope
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
applicationScope.launch { lifecycleScope.launch(Dispatchers.Main) {
val settings = appDataRepository.settings.getSettings() val settings = appDataRepository.settings.getSettings()
if (settings.isShortcutsEnabled) { if (settings.isShortcutsEnabled) {
when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) { when (intent.getStringExtra(CLASS_NAME_EXTRA_KEY)) {
WireGuardTunnelService::class.java.simpleName -> { WireGuardTunnelService::class.java.simpleName -> {
val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY) val tunnelName = intent.getStringExtra(TUNNEL_NAME_EXTRA_KEY)
val tunnelConfig = val tunnelConfig = tunnelName?.let {
tunnelName?.let { appDataRepository.tunnels.getAll().firstOrNull {
appDataRepository.tunnels.getAll().firstOrNull { it.name == tunnelName
it.name == tunnelName }
} }
} when (intent.action) {
when (intent.action) { Action.START.name -> serviceManager.startVpnServiceForeground(
Action.START.name -> this@ShortcutsActivity, tunnelConfig?.id, isManualStart = true,
serviceManager.startVpnServiceForeground( )
this@ShortcutsActivity,
tunnelConfig?.id,
isManualStart = true,
)
Action.STOP.name -> Action.STOP.name -> serviceManager.stopVpnService(
serviceManager.stopVpnServiceForeground( this@ShortcutsActivity,
this@ShortcutsActivity, isManualStop = true,
isManualStop = true, )
) }
} }
}
WireGuardConnectivityWatcherService::class.java.simpleName -> { WireGuardConnectivityWatcherService::class.java.simpleName -> {
when (intent.action) { when (intent.action) {
Action.START.name -> Action.START.name -> appDataRepository.settings.save(
appDataRepository.settings.save( settings.copy(
settings.copy( isAutoTunnelPaused = false,
isAutoTunnelPaused = false, ),
), )
)
Action.STOP.name -> Action.STOP.name -> appDataRepository.settings.save(
appDataRepository.settings.save( settings.copy(
settings.copy( isAutoTunnelPaused = true,
isAutoTunnelPaused = true, ),
), )
) }
} }
} }
} }
} }
} finish()
finish() }
}
companion object { companion object {
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"
} }
} }
@@ -3,102 +3,104 @@ package com.zaneschepke.wireguardautotunnel.service.tile
import android.os.Build import android.os.Build
import android.service.quicksettings.Tile import android.service.quicksettings.Tile
import android.service.quicksettings.TileService import android.service.quicksettings.TileService
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ServiceLifecycleDispatcher
import androidx.lifecycle.lifecycleScope
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class AutoTunnelControlTile : TileService(), LifecycleOwner { class AutoTunnelControlTile : TileService() {
@Inject
lateinit var appDataRepository: AppDataRepository
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var appDataRepository: AppDataRepository
private val dispatcher = ServiceLifecycleDispatcher(this) @Inject
lateinit var serviceManager: ServiceManager
private var manualStartConfig: TunnelConfig? = null private val scope = CoroutineScope(Dispatchers.IO)
override fun onStartListening() { private var manualStartConfig: TunnelConfig? = null
super.onStartListening()
lifecycleScope.launch {
val settings = appDataRepository.settings.getSettings()
when (settings.isAutoTunnelEnabled) {
true -> {
if (settings.isAutoTunnelPaused) {
setInactive()
setTileDescription(this@AutoTunnelControlTile.getString(R.string.paused))
} else {
setActive()
setTileDescription(this@AutoTunnelControlTile.getString(R.string.active))
}
}
false -> { override fun onStartListening() {
setTileDescription(this@AutoTunnelControlTile.getString(R.string.disabled)) super.onStartListening()
setUnavailable() scope.launch {
} appDataRepository.settings.getSettingsFlow().collectLatest {
} when (it.isAutoTunnelEnabled) {
} true -> {
} if (it.isAutoTunnelPaused) {
setInactive()
setTileDescription(this@AutoTunnelControlTile.getString(R.string.paused))
} else {
setActive()
setTileDescription(this@AutoTunnelControlTile.getString(R.string.active))
}
}
override fun onTileAdded() { false -> {
super.onTileAdded() setTileDescription(this@AutoTunnelControlTile.getString(R.string.disabled))
onStartListening() setUnavailable()
} }
}
}
}
}
override fun onClick() { override fun onDestroy() {
super.onClick() super.onDestroy()
unlockAndRun { scope.cancel()
lifecycleScope.launch { }
try {
appDataRepository.toggleWatcherServicePause()
onStartListening()
} catch (e: Exception) {
Timber.e(e.message)
} finally {
cancel()
}
}
}
}
private fun setActive() { override fun onTileRemoved() {
qsTile.state = Tile.STATE_ACTIVE super.onTileRemoved()
qsTile.updateTile() scope.cancel()
} }
private fun setInactive() { override fun onClick() {
qsTile.state = Tile.STATE_INACTIVE super.onClick()
qsTile.updateTile() unlockAndRun {
} scope.launch {
try {
appDataRepository.toggleWatcherServicePause()
} catch (e: Exception) {
Timber.e(e.message)
} finally {
cancel()
}
}
}
}
private fun setUnavailable() { private fun setActive() {
manualStartConfig = null qsTile.state = Tile.STATE_ACTIVE
qsTile.state = Tile.STATE_UNAVAILABLE qsTile.updateTile()
qsTile.updateTile() }
}
private fun setTileDescription(description: String) { private fun setInactive() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { qsTile.state = Tile.STATE_INACTIVE
qsTile.subtitle = description qsTile.updateTile()
} }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
qsTile.stateDescription = description
}
qsTile.updateTile()
}
override val lifecycle: Lifecycle private fun setUnavailable() {
get() = dispatcher.lifecycle manualStartConfig = null
qsTile.state = Tile.STATE_UNAVAILABLE
qsTile.updateTile()
}
private fun setTileDescription(description: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
qsTile.subtitle = description
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
qsTile.stateDescription = description
}
qsTile.updateTile()
}
} }
@@ -3,119 +3,116 @@ package com.zaneschepke.wireguardautotunnel.service.tile
import android.os.Build import android.os.Build
import android.service.quicksettings.Tile import android.service.quicksettings.Tile
import android.service.quicksettings.TileService import android.service.quicksettings.TileService
import androidx.lifecycle.Lifecycle import com.wireguard.android.backend.Tunnel
import androidx.lifecycle.LifecycleOwner import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import androidx.lifecycle.ServiceLifecycleDispatcher
import androidx.lifecycle.lifecycleScope
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnService
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class TunnelControlTile : TileService(), LifecycleOwner { class TunnelControlTile : TileService() {
@Inject
lateinit var appDataRepository: AppDataRepository
@Inject @Inject
lateinit var vpnService: VpnService lateinit var appDataRepository: AppDataRepository
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var vpnService: VpnService
private val dispatcher = ServiceLifecycleDispatcher(this) @Inject
lateinit var serviceManager: ServiceManager
private var manualStartConfig: TunnelConfig? = null private val scope = CoroutineScope(Dispatchers.IO)
override fun onStartListening() { private var manualStartConfig: TunnelConfig? = null
super.onStartListening()
Timber.d("On start listening called")
lifecycleScope.launch {
when (vpnService.getState()) {
TunnelState.UP -> {
setActive()
setTileDescription(vpnService.name)
}
TunnelState.DOWN -> { override fun onStartListening() {
setInactive() super.onStartListening()
val config = Timber.d("On start listening called")
appDataRepository.getStartTunnelConfig()?.also { config -> scope.launch {
manualStartConfig = config vpnService.vpnState.collect { it ->
} ?: appDataRepository.getPrimaryOrFirstTunnel() when (it.status) {
config?.let { Tunnel.State.UP -> {
setTileDescription(it.name) setActive()
} ?: setUnavailable() it.tunnelConfig?.name?.let { name -> setTileDescription(name) }
} }
else -> setInactive() Tunnel.State.DOWN -> {
} setInactive()
} val config = appDataRepository.getStartTunnelConfig()?.also { config ->
} manualStartConfig = config
} ?: appDataRepository.getPrimaryOrFirstTunnel()
config?.let {
setTileDescription(it.name)
} ?: setUnavailable()
}
override fun onTileAdded() { else -> setInactive()
super.onTileAdded() }
onStartListening() }
} }
}
override fun onClick() { override fun onDestroy() {
super.onClick() super.onDestroy()
unlockAndRun { scope.cancel()
lifecycleScope.launch { }
try {
if (vpnService.getState() == TunnelState.UP) {
serviceManager.stopVpnServiceForeground(
this@TunnelControlTile,
isManualStop = true,
)
} else {
serviceManager.startVpnServiceForeground(
this@TunnelControlTile,
manualStartConfig?.id,
isManualStart = true,
)
}
} catch (e: Exception) {
Timber.e(e.message)
} finally {
cancel()
}
}
}
}
private fun setActive() { override fun onTileRemoved() {
qsTile.state = Tile.STATE_ACTIVE super.onTileRemoved()
qsTile.updateTile() scope.cancel()
} }
private fun setInactive() { override fun onClick() {
qsTile.state = Tile.STATE_INACTIVE super.onClick()
qsTile.updateTile() unlockAndRun {
} scope.launch {
try {
if (vpnService.getState() == Tunnel.State.UP) {
serviceManager.stopVpnService(this@TunnelControlTile, isManualStop = true)
} else {
serviceManager.startVpnServiceForeground(
this@TunnelControlTile, manualStartConfig?.id, isManualStart = true,
)
}
} catch (e: Exception) {
Timber.e(e.message)
} finally {
cancel()
}
}
}
}
private fun setUnavailable() { private fun setActive() {
manualStartConfig = null qsTile.state = Tile.STATE_ACTIVE
qsTile.state = Tile.STATE_UNAVAILABLE qsTile.updateTile()
qsTile.updateTile() }
}
private fun setTileDescription(description: String) { private fun setInactive() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { qsTile.state = Tile.STATE_INACTIVE
qsTile.subtitle = description qsTile.updateTile()
} }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
qsTile.stateDescription = description
}
qsTile.updateTile()
}
override val lifecycle: Lifecycle private fun setUnavailable() {
get() = dispatcher.lifecycle manualStartConfig = null
qsTile.state = Tile.STATE_UNAVAILABLE
qsTile.updateTile()
}
private fun setTileDescription(description: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
qsTile.subtitle = description
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
qsTile.stateDescription = description
}
qsTile.updateTile()
}
} }
@@ -1,17 +1,16 @@
package com.zaneschepke.wireguardautotunnel.service.tunnel package com.zaneschepke.wireguardautotunnel.service.tunnel
enum class HandshakeStatus { enum class HandshakeStatus {
HEALTHY, HEALTHY,
STALE, STALE,
UNKNOWN, UNKNOWN,
NOT_STARTED, NOT_STARTED;
;
companion object { companion object {
private const val WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC = 180 private const val WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC = 180
const val STATUS_CHANGE_TIME_BUFFER = 30 const val STATUS_CHANGE_TIME_BUFFER = 30
const val STALE_TIME_LIMIT_SEC = const val STALE_TIME_LIMIT_SEC =
WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC + STATUS_CHANGE_TIME_BUFFER WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC + STATUS_CHANGE_TIME_BUFFER
const val NEVER_CONNECTED_TO_UNHEALTHY_TIME_LIMIT_SEC = 30 const val NEVER_CONNECTED_TO_UNHEALTHY_TIME_LIMIT_SEC = 30
} }
} }
@@ -1,44 +0,0 @@
package com.zaneschepke.wireguardautotunnel.service.tunnel
import com.wireguard.android.backend.Tunnel
enum class TunnelState {
UP,
DOWN,
TOGGLE,
;
fun toWgState(): Tunnel.State {
return when (this) {
UP -> Tunnel.State.UP
DOWN -> Tunnel.State.DOWN
TOGGLE -> Tunnel.State.TOGGLE
}
}
fun toAmState(): org.amnezia.awg.backend.Tunnel.State {
return when (this) {
UP -> org.amnezia.awg.backend.Tunnel.State.UP
DOWN -> org.amnezia.awg.backend.Tunnel.State.DOWN
TOGGLE -> org.amnezia.awg.backend.Tunnel.State.TOGGLE
}
}
companion object {
fun from(state: Tunnel.State): TunnelState {
return when (state) {
Tunnel.State.DOWN -> DOWN
Tunnel.State.TOGGLE -> TOGGLE
Tunnel.State.UP -> UP
}
}
fun from(state: org.amnezia.awg.backend.Tunnel.State): TunnelState {
return when (state) {
org.amnezia.awg.backend.Tunnel.State.DOWN -> DOWN
org.amnezia.awg.backend.Tunnel.State.TOGGLE -> TOGGLE
org.amnezia.awg.backend.Tunnel.State.UP -> UP
}
}
}
}
@@ -1,15 +1,15 @@
package com.zaneschepke.wireguardautotunnel.service.tunnel package com.zaneschepke.wireguardautotunnel.service.tunnel
import com.wireguard.android.backend.Tunnel import com.wireguard.android.backend.Tunnel
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
interface VpnService : Tunnel, org.amnezia.awg.backend.Tunnel { interface VpnService : Tunnel {
suspend fun startTunnel(tunnelConfig: TunnelConfig? = null): TunnelState suspend fun startTunnel(tunnelConfig: TunnelConfig? = null): Tunnel.State
suspend fun stopTunnel() suspend fun stopTunnel()
val vpnState: StateFlow<VpnState> val vpnState: StateFlow<VpnState>
fun getState(): TunnelState fun getState(): Tunnel.State
} }
@@ -1,10 +1,11 @@
package com.zaneschepke.wireguardautotunnel.service.tunnel package com.zaneschepke.wireguardautotunnel.service.tunnel
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.wireguard.android.backend.Statistics
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics import com.wireguard.android.backend.Tunnel
import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
data class VpnState( data class VpnState(
val status: TunnelState = TunnelState.DOWN, val status: Tunnel.State = Tunnel.State.DOWN,
val tunnelConfig: TunnelConfig? = null, val tunnelConfig: TunnelConfig? = null,
val statistics: TunnelStatistics? = null, val statistics: Statistics? = null
) )
@@ -2,232 +2,141 @@ package com.zaneschepke.wireguardautotunnel.service.tunnel
import com.wireguard.android.backend.Backend import com.wireguard.android.backend.Backend
import com.wireguard.android.backend.BackendException import com.wireguard.android.backend.BackendException
import com.wireguard.android.backend.Statistics
import com.wireguard.android.backend.Tunnel.State import com.wireguard.android.backend.Tunnel.State
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
import com.zaneschepke.wireguardautotunnel.module.Kernel import com.zaneschepke.wireguardautotunnel.module.Kernel
import com.zaneschepke.wireguardautotunnel.module.Userspace import com.zaneschepke.wireguardautotunnel.module.Userspace
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.AmneziaStatistics
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.WireGuardStatistics
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.amnezia.awg.backend.Tunnel
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Provider
class WireGuardTunnel class WireGuardTunnel
@Inject @Inject
constructor( constructor(
private val userspaceAmneziaBackend: Provider<org.amnezia.awg.backend.Backend>, @Userspace private val userspaceBackend: Backend,
@Userspace private val userspaceBackend: Provider<Backend>, @Kernel private val kernelBackend: Backend,
@Kernel private val kernelBackend: Provider<Backend>, private val appDataRepository: AppDataRepository,
private val appDataRepository: AppDataRepository,
@ApplicationScope private val applicationScope: CoroutineScope,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : VpnService { ) : VpnService {
private val _vpnState = MutableStateFlow(VpnState()) private val _vpnState = MutableStateFlow(VpnState())
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow() override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
private var statsJob: Job? = null private val scope = CoroutineScope(Dispatchers.IO)
private var backendIsWgUserspace = true private lateinit var statsJob: Job
private var backendIsAmneziaUserspace = false private var backend: Backend = userspaceBackend
init { private var backendIsUserspace = true
applicationScope.launch(ioDispatcher) {
appDataRepository.settings.getSettingsFlow().collect {
if (it.isKernelEnabled && (backendIsWgUserspace || backendIsAmneziaUserspace)) {
Timber.i("Setting kernel backend")
backendIsWgUserspace = false
backendIsAmneziaUserspace = false
} else if (!it.isKernelEnabled && !it.isAmneziaEnabled && !backendIsWgUserspace) {
Timber.i("Setting WireGuard userspace backend")
backendIsWgUserspace = true
backendIsAmneziaUserspace = false
} else if (it.isAmneziaEnabled && !backendIsAmneziaUserspace) {
Timber.i("Setting Amnezia userspace backend")
backendIsAmneziaUserspace = true
backendIsWgUserspace = false
}
}
}
}
private fun setState(tunnelConfig: TunnelConfig?, tunnelState: TunnelState): TunnelState { init {
return if (backendIsAmneziaUserspace) { scope.launch {
Timber.i("Using Amnezia backend") appDataRepository.settings.getSettingsFlow().collect {
val config = if (it.isKernelEnabled && backendIsUserspace) {
tunnelConfig?.let { Timber.d("Setting kernel backend")
if (it.amQuick != "") { backend = kernelBackend
TunnelConfig.configFromAmQuick(it.amQuick) backendIsUserspace = false
} else { } else if (!it.isKernelEnabled && !backendIsUserspace) {
Timber.w( Timber.d("Setting userspace backend")
"Using backwards compatible wg config, amnezia specific config not found.", backend = userspaceBackend
) backendIsUserspace = true
TunnelConfig.configFromAmQuick(it.wgQuick) }
} }
} }
val state = }
userspaceAmneziaBackend.get().setState(this, tunnelState.toAmState(), config)
TunnelState.from(state)
} else {
Timber.i("Using Wg backend")
val wgConfig = tunnelConfig?.let { TunnelConfig.configFromWgQuick(it.wgQuick) }
val state =
backend().setState(
this,
tunnelState.toWgState(),
wgConfig,
)
TunnelState.from(state)
}
}
override suspend fun startTunnel(tunnelConfig: TunnelConfig?): TunnelState { override suspend fun startTunnel(tunnelConfig: TunnelConfig?): State {
return withContext(ioDispatcher) { return try {
try { //TODO we need better error handling here
// TODO we need better error handling here val config = tunnelConfig ?: appDataRepository.getPrimaryOrFirstTunnel()
// need to bubble up these errors to the UI if (config != null) {
val config = tunnelConfig ?: appDataRepository.getPrimaryOrFirstTunnel() emitTunnelConfig(config)
if (config != null) { val wgConfig = TunnelConfig.configFromQuick(config.wgQuick)
emitTunnelConfig(config) val state =
setState(config, TunnelState.UP) backend.setState(
} else { this,
throw Exception("No tunnels") State.UP,
} wgConfig,
} catch (e: BackendException) { )
Timber.e("Failed to start tunnel with error: ${e.message}") state
TunnelState.from(State.DOWN) } else throw Exception("No tunnels")
} } catch (e: BackendException) {
} Timber.e("Failed to start tunnel with error: ${e.message}")
} State.DOWN
}
}
private fun backend(): Backend { private fun emitTunnelState(state: State) {
return when { _vpnState.tryEmit(
backendIsWgUserspace -> { _vpnState.value.copy(
userspaceBackend.get() status = state,
} ),
)
}
!backendIsWgUserspace && !backendIsAmneziaUserspace -> { private fun emitBackendStatistics(statistics: Statistics) {
kernelBackend.get() _vpnState.tryEmit(
} _vpnState.value.copy(
statistics = statistics,
),
)
}
else -> { private suspend fun emitTunnelConfig(tunnelConfig: TunnelConfig?) {
userspaceBackend.get() _vpnState.emit(
} _vpnState.value.copy(
} tunnelConfig = tunnelConfig,
} ),
)
}
private fun emitTunnelState(state: TunnelState) { override suspend fun stopTunnel() {
_vpnState.tryEmit( try {
_vpnState.value.copy( if (getState() == State.UP) {
status = state, val state = backend.setState(this, State.DOWN, null)
), emitTunnelState(state)
) }
} } catch (e: BackendException) {
Timber.e("Failed to stop tunnel with error: ${e.message}")
}
}
private fun emitBackendStatistics(statistics: TunnelStatistics) { override fun getState(): State {
_vpnState.tryEmit( return backend.getState(this)
_vpnState.value.copy( }
statistics = statistics,
),
)
}
private suspend fun emitTunnelConfig(tunnelConfig: TunnelConfig?) { override fun getName(): String {
_vpnState.emit( return _vpnState.value.tunnelConfig?.name ?: ""
_vpnState.value.copy( }
tunnelConfig = tunnelConfig,
),
)
}
private fun resetVpnState() { override fun onStateChange(state: State) {
_vpnState.tryEmit(VpnState()) val tunnel = this
} emitTunnelState(state)
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate(WireGuardAutoTunnel.instance)
override suspend fun stopTunnel() { if (state == State.UP) {
withContext(ioDispatcher) { statsJob =
try { scope.launch {
if (getState() == TunnelState.UP) { while (true) {
val state = setState(null, TunnelState.DOWN) val statistics = backend.getStatistics(tunnel)
resetVpnState() emitBackendStatistics(statistics)
emitTunnelState(state) delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
} }
} catch (e: BackendException) { }
Timber.e("Failed to stop wireguard tunnel with error: ${e.message}") }
} catch (e: org.amnezia.awg.backend.BackendException) { if (state == State.DOWN) {
Timber.e("Failed to stop amnezia tunnel with error: ${e.message}") if (this::statsJob.isInitialized) {
} statsJob.cancel()
} }
} }
}
override fun getState(): TunnelState {
return if (backendIsAmneziaUserspace) {
TunnelState.from(
userspaceAmneziaBackend.get().getState(this),
)
} else {
TunnelState.from(backend().getState(this))
}
}
override fun getName(): String {
return _vpnState.value.tunnelConfig?.name ?: ""
}
override fun onStateChange(newState: Tunnel.State) {
handleStateChange(TunnelState.from(newState))
}
private fun handleStateChange(state: TunnelState) {
emitTunnelState(state)
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
if (state == TunnelState.UP) {
statsJob = startTunnelStatisticsJob()
}
if (state == TunnelState.DOWN) {
try {
statsJob?.cancel()
} catch (e: CancellationException) {
Timber.i("Stats job cancelled")
}
}
}
private fun startTunnelStatisticsJob() = applicationScope.launch(ioDispatcher) {
while (true) {
if (backendIsAmneziaUserspace) {
emitBackendStatistics(
AmneziaStatistics(
userspaceAmneziaBackend.get().getStatistics(this@WireGuardTunnel),
),
)
} else {
emitBackendStatistics(
WireGuardStatistics(backend().getStatistics(this@WireGuardTunnel)),
)
}
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
}
}
override fun onStateChange(state: State) {
handleStateChange(TunnelState.from(state))
}
} }
@@ -1,34 +0,0 @@
package com.zaneschepke.wireguardautotunnel.service.tunnel.statistics
import org.amnezia.awg.backend.Statistics
import org.amnezia.awg.crypto.Key
class AmneziaStatistics(private val statistics: Statistics) : TunnelStatistics() {
override fun peerStats(peer: Key): PeerStats? {
val key = Key.fromBase64(peer.toBase64())
val stats = statistics.peer(key)
return stats?.let {
PeerStats(
rxBytes = stats.rxBytes,
txBytes = stats.txBytes,
latestHandshakeEpochMillis = stats.latestHandshakeEpochMillis,
)
}
}
override fun isTunnelStale(): Boolean {
return statistics.isStale
}
override fun getPeers(): Array<Key> {
return statistics.peers()
}
override fun rx(): Long {
return statistics.totalRx()
}
override fun tx(): Long {
return statistics.totalTx()
}
}
@@ -1,18 +0,0 @@
package com.zaneschepke.wireguardautotunnel.service.tunnel.statistics
import org.amnezia.awg.crypto.Key
abstract class TunnelStatistics {
@JvmRecord
data class PeerStats(val rxBytes: Long, val txBytes: Long, val latestHandshakeEpochMillis: Long)
abstract fun peerStats(peer: Key): PeerStats?
abstract fun isTunnelStale(): Boolean
abstract fun getPeers(): Array<Key>
abstract fun rx(): Long
abstract fun tx(): Long
}
@@ -1,36 +0,0 @@
package com.zaneschepke.wireguardautotunnel.service.tunnel.statistics
import com.wireguard.android.backend.Statistics
import org.amnezia.awg.crypto.Key
class WireGuardStatistics(private val statistics: Statistics) : TunnelStatistics() {
override fun peerStats(peer: Key): PeerStats? {
val key = com.wireguard.crypto.Key.fromBase64(peer.toBase64())
val peerStats = statistics.peer(key)
return peerStats?.let {
PeerStats(
txBytes = peerStats.txBytes,
rxBytes = peerStats.rxBytes,
latestHandshakeEpochMillis = peerStats.latestHandshakeEpochMillis,
)
}
}
override fun isTunnelStale(): Boolean {
return statistics.isStale
}
override fun getPeers(): Array<Key> {
return statistics.peers().map {
Key.fromBase64(it.toBase64())
}.toTypedArray()
}
override fun rx(): Long {
return statistics.totalRx()
}
override fun tx(): Long {
return statistics.totalTx()
}
}
@@ -1,9 +1,9 @@
package com.zaneschepke.wireguardautotunnel.ui package com.zaneschepke.wireguardautotunnel.ui
data class AppUiState( data class AppUiState(
val snackbarMessage: String = "", val snackbarMessage: String = "",
val snackbarMessageConsumed: Boolean = true, val snackbarMessageConsumed: Boolean = true,
val vpnPermissionAccepted: Boolean = false, val vpnPermissionAccepted: Boolean = false,
val notificationPermissionAccepted: Boolean = false, val notificationPermissionAccepted: Boolean = false,
val requestPermissions: Boolean = false, val requestPermissions: Boolean = false
) )
@@ -1,123 +1,148 @@
package com.zaneschepke.wireguardautotunnel.ui package com.zaneschepke.wireguardautotunnel.ui
import android.app.Application
import android.content.ActivityNotFoundException import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent import android.content.Intent
import android.net.Uri import android.net.Uri
import android.widget.Toast
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wireguard.android.backend.GoBackend import com.wireguard.android.backend.GoBackend
import com.zaneschepke.logcatter.Logcatter
import com.zaneschepke.logcatter.model.LogMessage
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.FileUtils
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
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.launch
import timber.log.Timber import timber.log.Timber
import java.time.Instant
import javax.inject.Inject import javax.inject.Inject
@HiltViewModel @HiltViewModel
class AppViewModel class AppViewModel
@Inject @Inject
constructor() : ViewModel() { constructor(
val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance) private val application: Application,
) : ViewModel() {
private val _appUiState = val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance)
MutableStateFlow(
AppUiState(
vpnPermissionAccepted = vpnIntent == null,
),
)
val appUiState = _appUiState.asStateFlow()
fun isRequiredPermissionGranted(): Boolean { private val _appUiState = MutableStateFlow(
val allAccepted = AppUiState(
(_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted) vpnPermissionAccepted = vpnIntent == null,
if (!allAccepted) requestPermissions() ),
return allAccepted )
} val appUiState = _appUiState.asStateFlow()
private fun requestPermissions() {
_appUiState.update {
it.copy(
requestPermissions = true,
)
}
}
fun permissionsRequested() { fun isRequiredPermissionGranted(): Boolean {
_appUiState.update { val allAccepted =
it.copy( (_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted)
requestPermissions = false, if (!allAccepted) requestPermissions()
) return allAccepted
} }
}
fun openWebPage(url: String, context: Context) { private fun requestPermissions() {
try { _appUiState.value = _appUiState.value.copy(
val webpage: Uri = Uri.parse(url) requestPermissions = true,
val intent = )
Intent(Intent.ACTION_VIEW, webpage).apply { }
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
} catch (e: ActivityNotFoundException) {
Timber.e(e)
showSnackbarMessage(context.getString(R.string.no_browser_detected))
}
}
fun onVpnPermissionAccepted() { fun permissionsRequested() {
_appUiState.update { _appUiState.value = _appUiState.value.copy(
it.copy( requestPermissions = false,
vpnPermissionAccepted = true, )
) }
}
}
fun launchEmail(context: Context) { fun openWebPage(url: String) {
try { try {
val intent = val webpage: Uri = Uri.parse(url)
Intent(Intent.ACTION_SENDTO).apply { val intent = Intent(Intent.ACTION_VIEW, webpage).apply {
type = Constants.EMAIL_MIME_TYPE addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
putExtra(Intent.EXTRA_EMAIL, arrayOf(context.getString(R.string.my_email))) }
putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.email_subject)) application.startActivity(intent)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } catch (e: ActivityNotFoundException) {
} Timber.e(e)
context.startActivity( showSnackbarMessage(application.getString(R.string.no_browser_detected))
Intent.createChooser(intent, context.getString(R.string.email_chooser)).apply { }
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }
},
)
} catch (e: ActivityNotFoundException) {
Timber.e(e)
showSnackbarMessage(context.getString(R.string.no_email_detected))
}
}
fun showSnackbarMessage(message: String) { fun onVpnPermissionAccepted() {
_appUiState.update { _appUiState.value = _appUiState.value.copy(
it.copy( vpnPermissionAccepted = true,
snackbarMessage = message, )
snackbarMessageConsumed = false, }
)
}
}
fun snackbarMessageConsumed() { fun launchEmail() {
_appUiState.update { try {
it.copy( val intent =
snackbarMessage = "", Intent(Intent.ACTION_SENDTO).apply {
snackbarMessageConsumed = true, type = Constants.EMAIL_MIME_TYPE
) putExtra(Intent.EXTRA_EMAIL, arrayOf(application.getString(R.string.my_email)))
} putExtra(Intent.EXTRA_SUBJECT, application.getString(R.string.email_subject))
} addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
application.startActivity(
Intent.createChooser(intent, application.getString(R.string.email_chooser)).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
},
)
} catch (e: ActivityNotFoundException) {
Timber.e(e)
showSnackbarMessage(application.getString(R.string.no_email_detected))
}
}
fun setNotificationPermissionAccepted(accepted: Boolean) { fun showSnackbarMessage(message: String) {
_appUiState.update { _appUiState.value = _appUiState.value.copy(
it.copy( snackbarMessage = message,
notificationPermissionAccepted = accepted, snackbarMessageConsumed = false,
) )
} }
}
fun snackbarMessageConsumed() {
_appUiState.value = _appUiState.value.copy(
snackbarMessage = "",
snackbarMessageConsumed = true,
)
}
val logs = mutableStateListOf<LogMessage>()
fun readLogCatOutput() =
viewModelScope.launch(viewModelScope.coroutineContext + Dispatchers.IO) {
launch {
Logcatter.logs {
logs.add(it)
if (logs.size > Constants.LOG_BUFFER_SIZE) {
logs.removeRange(0, (logs.size - Constants.LOG_BUFFER_SIZE).toInt())
}
}
}
}
fun clearLogs() {
logs.clear()
Logcatter.clear()
}
fun saveLogsToFile() {
val fileName = "${Constants.BASE_LOG_FILE_NAME}-${Instant.now().epochSecond}.txt"
val content = logs.joinToString(separator = "\n")
FileUtils.saveFileToDownloads(application.applicationContext, content, fileName)
Toast.makeText(application, application.getString(R.string.logs_saved), Toast.LENGTH_SHORT)
.show()
}
fun setNotificationPermissionAccepted(accepted: Boolean) {
_appUiState.value = _appUiState.value.copy(
notificationPermissionAccepted = accepted,
)
}
} }
@@ -0,0 +1,5 @@
package com.zaneschepke.wireguardautotunnel.ui
import com.journeyapps.barcodescanner.CaptureActivity
class CaptureActivityPortrait : CaptureActivity()
@@ -10,8 +10,6 @@ import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.focusable import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -21,43 +19,34 @@ import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.InfoDialog
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.options.OptionsScreen import com.zaneschepke.wireguardautotunnel.ui.screens.options.OptionsScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.pinlock.PinLockScreen import com.zaneschepke.wireguardautotunnel.ui.screens.pinlock.PinLockScreen
@@ -69,259 +58,211 @@ import com.zaneschepke.wireguardautotunnel.util.StringValue
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import xyz.teamgravity.pin_lock_compose.PinManager
import javax.inject.Inject import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class MainActivity : AppCompatActivity() { class MainActivity : AppCompatActivity() {
@Inject
lateinit var appStateRepository: AppStateRepository
@Inject @Inject
lateinit var settingsRepository: SettingsRepository lateinit var dataStoreManager: DataStoreManager
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var settingsRepository: SettingsRepository
@OptIn( @Inject
ExperimentalPermissionsApi::class, lateinit var serviceManager: ServiceManager
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val isPinLockEnabled = intent.extras?.getBoolean(SplashActivity.IS_PIN_LOCK_ENABLED_KEY) @OptIn(
ExperimentalPermissionsApi::class,
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb())) enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb()))
lifecycleScope.launch { // load preferences into memory and init data
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate() lifecycleScope.launch {
val settings = settingsRepository.getSettings() dataStoreManager.init()
if (settings.isAutoTunnelEnabled) { WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate(this@MainActivity)
serviceManager.startWatcherService(application.applicationContext) val settings = settingsRepository.getSettings()
} if (settings.isAutoTunnelEnabled) {
} serviceManager.startWatcherService(application.applicationContext)
}
}
setContent {
val appViewModel = hiltViewModel<AppViewModel>()
val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle()
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
setContent { val notificationPermissionState =
val appViewModel = hiltViewModel<AppViewModel>() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle() rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS) else null
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
var showVpnPermissionDialog by remember { mutableStateOf(false) }
val notificationPermissionState = val snackbarHostState = remember { SnackbarHostState() }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS)
} else {
null
}
val snackbarHostState = remember { SnackbarHostState() } val vpnActivityResultState =
rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
onResult = {
val accepted = (it.resultCode == RESULT_OK)
if (accepted) {
appViewModel.onVpnPermissionAccepted()
}
},
)
val vpnActivityResultState = fun showSnackBarMessage(message: StringValue) {
rememberLauncherForActivityResult( lifecycleScope.launch(Dispatchers.Main) {
ActivityResultContracts.StartActivityForResult(), val result =
onResult = { snackbarHostState.showSnackbar(
val accepted = (it.resultCode == RESULT_OK) message = message.asString(this@MainActivity),
if (accepted) { duration = SnackbarDuration.Short,
appViewModel.onVpnPermissionAccepted() )
} else { when (result) {
showVpnPermissionDialog = true SnackbarResult.ActionPerformed,
} SnackbarResult.Dismissed -> {
}, snackbarHostState.currentSnackbarData?.dismiss()
) }
}
}
}
fun showSnackBarMessage(message: StringValue) { LaunchedEffect(appUiState.requestPermissions) {
lifecycleScope.launch(Dispatchers.Main) { if (appUiState.requestPermissions) {
val result = appViewModel.permissionsRequested()
snackbarHostState.showSnackbar( if (notificationPermissionState != null && !notificationPermissionState.status.isGranted
message = message.asString(this@MainActivity), ) {
duration = SnackbarDuration.Short, showSnackBarMessage(StringValue.StringResource(R.string.notification_permission_required))
) return@LaunchedEffect notificationPermissionState.launchPermissionRequest()
when (result) { }
SnackbarResult.ActionPerformed, if (!appUiState.vpnPermissionAccepted) {
SnackbarResult.Dismissed, return@LaunchedEffect vpnActivityResultState.launch(appViewModel.vpnIntent)
-> { }
snackbarHostState.currentSnackbarData?.dismiss() }
} }
}
}
}
LaunchedEffect(appUiState.requestPermissions) { WireguardAutoTunnelTheme {
if (appUiState.requestPermissions) { LaunchedEffect(Unit) {
appViewModel.permissionsRequested() appViewModel.setNotificationPermissionAccepted(
if (notificationPermissionState != null && !notificationPermissionState.status.isGranted notificationPermissionState?.status?.isGranted ?: true,
) { )
notificationPermissionState.launchPermissionRequest() if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) appViewModel.readLogCatOutput()
return@LaunchedEffect if (notificationPermissionState.status.shouldShowRationale || !notificationPermissionState.status.isGranted) { }
showSnackBarMessage(
StringValue.StringResource(R.string.notification_permission_required),
)
} else {
Unit
}
}
if (!appUiState.vpnPermissionAccepted) {
return@LaunchedEffect appViewModel.vpnIntent?.let {
vpnActivityResultState.launch(
it,
)
} ?: Unit
}
}
}
WireguardAutoTunnelTheme { LaunchedEffect(appUiState.snackbarMessageConsumed) {
LaunchedEffect(Unit) { if (!appUiState.snackbarMessageConsumed) {
appViewModel.setNotificationPermissionAccepted( showSnackBarMessage(StringValue.DynamicString(appUiState.snackbarMessage))
notificationPermissionState?.status?.isGranted ?: true, appViewModel.snackbarMessageConsumed()
) }
} }
LaunchedEffect(appUiState.snackbarMessageConsumed) { val focusRequester = remember { FocusRequester() }
if (!appUiState.snackbarMessageConsumed) {
showSnackBarMessage(StringValue.DynamicString(appUiState.snackbarMessage))
appViewModel.snackbarMessageConsumed()
}
}
val focusRequester = remember { FocusRequester() } Scaffold(
snackbarHost = {
if (showVpnPermissionDialog) { SnackbarHost(snackbarHostState) { snackbarData: SnackbarData ->
InfoDialog( CustomSnackBar(
onDismiss = { showVpnPermissionDialog = false }, snackbarData.visuals.message,
onAttest = { showVpnPermissionDialog = false }, isRtl = false,
title = { Text(text = stringResource(R.string.vpn_denied_dialog_title)) }, containerColor =
body = { MaterialTheme.colorScheme.surfaceColorAtElevation(
Column(verticalArrangement = Arrangement.spacedBy(15.dp)) { 2.dp,
Text(text = stringResource(R.string.vpn_denied_dialog_message)) ),
Text(text = stringResource(R.string.vpn_denied_dialog_message2)) )
} }
}, },
confirmText = { Text(text = stringResource(R.string.okay)) }, //TODO refactor
) modifier = Modifier
} .focusable()
.focusProperties {
Scaffold( when (navBackStackEntry?.destination?.route) {
snackbarHost = { Screen.Lock.route -> Unit
SnackbarHost(snackbarHostState) { snackbarData: SnackbarData -> else -> up = focusRequester
CustomSnackBar( }
snackbarData.visuals.message, },
isRtl = false, bottomBar = {
containerColor = BottomNavBar(
MaterialTheme.colorScheme.surfaceColorAtElevation( navController,
2.dp, listOf(
), Screen.Main.navItem,
) Screen.Settings.navItem,
} Screen.Support.navItem,
}, ),
// TODO refactor )
modifier = },
Modifier ) { padding ->
.focusable() NavHost(
.focusProperties { navController,
when (navBackStackEntry?.destination?.route) { startDestination =
Screen.Lock.route -> Unit (if (PinManager.pinExists()) Screen.Lock.route else Screen.Main.route),
else -> up = focusRequester modifier =
} Modifier
}, .padding(padding)
bottomBar = { .fillMaxSize(),
BottomNavBar( ) {
navController, composable(
listOf( Screen.Main.route,
Screen.Main.navItem, ) {
Screen.Settings.navItem, MainScreen(
Screen.Support.navItem, focusRequester = focusRequester,
), appViewModel = appViewModel,
) navController = navController,
}, )
) { padding -> }
NavHost( composable(
navController, Screen.Settings.route,
startDestination = (if (isPinLockEnabled == true) Screen.Lock.route else Screen.Main.route), ) {
modifier = SettingsScreen(
Modifier appViewModel = appViewModel,
.padding(padding) navController = navController,
.fillMaxSize(), focusRequester = focusRequester,
) { )
composable( }
Screen.Main.route, composable(
) { Screen.Support.route,
MainScreen( ) {
focusRequester = focusRequester, SupportScreen(
appViewModel = appViewModel, focusRequester = focusRequester,
navController = navController, appViewModel = appViewModel,
) navController = navController,
} )
composable( }
Screen.Settings.route, composable(Screen.Support.Logs.route) {
) { LogsScreen(appViewModel)
SettingsScreen( }
appViewModel = appViewModel, composable("${Screen.Config.route}/{id}") {
navController = navController, val id = it.arguments?.getString("id")
focusRequester = focusRequester, if (!id.isNullOrBlank()) {
) ConfigScreen(
} navController = navController,
composable( tunnelId = id,
Screen.Support.route, appViewModel = appViewModel,
) { focusRequester = focusRequester,
SupportScreen( )
focusRequester = focusRequester, }
appViewModel = appViewModel, }
navController = navController, composable("${Screen.Option.route}/{id}") {
) val id = it.arguments?.getString("id")
} if (!id.isNullOrBlank()) {
composable(Screen.Support.Logs.route) { OptionsScreen(
LogsScreen() navController = navController,
} tunnelId = id,
composable( appViewModel = appViewModel,
"${Screen.Config.route}/{id}?configType={configType}", focusRequester = focusRequester,
arguments = )
listOf( }
navArgument("id") { }
type = NavType.StringType composable(Screen.Lock.route) {
defaultValue = "0" PinLockScreen(
}, navController = navController,
navArgument("configType") { appViewModel = appViewModel,
type = NavType.StringType )
defaultValue = ConfigType.WIREGUARD.name }
}, }
), }
) { }
val id = it.arguments?.getString("id") }
val configType = }
ConfigType.valueOf(
it.arguments?.getString("configType") ?: ConfigType.WIREGUARD.name,
)
if (!id.isNullOrBlank()) {
ConfigScreen(
navController = navController,
tunnelId = id,
appViewModel = appViewModel,
focusRequester = focusRequester,
configType = configType,
)
}
}
composable("${Screen.Option.route}/{id}") {
val id = it.arguments?.getString("id")
if (!id.isNullOrBlank()) {
OptionsScreen(
navController = navController,
tunnelId = id,
appViewModel = appViewModel,
focusRequester = focusRequester,
)
}
}
composable(Screen.Lock.route) {
PinLockScreen(
navController = navController,
appViewModel = appViewModel,
)
}
}
}
}
}
}
} }
@@ -4,43 +4,40 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Home import androidx.compose.material.icons.rounded.Home
import androidx.compose.material.icons.rounded.QuestionMark import androidx.compose.material.icons.rounded.QuestionMark
import androidx.compose.material.icons.rounded.Settings import androidx.compose.material.icons.rounded.Settings
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem
sealed class Screen(val route: String) { sealed class Screen(val route: String) {
data object Main : Screen("main") { data object Main : Screen("main") {
val navItem = val navItem =
BottomNavItem( BottomNavItem(
name = WireGuardAutoTunnel.instance.getString(R.string.tunnels), name = "Tunnels",
route = route, route = route,
icon = Icons.Rounded.Home, icon = Icons.Rounded.Home,
) )
} }
data object Settings : Screen("settings") { data object Settings : Screen("settings") {
val navItem = val navItem =
BottomNavItem( BottomNavItem(
name = WireGuardAutoTunnel.instance.getString(R.string.settings), name = "Settings",
route = route, route = route,
icon = Icons.Rounded.Settings, icon = Icons.Rounded.Settings,
) )
} }
data object Support : Screen("support") { data object Support : Screen("support") {
val navItem = val navItem =
BottomNavItem( BottomNavItem(
name = WireGuardAutoTunnel.instance.getString(R.string.support), name = "Support",
route = route, route = route,
icon = Icons.Rounded.QuestionMark, icon = Icons.Rounded.QuestionMark,
) )
data object Logs : Screen("support/logs") data object Logs : Screen("support/logs")
} }
data object Config : Screen("config") data object Config : Screen("config")
data object Lock : Screen("lock")
data object Lock : Screen("lock") data object Option : Screen("option")
data object Option : Screen("option")
} }
@@ -1,67 +0,0 @@
package com.zaneschepke.wireguardautotunnel.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.zaneschepke.logcatter.LocalLogCollector
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel.Companion.isRunningOnAndroidTv
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import xyz.teamgravity.pin_lock_compose.PinManager
import javax.inject.Inject
@SuppressLint("CustomSplashScreen")
@AndroidEntryPoint
class SplashActivity : ComponentActivity() {
@Inject
lateinit var appStateRepository: AppStateRepository
@Inject
lateinit var localLogCollector: LocalLogCollector
@Inject
@ApplicationScope
lateinit var applicationScope: CoroutineScope
override fun onCreate(savedInstanceState: Bundle?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val splashScreen = installSplashScreen()
splashScreen.setKeepOnScreenCondition { true }
}
super.onCreate(savedInstanceState)
applicationScope.launch {
if (!isRunningOnAndroidTv()) localLogCollector.start()
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
val pinLockEnabled = appStateRepository.isPinLockEnabled()
if (pinLockEnabled) {
PinManager.initialize(WireGuardAutoTunnel.instance)
}
val intent =
Intent(this@SplashActivity, MainActivity::class.java).apply {
putExtra(IS_PIN_LOCK_ENABLED_KEY, pinLockEnabled)
}
startActivity(intent)
finish()
}
}
}
companion object {
const val IS_PIN_LOCK_ENABLED_KEY = "is_pin_lock_enabled"
}
}
@@ -12,25 +12,31 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
@Composable @Composable
fun ClickableIconButton(onClick: () -> Unit, onIconClick: () -> Unit, text: String, icon: ImageVector, enabled: Boolean) { fun ClickableIconButton(
TextButton( onClick: () -> Unit,
onClick = onClick, onIconClick: () -> Unit,
enabled = enabled, text: String,
) { icon: ImageVector,
Text(text, Modifier.weight(1f, false)) enabled: Boolean
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing)) ) {
Icon( TextButton(
imageVector = icon, onClick = onClick,
contentDescription = icon.name, enabled = enabled,
modifier = ) {
Modifier Text(text, Modifier.weight(1f, false))
.size(ButtonDefaults.IconSize) Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
.weight(1f, false) Icon(
.clickable { imageVector = icon,
if (enabled) { contentDescription = icon.name,
onIconClick() modifier =
} Modifier
}, .size(ButtonDefaults.IconSize)
) .weight(1f, false)
} .clickable {
if (enabled) {
onIconClick()
}
},
)
}
} }
@@ -15,85 +15,78 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics import com.wireguard.android.backend.Statistics
import com.zaneschepke.wireguardautotunnel.util.NumberUtils import com.zaneschepke.wireguardautotunnel.util.NumberUtils
import com.zaneschepke.wireguardautotunnel.util.toThreeDecimalPlaceString import com.zaneschepke.wireguardautotunnel.util.toThreeDecimalPlaceString
@OptIn(ExperimentalFoundationApi::class) @OptIn(ExperimentalFoundationApi::class)
@Composable @Composable
fun RowListItem( fun RowListItem(
icon: @Composable () -> Unit, icon: @Composable () -> Unit,
text: String, text: String,
onHold: () -> Unit, onHold: () -> Unit,
onClick: () -> Unit, onClick: () -> Unit,
rowButton: @Composable () -> Unit, rowButton: @Composable () -> Unit,
expanded: Boolean, expanded: Boolean,
statistics: TunnelStatistics?, statistics: Statistics?
focusRequester: FocusRequester,
) { ) {
Box( Box(
modifier = modifier =
Modifier Modifier
.focusRequester(focusRequester) .animateContentSize()
.animateContentSize() .clip(RoundedCornerShape(30.dp))
.clip(RoundedCornerShape(30.dp)) .combinedClickable(
.combinedClickable( onClick = { onClick() },
onClick = { onClick() }, onLongClick = { onHold() },
onLongClick = { onHold() }, ),
), ) {
) { Column {
Column { Row(
Row( modifier = Modifier
modifier = .fillMaxWidth()
Modifier .padding(horizontal = 15.dp, vertical = 5.dp),
.fillMaxWidth() verticalAlignment = Alignment.CenterVertically,
.padding(horizontal = 15.dp, vertical = 5.dp), horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically, ) {
horizontalArrangement = Arrangement.SpaceBetween, Row(
) { verticalAlignment = Alignment.CenterVertically,
Row( ) {
verticalAlignment = Alignment.CenterVertically, icon()
modifier = Modifier.fillMaxWidth(13 / 20f), Text(text)
) { }
icon() rowButton()
Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis) }
} if (expanded) {
rowButton() statistics?.peers()?.forEach {
} Row(
if (expanded) { modifier =
statistics?.getPeers()?.forEach { Modifier
Row( .fillMaxWidth()
modifier = .padding(end = 10.dp, bottom = 10.dp, start = 10.dp),
Modifier verticalAlignment = Alignment.CenterVertically,
.fillMaxWidth() horizontalArrangement = Arrangement.SpaceEvenly,
.padding(end = 10.dp, bottom = 10.dp, start = 10.dp), ) {
verticalAlignment = Alignment.CenterVertically, //TODO change these to string resources
horizontalArrangement = Arrangement.SpaceEvenly, val handshakeEpoch = statistics.peer(it)!!.latestHandshakeEpochMillis
) { val peerTx = statistics.peer(it)!!.txBytes
// TODO change these to string resources val peerRx = statistics.peer(it)!!.rxBytes
val handshakeEpoch = statistics.peerStats(it)!!.latestHandshakeEpochMillis val peerId = it.toBase64().subSequence(0, 3).toString() + "***"
val peerTx = statistics.peerStats(it)!!.txBytes val handshakeSec =
val peerRx = statistics.peerStats(it)!!.rxBytes NumberUtils.getSecondsBetweenTimestampAndNow(handshakeEpoch)
val peerId = it.toBase64().subSequence(0, 3).toString() + "***" val handshake =
val handshakeSec = if (handshakeSec == null) "never" else "$handshakeSec secs ago"
NumberUtils.getSecondsBetweenTimestampAndNow(handshakeEpoch) val peerTxMB = NumberUtils.bytesToMB(peerTx).toThreeDecimalPlaceString()
val handshake = val peerRxMB = NumberUtils.bytesToMB(peerRx).toThreeDecimalPlaceString()
if (handshakeSec == null) "never" else "$handshakeSec secs ago" val fontSize = 9.sp
val peerTxMB = NumberUtils.bytesToMB(peerTx).toThreeDecimalPlaceString() Text("peer: $peerId", fontSize = fontSize)
val peerRxMB = NumberUtils.bytesToMB(peerRx).toThreeDecimalPlaceString() Text("handshake: $handshake", fontSize = fontSize)
val fontSize = 9.sp Text("tx: $peerTxMB MB", fontSize = fontSize)
Text("peer: $peerId", fontSize = fontSize) Text("rx: $peerRxMB MB", fontSize = fontSize)
Text("handshake: $handshake", fontSize = fontSize) }
Text("tx: $peerTxMB MB", fontSize = fontSize) }
Text("rx: $peerRxMB MB", fontSize = fontSize) }
} }
} }
}
}
}
} }
@@ -26,57 +26,55 @@ import com.zaneschepke.wireguardautotunnel.R
@Composable @Composable
fun SearchBar(onQuery: (queryString: String) -> Unit) { fun SearchBar(onQuery: (queryString: String) -> Unit) {
// Immediately update and keep track of query from text field changes. // Immediately update and keep track of query from text field changes.
var query: String by rememberSaveable { mutableStateOf("") } var query: String by rememberSaveable { mutableStateOf("") }
var showClearIcon by rememberSaveable { mutableStateOf(false) } var showClearIcon by rememberSaveable { mutableStateOf(false) }
if (query.isEmpty()) { if (query.isEmpty()) {
showClearIcon = false showClearIcon = false
} else if (query.isNotEmpty()) { } else if (query.isNotEmpty()) {
showClearIcon = true showClearIcon = true
} }
TextField( TextField(
value = query, value = query,
onValueChange = { onQueryChanged -> onValueChange = { onQueryChanged ->
// If user makes changes to text, immediately updated it. // If user makes changes to text, immediately updated it.
query = onQueryChanged query = onQueryChanged
onQuery(onQueryChanged) onQuery(onQueryChanged)
}, },
leadingIcon = { leadingIcon = {
val icon = Icons.Rounded.Search Icon(
Icon( imageVector = Icons.Rounded.Search,
imageVector = icon, tint = MaterialTheme.colorScheme.onBackground,
tint = MaterialTheme.colorScheme.onBackground, contentDescription = stringResource(id = R.string.search_icon),
contentDescription = icon.name, )
) },
}, trailingIcon = {
trailingIcon = { if (showClearIcon) {
if (showClearIcon) { IconButton(onClick = { query = "" }) {
IconButton(onClick = { query = "" }) { Icon(
val icon = Icons.Rounded.Clear imageVector = Icons.Rounded.Clear,
Icon( tint = MaterialTheme.colorScheme.onBackground,
imageVector = icon, contentDescription = stringResource(id = R.string.clear_icon),
tint = MaterialTheme.colorScheme.onBackground, )
contentDescription = icon.name, }
) }
} },
} maxLines = 1,
}, colors =
maxLines = 1, TextFieldDefaults.colors(
colors = focusedContainerColor = Color.Transparent,
TextFieldDefaults.colors( unfocusedContainerColor = Color.Transparent,
focusedContainerColor = Color.Transparent, disabledContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent, ),
disabledContainerColor = Color.Transparent, placeholder = { Text(text = stringResource(R.string.hint_search_packages)) },
), textStyle = MaterialTheme.typography.bodySmall,
placeholder = { Text(text = stringResource(R.string.hint_search_packages)) }, singleLine = true,
textStyle = MaterialTheme.typography.bodySmall, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
singleLine = true, modifier =
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), Modifier
modifier = .fillMaxWidth()
Modifier .background(color = MaterialTheme.colorScheme.background, shape = RectangleShape),
.fillMaxWidth() )
.background(color = MaterialTheme.colorScheme.background, shape = RectangleShape),
)
} }
@@ -11,26 +11,26 @@ import androidx.compose.ui.text.input.KeyboardCapitalization
@Composable @Composable
fun ConfigurationTextBox( fun ConfigurationTextBox(
value: String, value: String,
hint: String, hint: String,
onValueChange: (String) -> Unit, onValueChange: (String) -> Unit,
keyboardActions: KeyboardActions, keyboardActions: KeyboardActions,
label: String, label: String,
modifier: Modifier, modifier: Modifier
) { ) {
OutlinedTextField( OutlinedTextField(
modifier = modifier, modifier = modifier,
value = value, value = value,
singleLine = true, singleLine = true,
onValueChange = { onValueChange(it) }, onValueChange = { onValueChange(it) },
label = { Text(label) }, label = { Text(label) },
maxLines = 1, maxLines = 1,
placeholder = { Text(hint) }, placeholder = { Text(hint) },
keyboardOptions = keyboardOptions =
KeyboardOptions( KeyboardOptions(
capitalization = KeyboardCapitalization.None, capitalization = KeyboardCapitalization.None,
imeAction = ImeAction.Done, imeAction = ImeAction.Done,
), ),
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
) )
} }
@@ -13,31 +13,27 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
@Composable @Composable
fun ConfigurationToggle(label: String, enabled: Boolean, checked: Boolean, padding: Dp, onCheckChanged: () -> Unit, modifier: Modifier = Modifier) { fun ConfigurationToggle(
Row( label: String,
modifier = enabled: Boolean,
Modifier checked: Boolean,
.fillMaxWidth() padding: Dp,
.padding(padding), onCheckChanged: () -> Unit,
verticalAlignment = Alignment.CenterVertically, modifier: Modifier = Modifier
horizontalArrangement = Arrangement.SpaceBetween, ) {
) { Row(
Text( modifier = Modifier
label, .fillMaxWidth()
textAlign = TextAlign.Start, .padding(padding),
modifier = verticalAlignment = Alignment.CenterVertically,
Modifier horizontalArrangement = Arrangement.SpaceBetween,
.weight( ) {
weight = 1.0f, Text(label, textAlign = TextAlign.Start)
fill = false, Switch(
), modifier = modifier,
softWrap = true, enabled = enabled,
) checked = checked,
Switch( onCheckedChange = { onCheckChanged() },
modifier = modifier, )
enabled = enabled, }
checked = checked,
onCheckedChange = { onCheckChanged() },
)
}
} }
@@ -1,37 +0,0 @@
package com.zaneschepke.wireguardautotunnel.ui.common.dialog
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.zaneschepke.wireguardautotunnel.R
@Composable
fun InfoDialog(
onAttest: () -> Unit,
onDismiss: () -> Unit,
title: @Composable () -> Unit,
body: @Composable () -> Unit,
confirmText: @Composable () -> Unit,
) {
AlertDialog(
onDismissRequest = { onDismiss() },
confirmButton = {
TextButton(
onClick = {
onAttest()
},
) {
confirmText()
}
},
dismissButton = {
TextButton(onClick = { onDismiss() }) {
Text(text = stringResource(R.string.cancel))
}
},
title = { title() },
text = { body() },
)
}
@@ -18,42 +18,39 @@ import com.zaneschepke.wireguardautotunnel.ui.Screen
@Composable @Composable
fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavItem>) { fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavItem>) {
val backStackEntry = navController.currentBackStackEntryAsState() val backStackEntry = navController.currentBackStackEntryAsState()
var showBottomBar by rememberSaveable { mutableStateOf(true) } var showBottomBar by rememberSaveable { mutableStateOf(true) }
val navBackStackEntry by navController.currentBackStackEntryAsState() val navBackStackEntry by navController.currentBackStackEntryAsState()
// TODO find a better way to hide nav bar //TODO find a better way to hide nav bar
showBottomBar = showBottomBar = when (navBackStackEntry?.destination?.route) {
when (navBackStackEntry?.destination?.route) { Screen.Lock.route -> false
Screen.Lock.route -> false else -> true
else -> true }
}
NavigationBar( NavigationBar(
containerColor = if (!showBottomBar) Color.Transparent else MaterialTheme.colorScheme.background, containerColor = if (!showBottomBar) Color.Transparent else MaterialTheme.colorScheme.background,
) { ) {
if (showBottomBar) { if (showBottomBar) bottomNavItems.forEach { item ->
bottomNavItems.forEach { item -> val selected = item.route == backStackEntry.value?.destination?.route
val selected = item.route == backStackEntry.value?.destination?.route
NavigationBarItem( NavigationBarItem(
selected = selected, selected = selected,
onClick = { navController.navigate(item.route) }, onClick = { navController.navigate(item.route) },
label = { label = {
Text( Text(
text = item.name, text = item.name,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
) )
}, },
icon = { icon = {
Icon( Icon(
imageVector = item.icon, imageVector = item.icon,
contentDescription = "${item.name} Icon", contentDescription = "${item.name} Icon",
) )
}, },
) )
} }
} }
}
} }
@@ -3,7 +3,7 @@ package com.zaneschepke.wireguardautotunnel.ui.common.navigation
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
data class BottomNavItem( data class BottomNavItem(
val name: String, val name: String,
val route: String, val route: String,
val icon: ImageVector, val icon: ImageVector,
) )
@@ -12,77 +12,78 @@ import androidx.fragment.app.FragmentActivity
@Composable @Composable
fun AuthorizationPrompt(onSuccess: () -> Unit, onFailure: () -> Unit, onError: (String) -> Unit) { fun AuthorizationPrompt(onSuccess: () -> Unit, onFailure: () -> Unit, onError: (String) -> Unit) {
val context = LocalContext.current val context = LocalContext.current
val biometricManager = BiometricManager.from(context) val biometricManager = BiometricManager.from(context)
val bio = biometricManager.canAuthenticate(BIOMETRIC_WEAK or DEVICE_CREDENTIAL) val bio = biometricManager.canAuthenticate(BIOMETRIC_WEAK or DEVICE_CREDENTIAL)
val isBiometricAvailable = val isBiometricAvailable = remember {
remember { when (bio) {
when (bio) { BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> { onError("Biometrics not available")
onError("Biometrics not available") false
false }
}
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> { BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
onError("Biometrics not created") onError("Biometrics not created")
false false
} }
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> { BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
onError("Biometric hardware not found") onError("Biometric hardware not found")
false false
} }
BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> { BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> {
onError("Biometric security update required") onError("Biometric security update required")
false false
} }
BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED -> { BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED -> {
onError("Biometrics not supported") onError("Biometrics not supported")
false false
} }
BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> { BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> {
onError("Biometrics status unknown") onError("Biometrics status unknown")
false false
} }
BiometricManager.BIOMETRIC_SUCCESS -> true BiometricManager.BIOMETRIC_SUCCESS -> true
else -> false else -> false
} }
} }
if (isBiometricAvailable) { if (isBiometricAvailable) {
val executor = remember { ContextCompat.getMainExecutor(context) } val executor = remember { ContextCompat.getMainExecutor(context) }
val promptInfo = val promptInfo =
BiometricPrompt.PromptInfo.Builder() BiometricPrompt.PromptInfo.Builder()
.setAllowedAuthenticators(BIOMETRIC_WEAK or DEVICE_CREDENTIAL) .setAllowedAuthenticators(BIOMETRIC_WEAK or DEVICE_CREDENTIAL)
.setTitle("Biometric Authentication") .setTitle("Biometric Authentication")
.setSubtitle("Log in using your biometric credential") .setSubtitle("Log in using your biometric credential")
.build() .build()
val biometricPrompt = val biometricPrompt =
BiometricPrompt( BiometricPrompt(
context as FragmentActivity, context as FragmentActivity,
executor, executor,
object : BiometricPrompt.AuthenticationCallback() { object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString) super.onAuthenticationError(errorCode, errString)
onFailure() onFailure()
} }
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { override fun onAuthenticationSucceeded(
super.onAuthenticationSucceeded(result) result: BiometricPrompt.AuthenticationResult
onSuccess() ) {
} super.onAuthenticationSucceeded(result)
onSuccess()
}
override fun onAuthenticationFailed() { override fun onAuthenticationFailed() {
super.onAuthenticationFailed() super.onAuthenticationFailed()
onFailure() onFailure()
} }
}, },
) )
biometricPrompt.authenticate(promptInfo) biometricPrompt.authenticate(promptInfo)
} }
} }
@@ -25,37 +25,40 @@ import androidx.compose.ui.unit.dp
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
@Composable @Composable
fun CustomSnackBar(message: String, isRtl: Boolean = true, containerColor: Color = MaterialTheme.colorScheme.surface) { fun CustomSnackBar(
Snackbar( message: String,
containerColor = containerColor, isRtl: Boolean = true,
modifier = containerColor: Color = MaterialTheme.colorScheme.surface
Modifier ) {
.fillMaxWidth( Snackbar(
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) 1 / 3f else 2 / 3f, containerColor = containerColor,
) modifier =
.padding(bottom = 100.dp), Modifier
shape = RoundedCornerShape(16.dp), .fillMaxWidth(
) { if (WireGuardAutoTunnel.isRunningOnAndroidTv()) 1 / 3f else 2 / 3f,
CompositionLocalProvider( )
LocalLayoutDirection provides if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr, .padding(bottom = 100.dp),
) { shape = RoundedCornerShape(16.dp),
Row( ) {
modifier = CompositionLocalProvider(
Modifier LocalLayoutDirection provides if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr,
.width(IntrinsicSize.Max) ) {
.height(IntrinsicSize.Min), Row(
verticalAlignment = Alignment.CenterVertically, modifier = Modifier
horizontalArrangement = Arrangement.Start, .width(IntrinsicSize.Max)
) { .height(IntrinsicSize.Min),
val icon = Icons.Rounded.Info verticalAlignment = Alignment.CenterVertically,
Icon( horizontalArrangement = Arrangement.Start,
icon, ) {
contentDescription = icon.name, val icon = Icons.Rounded.Info
tint = Color.White, Icon(
modifier = Modifier.padding(end = 10.dp), icon,
) contentDescription = icon.name,
Text(message, color = Color.White, modifier = Modifier.padding(end = 5.dp)) tint = Color.White,
} modifier = Modifier.padding(end = 10.dp),
} )
} Text(message, color = Color.White, modifier = Modifier.padding(end = 5.dp))
}
}
}
} }
@@ -13,15 +13,14 @@ import androidx.compose.ui.unit.dp
@Composable @Composable
fun LoadingScreen() { fun LoadingScreen() {
Column( Column(
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top, verticalArrangement = Arrangement.Top,
modifier = modifier = Modifier
Modifier .fillMaxSize()
.fillMaxSize() .focusable()
.focusable() .padding(),
.padding(), ) {
) { Column(modifier = Modifier.padding(120.dp)) { CircularProgressIndicator() }
Column(modifier = Modifier.padding(120.dp)) { CircularProgressIndicator() } }
}
} }
@@ -13,14 +13,13 @@ import androidx.compose.ui.unit.dp
@Composable @Composable
fun LogTypeLabel(color: Color, content: @Composable () -> Unit) { fun LogTypeLabel(color: Color, content: @Composable () -> Unit) {
Box( Box(
modifier = modifier = Modifier
Modifier .size(20.dp)
.size(20.dp) .clip(RoundedCornerShape(2.dp))
.clip(RoundedCornerShape(2.dp)) .background(color),
.background(color), contentAlignment = Alignment.Center,
contentAlignment = Alignment.Center, ) {
) { content()
content() }
}
} }
@@ -13,10 +13,10 @@ import androidx.compose.ui.unit.sp
@Composable @Composable
fun SectionTitle(title: String, padding: Dp) { fun SectionTitle(title: String, padding: Dp) {
Text( Text(
title, title,
textAlign = TextAlign.Start, textAlign = TextAlign.Start,
style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.ExtraBold), style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.ExtraBold),
modifier = Modifier.padding(padding, bottom = 5.dp, top = 5.dp), modifier = Modifier.padding(padding, bottom = 5.dp, top = 5.dp),
) )
} }
@@ -0,0 +1,30 @@
package com.zaneschepke.wireguardautotunnel.ui.models
import com.wireguard.config.Interface
data class InterfaceProxy(
var privateKey: String = "",
var publicKey: String = "",
var addresses: String = "",
var dnsServers: String = "",
var listenPort: String = "",
var mtu: String = ""
) {
companion object {
fun from(i: Interface): InterfaceProxy {
return InterfaceProxy(
publicKey = i.keyPair.publicKey.toBase64().trim(),
privateKey = i.keyPair.privateKey.toBase64().trim(),
addresses = i.addresses.joinToString(", ").trim(),
dnsServers = i.dnsServers.joinToString(", ").replace("/", "").trim(),
listenPort =
if (i.listenPort.isPresent) {
i.listenPort.get().toString().trim()
} else {
""
},
mtu = if (i.mtu.isPresent) i.mtu.get().toString().trim() else "",
)
}
}
}
@@ -0,0 +1,73 @@
package com.zaneschepke.wireguardautotunnel.ui.models
import com.wireguard.config.Peer
data class PeerProxy(
var publicKey: String = "",
var preSharedKey: String = "",
var persistentKeepalive: String = "",
var endpoint: String = "",
var allowedIps: String = IPV4_WILDCARD.joinToString(", ").trim()
) {
companion object {
fun from(peer: Peer): PeerProxy {
return PeerProxy(
publicKey = peer.publicKey.toBase64(),
preSharedKey =
if (peer.preSharedKey.isPresent) {
peer.preSharedKey.get().toBase64().trim()
} else {
""
},
persistentKeepalive =
if (peer.persistentKeepalive.isPresent) {
peer.persistentKeepalive.get().toString().trim()
} else {
""
},
endpoint =
if (peer.endpoint.isPresent) {
peer.endpoint.get().toString().trim()
} else {
""
},
allowedIps = peer.allowedIps.joinToString(", ").trim(),
)
}
val IPV4_PUBLIC_NETWORKS =
setOf(
"0.0.0.0/5",
"8.0.0.0/7",
"11.0.0.0/8",
"12.0.0.0/6",
"16.0.0.0/4",
"32.0.0.0/3",
"64.0.0.0/2",
"128.0.0.0/3",
"160.0.0.0/5",
"168.0.0.0/6",
"172.0.0.0/12",
"172.32.0.0/11",
"172.64.0.0/10",
"172.128.0.0/9",
"173.0.0.0/8",
"174.0.0.0/7",
"176.0.0.0/4",
"192.0.0.0/9",
"192.128.0.0/11",
"192.160.0.0/13",
"192.169.0.0/16",
"192.170.0.0/15",
"192.172.0.0/14",
"192.176.0.0/12",
"192.192.0.0/10",
"193.0.0.0/8",
"194.0.0.0/7",
"196.0.0.0/6",
"200.0.0.0/5",
"208.0.0.0/4",
)
val IPV4_WILDCARD = setOf("0.0.0.0/0")
}
}
@@ -1,73 +1,18 @@
package com.zaneschepke.wireguardautotunnel.ui.screens.config package com.zaneschepke.wireguardautotunnel.ui.screens.config
import com.wireguard.config.Config import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.ui.models.InterfaceProxy
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.InterfaceProxy import com.zaneschepke.wireguardautotunnel.ui.models.PeerProxy
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.PeerProxy
import com.zaneschepke.wireguardautotunnel.util.Packages import com.zaneschepke.wireguardautotunnel.util.Packages
data class ConfigUiState( data class ConfigUiState(
val proxyPeers: List<PeerProxy> = arrayListOf(PeerProxy()), val proxyPeers: List<PeerProxy> = arrayListOf(PeerProxy()),
val interfaceProxy: InterfaceProxy = InterfaceProxy(), val interfaceProxy: InterfaceProxy = InterfaceProxy(),
val packages: Packages = emptyList(), val packages: Packages = emptyList(),
val checkedPackageNames: List<String> = emptyList(), val checkedPackageNames: List<String> = emptyList(),
val include: Boolean = true, val include: Boolean = true,
val isAllApplicationsEnabled: Boolean = false, val isAllApplicationsEnabled: Boolean = false,
val loading: Boolean = true, val loading: Boolean = true,
val tunnel: TunnelConfig? = null, val tunnel: TunnelConfig? = null,
val tunnelName: String = "", val tunnelName: String = ""
val isAmneziaEnabled: Boolean = false, )
) {
companion object {
fun from(config: Config): ConfigUiState {
val proxyPeers = config.peers.map { PeerProxy.from(it) }
val proxyInterface = InterfaceProxy.from(config.`interface`)
var include = true
var isAllApplicationsEnabled = false
val checkedPackages =
if (config.`interface`.includedApplications.isNotEmpty()) {
config.`interface`.includedApplications
} else if (config.`interface`.excludedApplications.isNotEmpty()) {
include = false
config.`interface`.excludedApplications
} else {
isAllApplicationsEnabled = true
emptySet()
}
return ConfigUiState(
proxyPeers,
proxyInterface,
emptyList(),
checkedPackages.toList(),
include,
isAllApplicationsEnabled,
)
}
fun from(config: org.amnezia.awg.config.Config): ConfigUiState {
// TODO update with new values
val proxyPeers = config.peers.map { PeerProxy.from(it) }
val proxyInterface = InterfaceProxy.from(config.`interface`)
var include = true
var isAllApplicationsEnabled = false
val checkedPackages =
if (config.`interface`.includedApplications.isNotEmpty()) {
config.`interface`.includedApplications
} else if (config.`interface`.excludedApplications.isNotEmpty()) {
include = false
config.`interface`.excludedApplications
} else {
isAllApplicationsEnabled = true
emptySet()
}
return ConfigUiState(
proxyPeers,
proxyInterface,
emptyList(),
checkedPackages.toList(),
include,
isAllApplicationsEnabled,
)
}
}
}
@@ -1,6 +1,7 @@
package com.zaneschepke.wireguardautotunnel.ui.screens.config package com.zaneschepke.wireguardautotunnel.ui.screens.config
import android.Manifest import android.Manifest
import android.app.Application
import android.content.pm.PackageInfo import android.content.pm.PackageInfo
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Build import android.os.Build
@@ -11,25 +12,21 @@ import com.wireguard.config.Interface
import com.wireguard.config.Peer import com.wireguard.config.Peer
import com.wireguard.crypto.Key import com.wireguard.crypto.Key
import com.wireguard.crypto.KeyPair import com.wireguard.crypto.KeyPair
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository import com.zaneschepke.wireguardautotunnel.ui.models.InterfaceProxy
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher import com.zaneschepke.wireguardautotunnel.ui.models.PeerProxy
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.PeerProxy
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.Event
import com.zaneschepke.wireguardautotunnel.util.NumberUtils import com.zaneschepke.wireguardautotunnel.util.NumberUtils
import com.zaneschepke.wireguardautotunnel.util.StringValue import com.zaneschepke.wireguardautotunnel.util.Result
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
import com.zaneschepke.wireguardautotunnel.util.removeAt import com.zaneschepke.wireguardautotunnel.util.removeAt
import com.zaneschepke.wireguardautotunnel.util.update import com.zaneschepke.wireguardautotunnel.util.update
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers
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.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@@ -38,529 +35,315 @@ import javax.inject.Inject
class ConfigViewModel class ConfigViewModel
@Inject @Inject
constructor( constructor(
private val settingsRepository: SettingsRepository, private val application: Application,
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : ViewModel() { ) : ViewModel() {
private val packageManager = WireGuardAutoTunnel.instance.packageManager
private val _uiState = MutableStateFlow(ConfigUiState()) private val packageManager = application.packageManager
val uiState = _uiState.asStateFlow()
fun init(tunnelId: String) = viewModelScope.launch(ioDispatcher) { private val _uiState = MutableStateFlow(ConfigUiState())
val packages = getQueriedPackages("") val uiState = _uiState.asStateFlow()
val state =
if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) {
val tunnelConfig =
appDataRepository.tunnels.getAll()
.firstOrNull { it.id.toString() == tunnelId }
val isAmneziaEnabled = settingsRepository.getSettings().isAmneziaEnabled
if (tunnelConfig != null) {
(
if (isAmneziaEnabled) {
val amConfig =
if (tunnelConfig.amQuick == "") tunnelConfig.wgQuick else tunnelConfig.amQuick
ConfigUiState.from(TunnelConfig.configFromAmQuick(amConfig))
} else {
ConfigUiState.from(
TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick),
)
}
).copy(
packages = packages,
loading = false,
tunnel = tunnelConfig,
tunnelName = tunnelConfig.name,
isAmneziaEnabled = isAmneziaEnabled,
)
} else {
ConfigUiState(loading = false, packages = packages)
}
} else {
ConfigUiState(loading = false, packages = packages)
}
_uiState.value = state
}
fun onTunnelNameChange(name: String) { fun init(tunnelId: String) =
_uiState.value = _uiState.value.copy(tunnelName = name) viewModelScope.launch(Dispatchers.IO) {
} val packages = getQueriedPackages("")
val state =
if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) {
val tunnelConfig =
appDataRepository.tunnels.getAll()
.firstOrNull { it.id.toString() == tunnelId }
if (tunnelConfig != null) {
val config = TunnelConfig.configFromQuick(tunnelConfig.wgQuick)
val proxyPeers = config.peers.map { PeerProxy.from(it) }
val proxyInterface = InterfaceProxy.from(config.`interface`)
var include = true
var isAllApplicationsEnabled = false
val checkedPackages =
if (config.`interface`.includedApplications.isNotEmpty()) {
config.`interface`.includedApplications
} else if (config.`interface`.excludedApplications.isNotEmpty()) {
include = false
config.`interface`.excludedApplications
} else {
isAllApplicationsEnabled = true
emptySet()
}
ConfigUiState(
proxyPeers,
proxyInterface,
packages,
checkedPackages.toList(),
include,
isAllApplicationsEnabled,
false,
tunnelConfig,
tunnelConfig.name,
)
} else {
ConfigUiState(loading = false, packages = packages)
}
} else {
ConfigUiState(loading = false, packages = packages)
}
_uiState.value = state
}
fun onIncludeChange(include: Boolean) { fun onTunnelNameChange(name: String) {
_uiState.value = _uiState.value.copy(include = include) _uiState.value = _uiState.value.copy(tunnelName = name)
} }
fun onAddCheckedPackage(packageName: String) { fun onIncludeChange(include: Boolean) {
_uiState.value = _uiState.value = _uiState.value.copy(include = include)
_uiState.value.copy( }
checkedPackageNames = _uiState.value.checkedPackageNames + packageName,
)
}
fun onAllApplicationsChange(isAllApplicationsEnabled: Boolean) { fun onAddCheckedPackage(packageName: String) {
_uiState.value = _uiState.value.copy(isAllApplicationsEnabled = isAllApplicationsEnabled) _uiState.value =
} _uiState.value.copy(
checkedPackageNames = _uiState.value.checkedPackageNames + packageName,
)
}
fun onRemoveCheckedPackage(packageName: String) { fun onAllApplicationsChange(isAllApplicationsEnabled: Boolean) {
_uiState.value = _uiState.value = _uiState.value.copy(isAllApplicationsEnabled = isAllApplicationsEnabled)
_uiState.value.copy( }
checkedPackageNames = _uiState.value.checkedPackageNames - packageName,
)
}
private fun getQueriedPackages(query: String): List<PackageInfo> { fun onRemoveCheckedPackage(packageName: String) {
return getAllInternetCapablePackages().filter { _uiState.value =
getPackageLabel(it).lowercase().contains(query.lowercase()) _uiState.value.copy(
} checkedPackageNames = _uiState.value.checkedPackageNames - packageName,
} )
}
fun getPackageLabel(packageInfo: PackageInfo): String { private fun getQueriedPackages(query: String): List<PackageInfo> {
return packageInfo.applicationInfo?.loadLabel(packageManager).toString() return getAllInternetCapablePackages().filter {
} getPackageLabel(it).lowercase().contains(query.lowercase())
}
}
private fun getAllInternetCapablePackages(): List<PackageInfo> { fun getPackageLabel(packageInfo: PackageInfo): String {
return getPackagesHoldingPermissions(arrayOf(Manifest.permission.INTERNET)) return packageInfo.applicationInfo.loadLabel(application.packageManager).toString()
} }
private fun getPackagesHoldingPermissions(permissions: Array<String>): List<PackageInfo> { private fun getAllInternetCapablePackages(): List<PackageInfo> {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { return getPackagesHoldingPermissions(arrayOf(Manifest.permission.INTERNET))
packageManager.getPackagesHoldingPermissions( }
permissions,
PackageManager.PackageInfoFlags.of(0L),
)
} else {
packageManager.getPackagesHoldingPermissions(permissions, 0)
}
}
private fun isAllApplicationsEnabled(): Boolean { private fun getPackagesHoldingPermissions(permissions: Array<String>): List<PackageInfo> {
return _uiState.value.isAllApplicationsEnabled return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
} packageManager.getPackagesHoldingPermissions(
permissions,
PackageManager.PackageInfoFlags.of(0L),
)
} else {
packageManager.getPackagesHoldingPermissions(permissions, 0)
}
}
private fun saveConfig(tunnelConfig: TunnelConfig) = viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) } private fun isAllApplicationsEnabled(): Boolean {
return _uiState.value.isAllApplicationsEnabled
}
private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) = viewModelScope.launch { private fun saveConfig(tunnelConfig: TunnelConfig) =
if (tunnelConfig != null) { viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) }
saveConfig(tunnelConfig).join()
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
}
}
private fun buildPeerListFromProxyPeers(): List<Peer> { private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) =
return _uiState.value.proxyPeers.map { viewModelScope.launch {
val builder = Peer.Builder() if (tunnelConfig != null) {
if (it.allowedIps.isNotEmpty()) builder.parseAllowedIPs(it.allowedIps.trim()) saveConfig(tunnelConfig).join()
if (it.publicKey.isNotEmpty()) builder.parsePublicKey(it.publicKey.trim()) WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate(application)
if (it.preSharedKey.isNotEmpty()) builder.parsePreSharedKey(it.preSharedKey.trim()) }
if (it.endpoint.isNotEmpty()) builder.parseEndpoint(it.endpoint.trim()) }
if (it.persistentKeepalive.isNotEmpty()) {
builder.parsePersistentKeepalive(it.persistentKeepalive.trim())
}
builder.build()
}
}
private fun buildAmPeerListFromProxyPeers(): List<org.amnezia.awg.config.Peer> { private fun buildPeerListFromProxyPeers(): List<Peer> {
return _uiState.value.proxyPeers.map { return _uiState.value.proxyPeers.map {
val builder = org.amnezia.awg.config.Peer.Builder() val builder = Peer.Builder()
if (it.allowedIps.isNotEmpty()) builder.parseAllowedIPs(it.allowedIps.trim()) if (it.allowedIps.isNotEmpty()) builder.parseAllowedIPs(it.allowedIps.trim())
if (it.publicKey.isNotEmpty()) builder.parsePublicKey(it.publicKey.trim()) if (it.publicKey.isNotEmpty()) builder.parsePublicKey(it.publicKey.trim())
if (it.preSharedKey.isNotEmpty()) builder.parsePreSharedKey(it.preSharedKey.trim()) if (it.preSharedKey.isNotEmpty()) builder.parsePreSharedKey(it.preSharedKey.trim())
if (it.endpoint.isNotEmpty()) builder.parseEndpoint(it.endpoint.trim()) if (it.endpoint.isNotEmpty()) builder.parseEndpoint(it.endpoint.trim())
if (it.persistentKeepalive.isNotEmpty()) { if (it.persistentKeepalive.isNotEmpty()) {
builder.parsePersistentKeepalive(it.persistentKeepalive.trim()) builder.parsePersistentKeepalive(it.persistentKeepalive.trim())
} }
builder.build() builder.build()
} }
} }
private fun emptyCheckedPackagesList() { private fun emptyCheckedPackagesList() {
_uiState.value = _uiState.value.copy(checkedPackageNames = emptyList()) _uiState.value = _uiState.value.copy(checkedPackageNames = emptyList())
} }
private fun buildInterfaceListFromProxyInterface(): Interface { private fun buildInterfaceListFromProxyInterface(): Interface {
val builder = Interface.Builder() val builder = Interface.Builder()
builder.parsePrivateKey(_uiState.value.interfaceProxy.privateKey.trim()) builder.parsePrivateKey(_uiState.value.interfaceProxy.privateKey.trim())
builder.parseAddresses(_uiState.value.interfaceProxy.addresses.trim()) builder.parseAddresses(_uiState.value.interfaceProxy.addresses.trim())
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) { if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) {
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim()) builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim())
} }
if (_uiState.value.interfaceProxy.mtu.isNotEmpty()) { if (_uiState.value.interfaceProxy.mtu.isNotEmpty())
builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim()) builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim())
} if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) { builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim()) }
} if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
if (isAllApplicationsEnabled()) emptyCheckedPackagesList() if (_uiState.value.include) builder.includeApplications(_uiState.value.checkedPackageNames)
if (_uiState.value.include) { if (!_uiState.value.include) builder.excludeApplications(_uiState.value.checkedPackageNames)
builder.includeApplications( return builder.build()
_uiState.value.checkedPackageNames, }
)
}
if (!_uiState.value.include) {
builder.excludeApplications(
_uiState.value.checkedPackageNames,
)
}
return builder.build()
}
private fun buildAmInterfaceListFromProxyInterface(): org.amnezia.awg.config.Interface { fun onSaveAllChanges(): Result<Event> {
val builder = org.amnezia.awg.config.Interface.Builder() return try {
builder.parsePrivateKey(_uiState.value.interfaceProxy.privateKey.trim()) val peerList = buildPeerListFromProxyPeers()
builder.parseAddresses(_uiState.value.interfaceProxy.addresses.trim()) val wgInterface = buildInterfaceListFromProxyInterface()
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) { val config = Config.Builder().addPeers(peerList).setInterface(wgInterface).build()
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim()) val tunnelConfig = when (uiState.value.tunnel) {
} null -> TunnelConfig(
if (_uiState.value.interfaceProxy.mtu.isNotEmpty()) { name = _uiState.value.tunnelName,
builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim()) wgQuick = config.toWgQuickString(),
} )
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
}
if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
if (_uiState.value.include) {
builder.includeApplications(
_uiState.value.checkedPackageNames,
)
}
if (!_uiState.value.include) {
builder.excludeApplications(
_uiState.value.checkedPackageNames,
)
}
if (_uiState.value.interfaceProxy.junkPacketCount.isNotEmpty()) {
builder.setJunkPacketCount(
_uiState.value.interfaceProxy.junkPacketCount.trim().toInt(),
)
}
if (_uiState.value.interfaceProxy.junkPacketMinSize.isNotEmpty()) {
builder.setJunkPacketMinSize(
_uiState.value.interfaceProxy.junkPacketMinSize.trim().toInt(),
)
}
if (_uiState.value.interfaceProxy.junkPacketMaxSize.isNotEmpty()) {
builder.setJunkPacketMaxSize(
_uiState.value.interfaceProxy.junkPacketMaxSize.trim().toInt(),
)
}
if (_uiState.value.interfaceProxy.initPacketJunkSize.isNotEmpty()) {
builder.setInitPacketJunkSize(
_uiState.value.interfaceProxy.initPacketJunkSize.trim().toInt(),
)
}
if (_uiState.value.interfaceProxy.responsePacketJunkSize.isNotEmpty()) {
builder.setResponsePacketJunkSize(
_uiState.value.interfaceProxy.responsePacketJunkSize.trim().toInt(),
)
}
if (_uiState.value.interfaceProxy.initPacketMagicHeader.isNotEmpty()) {
builder.setInitPacketMagicHeader(
_uiState.value.interfaceProxy.initPacketMagicHeader.trim().toLong(),
)
}
if (_uiState.value.interfaceProxy.responsePacketMagicHeader.isNotEmpty()) {
builder.setResponsePacketMagicHeader(
_uiState.value.interfaceProxy.responsePacketMagicHeader.trim().toLong(),
)
}
if (_uiState.value.interfaceProxy.transportPacketMagicHeader.isNotEmpty()) {
builder.setTransportPacketMagicHeader(
_uiState.value.interfaceProxy.transportPacketMagicHeader.trim().toLong(),
)
}
if (_uiState.value.interfaceProxy.underloadPacketMagicHeader.isNotEmpty()) {
builder.setUnderloadPacketMagicHeader(
_uiState.value.interfaceProxy.underloadPacketMagicHeader.trim().toLong(),
)
}
return builder.build()
}
private fun buildConfig(): Config { else -> uiState.value.tunnel!!.copy(
val peerList = buildPeerListFromProxyPeers() name = _uiState.value.tunnelName,
val wgInterface = buildInterfaceListFromProxyInterface() wgQuick = config.toWgQuickString(),
return Config.Builder().addPeers(peerList).setInterface(wgInterface).build() )
} }
updateTunnelConfig(tunnelConfig)
Result.Success(Event.Message.ConfigSaved)
} catch (e: Exception) {
Timber.e(e)
val message = e.message?.substringAfter(":", missingDelimiterValue = "")
Result.Error(Event.Error.ConfigParseError(message ?: ""))
}
}
private fun buildAmConfig(): org.amnezia.awg.config.Config { fun onPeerPublicKeyChange(index: Int, value: String) {
val peerList = buildAmPeerListFromProxyPeers() _uiState.value =
val amInterface = buildAmInterfaceListFromProxyInterface() _uiState.value.copy(
return org.amnezia.awg.config.Config.Builder().addPeers( proxyPeers =
peerList, _uiState.value.proxyPeers.update(
).setInterface(amInterface) index,
.build() _uiState.value.proxyPeers[index].copy(publicKey = value),
} ),
)
}
fun onSaveAllChanges(configType: ConfigType): Result<Unit> { fun onPreSharedKeyChange(index: Int, value: String) {
return try { _uiState.value =
val wgQuick = buildConfig().toWgQuickString() _uiState.value.copy(
val amQuick = proxyPeers =
if (configType == ConfigType.AMNEZIA) { _uiState.value.proxyPeers.update(
buildAmConfig().toAwgQuickString() index,
} else { _uiState.value.proxyPeers[index].copy(preSharedKey = value),
TunnelConfig.AM_QUICK_DEFAULT ),
} )
val tunnelConfig = }
when (uiState.value.tunnel) {
null ->
TunnelConfig(
name = _uiState.value.tunnelName,
wgQuick = wgQuick,
amQuick = amQuick,
)
else -> fun onEndpointChange(index: Int, value: String) {
uiState.value.tunnel!!.copy( _uiState.value =
name = _uiState.value.tunnelName, _uiState.value.copy(
wgQuick = wgQuick, proxyPeers =
amQuick = amQuick, _uiState.value.proxyPeers.update(
) index,
} _uiState.value.proxyPeers[index].copy(endpoint = value),
updateTunnelConfig(tunnelConfig) ),
Result.success(Unit) )
} catch (e: Exception) { }
Timber.e(e)
val message = e.message?.substringAfter(":", missingDelimiterValue = "")
val stringValue =
message?.let {
StringValue.DynamicString(message)
} ?: StringValue.StringResource(R.string.unknown_error)
Result.failure(WgTunnelExceptions.ConfigParseError(stringValue))
}
}
fun onPeerPublicKeyChange(index: Int, value: String) { fun onAllowedIpsChange(index: Int, value: String) {
_uiState.update { _uiState.value =
it.copy( _uiState.value.copy(
proxyPeers = proxyPeers =
_uiState.value.proxyPeers.update( _uiState.value.proxyPeers.update(
index, index,
_uiState.value.proxyPeers[index].copy(publicKey = value), _uiState.value.proxyPeers[index].copy(allowedIps = value),
), ),
) )
} }
}
fun onPreSharedKeyChange(index: Int, value: String) { fun onPersistentKeepaliveChanged(index: Int, value: String) {
_uiState.update { _uiState.value =
it.copy( _uiState.value.copy(
proxyPeers = proxyPeers =
_uiState.value.proxyPeers.update( _uiState.value.proxyPeers.update(
index, index,
_uiState.value.proxyPeers[index].copy(preSharedKey = value), _uiState.value.proxyPeers[index].copy(persistentKeepalive = value),
), ),
) )
} }
}
fun onEndpointChange(index: Int, value: String) { fun onDeletePeer(index: Int) {
_uiState.update { _uiState.value =
it.copy( _uiState.value.copy(
proxyPeers = proxyPeers = _uiState.value.proxyPeers.removeAt(index),
_uiState.value.proxyPeers.update( )
index, }
_uiState.value.proxyPeers[index].copy(endpoint = value),
),
)
}
}
fun onAllowedIpsChange(index: Int, value: String) { fun addEmptyPeer() {
_uiState.update { _uiState.value = _uiState.value.copy(proxyPeers = _uiState.value.proxyPeers + PeerProxy())
it.copy( }
proxyPeers =
_uiState.value.proxyPeers.update(
index,
_uiState.value.proxyPeers[index].copy(allowedIps = value),
),
)
}
}
fun onPersistentKeepaliveChanged(index: Int, value: String) { fun generateKeyPair() {
_uiState.update { val keyPair = KeyPair()
it.copy( _uiState.value =
proxyPeers = _uiState.value.copy(
_uiState.value.proxyPeers.update( interfaceProxy =
index, _uiState.value.interfaceProxy.copy(
_uiState.value.proxyPeers[index].copy(persistentKeepalive = value), privateKey = keyPair.privateKey.toBase64(),
), publicKey = keyPair.publicKey.toBase64(),
) ),
} )
} }
fun onDeletePeer(index: Int) { fun onAddressesChanged(value: String) {
_uiState.update { _uiState.value =
it.copy( _uiState.value.copy(
proxyPeers = _uiState.value.proxyPeers.removeAt(index), interfaceProxy = _uiState.value.interfaceProxy.copy(addresses = value),
) )
} }
}
fun addEmptyPeer() { fun onListenPortChanged(value: String) {
_uiState.update { _uiState.value =
it.copy(proxyPeers = _uiState.value.proxyPeers + PeerProxy()) _uiState.value.copy(
} interfaceProxy = _uiState.value.interfaceProxy.copy(listenPort = value),
} )
}
fun generateKeyPair() { fun onDnsServersChanged(value: String) {
val keyPair = KeyPair() _uiState.value =
_uiState.update { _uiState.value.copy(
it.copy( interfaceProxy = _uiState.value.interfaceProxy.copy(dnsServers = value),
interfaceProxy = )
_uiState.value.interfaceProxy.copy( }
privateKey = keyPair.privateKey.toBase64(),
publicKey = keyPair.publicKey.toBase64(),
),
)
}
}
fun onAddressesChanged(value: String) { fun onMtuChanged(value: String) {
_uiState.update { _uiState.value =
it.copy( _uiState.value.copy(interfaceProxy = _uiState.value.interfaceProxy.copy(mtu = value))
interfaceProxy = _uiState.value.interfaceProxy.copy(addresses = value), }
)
}
}
fun onListenPortChanged(value: String) { private fun onInterfacePublicKeyChange(value: String) {
_uiState.update { _uiState.value =
it.copy( _uiState.value.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(listenPort = value), interfaceProxy = _uiState.value.interfaceProxy.copy(publicKey = value),
) )
} }
}
fun onDnsServersChanged(value: String) { fun onPrivateKeyChange(value: String) {
_uiState.update { _uiState.value =
it.copy( _uiState.value.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(dnsServers = value), interfaceProxy = _uiState.value.interfaceProxy.copy(privateKey = value),
) )
} if (NumberUtils.isValidKey(value)) {
} val pair = KeyPair(Key.fromBase64(value))
onInterfacePublicKeyChange(pair.publicKey.toBase64())
} else {
onInterfacePublicKeyChange("")
}
}
fun onMtuChanged(value: String) { fun emitQueriedPackages(query: String) {
_uiState.update { val packages =
it.copy(interfaceProxy = _uiState.value.interfaceProxy.copy(mtu = value)) getAllInternetCapablePackages().filter {
} getPackageLabel(it).lowercase().contains(query.lowercase())
} }
_uiState.value = _uiState.value.copy(packages = packages)
private fun onInterfacePublicKeyChange(value: String) { }
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(publicKey = value),
)
}
}
fun onPrivateKeyChange(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(privateKey = value),
)
}
if (NumberUtils.isValidKey(value)) {
val pair = KeyPair(Key.fromBase64(value))
onInterfacePublicKeyChange(pair.publicKey.toBase64())
} else {
onInterfacePublicKeyChange("")
}
}
fun emitQueriedPackages(query: String) {
val packages =
getAllInternetCapablePackages().filter {
getPackageLabel(it).lowercase().contains(query.lowercase())
}
_uiState.update { it.copy(packages = packages) }
}
fun onJunkPacketCountChanged(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(junkPacketCount = value),
)
}
}
fun onJunkPacketMinSizeChanged(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(junkPacketMinSize = value),
)
}
}
fun onJunkPacketMaxSizeChanged(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(junkPacketMaxSize = value),
)
}
}
fun onInitPacketJunkSizeChanged(value: String) {
_uiState.update {
it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(initPacketJunkSize = value),
)
}
}
fun onResponsePacketJunkSize(value: String) {
_uiState.update {
it.copy(
interfaceProxy =
_uiState.value.interfaceProxy.copy(
responsePacketJunkSize = value,
),
)
}
}
fun onInitPacketMagicHeader(value: String) {
_uiState.update {
it.copy(
interfaceProxy =
_uiState.value.interfaceProxy.copy(
initPacketMagicHeader = value,
),
)
}
}
fun onResponsePacketMagicHeader(value: String) {
_uiState.update {
it.copy(
interfaceProxy =
_uiState.value.interfaceProxy.copy(
responsePacketMagicHeader = value,
),
)
}
}
fun onTransportPacketMagicHeader(value: String) {
_uiState.update {
it.copy(
interfaceProxy =
_uiState.value.interfaceProxy.copy(
transportPacketMagicHeader = value,
),
)
}
}
fun onUnderloadPacketMagicHeader(value: String) {
_uiState.update {
it.copy(
interfaceProxy =
_uiState.value.interfaceProxy.copy(
underloadPacketMagicHeader = value,
),
)
}
}
} }
@@ -1,118 +0,0 @@
package com.zaneschepke.wireguardautotunnel.ui.screens.config.model
import com.wireguard.config.Interface
data class InterfaceProxy(
val privateKey: String = "",
val publicKey: String = "",
val addresses: String = "",
val dnsServers: String = "",
val listenPort: String = "",
val mtu: String = "",
val junkPacketCount: String = "",
val junkPacketMinSize: String = "",
val junkPacketMaxSize: String = "",
val initPacketJunkSize: String = "",
val responsePacketJunkSize: String = "",
val initPacketMagicHeader: String = "",
val responsePacketMagicHeader: String = "",
val underloadPacketMagicHeader: String = "",
val transportPacketMagicHeader: String = "",
) {
companion object {
fun from(i: Interface): InterfaceProxy {
return InterfaceProxy(
publicKey = i.keyPair.publicKey.toBase64().trim(),
privateKey = i.keyPair.privateKey.toBase64().trim(),
addresses = i.addresses.joinToString(", ").trim(),
dnsServers = i.dnsServers.joinToString(", ").replace("/", "").trim(),
listenPort =
if (i.listenPort.isPresent) {
i.listenPort.get().toString().trim()
} else {
""
},
mtu = if (i.mtu.isPresent) i.mtu.get().toString().trim() else "",
)
}
fun from(i: org.amnezia.awg.config.Interface): InterfaceProxy {
return InterfaceProxy(
publicKey = i.keyPair.publicKey.toBase64().trim(),
privateKey = i.keyPair.privateKey.toBase64().trim(),
addresses = i.addresses.joinToString(", ").trim(),
dnsServers = i.dnsServers.joinToString(", ").replace("/", "").trim(),
listenPort =
if (i.listenPort.isPresent) {
i.listenPort.get().toString().trim()
} else {
""
},
mtu = if (i.mtu.isPresent) i.mtu.get().toString().trim() else "",
junkPacketCount =
if (i.junkPacketCount.isPresent) {
i.junkPacketCount.get()
.toString()
} else {
""
},
junkPacketMinSize =
if (i.junkPacketMinSize.isPresent) {
i.junkPacketMinSize.get()
.toString()
} else {
""
},
junkPacketMaxSize =
if (i.junkPacketMaxSize.isPresent) {
i.junkPacketMaxSize.get()
.toString()
} else {
""
},
initPacketJunkSize =
if (i.initPacketJunkSize.isPresent) {
i.initPacketJunkSize.get()
.toString()
} else {
""
},
responsePacketJunkSize =
if (i.responsePacketJunkSize.isPresent) {
i.responsePacketJunkSize.get()
.toString()
} else {
""
},
initPacketMagicHeader =
if (i.initPacketMagicHeader.isPresent) {
i.initPacketMagicHeader.get()
.toString()
} else {
""
},
responsePacketMagicHeader =
if (i.responsePacketMagicHeader.isPresent) {
i.responsePacketMagicHeader.get()
.toString()
} else {
""
},
transportPacketMagicHeader =
if (i.transportPacketMagicHeader.isPresent) {
i.transportPacketMagicHeader.get()
.toString()
} else {
""
},
underloadPacketMagicHeader =
if (i.underloadPacketMagicHeader.isPresent) {
i.underloadPacketMagicHeader.get()
.toString()
} else {
""
},
)
}
}
}

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