Compare commits

...

38 Commits

Author SHA1 Message Date
dependabot[bot] 19961ca343 build(deps): bump actions/upload-artifact from 4.3.5 to 4.3.6 (#308)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-08 07:51:05 -04:00
dependabot[bot] 6c007a8ca8 build(deps): bump actions/upload-artifact from 4.3.4 to 4.3.5 (#302)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-05 16:51:41 -04:00
Zane Schepke 8e6a9bb309 fix: remove old nightly versions (#295) 2024-07-31 00:00:14 -04:00
Zane Schepke 594834a908 fix: tasker launch of shortcuts (#290) 2024-07-29 17:14:08 -04:00
Zane Schepke a5e9aa83b8 feat: check for always-on VPN (#289) 2024-07-28 22:21:32 -04:00
Languages add-on 5a77661fb3 Added translation using Weblate (Ukrainian) 2024-07-28 15:37:44 -04:00
Luiz Fellipe Carneiro ee5d3ea6a9 Translated using Weblate (Portuguese)
Currently translated at 18.5% (5 of 27 strings)

Translation: WG Tunnel/fastlane
Translate-URL: https://hosted.weblate.org/projects/wg-tunnel/fastlane/pt/
2024-07-28 15:37:06 -04:00
Languages add-on f6da0fe31b Added translation using Weblate (Portuguese) 2024-07-28 15:37:06 -04:00
Zane Schepke 80a02382e1 ci: add basic ci (#287)
- add ktlint
2024-07-28 14:49:35 -04:00
Zane Schepke b9a8400453 fix: app lock bypass (#286) 2024-07-28 14:24:22 -04:00
Zane Schepke 3a17d2855b fix: fastlane deploy (#285) 2024-07-28 14:05:15 -04:00
Zane Schepke 086b48c79d fix: signing config bug 2024-07-28 12:18:17 -04:00
Zane Schepke 1f561fbf38 Fix/app signature (#284) 2024-07-28 12:11:16 -04:00
Zane Schepke 45e63e9910 fix versioning (#280) 2024-07-28 03:27:12 -04:00
Zane Schepke 66e89c83e2 chore: fmt 2024-07-28 02:17:01 -04:00
Zane Schepke 470fa0191b fix: signing issue (#279) 2024-07-28 02:13:18 -04:00
Zane Schepke 7c15943a81 fix: nightly release bug 2024-07-27 23:32:57 -04:00
Zane Schepke 05adf7539f fix: github cli for cd 2024-07-27 23:18:30 -04:00
Zane Schepke a9a49e3421 fix: nightly versioning 2024-07-27 22:56:56 -04:00
Zane Schepke 4dd8241fa1 fix: nightly check 2024-07-27 22:34:07 -04:00
Zane Schepke 431b2f9061 fix: nightly grep 2024-07-27 07:59:55 -04:00
Zane Schepke f822292584 fix: nightly check 2024-07-27 07:54:52 -04:00
Zane Schepke 4ffc5d4069 fix: play deploy job 2024-07-27 07:42:02 -04:00
Zane Schepke 680fbed28c fix: nightly detection 2024-07-27 07:37:47 -04:00
Zane Schepke 737524831b fix: auto tunnel tile bug
Fixes bug where auto tunnel tile was the opposite state

Closes #241
2024-07-27 07:21:27 -04:00
Zane Schepke b8c36ac192 fix: notification pin lock bypass
Closes #242
2024-07-27 06:44:02 -04:00
Zane Schepke 547686069f fix: androidtv multiple tunnel control
Fixes a bug where androidTV was only allowing control of a single tunnel.
Closes #268
2024-07-27 06:04:25 -04:00
Zane Schepke ac18ac8274 fix: cd upload bug 2024-07-27 04:53:16 -04:00
Zane Schepke cb983da990 fix: cd apk upload 2024-07-27 04:42:21 -04:00
Zane Schepke cfe64dcb61 fix: cd fdroid dispatch bug 2024-07-27 04:24:26 -04:00
Zane Schepke 2db521d510 fix: add missing cd deps 2024-07-27 04:20:35 -04:00
Zane Schepke ff6c763b7b fix: cd typo 2024-07-27 04:18:04 -04:00
Zane Schepke ebf7521fa1 cd: improve release workflow w/nightly 2024-07-27 04:15:57 -04:00
Zane Schepke 7a2d96fcd7 fix: remove portrait lock
bump deps

Closes #259
Closes #227
Closes #226
Closes #219
Closes #218
2024-07-27 02:20:01 -04:00
𝗪𝗜𝗡𝗭𝗢𝗥𝗧 c6c8047982 update-tr-locales (#255) 2024-07-11 01:00:40 -04:00
dependabot[bot] 9cfb7250de build(deps): bump actions/upload-artifact from 4.3.3 to 4.3.4 (#257)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-11 00:21:25 -04:00
Zane Schepke 79b5b039b0 fix: crashing and pin lock
Re-enabled pin lock after disablement from crashes.

Fixed crashing issues.

Closes #237

Fixed bug where pin lock will no longer initialize if never not enabled/in use.

Improved tunnel control tile performance.

Fix bad address crash when user enters bad addresses into allowedIps.
Closes #229

Disabled auto rotate
Closes #212

Add restart on boot toggle to make restart of services feature more obvious and configurable.
2024-06-18 23:08:40 -04:00
Weblate (bot) 29616f8325 Translations update from Hosted Weblate (#228)
Co-authored-by: gallegonovato <fran-carro@hotmail.es>
Co-authored-by: Kirill Isakov <k@isakov.net>
Co-authored-by: Roman Nahálka <nahalkaroman@gmail.com>
Co-authored-by: Languages add-on <noreply-addon-languages@weblate.org>
Co-authored-by: Luiz Fellipe Carneiro <fellipec@outlook.com>
Co-authored-by: Kachelkaiser <kachelkaiser@outlook.com>
Co-authored-by: yura04 <yura.panasiuk04@gmail.com>
2024-06-18 19:13:41 -04:00
157 changed files with 9063 additions and 7999 deletions
+22 -10
View File
@@ -1,8 +1,14 @@
[{*.kt,*.kts}] root = true
indent_style = space
insert_final_newline = true [*]
max_line_length = 100 charset = utf-8
indent_size = 4 indent_size = 4
indent_style = tab
max_line_length = 150
trim_trailing_whitespace = true
insert_final_newline = true
[{*.kt,*.kts}]
ij_continuation_indent_size = 4 ij_continuation_indent_size = 4
ij_java_names_count_to_use_import_on_demand = 9999 ij_java_names_count_to_use_import_on_demand = 9999
ij_kotlin_align_in_columns_case_branch = false ij_kotlin_align_in_columns_case_branch = false
@@ -11,8 +17,6 @@ ij_kotlin_align_multiline_extends_list = false
ij_kotlin_align_multiline_method_parentheses = false ij_kotlin_align_multiline_method_parentheses = false
ij_kotlin_align_multiline_parameters = true ij_kotlin_align_multiline_parameters = true
ij_kotlin_align_multiline_parameters_in_calls = false ij_kotlin_align_multiline_parameters_in_calls = false
ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true
ij_kotlin_assignment_wrap = normal ij_kotlin_assignment_wrap = normal
ij_kotlin_blank_lines_after_class_header = 0 ij_kotlin_blank_lines_after_class_header = 0
ij_kotlin_blank_lines_around_block_when_branches = 0 ij_kotlin_blank_lines_around_block_when_branches = 0
@@ -20,10 +24,7 @@ ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_
ij_kotlin_block_comment_at_first_column = true ij_kotlin_block_comment_at_first_column = true
ij_kotlin_call_parameters_new_line_after_left_paren = true ij_kotlin_call_parameters_new_line_after_left_paren = true
ij_kotlin_call_parameters_right_paren_on_new_line = false ij_kotlin_call_parameters_right_paren_on_new_line = false
ij_kotlin_call_parameters_wrap = on_every_item
ij_kotlin_catch_on_new_line = false ij_kotlin_catch_on_new_line = false
ij_kotlin_class_annotation_wrap = split_into_lines
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
ij_kotlin_continuation_indent_for_chained_calls = true ij_kotlin_continuation_indent_for_chained_calls = true
ij_kotlin_continuation_indent_for_expression_bodies = true ij_kotlin_continuation_indent_for_expression_bodies = true
ij_kotlin_continuation_indent_in_argument_lists = true ij_kotlin_continuation_indent_in_argument_lists = true
@@ -52,7 +53,6 @@ ij_kotlin_method_annotation_wrap = split_into_lines
ij_kotlin_method_call_chain_wrap = normal ij_kotlin_method_call_chain_wrap = normal
ij_kotlin_method_parameters_new_line_after_left_paren = true ij_kotlin_method_parameters_new_line_after_left_paren = true
ij_kotlin_method_parameters_right_paren_on_new_line = true ij_kotlin_method_parameters_right_paren_on_new_line = true
ij_kotlin_method_parameters_wrap = on_every_item
ij_kotlin_name_count_to_use_star_import = 9999 ij_kotlin_name_count_to_use_star_import = 9999
ij_kotlin_name_count_to_use_star_import_for_members = 9999 ij_kotlin_name_count_to_use_star_import_for_members = 9999
ij_kotlin_parameter_annotation_wrap = off ij_kotlin_parameter_annotation_wrap = off
@@ -83,3 +83,15 @@ ij_kotlin_while_on_new_line = false
ij_kotlin_wrap_elvis_expressions = 1 ij_kotlin_wrap_elvis_expressions = 1
ij_kotlin_wrap_expression_body_functions = 1 ij_kotlin_wrap_expression_body_functions = 1
ij_kotlin_wrap_first_method_in_call_chain = false ij_kotlin_wrap_first_method_in_call_chain = false
#compose
ktlint_standard_filename = disabled
ktlint_standard_no-wildcard-imports = disabled
ktlint_standard_function-naming = disabled
ktlint_standard_property-naming = disabled
ktlint_standard_package-naming = disabled
ktlint_function_naming_ignore_when_annotated_with = Composable
ktlint_code_style = android_studio
ktlint_standard_import-ordering = disabled
ktlint_standard_package-naming = disabled
ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true
+23
View File
@@ -0,0 +1,23 @@
name: ci-android
on:
workflow_dispatch:
pull_request:
jobs:
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Run ktlint
run: ./gradlew ktlintCheck
-124
View File
@@ -1,124 +0,0 @@
name: Android CI Tag Deployment (Pre-release)
on:
workflow_dispatch:
push:
tags:
- '*.*.*-**'
jobs:
build:
name: Build Signed APK
runs-on: ubuntu-latest
env:
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
KEY_STORE_FILE: 'android_keystore.jks'
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
GH_USER: ${{ secrets.GH_USER }}
GH_TOKEN: ${{ secrets.GH_TOKEN }}
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
# Here we need to decode keystore.jks from base64 string and place it
# in the folder specified in the release signing configuration
- name: Decode Keystore
id: decode_keystore
uses: timheuer/base64-to-file@v1.2
with:
fileName: ${{ env.KEY_STORE_FILE }}
fileDir: ${{ env.KEY_STORE_LOCATION }}
encodedString: ${{ secrets.KEYSTORE }}
# create keystore path for gradle to read
- name: Create keystore path env var
run: |
store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }}
echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV
- name: Create service_account.json
id: createServiceAccount
run: echo '${{ secrets.SERVICE_ACCOUNT_JSON }}' > service_account.json
# Build and sign APK ("-x test" argument is used to skip tests)
# add fdroid flavor for apk upload
- name: Build Fdroid Release APK
run: ./gradlew :app:assembleFdroidRelease -x test
# get fdroid flavor release apk path
- name: Get apk path
id: apk-path
run: echo "path=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_OUTPUT
- name: Get version code
run: |
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
# Save the APK after the Build job is complete to publish it as a Github release in the next job
- name: Upload APK
uses: actions/upload-artifact@v4.3.3
with:
name: wgtunnel
path: ${{ steps.apk-path.outputs.path }}
- name: Download APK from build
uses: actions/download-artifact@v4
with:
name: wgtunnel
- name: Create Release with Fastlane changelog notes
id: create_release
uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# fix hardcode changelog file name
body_path: ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt
tag_name: ${{ github.ref_name }}
name: ${{ github.ref_name }}
draft: false
prerelease: true
files: ${{ github.workspace }}/${{ steps.apk-path.outputs.path }}
- name: Install apksigner
run: |
sudo apt-get update
sudo apt-get install -y apksigner
- name: Get checksum
id: checksum
run: echo "checksum=$(apksigner verify -print-certs ${{ steps.apk-path.outputs.path }} | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT
- name: Append checksum
id: append_checksum
uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
body: |
SHA256 fingerprint:
```${{ steps.checksum.outputs.checksum }}```
tag_name: ${{ github.ref_name }}
name: ${{ github.ref_name }}
draft: false
prerelease: true
append_body: true
- name: Deploy with fastlane
uses: ruby/setup-ruby@v1
with:
ruby-version: '3.2' # Not needed with a .ruby-version file
bundler-cache: true
- name: Distribute app to Beta track 🚀
run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane beta)
+146 -41
View File
@@ -1,17 +1,40 @@
# name of the workflow name: release-android
name: Android CI Tag Deployment (Release)
on: on:
schedule:
- cron: "4 3 * * *"
workflow_dispatch: workflow_dispatch:
push: inputs:
tags: track:
- '*.*.*' type: choice
- '!*.*.*-**' description: "Google play release track"
options:
- none
- internal
- alpha
- beta
- production
default: 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:
@@ -21,7 +44,9 @@ jobs:
KEY_STORE_FILE: 'android_keystore.jks' KEY_STORE_FILE: 'android_keystore.jks'
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/ KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
GH_USER: ${{ secrets.GH_USER }} GH_USER: ${{ secrets.GH_USER }}
# GH needed for gh cli
GH_TOKEN: ${{ secrets.GH_TOKEN }} GH_TOKEN: ${{ secrets.GH_TOKEN }}
GH_REPO: ${{ github.repository }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -34,6 +59,10 @@ jobs:
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x gradlew run: chmod +x gradlew
- name: Install system dependencies
run: |
sudo apt update && sudo apt install -y gh apksigner
# Here we need to decode keystore.jks from base64 string and place it # Here we need to decode keystore.jks from base64 string and place it
# in the folder specified in the release signing configuration # in the folder specified in the release signing configuration
- name: Decode Keystore - name: Decode Keystore
@@ -57,75 +86,151 @@ jobs:
# Build and sign APK ("-x test" argument is used to skip tests) # Build and sign APK ("-x test" argument is used to skip tests)
# add fdroid flavor for apk upload # add fdroid flavor for apk upload
- name: Build Fdroid Release APK - name: Build Fdroid Release APK
if: ${{ inputs.release_type != '' && inputs.release_type == 'release' }}
run: ./gradlew :app:assembleFdroidRelease -x test run: ./gradlew :app:assembleFdroidRelease -x test
# get fdroid flavor release apk path - name: Build Fdroid Prerelease APK
- name: Get apk path if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }}
id: apk-path run: ./gradlew :app:assembleFdroidPrerelease -x test
run: echo "path=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_OUTPUT
- name: Build Fdroid Nightly APK
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
run: ./gradlew :app:assembleFdroidNightly -x test
- if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' }}
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/nightly/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
- if: ${{ inputs.release_type != '' && inputs.release_type == 'release' }}
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/release/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
- if: ${{ inputs.release_type != '' && inputs.release_type == 'prerelease' }}
run: echo "APK_PATH=$(find . -regex '^.*/build/outputs/apk/fdroid/prerelease/.*\.apk$' -type f | head -1)" >> $GITHUB_ENV
- name: Get version code - name: Get version code
if: ${{ inputs.release_type == 'release' }}
run: | run: |
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n') version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
# Save the APK after the Build job is complete to publish it as a Github release in the next job # Save the APK after the Build job is complete to publish it as a Github release in the next job
- name: Upload APK - name: Upload APK
uses: actions/upload-artifact@v4.3.3 uses: actions/upload-artifact@v4.3.6
with: with:
name: wgtunnel name: wgtunnel
path: ${{ steps.apk-path.outputs.path }} path: ${{ env.APK_PATH }}
- name: Download APK from build - name: Download APK from build
uses: actions/download-artifact@v4 uses: actions/download-artifact@v4
with: with:
name: wgtunnel name: wgtunnel
- name: Repository Dispatch for my F-Droid repo - name: Repository Dispatch for my F-Droid repo
uses: peter-evans/repository-dispatch@v3 uses: peter-evans/repository-dispatch@v3
if: ${{ inputs.release_type == 'release' }}
with: with:
token: ${{ secrets.PAT }} token: ${{ secrets.PAT }}
repository: zaneschepke/fdroid repository: zaneschepke/fdroid
event-type: fdroid-update event-type: fdroid-update
# Setup TAG_NAME, which is used as a general "name"
- if: github.event_name == 'workflow_dispatch'
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
- if: github.event_name == 'schedule'
run: echo "TAG_NAME=nightly" >> $GITHUB_ENV
- name: Set version release notes
if: ${{ inputs.release_type == 'release' }}
run: |
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)"
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
echo "$RELEASE_NOTES" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
- name: On nightly release notes
if: ${{ contains(env.TAG_NAME, 'nightly') }}
run: |
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
gh release delete nightly --yes || true
- name: On prerelease release notes
if: ${{ inputs.release_type == 'prerelease' }}
run: |
echo "RELEASE_NOTES=Testing version of app for specific feature." >> $GITHUB_ENV
gh release delete ${{ github.event.inputs.tag_name }} --yes || true
- name: Get checksum
id: checksum
run: echo "checksum=$(apksigner verify -print-certs ${{ env.APK_PATH }} | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT
- name: Create Release with Fastlane changelog notes - name: Create Release with Fastlane changelog notes
id: create_release id: create_release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
body_path: ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt
tag_name: ${{ github.ref_name }}
name: ${{ github.ref_name }}
draft: false
prerelease: false
files: ${{ github.workspace }}/${{ steps.apk-path.outputs.path }}
- name: Install apksigner
run: |
sudo apt-get update
sudo apt-get install -y apksigner
- name: Get checksum
id: checksum
run: echo "checksum=$(apksigner verify -print-certs ${{ steps.apk-path.outputs.path }} | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT
- name: Append checksum
id: append_checksum
uses: softprops/action-gh-release@v2
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
body: | body: |
${{ env.RELEASE_NOTES }}
SHA256 fingerprint: SHA256 fingerprint:
```${{ steps.checksum.outputs.checksum }}``` ```${{ steps.checksum.outputs.checksum }}```
tag_name: ${{ github.ref_name }} tag_name: ${{ env.TAG_NAME }}
name: ${{ github.ref_name }} name: ${{ env.TAG_NAME }}
draft: false draft: false
prerelease: false prerelease: ${{ inputs.release_type == 'prerelease' || inputs.release_type == '' || inputs.release_type == 'nightly' }}
append_body: true make_latest: ${{ inputs.release_type == 'release' }}
files: ${{ github.workspace }}/${{ env.APK_PATH }}
publish-play:
if: ${{ inputs.track != 'none' && inputs.track != '' }}
name: Publish to Google Play
runs-on: ubuntu-latest
env:
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
KEY_STORE_FILE: 'android_keystore.jks'
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
GH_USER: ${{ secrets.GH_USER }}
GH_TOKEN: ${{ secrets.GH_TOKEN }}
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
# Here we need to decode keystore.jks from base64 string and place it
# in the folder specified in the release signing configuration
- name: Decode Keystore
id: decode_keystore
uses: timheuer/base64-to-file@v1.2
with:
fileName: ${{ env.KEY_STORE_FILE }}
fileDir: ${{ env.KEY_STORE_LOCATION }}
encodedString: ${{ secrets.KEYSTORE }}
# create keystore path for gradle to read
- name: Create keystore path env var
run: |
store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }}
echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV
- name: Create service_account.json
id: createServiceAccount
run: echo '${{ secrets.SERVICE_ACCOUNT_JSON }}' > service_account.json
- name: Deploy with fastlane - name: Deploy with fastlane
uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1
with: with:
ruby-version: '3.2' # Not needed with a .ruby-version file ruby-version: '3.2' # Not needed with a .ruby-version file
bundler-cache: true bundler-cache: true
- name: Distribute app to Prod track 🚀
run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane production) - name: Distribute app to Prod track 🚀
run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane ${{ inputs.track }})
+4 -3
View File
@@ -69,15 +69,16 @@ and on while on different networks. This app was created to offer a free solutio
Want updates faster? Want updates faster?
Check out my personal [fdroid repository](https://github.com/zaneschepke/fdroid) to get updates the moment they are released. Check out my personal [fdroid repository](https://github.com/zaneschepke/fdroid) to get updates the
moment they are released.
## Docs ## Docs
Information about features, behaviors, and answers to common questions can be found in the app [documentation](https://zaneschepke.com/wgtunnel-docs/overview.html). 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 ## Translation
This app is using [Weblate](https://weblate.org) to assist with translations. This app is using [Weblate](https://weblate.org) to assist with translations.
+52 -57
View File
@@ -1,11 +1,11 @@
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 {
@@ -20,8 +20,8 @@ android {
applicationId = Constants.APP_ID applicationId = Constants.APP_ID
minSdk = Constants.MIN_SDK minSdk = Constants.MIN_SDK
targetSdk = Constants.TARGET_SDK targetSdk = Constants.TARGET_SDK
versionCode = Constants.VERSION_CODE versionCode = determineVersionCode()
versionName = Constants.VERSION_NAME versionName = determineVersionName()
ksp { arg("room.schemaLocation", "$projectDir/schemas") } ksp { arg("room.schemaLocation", "$projectDir/schemas") }
@@ -35,44 +35,10 @@ android {
signingConfigs { signingConfigs {
create(Constants.RELEASE) { create(Constants.RELEASE) {
val properties = storeFile = getStoreFile()
Properties().apply { storePassword = getSigningProperty(Constants.STORE_PASS_VAR)
// created local file for signing details keyAlias = getSigningProperty(Constants.KEY_ALIAS_VAR)
try { keyPassword = getSigningProperty(Constants.KEY_PASS_VAR)
load(file("signing.properties").reader())
} catch (_: Exception) {
load(file("signing_template.properties").reader())
}
}
// try to get secrets from env first for pipeline build, then properties file for local
// build
storeFile =
file(
System.getenv()
.getOrDefault(
Constants.KEY_STORE_PATH_VAR,
properties.getProperty(Constants.KEY_STORE_PATH_VAR),
),
)
storePassword =
System.getenv()
.getOrDefault(
Constants.STORE_PASS_VAR,
properties.getProperty(Constants.STORE_PASS_VAR),
)
keyAlias =
System.getenv()
.getOrDefault(
Constants.KEY_ALIAS_VAR,
properties.getProperty(Constants.KEY_ALIAS_VAR),
)
keyPassword =
System.getenv()
.getOrDefault(
Constants.KEY_PASS_VAR,
properties.getProperty(Constants.KEY_PASS_VAR),
)
} }
} }
@@ -82,16 +48,6 @@ android {
listOf("libwg-go.so", "libwg-quick.so", "libwg.so"), listOf("libwg-go.so", "libwg-quick.so", "libwg.so"),
) )
applicationVariants.all {
val variant = this
variant.outputs
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
.forEach { output ->
val outputFileName =
"${Constants.APP_NAME}-${variant.flavorName}-${variant.buildType.name}-${variant.versionName}.apk"
output.outputFileName = outputFileName
}
}
release { release {
isDebuggable = false isDebuggable = false
isMinifyEnabled = true isMinifyEnabled = true
@@ -103,6 +59,26 @@ android {
signingConfig = signingConfigs.getByName(Constants.RELEASE) signingConfig = signingConfigs.getByName(Constants.RELEASE)
} }
debug { isDebuggable = true } debug { isDebuggable = true }
create(Constants.PRERELEASE) {
initWith(buildTypes.getByName(Constants.RELEASE))
}
create(Constants.NIGHTLY) {
initWith(buildTypes.getByName(Constants.RELEASE))
}
applicationVariants.all {
val variant = this
variant.outputs
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
.forEach { output ->
val outputFileName =
"${Constants.APP_NAME}-${variant.flavorName}-" +
"${variant.buildType.name}-${variant.versionName}.apk"
output.outputFileName = outputFileName
}
}
} }
flavorDimensions.add(Constants.TYPE) flavorDimensions.add(Constants.TYPE)
productFlavors { productFlavors {
@@ -112,9 +88,6 @@ android {
} }
create("general") { create("general") {
dimension = Constants.TYPE dimension = Constants.TYPE
if (BuildHelper.isReleaseBuild(gradle) && BuildHelper.isGeneralFlavor(gradle)) {
//any plugins general specific
}
} }
} }
compileOptions { compileOptions {
@@ -127,7 +100,6 @@ android {
compose = true compose = true
buildConfig = true buildConfig = true
} }
composeOptions { kotlinCompilerExtensionVersion = Constants.COMPOSE_COMPILER_EXTENSION_VERSION }
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } } packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
} }
@@ -169,7 +141,6 @@ dependencies {
// logging // logging
implementation(libs.timber) implementation(libs.timber)
// compose navigation // compose navigation
implementation(libs.androidx.navigation.compose) implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.hilt.navigation.compose) implementation(libs.androidx.hilt.navigation.compose)
@@ -211,4 +182,28 @@ dependencies {
// shortcuts // shortcuts
implementation(libs.androidx.core) implementation(libs.androidx.core)
implementation(libs.androidx.core.google.shortcuts) implementation(libs.androidx.core.google.shortcuts)
// splash
implementation(libs.androidx.core.splashscreen)
}
fun 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
}
}
} }
+15 -10
View File
@@ -60,18 +60,17 @@
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.WireguardAutoTunnel" android:theme="@style/Theme.AppSplashScreen"
tools:targetApi="tiramisu"> tools:targetApi="tiramisu">
<activity <activity
android:name=".ui.MainActivity" android:name=".ui.SplashActivity"
android:exported="true" android:exported="true"
android:theme="@style/Theme.WireguardAutoTunnel"> android:theme="@style/Theme.AppSplashScreen">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" /> <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" /> <action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
</intent-filter> </intent-filter>
<meta-data <meta-data
@@ -79,17 +78,23 @@
android:resource="@xml/shortcuts" /> android:resource="@xml/shortcuts" />
</activity> </activity>
<activity <activity
android:name=".ui.CaptureActivityPortrait" android:name=".ui.MainActivity"
android:screenOrientation="fullSensor" android:exported="true"
android:stateNotNeeded="true" android:theme="@style/Theme.WireguardAutoTunnel">
android:theme="@style/zxing_CaptureTheme" </activity>
android:windowSoftInputMode="stateAlwaysHidden" <activity
tools:ignore="DiscouragedApi" /> android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="screenOrientation" />
<activity <activity
android:name=".service.shortcut.ShortcutsActivity" android:name=".service.shortcut.ShortcutsActivity"
android:enabled="true" android:enabled="true"
android:exported="true" android:exported="true"
android:noHistory="true"
android:excludeFromRecents="true"
android:finishOnTaskLaunch="true" android:finishOnTaskLaunch="true"
android:launchMode="singleInstance"
android:theme="@android:style/Theme.NoDisplay" /> android:theme="@android:style/Theme.NoDisplay" />
<service <service
@@ -6,34 +6,14 @@ import android.content.pm.PackageManager
import android.os.StrictMode import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy import android.os.StrictMode.ThreadPolicy
import android.service.quicksettings.TileService import android.service.quicksettings.TileService
import com.zaneschepke.logcatter.LocalLogCollector
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
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 kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import xyz.teamgravity.pin_lock_compose.PinManager
import javax.inject.Inject
@HiltAndroidApp @HiltAndroidApp
class WireGuardAutoTunnel : Application() { class WireGuardAutoTunnel : Application() {
@Inject
lateinit var localLogCollector: LocalLogCollector
@Inject
@ApplicationScope
lateinit var applicationScope: CoroutineScope
@Inject
@IoDispatcher
lateinit var ioDispatcher: CoroutineDispatcher
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
instance = this instance = this
@@ -47,16 +27,12 @@ class WireGuardAutoTunnel : Application() {
.penaltyLog() .penaltyLog()
.build(), .build(),
) )
} else Timber.plant(ReleaseTree()) } else {
applicationScope.launch(ioDispatcher) { Timber.plant(ReleaseTree())
//TODO disable pin lock for now
//PinManager.initialize(this@WireGuardAutoTunnel)
if (!isRunningOnAndroidTv()) localLogCollector.start()
} }
} }
companion object { companion object {
lateinit var instance: WireGuardAutoTunnel lateinit var instance: WireGuardAutoTunnel
private set private set
@@ -19,7 +19,7 @@ import java.io.IOException
class DataStoreManager( class DataStoreManager(
private val context: Context, private val context: Context,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) { ) {
companion object { companion object {
val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN") val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
@@ -28,6 +28,7 @@ class DataStoreManager(
booleanPreferencesKey("TUNNEL_RUNNING_FROM_MANUAL_START") booleanPreferencesKey("TUNNEL_RUNNING_FROM_MANUAL_START")
val ACTIVE_TUNNEL = intPreferencesKey("ACTIVE_TUNNEL") val ACTIVE_TUNNEL = intPreferencesKey("ACTIVE_TUNNEL")
val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID") val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
val IS_PIN_LOCK_ENABLED = booleanPreferencesKey("PIN_LOCK_ENABLED")
} }
// preferences // preferences
@@ -59,7 +60,6 @@ class DataStoreManager(
} }
} }
fun <T> getFromStoreFlow(key: Preferences.Key<T>) = context.dataStore.data.map { it[key] } fun <T> getFromStoreFlow(key: Preferences.Key<T>) = context.dataStore.data.map { it[key] }
suspend fun <T> getFromStore(key: Preferences.Key<T>): T? { suspend fun <T> getFromStore(key: Preferences.Key<T>): T? {
@@ -73,7 +73,6 @@ class DataStoreManager(
} }
} }
fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking { fun <T> getFromStoreBlocking(key: Preferences.Key<T>) = runBlocking {
context.dataStore.data.map { it[key] }.first() context.dataStore.data.map { it[key] }.first()
} }
@@ -1,14 +1,16 @@
package com.zaneschepke.wireguardautotunnel.data.domain package com.zaneschepke.wireguardautotunnel.data.domain
data class GeneralState( data class GeneralState(
val locationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT, val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
val batteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT, val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
val tunnelRunningFromManualStart: Boolean = TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT, val isTunnelRunningFromManualStart: Boolean = TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
val activeTunnelId: Int? = null val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
val activeTunnelId: Int? = null,
) { ) {
companion object { companion object {
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
const val TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT = false const val TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT = false
const val PIN_LOCK_ENABLED_DEFAULT = false
} }
} }
@@ -4,6 +4,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
interface AppDataRepository { interface AppDataRepository {
suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? suspend fun getPrimaryOrFirstTunnel(): TunnelConfig?
suspend fun getStartTunnelConfig(): TunnelConfig? suspend fun getStartTunnelConfig(): TunnelConfig?
suspend fun toggleWatcherServicePause() suspend fun toggleWatcherServicePause()
@@ -3,10 +3,12 @@ package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
import javax.inject.Inject import javax.inject.Inject
class AppDataRoomRepository @Inject constructor( class AppDataRoomRepository
@Inject
constructor(
override val settings: SettingsRepository, override val settings: SettingsRepository,
override val tunnels: TunnelConfigRepository, override val tunnels: TunnelConfigRepository,
override val appState: AppStateRepository override val appState: AppStateRepository,
) : AppDataRepository { ) : AppDataRepository {
override suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? { override suspend fun getPrimaryOrFirstTunnel(): TunnelConfig? {
return tunnels.findPrimary().firstOrNull() ?: tunnels.getAll().firstOrNull() return tunnels.findPrimary().firstOrNull() ?: tunnels.getAll().firstOrNull()
@@ -17,7 +19,9 @@ class AppDataRoomRepository @Inject constructor(
appState.getActiveTunnelId()?.let { appState.getActiveTunnelId()?.let {
tunnels.getById(it) tunnels.getById(it)
} }
} else null } else {
null
}
} }
override suspend fun toggleWatcherServicePause() { override suspend fun toggleWatcherServicePause() {
@@ -5,12 +5,19 @@ import kotlinx.coroutines.flow.Flow
interface AppStateRepository { interface AppStateRepository {
suspend fun isLocationDisclosureShown(): Boolean suspend fun isLocationDisclosureShown(): Boolean
suspend fun setLocationDisclosureShown(shown: Boolean) suspend fun setLocationDisclosureShown(shown: Boolean)
suspend fun isPinLockEnabled(): Boolean
suspend fun setPinLockEnabled(enabled: Boolean)
suspend fun isBatteryOptimizationDisableShown(): Boolean suspend fun isBatteryOptimizationDisableShown(): Boolean
suspend fun setBatteryOptimizationDisableShown(shown: Boolean) suspend fun setBatteryOptimizationDisableShown(shown: Boolean)
suspend fun isTunnelRunningFromManualStart(): Boolean suspend fun isTunnelRunningFromManualStart(): Boolean
suspend fun setTunnelRunningFromManualStart(id: Int) suspend fun setTunnelRunningFromManualStart(id: Int)
suspend fun setManualStop() suspend fun setManualStop()
@@ -22,5 +29,4 @@ interface AppStateRepository {
suspend fun setCurrentSsid(ssid: String) suspend fun setCurrentSsid(ssid: String)
val generalStateFlow: Flow<GeneralState> val generalStateFlow: Flow<GeneralState>
} }
@@ -17,6 +17,15 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown) dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown)
} }
override suspend fun isPinLockEnabled(): Boolean {
return dataStoreManager.getFromStore(DataStoreManager.IS_PIN_LOCK_ENABLED)
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT
}
override suspend fun setPinLockEnabled(enabled: Boolean) {
dataStoreManager.saveToDataStore(DataStoreManager.IS_PIN_LOCK_ENABLED, enabled)
}
override suspend fun isBatteryOptimizationDisableShown(): Boolean { override suspend fun isBatteryOptimizationDisableShown(): Boolean {
return dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN) return dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN)
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT ?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
@@ -65,11 +74,17 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
prefs?.let { pref -> prefs?.let { pref ->
try { try {
GeneralState( GeneralState(
locationDisclosureShown = pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN] isLocationDisclosureShown =
pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT, ?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
batteryOptimizationDisableShown = pref[DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN] isBatteryOptimizationDisableShown =
pref[DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN]
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT, ?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
tunnelRunningFromManualStart = pref[DataStoreManager.TUNNEL_RUNNING_FROM_MANUAL_START] 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, ?: GeneralState.TUNNELING_RUNNING_FROM_MANUAL_START_DEFAULT,
) )
} catch (e: IllegalArgumentException) { } catch (e: IllegalArgumentException) {
@@ -5,7 +5,6 @@ import com.zaneschepke.wireguardautotunnel.data.domain.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) { override suspend fun save(settings: Settings) {
settingsDoa.save(settings) settingsDoa.save(settings)
} }
@@ -28,7 +28,6 @@ class RoomTunnelConfigRepository(private val tunnelConfigDao: TunnelConfigDao) :
), ),
) )
} }
} }
override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) { override suspend fun updateMobileDataTunnel(tunnelConfig: TunnelConfig?) {
@@ -5,7 +5,6 @@ import com.zaneschepke.wireguardautotunnel.util.TunnelConfigs
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface TunnelConfigRepository { interface TunnelConfigRepository {
fun getTunnelConfigsFlow(): Flow<TunnelConfigs> fun getTunnelConfigsFlow(): Flow<TunnelConfigs>
suspend fun getAll(): TunnelConfigs suspend fun getAll(): TunnelConfigs
@@ -2,7 +2,7 @@ package com.zaneschepke.wireguardautotunnel.module
import android.content.Context import android.content.Context
import com.zaneschepke.logcatter.LocalLogCollector import com.zaneschepke.logcatter.LocalLogCollector
import com.zaneschepke.logcatter.LogcatHelper import com.zaneschepke.logcatter.LogcatUtil
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
@@ -25,6 +25,6 @@ class AppModule {
@Singleton @Singleton
@Provides @Provides
fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector { fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector {
return LogcatHelper.init(context = context) return LogcatUtil.init(context = context)
} }
} }
@@ -66,10 +66,7 @@ class RepositoryModule {
@Singleton @Singleton
@Provides @Provides
fun providePreferencesDataStore( fun providePreferencesDataStore(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): DataStoreManager {
@ApplicationContext context: Context,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): DataStoreManager {
return DataStoreManager(context, ioDispatcher) return DataStoreManager(context, ioDispatcher)
} }
@@ -84,10 +81,8 @@ class RepositoryModule {
fun provideAppDataRepository( fun provideAppDataRepository(
settingsRepository: SettingsRepository, settingsRepository: SettingsRepository,
tunnelConfigRepository: TunnelConfigRepository, tunnelConfigRepository: TunnelConfigRepository,
appStateRepository: AppStateRepository appStateRepository: AppStateRepository,
): AppDataRepository { ): AppDataRepository {
return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository) return AppDataRoomRepository(settingsRepository, tunnelConfigRepository, appStateRepository)
} }
} }
@@ -17,9 +17,7 @@ import dagger.hilt.android.scopes.ServiceScoped
abstract class ServiceModule { abstract class ServiceModule {
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideNotificationService( abstract fun provideNotificationService(wireGuardNotification: WireGuardNotification): NotificationService
wireGuardNotification: WireGuardNotification
): NotificationService
@Binds @Binds
@ServiceScoped @ServiceScoped
@@ -27,13 +25,9 @@ abstract class ServiceModule {
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideMobileDataService( abstract fun provideMobileDataService(mobileDataService: MobileDataService): NetworkService<MobileDataService>
mobileDataService: MobileDataService
): NetworkService<MobileDataService>
@Binds @Binds
@ServiceScoped @ServiceScoped
abstract fun provideEthernetService( abstract fun provideEthernetService(ethernetService: EthernetService): NetworkService<EthernetService>
ethernetService: EthernetService
): NetworkService<EthernetService>
} }
@@ -57,7 +57,7 @@ class TunnelModule {
@Kernel kernelBackend: Provider<Backend>, @Kernel kernelBackend: Provider<Backend>,
appDataRepository: AppDataRepository, appDataRepository: AppDataRepository,
@ApplicationScope applicationScope: CoroutineScope, @ApplicationScope applicationScope: CoroutineScope,
@IoDispatcher ioDispatcher: CoroutineDispatcher @IoDispatcher ioDispatcher: CoroutineDispatcher,
): VpnService { ): VpnService {
return WireGuardTunnel( return WireGuardTunnel(
amneziaBackend, amneziaBackend,
@@ -71,10 +71,7 @@ class TunnelModule {
@Provides @Provides
@Singleton @Singleton
fun provideServiceManager( fun provideServiceManager(appDataRepository: AppDataRepository, @IoDispatcher ioDispatcher: CoroutineDispatcher): ServiceManager {
appDataRepository: AppDataRepository,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): ServiceManager {
return ServiceManager(appDataRepository, ioDispatcher) return ServiceManager(appDataRepository, ioDispatcher)
} }
} }
@@ -13,13 +13,9 @@ import kotlinx.coroutines.CoroutineDispatcher
@Module @Module
@InstallIn(ViewModelComponent::class) @InstallIn(ViewModelComponent::class)
class ViewModelModule { class ViewModelModule {
@ViewModelScoped @ViewModelScoped
@Provides @Provides
fun provideFileUtils( fun provideFileUtils(@ApplicationContext context: Context, @IoDispatcher ioDispatcher: CoroutineDispatcher): FileUtils {
@ApplicationContext context: Context,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): FileUtils {
return FileUtils(context, ioDispatcher) return FileUtils(context, ioDispatcher)
} }
} }
@@ -4,25 +4,32 @@ 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 @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var serviceManager: ServiceManager
override fun onReceive(context: Context?, intent: Intent?) = goAsync { @Inject
if (Intent.ACTION_BOOT_COMPLETED != intent?.action) return@goAsync @ApplicationScope
lateinit var applicationScope: CoroutineScope
override fun onReceive(context: Context?, intent: Intent?) {
if (Intent.ACTION_BOOT_COMPLETED != intent?.action) return
context?.run { context?.run {
applicationScope.launch {
val settings = appDataRepository.settings.getSettings() val settings = appDataRepository.settings.getSettings()
if (settings.isRestoreOnBootEnabled) {
if (settings.isAutoTunnelEnabled) { if (settings.isAutoTunnelEnabled) {
Timber.i("Starting watcher service from boot") Timber.i("Starting watcher service from boot")
serviceManager.startWatcherServiceForeground(context) serviceManager.startWatcherServiceForeground(context)
@@ -34,6 +41,7 @@ class BootReceiver : BroadcastReceiver() {
context, context,
appDataRepository.tunnels.getById(it)?.id, appDataRepository.tunnels.getById(it)?.id,
) )
return@launch
} }
} }
if (settings.isAlwaysOnVpnEnabled) { if (settings.isAlwaysOnVpnEnabled) {
@@ -43,3 +51,5 @@ class BootReceiver : BroadcastReceiver() {
} }
} }
} }
}
}
@@ -4,12 +4,14 @@ 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
@@ -21,7 +23,12 @@ class NotificationActionReceiver : BroadcastReceiver() {
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var serviceManager: ServiceManager
override fun onReceive(context: Context, intent: Intent?) = goAsync { @Inject
@ApplicationScope
lateinit var applicationScope: CoroutineScope
override fun onReceive(context: Context, intent: Intent?) {
applicationScope.launch {
try { try {
// TODO fix for manual start changes when enabled // TODO fix for manual start changes when enabled
serviceManager.stopVpnServiceForeground(context) serviceManager.stopVpnServiceForeground(context)
@@ -34,3 +41,4 @@ class NotificationActionReceiver : BroadcastReceiver() {
} }
} }
} }
}
@@ -4,5 +4,5 @@ enum class Action {
START, START,
START_FOREGROUND, START_FOREGROUND,
STOP, STOP,
STOP_FOREGROUND STOP_FOREGROUND,
} }
@@ -23,7 +23,8 @@ open class ForegroundService : LifecycleService() {
val action = intent.action val action = intent.action
when (action) { when (action) {
Action.START.name, Action.START.name,
Action.START_FOREGROUND.name -> startService(intent.extras) Action.START_FOREGROUND.name,
-> startService(intent.extras)
Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService() Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService()
Constants.ALWAYS_ON_VPN_ACTION -> { Constants.ALWAYS_ON_VPN_ACTION -> {
@@ -12,15 +12,9 @@ import timber.log.Timber
class ServiceManager( class ServiceManager(
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) {
private fun <T : Service> actionOnService(
action: Action,
context: Context,
cls: Class<T>,
extras: Map<String, Int>? = null
) { ) {
private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) {
val intent = val intent =
Intent(context, cls).also { Intent(context, cls).also {
it.action = action.name it.action = action.name
@@ -29,7 +23,8 @@ class ServiceManager(
intent.component?.javaClass intent.component?.javaClass
try { try {
when (action) { when (action) {
Action.START_FOREGROUND, Action.STOP_FOREGROUND -> context.startForegroundService( Action.START_FOREGROUND, Action.STOP_FOREGROUND ->
context.startForegroundService(
intent, intent,
) )
@@ -40,11 +35,7 @@ class ServiceManager(
} }
} }
suspend fun startVpnService( suspend fun startVpnService(context: Context, tunnelId: Int? = null, isManualStart: Boolean = false) {
context: Context,
tunnelId: Int? = null,
isManualStart: Boolean = false
) {
if (isManualStart) onManualStart(tunnelId) if (isManualStart) onManualStart(tunnelId)
actionOnService( actionOnService(
Action.START, Action.START,
@@ -88,11 +79,7 @@ class ServiceManager(
} }
} }
suspend fun startVpnServiceForeground( suspend fun startVpnServiceForeground(context: Context, tunnelId: Int? = null, isManualStart: Boolean = false) {
context: Context,
tunnelId: Int? = null,
isManualStart: Boolean = false
) {
withContext(ioDispatcher) { withContext(ioDispatcher) {
if (isManualStart) onManualStart(tunnelId) if (isManualStart) onManualStart(tunnelId)
actionOnService( actionOnService(
@@ -104,9 +91,7 @@ class ServiceManager(
} }
} }
fun startWatcherServiceForeground( fun startWatcherServiceForeground(context: Context) {
context: Context,
) {
actionOnService( actionOnService(
Action.START_FOREGROUND, Action.START_FOREGROUND,
context, context,
@@ -7,50 +7,67 @@ data class WatcherState(
val isEthernetConnected: Boolean = false, val isEthernetConnected: Boolean = false,
val isMobileDataConnected: Boolean = false, val isMobileDataConnected: Boolean = false,
val currentNetworkSSID: String = "", val currentNetworkSSID: String = "",
val settings: Settings = Settings() val settings: Settings = Settings(),
) { ) {
fun isEthernetConditionMet(): Boolean { fun isEthernetConditionMet(): Boolean {
return (isEthernetConnected && return (
settings.isTunnelOnEthernetEnabled) isEthernetConnected &&
settings.isTunnelOnEthernetEnabled
)
} }
fun isMobileDataConditionMet(): Boolean { fun isMobileDataConditionMet(): Boolean {
return (!isEthernetConnected && return (
!isEthernetConnected &&
settings.isTunnelOnMobileDataEnabled && settings.isTunnelOnMobileDataEnabled &&
!isWifiConnected && !isWifiConnected &&
isMobileDataConnected) isMobileDataConnected
)
} }
fun isTunnelOffOnMobileDataConditionMet(): Boolean { fun isTunnelOffOnMobileDataConditionMet(): Boolean {
return (!isEthernetConnected && return (
!isEthernetConnected &&
!settings.isTunnelOnMobileDataEnabled && !settings.isTunnelOnMobileDataEnabled &&
isMobileDataConnected && isMobileDataConnected &&
!isWifiConnected) !isWifiConnected
)
} }
fun isUntrustedWifiConditionMet(): Boolean { fun isUntrustedWifiConditionMet(): Boolean {
return (!isEthernetConnected && return (
!isEthernetConnected &&
isWifiConnected && isWifiConnected &&
!settings.trustedNetworkSSIDs.contains(currentNetworkSSID) && !settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
settings.isTunnelOnWifiEnabled) settings.isTunnelOnWifiEnabled
)
} }
fun isTrustedWifiConditionMet(): Boolean { fun isTrustedWifiConditionMet(): Boolean {
return (!isEthernetConnected && return (
(isWifiConnected && !isEthernetConnected &&
settings.trustedNetworkSSIDs.contains(currentNetworkSSID))) (
isWifiConnected &&
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)
)
)
} }
fun isTunnelOffOnWifiConditionMet(): Boolean { fun isTunnelOffOnWifiConditionMet(): Boolean {
return (!isEthernetConnected && return (
(isWifiConnected && !isEthernetConnected &&
!settings.isTunnelOnWifiEnabled)) (
isWifiConnected &&
!settings.isTunnelOnWifiEnabled
)
)
} }
fun isTunnelOffOnNoConnectivityMet(): Boolean { fun isTunnelOffOnNoConnectivityMet(): Boolean {
return (!isEthernetConnected && return (
!isEthernetConnected &&
!isWifiConnected && !isWifiConnected &&
!isMobileDataConnected) !isMobileDataConnected
)
} }
} }
@@ -33,7 +33,6 @@ 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
@@ -80,7 +79,9 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
try { try {
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) { if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
launchWatcherPausedNotification() launchWatcherPausedNotification()
} else launchWatcherNotification() } else {
launchWatcherNotification()
}
} catch (e: Exception) { } catch (e: Exception) {
Timber.e("Failed to start watcher service, not enough permissions") Timber.e("Failed to start watcher service, not enough permissions")
} }
@@ -110,9 +111,7 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
stopSelf() stopSelf()
} }
private fun launchWatcherNotification( private fun launchWatcherNotification(description: String = getString(R.string.watcher_notification_text_active)) {
description: String = getString(R.string.watcher_notification_text_active)
) {
val notification = val notification =
notificationService.createNotification( notificationService.createNotification(
channelId = getString(R.string.watcher_channel_id), channelId = getString(R.string.watcher_channel_id),
@@ -188,7 +187,6 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
Timber.i("Starting management watcher") Timber.i("Starting management watcher")
manageVpn() manageVpn()
} }
} }
} }
@@ -236,13 +234,19 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
val tunnelConfig = vpnService.vpnState.value.tunnelConfig val tunnelConfig = vpnService.vpnState.value.tunnelConfig
tunnelConfig?.let { tunnelConfig?.let {
val config = TunnelConfig.configFromWgQuick(it.wgQuick) val config = TunnelConfig.configFromWgQuick(it.wgQuick)
val results = config.peers.map { peer -> val results =
val host = if (peer.endpoint.isPresent && config.peers.map { peer ->
peer.endpoint.get().resolved.isPresent) val host =
if (peer.endpoint.isPresent &&
peer.endpoint.get().resolved.isPresent
) {
peer.endpoint.get().resolved.get().host peer.endpoint.get().resolved.get().host
else Constants.DEFAULT_PING_IP } else {
Constants.DEFAULT_PING_IP
}
Timber.i("Checking reachability of: $host") Timber.i("Checking reachability of: $host")
val reachable = InetAddress.getByName(host) val reachable =
InetAddress.getByName(host)
.isReachable(Constants.PING_TIMEOUT.toInt()) .isReachable(Constants.PING_TIMEOUT.toInt())
Timber.i("Result: reachable - $reachable") Timber.i("Result: reachable - $reachable")
reachable reachable
@@ -266,7 +270,9 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
private suspend fun watchForSettingsChanges() { private suspend fun watchForSettingsChanges() {
appDataRepository.settings.getSettingsFlow().collect { settings -> appDataRepository.settings.getSettingsFlow().collect { settings ->
if (networkEventsFlow.value.settings.isAutoTunnelPaused != settings.isAutoTunnelPaused) { if (networkEventsFlow.value.settings.isAutoTunnelPaused
!= settings.isAutoTunnelPaused
) {
when (settings.isAutoTunnelPaused) { when (settings.isAutoTunnelPaused) {
true -> launchWatcherPausedNotification() true -> launchWatcherPausedNotification()
false -> launchWatcherNotification() false -> launchWatcherNotification()
@@ -339,7 +345,9 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
ssid?.let { name -> ssid?.let { name ->
if (name.contains(Constants.UNREADABLE_SSID)) { if (name.contains(Constants.UNREADABLE_SSID)) {
Timber.w("SSID unreadable: missing permissions") Timber.w("SSID unreadable: missing permissions")
} else Timber.i("Detected valid SSID") } else {
Timber.i("Detected valid SSID")
}
appDataRepository.appState.setCurrentSsid(name) appDataRepository.appState.setCurrentSsid(name)
networkEventsFlow.update { networkEventsFlow.update {
it.copy( it.copy(
@@ -409,14 +417,19 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
watcherState.isUntrustedWifiConditionMet() -> { watcherState.isUntrustedWifiConditionMet() -> {
if (tunnelConfig?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false || if (tunnelConfig?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false ||
tunnelConfig == null) { tunnelConfig == null
Timber.i("$autoTunnel - tunnel on ssid not associated with current tunnel condition met") ) {
Timber.i(
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met",
)
getSsidTunnel(watcherState.currentNetworkSSID)?.let { getSsidTunnel(watcherState.currentNetworkSSID)?.let {
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}") Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}")
if (isTunnelDown() || tunnelConfig?.id != it.id) serviceManager.startVpnServiceForeground( if (isTunnelDown() || tunnelConfig?.id != it.id) {
serviceManager.startVpnServiceForeground(
context, context,
it.id, it.id,
) )
}
} ?: suspend { } ?: suspend {
Timber.i("No tunnel associated with this SSID, using defaults") Timber.i("No tunnel associated with this SSID, using defaults")
val default = appDataRepository.getPrimaryOrFirstTunnel() val default = appDataRepository.getPrimaryOrFirstTunnel()
@@ -424,24 +437,29 @@ class WireGuardConnectivityWatcherService : ForegroundService() {
default?.let { default?.let {
serviceManager.startVpnServiceForeground(context, it.id) serviceManager.startVpnServiceForeground(context, it.id)
} }
} }
}.invoke() }.invoke()
} }
} }
watcherState.isTrustedWifiConditionMet() -> { watcherState.isTrustedWifiConditionMet() -> {
Timber.i("$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off") Timber.i(
"$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off",
)
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context) if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
} }
watcherState.isTunnelOffOnWifiConditionMet() -> { watcherState.isTunnelOffOnWifiConditionMet() -> {
Timber.i("$autoTunnel - tunnel off on wifi condition met, turning vpn off") Timber.i(
"$autoTunnel - tunnel off on wifi condition met, turning vpn off",
)
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context) if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
} }
watcherState.isTunnelOffOnNoConnectivityMet() -> { watcherState.isTunnelOffOnNoConnectivityMet() -> {
Timber.i("$autoTunnel - tunnel off on no connectivity met, turning vpn off") Timber.i(
"$autoTunnel - tunnel off on no connectivity met, turning vpn off",
)
if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context) if (!isTunnelDown()) serviceManager.stopVpnServiceForeground(context)
} }
@@ -142,10 +142,7 @@ class WireGuardTunnelService : ForegroundService() {
stopSelf() stopSelf()
} }
private fun launchVpnNotification( private fun launchVpnNotification(title: String = getString(R.string.vpn_starting), description: String = getString(R.string.attempt_connection)) {
title: String = getString(R.string.vpn_starting),
description: String = getString(R.string.attempt_connection)
) {
val notification = val notification =
notificationService.createNotification( notificationService.createNotification(
channelId = getString(R.string.vpn_channel_id), channelId = getString(R.string.vpn_channel_id),
@@ -16,7 +16,7 @@ import kotlinx.coroutines.flow.map
abstract class BaseNetworkService<T : BaseNetworkService<T>>( abstract class BaseNetworkService<T : BaseNetworkService<T>>(
val context: Context, val context: Context,
networkCapability: Int networkCapability: Int,
) : NetworkService<T> { ) : NetworkService<T> {
private val connectivityManager = private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@@ -24,7 +24,8 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
private val wifiManager = private val wifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
override val networkStatus = callbackFlow { override val networkStatus =
callbackFlow {
val networkStatusCallback = val networkStatusCallback =
when (Build.VERSION.SDK_INT) { when (Build.VERSION.SDK_INT) {
in Build.VERSION_CODES.S..Int.MAX_VALUE -> { in Build.VERSION_CODES.S..Int.MAX_VALUE -> {
@@ -40,10 +41,7 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
trySend(NetworkStatus.Unavailable(network)) trySend(NetworkStatus.Unavailable(network))
} }
override fun onCapabilitiesChanged( override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
network: Network,
networkCapabilities: NetworkCapabilities
) {
trySend( trySend(
NetworkStatus.CapabilitiesChanged( NetworkStatus.CapabilitiesChanged(
network, network,
@@ -64,10 +62,7 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
trySend(NetworkStatus.Unavailable(network)) trySend(NetworkStatus.Unavailable(network))
} }
override fun onCapabilitiesChanged( override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
network: Network,
networkCapabilities: NetworkCapabilities
) {
trySend( trySend(
NetworkStatus.CapabilitiesChanged( NetworkStatus.CapabilitiesChanged(
network, network,
@@ -118,7 +113,7 @@ inline fun <Result> Flow<NetworkStatus>.map(
crossinline onUnavailable: suspend (network: Network) -> Result, crossinline onUnavailable: suspend (network: Network) -> Result,
crossinline onAvailable: suspend (network: Network) -> Result, crossinline onAvailable: suspend (network: Network) -> Result,
crossinline onCapabilitiesChanged: crossinline onCapabilitiesChanged:
suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result suspend (network: Network, networkCapabilities: NetworkCapabilities) -> Result,
): Flow<Result> = map { status -> ): Flow<Result> = map { status ->
when (status) { when (status) {
is NetworkStatus.Unavailable -> onUnavailable(status.network) is NetworkStatus.Unavailable -> onUnavailable(status.network)
@@ -5,5 +5,9 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class EthernetService @Inject constructor(@ApplicationContext context: Context) : class EthernetService
@Inject
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET) BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET)
@@ -5,5 +5,9 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class MobileDataService @Inject constructor(@ApplicationContext context: Context) : class MobileDataService
@Inject
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR) BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR)
@@ -5,5 +5,9 @@ import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class WifiService @Inject constructor(@ApplicationContext context: Context) : class WifiService
@Inject
constructor(
@ApplicationContext context: Context,
) :
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI) BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI)
@@ -9,11 +9,15 @@ import android.content.Intent
import android.graphics.Color import android.graphics.Color
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.ui.MainActivity import com.zaneschepke.wireguardautotunnel.ui.SplashActivity
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject import javax.inject.Inject
class WireGuardNotification @Inject constructor(@ApplicationContext private val context: Context) : class WireGuardNotification
@Inject
constructor(
@ApplicationContext private val context: Context,
) :
NotificationService { NotificationService {
private val notificationManager = private val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
@@ -59,7 +63,7 @@ class WireGuardNotification @Inject constructor(@ApplicationContext private val
} }
notificationManager.createNotificationChannel(channel) notificationManager.createNotificationChannel(channel)
val pendingIntent: PendingIntent = val pendingIntent: PendingIntent =
Intent(context, MainActivity::class.java).let { notificationIntent -> Intent(context, SplashActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity( PendingIntent.getActivity(
context, context,
0, 0,
@@ -15,7 +15,6 @@ import javax.inject.Inject
@AndroidEntryPoint @AndroidEntryPoint
class ShortcutsActivity : ComponentActivity() { class ShortcutsActivity : ComponentActivity() {
@Inject @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@@ -34,17 +33,22 @@ class ShortcutsActivity : ComponentActivity() {
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 = tunnelName?.let { val tunnelConfig =
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 -> serviceManager.stopVpnServiceForeground( Action.STOP.name ->
serviceManager.stopVpnServiceForeground(
this@ShortcutsActivity, this@ShortcutsActivity,
isManualStop = true, isManualStop = true,
) )
@@ -53,13 +57,15 @@ class ShortcutsActivity : ComponentActivity() {
WireGuardConnectivityWatcherService::class.java.simpleName -> { WireGuardConnectivityWatcherService::class.java.simpleName -> {
when (intent.action) { when (intent.action) {
Action.START.name -> appDataRepository.settings.save( Action.START.name ->
appDataRepository.settings.save(
settings.copy( settings.copy(
isAutoTunnelPaused = false, isAutoTunnelPaused = false,
), ),
) )
Action.STOP.name -> appDataRepository.settings.save( Action.STOP.name ->
appDataRepository.settings.save(
settings.copy( settings.copy(
isAutoTunnelPaused = true, isAutoTunnelPaused = true,
), ),
@@ -3,36 +3,35 @@ 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.domain.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import com.zaneschepke.wireguardautotunnel.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.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 AutoTunnelControlTile : TileService() { class AutoTunnelControlTile : TileService(), LifecycleOwner {
@Inject @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var serviceManager: ServiceManager
@Inject private val dispatcher = ServiceLifecycleDispatcher(this)
@ApplicationScope
lateinit var applicationScope: CoroutineScope
private var manualStartConfig: TunnelConfig? = null private var manualStartConfig: TunnelConfig? = null
override fun onStartListening() { override fun onStartListening() {
super.onStartListening() super.onStartListening()
applicationScope.launch { lifecycleScope.launch {
val settings = appDataRepository.settings.getSettings() val settings = appDataRepository.settings.getSettings()
when (settings.isAutoTunnelEnabled) { when (settings.isAutoTunnelEnabled) {
true -> { true -> {
@@ -61,9 +60,10 @@ class AutoTunnelControlTile : TileService() {
override fun onClick() { override fun onClick() {
super.onClick() super.onClick()
unlockAndRun { unlockAndRun {
applicationScope.launch { lifecycleScope.launch {
try { try {
appDataRepository.toggleWatcherServicePause() appDataRepository.toggleWatcherServicePause()
onStartListening()
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e.message) Timber.e(e.message)
} finally { } finally {
@@ -98,4 +98,7 @@ class AutoTunnelControlTile : TileService() {
} }
qsTile.updateTile() qsTile.updateTile()
} }
override val lifecycle: Lifecycle
get() = dispatcher.lifecycle
} }
@@ -3,23 +3,23 @@ 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.data.domain.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState 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.Job
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() { class TunnelControlTile : TileService(), LifecycleOwner {
@Inject @Inject
lateinit var appDataRepository: AppDataRepository lateinit var appDataRepository: AppDataRepository
@@ -29,29 +29,24 @@ class TunnelControlTile : TileService() {
@Inject @Inject
lateinit var serviceManager: ServiceManager lateinit var serviceManager: ServiceManager
@Inject private val dispatcher = ServiceLifecycleDispatcher(this)
@ApplicationScope
lateinit var applicationScope: CoroutineScope
private var manualStartConfig: TunnelConfig? = null private var manualStartConfig: TunnelConfig? = null
private var job: Job? = null;
override fun onStartListening() { override fun onStartListening() {
super.onStartListening() super.onStartListening()
Timber.d("On start listening called") Timber.d("On start listening called")
//TODO Fix this lifecycleScope.launch {
if (job == null || job?.isCancelled == true) job = applicationScope.launch { when (vpnService.getState()) {
vpnService.vpnState.collect { it ->
when (it.status) {
TunnelState.UP -> { TunnelState.UP -> {
setActive() setActive()
it.tunnelConfig?.name?.let { name -> setTileDescription(name) } setTileDescription(vpnService.name)
} }
TunnelState.DOWN -> { TunnelState.DOWN -> {
setInactive() setInactive()
val config = appDataRepository.getStartTunnelConfig()?.also { config -> val config =
appDataRepository.getStartTunnelConfig()?.also { config ->
manualStartConfig = config manualStartConfig = config
} ?: appDataRepository.getPrimaryOrFirstTunnel() } ?: appDataRepository.getPrimaryOrFirstTunnel()
config?.let { config?.let {
@@ -63,7 +58,6 @@ class TunnelControlTile : TileService() {
} }
} }
} }
}
override fun onTileAdded() { override fun onTileAdded() {
super.onTileAdded() super.onTileAdded()
@@ -73,7 +67,7 @@ class TunnelControlTile : TileService() {
override fun onClick() { override fun onClick() {
super.onClick() super.onClick()
unlockAndRun { unlockAndRun {
applicationScope.launch { lifecycleScope.launch {
try { try {
if (vpnService.getState() == TunnelState.UP) { if (vpnService.getState() == TunnelState.UP) {
serviceManager.stopVpnServiceForeground( serviceManager.stopVpnServiceForeground(
@@ -82,7 +76,9 @@ class TunnelControlTile : TileService() {
) )
} else { } else {
serviceManager.startVpnServiceForeground( serviceManager.startVpnServiceForeground(
this@TunnelControlTile, manualStartConfig?.id, isManualStart = true, this@TunnelControlTile,
manualStartConfig?.id,
isManualStart = true,
) )
} }
} catch (e: Exception) { } catch (e: Exception) {
@@ -119,4 +115,7 @@ class TunnelControlTile : TileService() {
} }
qsTile.updateTile() qsTile.updateTile()
} }
override val lifecycle: Lifecycle
get() = dispatcher.lifecycle
} }
@@ -4,7 +4,8 @@ enum class HandshakeStatus {
HEALTHY, HEALTHY,
STALE, STALE,
UNKNOWN, UNKNOWN,
NOT_STARTED; NOT_STARTED,
;
companion object { companion object {
private const val WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC = 180 private const val WG_TYPICAL_HANDSHAKE_INTERVAL_WHEN_HEALTHY_SEC = 180
@@ -5,7 +5,8 @@ import com.wireguard.android.backend.Tunnel
enum class TunnelState { enum class TunnelState {
UP, UP,
DOWN, DOWN,
TOGGLE; TOGGLE,
;
fun toWgState(): Tunnel.State { fun toWgState(): Tunnel.State {
return when (this) { return when (this) {
@@ -6,5 +6,5 @@ import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStati
data class VpnState( data class VpnState(
val status: TunnelState = TunnelState.DOWN, val status: TunnelState = TunnelState.DOWN,
val tunnelConfig: TunnelConfig? = null, val tunnelConfig: TunnelConfig? = null,
val statistics: TunnelStatistics? = null val statistics: TunnelStatistics? = null,
) )
@@ -37,32 +37,26 @@ constructor(
@Kernel private val kernelBackend: Provider<Backend>, @Kernel private val kernelBackend: Provider<Backend>,
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
@ApplicationScope private val applicationScope: CoroutineScope, @ApplicationScope private val applicationScope: CoroutineScope,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : VpnService { ) : 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 var statsJob: Job? = null
private lateinit var backend: Backend;
private var backendIsWgUserspace = true private var backendIsWgUserspace = true
private var backendIsAmneziaUserspace = false private var backendIsAmneziaUserspace = false
init { init {
applicationScope.launch(ioDispatcher) { applicationScope.launch(ioDispatcher) {
backend = userspaceBackend.get()
appDataRepository.settings.getSettingsFlow().collect { appDataRepository.settings.getSettingsFlow().collect {
if (it.isKernelEnabled && (backendIsWgUserspace || backendIsAmneziaUserspace)) { if (it.isKernelEnabled && (backendIsWgUserspace || backendIsAmneziaUserspace)) {
Timber.i("Setting kernel backend") Timber.i("Setting kernel backend")
backend = kernelBackend.get()
backendIsWgUserspace = false backendIsWgUserspace = false
backendIsAmneziaUserspace = false backendIsAmneziaUserspace = false
} else if (!it.isKernelEnabled && !it.isAmneziaEnabled && !backendIsWgUserspace) { } else if (!it.isKernelEnabled && !it.isAmneziaEnabled && !backendIsWgUserspace) {
Timber.i("Setting WireGuard userspace backend") Timber.i("Setting WireGuard userspace backend")
backend = userspaceBackend.get()
backendIsWgUserspace = true backendIsWgUserspace = true
backendIsAmneziaUserspace = false backendIsAmneziaUserspace = false
} else if (it.isAmneziaEnabled && !backendIsAmneziaUserspace) { } else if (it.isAmneziaEnabled && !backendIsAmneziaUserspace) {
@@ -77,9 +71,14 @@ constructor(
private fun setState(tunnelConfig: TunnelConfig?, tunnelState: TunnelState): TunnelState { private fun setState(tunnelConfig: TunnelConfig?, tunnelState: TunnelState): TunnelState {
return if (backendIsAmneziaUserspace) { return if (backendIsAmneziaUserspace) {
Timber.i("Using Amnezia backend") Timber.i("Using Amnezia backend")
val config = tunnelConfig?.let { val config =
if (it.amQuick != "") TunnelConfig.configFromAmQuick(it.amQuick) else { tunnelConfig?.let {
Timber.w("Using backwards compatible wg config, amnezia specific config not found.") if (it.amQuick != "") {
TunnelConfig.configFromAmQuick(it.amQuick)
} else {
Timber.w(
"Using backwards compatible wg config, amnezia specific config not found.",
)
TunnelConfig.configFromAmQuick(it.wgQuick) TunnelConfig.configFromAmQuick(it.wgQuick)
} }
} }
@@ -89,7 +88,8 @@ constructor(
} else { } else {
Timber.i("Using Wg backend") Timber.i("Using Wg backend")
val wgConfig = tunnelConfig?.let { TunnelConfig.configFromWgQuick(it.wgQuick) } val wgConfig = tunnelConfig?.let { TunnelConfig.configFromWgQuick(it.wgQuick) }
val state = backend.setState( val state =
backend().setState(
this, this,
tunnelState.toWgState(), tunnelState.toWgState(),
wgConfig, wgConfig,
@@ -102,11 +102,14 @@ constructor(
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
try { try {
// TODO we need better error handling here // TODO we need better error handling here
// need to bubble up these errors to the UI
val config = tunnelConfig ?: appDataRepository.getPrimaryOrFirstTunnel() val config = tunnelConfig ?: appDataRepository.getPrimaryOrFirstTunnel()
if (config != null) { if (config != null) {
emitTunnelConfig(config) emitTunnelConfig(config)
setState(config, TunnelState.UP) setState(config, TunnelState.UP)
} else throw Exception("No tunnels") } else {
throw Exception("No tunnels")
}
} catch (e: BackendException) { } catch (e: BackendException) {
Timber.e("Failed to start tunnel with error: ${e.message}") Timber.e("Failed to start tunnel with error: ${e.message}")
TunnelState.from(State.DOWN) TunnelState.from(State.DOWN)
@@ -114,6 +117,22 @@ constructor(
} }
} }
private fun backend(): Backend {
return when {
backendIsWgUserspace -> {
userspaceBackend.get()
}
!backendIsWgUserspace && !backendIsAmneziaUserspace -> {
kernelBackend.get()
}
else -> {
userspaceBackend.get()
}
}
}
private fun emitTunnelState(state: TunnelState) { private fun emitTunnelState(state: TunnelState) {
_vpnState.tryEmit( _vpnState.tryEmit(
_vpnState.value.copy( _vpnState.value.copy(
@@ -159,17 +178,19 @@ constructor(
} }
override fun getState(): TunnelState { override fun getState(): TunnelState {
return if (backendIsAmneziaUserspace) TunnelState.from( return if (backendIsAmneziaUserspace) {
TunnelState.from(
userspaceAmneziaBackend.get().getState(this), userspaceAmneziaBackend.get().getState(this),
) )
else TunnelState.from(backend.getState(this)) } else {
TunnelState.from(backend().getState(this))
}
} }
override fun getName(): String { override fun getName(): String {
return _vpnState.value.tunnelConfig?.name ?: "" return _vpnState.value.tunnelConfig?.name ?: ""
} }
override fun onStateChange(newState: Tunnel.State) { override fun onStateChange(newState: Tunnel.State) {
handleStateChange(TunnelState.from(newState)) handleStateChange(TunnelState.from(newState))
} }
@@ -198,7 +219,9 @@ constructor(
), ),
) )
} else { } else {
emitBackendStatistics(WireGuardStatistics(backend.getStatistics(this@WireGuardTunnel))) emitBackendStatistics(
WireGuardStatistics(backend().getStatistics(this@WireGuardTunnel)),
)
} }
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL) delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
} }
@@ -5,5 +5,5 @@ data class AppUiState(
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,
) )
@@ -20,17 +20,16 @@ import javax.inject.Inject
class AppViewModel class AppViewModel
@Inject @Inject
constructor() : ViewModel() { constructor() : ViewModel() {
val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance) val vpnIntent: Intent? = GoBackend.VpnService.prepare(WireGuardAutoTunnel.instance)
private val _appUiState = MutableStateFlow( private val _appUiState =
MutableStateFlow(
AppUiState( AppUiState(
vpnPermissionAccepted = vpnIntent == null, vpnPermissionAccepted = vpnIntent == null,
), ),
) )
val appUiState = _appUiState.asStateFlow() val appUiState = _appUiState.asStateFlow()
fun isRequiredPermissionGranted(): Boolean { fun isRequiredPermissionGranted(): Boolean {
val allAccepted = val allAccepted =
(_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted) (_appUiState.value.vpnPermissionAccepted && _appUiState.value.vpnPermissionAccepted)
@@ -57,7 +56,8 @@ constructor() : ViewModel() {
fun openWebPage(url: String, context: Context) { fun openWebPage(url: String, context: Context) {
try { try {
val webpage: Uri = Uri.parse(url) val webpage: Uri = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, webpage).apply { val intent =
Intent(Intent.ACTION_VIEW, webpage).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
} }
context.startActivity(intent) context.startActivity(intent)
@@ -1,5 +0,0 @@
package com.zaneschepke.wireguardautotunnel.ui
import com.journeyapps.barcodescanner.CaptureActivity
class CaptureActivityPortrait : CaptureActivity()
@@ -10,6 +10,8 @@ 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
@@ -19,15 +21,19 @@ 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
@@ -41,11 +47,13 @@ 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.datastore.DataStoreManager import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
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
@@ -61,14 +69,12 @@ 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 @Inject
lateinit var dataStoreManager: DataStoreManager lateinit var appStateRepository: AppStateRepository
@Inject @Inject
lateinit var settingsRepository: SettingsRepository lateinit var settingsRepository: SettingsRepository
@@ -82,26 +88,31 @@ class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
val isPinLockEnabled = intent.extras?.getBoolean(SplashActivity.IS_PIN_LOCK_ENABLED_KEY)
enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb())) enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb()))
// load preferences into memory and init data
lifecycleScope.launch { lifecycleScope.launch {
dataStoreManager.init()
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate() WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
val settings = settingsRepository.getSettings() val settings = settingsRepository.getSettings()
if (settings.isAutoTunnelEnabled) { if (settings.isAutoTunnelEnabled) {
serviceManager.startWatcherService(application.applicationContext) serviceManager.startWatcherService(application.applicationContext)
} }
} }
setContent { setContent {
val appViewModel = hiltViewModel<AppViewModel>() val appViewModel = hiltViewModel<AppViewModel>()
val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle() val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle()
val navController = rememberNavController() val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState() val navBackStackEntry by navController.currentBackStackEntryAsState()
var showVpnPermissionDialog by remember { mutableStateOf(false) }
val notificationPermissionState = val notificationPermissionState =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS) else null rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS)
} else {
null
}
val snackbarHostState = remember { SnackbarHostState() } val snackbarHostState = remember { SnackbarHostState() }
@@ -112,6 +123,8 @@ class MainActivity : AppCompatActivity() {
val accepted = (it.resultCode == RESULT_OK) val accepted = (it.resultCode == RESULT_OK)
if (accepted) { if (accepted) {
appViewModel.onVpnPermissionAccepted() appViewModel.onVpnPermissionAccepted()
} else {
showVpnPermissionDialog = true
} }
}, },
) )
@@ -125,7 +138,8 @@ class MainActivity : AppCompatActivity() {
) )
when (result) { when (result) {
SnackbarResult.ActionPerformed, SnackbarResult.ActionPerformed,
SnackbarResult.Dismissed -> { SnackbarResult.Dismissed,
-> {
snackbarHostState.currentSnackbarData?.dismiss() snackbarHostState.currentSnackbarData?.dismiss()
} }
} }
@@ -137,15 +151,21 @@ class MainActivity : AppCompatActivity() {
appViewModel.permissionsRequested() appViewModel.permissionsRequested()
if (notificationPermissionState != null && !notificationPermissionState.status.isGranted if (notificationPermissionState != null && !notificationPermissionState.status.isGranted
) { ) {
showSnackBarMessage(StringValue.StringResource(R.string.notification_permission_required)) notificationPermissionState.launchPermissionRequest()
return@LaunchedEffect notificationPermissionState.launchPermissionRequest() return@LaunchedEffect if (notificationPermissionState.status.shouldShowRationale || !notificationPermissionState.status.isGranted) {
showSnackBarMessage(
StringValue.StringResource(R.string.notification_permission_required),
)
} else {
Unit
}
} }
if (!appUiState.vpnPermissionAccepted) { if (!appUiState.vpnPermissionAccepted) {
return@LaunchedEffect appViewModel.vpnIntent?.let { return@LaunchedEffect appViewModel.vpnIntent?.let {
vpnActivityResultState.launch( vpnActivityResultState.launch(
it, it,
) )
}!! } ?: Unit
} }
} }
} }
@@ -166,6 +186,21 @@ class MainActivity : AppCompatActivity() {
val focusRequester = remember { FocusRequester() } val focusRequester = remember { FocusRequester() }
if (showVpnPermissionDialog) {
InfoDialog(
onDismiss = { showVpnPermissionDialog = false },
onAttest = { showVpnPermissionDialog = false },
title = { Text(text = stringResource(R.string.vpn_denied_dialog_title)) },
body = {
Column(verticalArrangement = Arrangement.spacedBy(15.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)) },
)
}
Scaffold( Scaffold(
snackbarHost = { snackbarHost = {
SnackbarHost(snackbarHostState) { snackbarData: SnackbarData -> SnackbarHost(snackbarHostState) { snackbarData: SnackbarData ->
@@ -180,7 +215,8 @@ class MainActivity : AppCompatActivity() {
} }
}, },
// TODO refactor // TODO refactor
modifier = Modifier modifier =
Modifier
.focusable() .focusable()
.focusProperties { .focusProperties {
when (navBackStackEntry?.destination?.route) { when (navBackStackEntry?.destination?.route) {
@@ -201,10 +237,7 @@ class MainActivity : AppCompatActivity() {
) { padding -> ) { padding ->
NavHost( NavHost(
navController, navController,
startDestination = startDestination = (if (isPinLockEnabled == true) Screen.Lock.route else Screen.Main.route),
//TODO disable pin lock
//(if (PinManager.pinExists()) Screen.Lock.route else Screen.Main.route),
Screen.Main.route,
modifier = modifier =
Modifier Modifier
.padding(padding) .padding(padding)
@@ -255,7 +288,8 @@ class MainActivity : AppCompatActivity() {
), ),
) { ) {
val id = it.arguments?.getString("id") val id = it.arguments?.getString("id")
val configType = ConfigType.valueOf( val configType =
ConfigType.valueOf(
it.arguments?.getString("configType") ?: ConfigType.WIREGUARD.name, it.arguments?.getString("configType") ?: ConfigType.WIREGUARD.name,
) )
if (!id.isNullOrBlank()) { if (!id.isNullOrBlank()) {
@@ -39,6 +39,7 @@ sealed class Screen(val route: String) {
} }
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")
@@ -0,0 +1,67 @@
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,13 +12,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
@Composable @Composable
fun ClickableIconButton( fun ClickableIconButton(onClick: () -> Unit, onIconClick: () -> Unit, text: String, icon: ImageVector, enabled: Boolean) {
onClick: () -> Unit,
onIconClick: () -> Unit,
text: String,
icon: ImageVector,
enabled: Boolean
) {
TextButton( TextButton(
onClick = onClick, onClick = onClick,
enabled = enabled, enabled = enabled,
@@ -15,6 +15,8 @@ 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.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
@@ -31,11 +33,13 @@ fun RowListItem(
onClick: () -> Unit, onClick: () -> Unit,
rowButton: @Composable () -> Unit, rowButton: @Composable () -> Unit,
expanded: Boolean, expanded: Boolean,
statistics: TunnelStatistics? statistics: TunnelStatistics?,
focusRequester: FocusRequester,
) { ) {
Box( Box(
modifier = modifier =
Modifier Modifier
.focusRequester(focusRequester)
.animateContentSize() .animateContentSize()
.clip(RoundedCornerShape(30.dp)) .clip(RoundedCornerShape(30.dp))
.combinedClickable( .combinedClickable(
@@ -45,7 +49,8 @@ fun RowListItem(
) { ) {
Column { Column {
Row( Row(
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 15.dp, vertical = 5.dp), .padding(horizontal = 15.dp, vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -16,7 +16,7 @@ fun ConfigurationTextBox(
onValueChange: (String) -> Unit, onValueChange: (String) -> Unit,
keyboardActions: KeyboardActions, keyboardActions: KeyboardActions,
label: String, label: String,
modifier: Modifier modifier: Modifier,
) { ) {
OutlinedTextField( OutlinedTextField(
modifier = modifier, modifier = modifier,
@@ -13,24 +13,20 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
@Composable @Composable
fun ConfigurationToggle( fun ConfigurationToggle(label: String, enabled: Boolean, checked: Boolean, padding: Dp, onCheckChanged: () -> Unit, modifier: Modifier = Modifier) {
label: String,
enabled: Boolean,
checked: Boolean,
padding: Dp,
onCheckChanged: () -> Unit,
modifier: Modifier = Modifier
) {
Row( Row(
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(padding), .padding(padding),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
) { ) {
Text( Text(
label, textAlign = TextAlign.Start, label,
modifier = Modifier textAlign = TextAlign.Start,
modifier =
Modifier
.weight( .weight(
weight = 1.0f, weight = 1.0f,
fill = false, fill = false,
@@ -0,0 +1,37 @@
package com.zaneschepke.wireguardautotunnel.ui.common.dialog
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.zaneschepke.wireguardautotunnel.R
@Composable
fun InfoDialog(
onAttest: () -> Unit,
onDismiss: () -> Unit,
title: @Composable () -> Unit,
body: @Composable () -> Unit,
confirmText: @Composable () -> Unit,
) {
AlertDialog(
onDismissRequest = { onDismiss() },
confirmButton = {
TextButton(
onClick = {
onAttest()
},
) {
confirmText()
}
},
dismissButton = {
TextButton(onClick = { onDismiss() }) {
Text(text = stringResource(R.string.cancel))
}
},
title = { title() },
text = { body() },
)
}
@@ -24,7 +24,8 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
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 = when (navBackStackEntry?.destination?.route) { showBottomBar =
when (navBackStackEntry?.destination?.route) {
Screen.Lock.route -> false Screen.Lock.route -> false
else -> true else -> true
} }
@@ -32,7 +33,8 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
NavigationBar( NavigationBar(
containerColor = if (!showBottomBar) Color.Transparent else MaterialTheme.colorScheme.background, containerColor = if (!showBottomBar) Color.Transparent else MaterialTheme.colorScheme.background,
) { ) {
if (showBottomBar) bottomNavItems.forEach { item -> if (showBottomBar) {
bottomNavItems.forEach { item ->
val selected = item.route == backStackEntry.value?.destination?.route val selected = item.route == backStackEntry.value?.destination?.route
NavigationBarItem( NavigationBarItem(
@@ -54,3 +56,4 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
} }
} }
} }
}
@@ -15,7 +15,8 @@ fun AuthorizationPrompt(onSuccess: () -> Unit, onFailure: () -> Unit, onError: (
val context = LocalContext.current val context = LocalContext.current
val biometricManager = BiometricManager.from(context) val biometricManager = BiometricManager.from(context)
val bio = biometricManager.canAuthenticate(BIOMETRIC_WEAK or DEVICE_CREDENTIAL) val bio = biometricManager.canAuthenticate(BIOMETRIC_WEAK or DEVICE_CREDENTIAL)
val isBiometricAvailable = remember { val isBiometricAvailable =
remember {
when (bio) { when (bio) {
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> { BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
onError("Biometrics not available") onError("Biometrics not available")
@@ -71,9 +72,7 @@ fun AuthorizationPrompt(onSuccess: () -> Unit, onFailure: () -> Unit, onError: (
onFailure() onFailure()
} }
override fun onAuthenticationSucceeded( override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
result: BiometricPrompt.AuthenticationResult
) {
super.onAuthenticationSucceeded(result) super.onAuthenticationSucceeded(result)
onSuccess() onSuccess()
} }
@@ -25,11 +25,7 @@ import androidx.compose.ui.unit.dp
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
@Composable @Composable
fun CustomSnackBar( fun CustomSnackBar(message: String, isRtl: Boolean = true, containerColor: Color = MaterialTheme.colorScheme.surface) {
message: String,
isRtl: Boolean = true,
containerColor: Color = MaterialTheme.colorScheme.surface
) {
Snackbar( Snackbar(
containerColor = containerColor, containerColor = containerColor,
modifier = modifier =
@@ -44,7 +40,8 @@ fun CustomSnackBar(
LocalLayoutDirection provides if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr, LocalLayoutDirection provides if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr,
) { ) {
Row( Row(
modifier = Modifier modifier =
Modifier
.width(IntrinsicSize.Max) .width(IntrinsicSize.Max)
.height(IntrinsicSize.Min), .height(IntrinsicSize.Min),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -16,7 +16,8 @@ fun LoadingScreen() {
Column( Column(
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top, verticalArrangement = Arrangement.Top,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.focusable() .focusable()
.padding(), .padding(),
@@ -14,7 +14,8 @@ import androidx.compose.ui.unit.dp
@Composable @Composable
fun LogTypeLabel(color: Color, content: @Composable () -> Unit) { fun LogTypeLabel(color: Color, content: @Composable () -> Unit) {
Box( Box(
modifier = Modifier modifier =
Modifier
.size(20.dp) .size(20.dp)
.clip(RoundedCornerShape(2.dp)) .clip(RoundedCornerShape(2.dp))
.background(color), .background(color),
@@ -95,7 +95,7 @@ fun ConfigScreen(
navController: NavController, navController: NavController,
appViewModel: AppViewModel, appViewModel: AppViewModel,
tunnelId: String, tunnelId: String,
configType: ConfigType configType: ConfigType,
) { ) {
val context = LocalContext.current val context = LocalContext.current
val clipboardManager: ClipboardManager = LocalClipboardManager.current val clipboardManager: ClipboardManager = LocalClipboardManager.current
@@ -128,16 +128,23 @@ fun ConfigScreen(
val fillMaxWidth = .85f val fillMaxWidth = .85f
val screenPadding = 5.dp val screenPadding = 5.dp
val applicationButtonText = buildAnnotatedString { val applicationButtonText =
buildAnnotatedString {
append(stringResource(id = R.string.tunneling_apps)) append(stringResource(id = R.string.tunneling_apps))
append(": ") append(": ")
if (uiState.isAllApplicationsEnabled) { if (uiState.isAllApplicationsEnabled) {
append(stringResource(id = R.string.all)) append(stringResource(id = R.string.all))
} else { } else {
append("${uiState.checkedPackageNames.size} ") append("${uiState.checkedPackageNames.size} ")
(if (uiState.include) append(stringResource(id = R.string.included)) else append( (
if (uiState.include) {
append(stringResource(id = R.string.included))
} else {
append(
stringResource(id = R.string.excluded), stringResource(id = R.string.excluded),
)) )
}
)
} }
} }
@@ -149,11 +156,15 @@ fun ConfigScreen(
}, },
onError = { onError = {
showAuthPrompt = false showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authentication_failed)) appViewModel.showSnackbarMessage(
context.getString(R.string.error_authentication_failed),
)
}, },
onFailure = { onFailure = {
showAuthPrompt = false showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authorization_failed)) appViewModel.showSnackbarMessage(
context.getString(R.string.error_authorization_failed),
)
}, },
) )
} }
@@ -175,7 +186,8 @@ fun ConfigScreen(
.fillMaxHeight(if (uiState.isAllApplicationsEnabled) 1 / 5f else 4 / 5f), .fillMaxHeight(if (uiState.isAllApplicationsEnabled) 1 / 5f else 4 / 5f),
) { ) {
Column( Column(
modifier = Modifier modifier =
Modifier
.fillMaxWidth(), .fillMaxWidth(),
) { ) {
Row( Row(
@@ -246,7 +258,8 @@ fun ConfigScreen(
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(5.dp), .padding(5.dp),
) { ) {
@@ -275,9 +288,11 @@ fun ConfigScreen(
Checkbox( Checkbox(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
checked = checked =
(uiState.checkedPackageNames.contains( (
uiState.checkedPackageNames.contains(
pack.packageName, pack.packageName,
)), )
),
onCheckedChange = { onCheckedChange = {
if (it) { if (it) {
viewModel.onAddCheckedPackage(pack.packageName) viewModel.onAddCheckedPackage(pack.packageName)
@@ -292,7 +307,8 @@ fun ConfigScreen(
} }
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(top = 5.dp), .padding(top = 5.dp),
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
@@ -321,7 +337,9 @@ fun ConfigScreen(
}, },
onClick = { onClick = {
viewModel.onSaveAllChanges(configType).onSuccess { viewModel.onSaveAllChanges(configType).onSuccess {
appViewModel.showSnackbarMessage(context.getString(R.string.config_changes_saved)) appViewModel.showSnackbarMessage(
context.getString(R.string.config_changes_saved),
)
navController.navigate(Screen.Main.route) navController.navigate(Screen.Main.route)
}.onFailure { }.onFailure {
appViewModel.showSnackbarMessage(it.getMessage(context)) appViewModel.showSnackbarMessage(it.getMessage(context))
@@ -354,19 +372,22 @@ fun ConfigScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.fillMaxHeight(fillMaxHeight) .fillMaxHeight(fillMaxHeight)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
} else { } else {
Modifier.fillMaxWidth(fillMaxWidth) Modifier.fillMaxWidth(fillMaxWidth)
}) }
)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Column( Column(
horizontalAlignment = Alignment.Start, horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top, verticalArrangement = Arrangement.Top,
modifier = Modifier modifier =
Modifier
.padding(15.dp) .padding(15.dp)
.focusGroup(), .focusGroup(),
) { ) {
@@ -380,19 +401,23 @@ fun ConfigScreen(
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.name), label = stringResource(R.string.name),
hint = stringResource(R.string.tunnel_name).lowercase(), hint = stringResource(R.string.tunnel_name).lowercase(),
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
OutlinedTextField( OutlinedTextField(
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.clickable { showAuthPrompt = true }, .clickable { showAuthPrompt = true },
value = uiState.interfaceProxy.privateKey, value = uiState.interfaceProxy.privateKey,
visualTransformation = visualTransformation =
if ((tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated) if ((tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated) {
VisualTransformation.None VisualTransformation.None
else PasswordVisualTransformation(), } else {
PasswordVisualTransformation()
},
enabled = (tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated, enabled = (tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated,
onValueChange = { value -> viewModel.onPrivateKeyChange(value) }, onValueChange = { value -> viewModel.onPrivateKeyChange(value) },
trailingIcon = { trailingIcon = {
@@ -450,7 +475,8 @@ fun ConfigScreen(
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.addresses), label = stringResource(R.string.addresses),
hint = stringResource(R.string.comma_separated_list), hint = stringResource(R.string.comma_separated_list),
modifier = Modifier modifier =
Modifier
.fillMaxWidth(3 / 5f) .fillMaxWidth(3 / 5f)
.padding(end = 5.dp), .padding(end = 5.dp),
) )
@@ -470,7 +496,8 @@ fun ConfigScreen(
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.dns_servers), label = stringResource(R.string.dns_servers),
hint = stringResource(R.string.comma_separated_list), hint = stringResource(R.string.comma_separated_list),
modifier = Modifier modifier =
Modifier
.fillMaxWidth(3 / 5f) .fillMaxWidth(3 / 5f)
.padding(end = 5.dp), .padding(end = 5.dp),
) )
@@ -486,11 +513,15 @@ fun ConfigScreen(
if (configType == ConfigType.AMNEZIA) { if (configType == ConfigType.AMNEZIA) {
ConfigurationTextBox( ConfigurationTextBox(
value = uiState.interfaceProxy.junkPacketCount, value = uiState.interfaceProxy.junkPacketCount,
onValueChange = { value -> viewModel.onJunkPacketCountChanged(value) }, onValueChange = {
value ->
viewModel.onJunkPacketCountChanged(value)
},
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.junk_packet_count), label = stringResource(R.string.junk_packet_count),
hint = stringResource(R.string.junk_packet_count).lowercase(), hint = stringResource(R.string.junk_packet_count).lowercase(),
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -503,8 +534,12 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.junk_packet_minimum_size), label = stringResource(R.string.junk_packet_minimum_size),
hint = stringResource(R.string.junk_packet_minimum_size).lowercase(), hint =
modifier = Modifier stringResource(
R.string.junk_packet_minimum_size,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -517,8 +552,12 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.junk_packet_maximum_size), label = stringResource(R.string.junk_packet_maximum_size),
hint = stringResource(R.string.junk_packet_maximum_size).lowercase(), hint =
modifier = Modifier stringResource(
R.string.junk_packet_maximum_size,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -532,27 +571,42 @@ fun ConfigScreen(
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.init_packet_junk_size), label = stringResource(R.string.init_packet_junk_size),
hint = stringResource(R.string.init_packet_junk_size).lowercase(), hint = stringResource(R.string.init_packet_junk_size).lowercase(),
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
ConfigurationTextBox( ConfigurationTextBox(
value = uiState.interfaceProxy.responsePacketJunkSize, value = uiState.interfaceProxy.responsePacketJunkSize,
onValueChange = { value -> viewModel.onResponsePacketJunkSize(value) }, onValueChange = {
value ->
viewModel.onResponsePacketJunkSize(value)
},
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.response_packet_junk_size), label = stringResource(R.string.response_packet_junk_size),
hint = stringResource(R.string.response_packet_junk_size).lowercase(), hint =
modifier = Modifier stringResource(
R.string.response_packet_junk_size,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
ConfigurationTextBox( ConfigurationTextBox(
value = uiState.interfaceProxy.initPacketMagicHeader, value = uiState.interfaceProxy.initPacketMagicHeader,
onValueChange = { value -> viewModel.onInitPacketMagicHeader(value) }, onValueChange = {
value ->
viewModel.onInitPacketMagicHeader(value)
},
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.init_packet_magic_header), label = stringResource(R.string.init_packet_magic_header),
hint = stringResource(R.string.init_packet_magic_header).lowercase(), hint =
modifier = Modifier stringResource(
R.string.init_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -565,8 +619,12 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.response_packet_magic_header), label = stringResource(R.string.response_packet_magic_header),
hint = stringResource(R.string.response_packet_magic_header).lowercase(), hint =
modifier = Modifier stringResource(
R.string.response_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -579,8 +637,12 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.underload_packet_magic_header), label = stringResource(R.string.underload_packet_magic_header),
hint = stringResource(R.string.underload_packet_magic_header).lowercase(), hint =
modifier = Modifier stringResource(
R.string.underload_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
@@ -593,15 +655,20 @@ fun ConfigScreen(
}, },
keyboardActions = keyboardActions, keyboardActions = keyboardActions,
label = stringResource(R.string.transport_packet_magic_header), label = stringResource(R.string.transport_packet_magic_header),
hint = stringResource(R.string.transport_packet_magic_header).lowercase(), hint =
modifier = Modifier stringResource(
R.string.transport_packet_magic_header,
).lowercase(),
modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.focusRequester(focusRequester), .focusRequester(focusRequester),
) )
} }
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(top = 5.dp), .padding(top = 5.dp),
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
@@ -619,26 +686,30 @@ fun ConfigScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.fillMaxHeight(fillMaxHeight) .fillMaxHeight(fillMaxHeight)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
} else { } else {
Modifier.fillMaxWidth(fillMaxWidth) Modifier.fillMaxWidth(fillMaxWidth)
}) }
)
.padding(top = 10.dp, bottom = 10.dp), .padding(top = 10.dp, bottom = 10.dp),
) { ) {
Column( Column(
horizontalAlignment = Alignment.Start, horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top, verticalArrangement = Arrangement.Top,
modifier = Modifier modifier =
Modifier
.padding(horizontal = 15.dp) .padding(horizontal = 15.dp)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Row( Row(
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 5.dp), .padding(horizontal = 5.dp),
) { ) {
@@ -724,7 +795,8 @@ fun ConfigScreen(
Row( Row(
horizontalArrangement = Arrangement.SpaceEvenly, horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(bottom = 140.dp), .padding(bottom = 140.dp),
) { ) {
@@ -16,7 +16,7 @@ data class ConfigUiState(
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 val isAmneziaEnabled: Boolean = false,
) { ) {
companion object { companion object {
fun from(config: Config): ConfigUiState { fun from(config: Config): ConfigUiState {
@@ -40,16 +40,14 @@ class ConfigViewModel
constructor( constructor(
private val settingsRepository: SettingsRepository, private val settingsRepository: SettingsRepository,
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : ViewModel() { ) : ViewModel() {
private val packageManager = WireGuardAutoTunnel.instance.packageManager private val packageManager = WireGuardAutoTunnel.instance.packageManager
private val _uiState = MutableStateFlow(ConfigUiState()) private val _uiState = MutableStateFlow(ConfigUiState())
val uiState = _uiState.asStateFlow() val uiState = _uiState.asStateFlow()
fun init(tunnelId: String) = fun init(tunnelId: String) = viewModelScope.launch(ioDispatcher) {
viewModelScope.launch(ioDispatcher) {
val packages = getQueriedPackages("") val packages = getQueriedPackages("")
val state = val state =
if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) { if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) {
@@ -58,11 +56,17 @@ constructor(
.firstOrNull { it.id.toString() == tunnelId } .firstOrNull { it.id.toString() == tunnelId }
val isAmneziaEnabled = settingsRepository.getSettings().isAmneziaEnabled val isAmneziaEnabled = settingsRepository.getSettings().isAmneziaEnabled
if (tunnelConfig != null) { if (tunnelConfig != null) {
(if (isAmneziaEnabled) { (
if (isAmneziaEnabled) {
val amConfig = val amConfig =
if (tunnelConfig.amQuick == "") tunnelConfig.wgQuick else tunnelConfig.amQuick if (tunnelConfig.amQuick == "") tunnelConfig.wgQuick else tunnelConfig.amQuick
ConfigUiState.from(TunnelConfig.configFromAmQuick(amConfig)) ConfigUiState.from(TunnelConfig.configFromAmQuick(amConfig))
} else ConfigUiState.from(TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick))).copy( } else {
ConfigUiState.from(
TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick),
)
}
).copy(
packages = packages, packages = packages,
loading = false, loading = false,
tunnel = tunnelConfig, tunnel = tunnelConfig,
@@ -111,7 +115,7 @@ constructor(
} }
fun getPackageLabel(packageInfo: PackageInfo): String { fun getPackageLabel(packageInfo: PackageInfo): String {
return packageInfo.applicationInfo.loadLabel(packageManager).toString() return packageInfo.applicationInfo?.loadLabel(packageManager).toString()
} }
private fun getAllInternetCapablePackages(): List<PackageInfo> { private fun getAllInternetCapablePackages(): List<PackageInfo> {
@@ -133,11 +137,9 @@ constructor(
return _uiState.value.isAllApplicationsEnabled return _uiState.value.isAllApplicationsEnabled
} }
private fun saveConfig(tunnelConfig: TunnelConfig) = private fun saveConfig(tunnelConfig: TunnelConfig) = viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) }
viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) }
private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) = private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) = viewModelScope.launch {
viewModelScope.launch {
if (tunnelConfig != null) { if (tunnelConfig != null) {
saveConfig(tunnelConfig).join() saveConfig(tunnelConfig).join()
WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate() WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
@@ -183,14 +185,23 @@ constructor(
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(
_uiState.value.checkedPackageNames,
)
}
if (!_uiState.value.include) {
builder.excludeApplications(
_uiState.value.checkedPackageNames,
)
}
return builder.build() return builder.build()
} }
@@ -201,16 +212,27 @@ constructor(
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(
_uiState.value.checkedPackageNames,
)
}
if (!_uiState.value.include) {
builder.excludeApplications(
_uiState.value.checkedPackageNames,
)
}
if (_uiState.value.interfaceProxy.junkPacketCount.isNotEmpty()) { if (_uiState.value.interfaceProxy.junkPacketCount.isNotEmpty()) {
builder.setJunkPacketCount(_uiState.value.interfaceProxy.junkPacketCount.trim().toInt()) builder.setJunkPacketCount(
_uiState.value.interfaceProxy.junkPacketCount.trim().toInt(),
)
} }
if (_uiState.value.interfaceProxy.junkPacketMinSize.isNotEmpty()) { if (_uiState.value.interfaceProxy.junkPacketMinSize.isNotEmpty()) {
builder.setJunkPacketMinSize( builder.setJunkPacketMinSize(
@@ -264,24 +286,32 @@ constructor(
private fun buildAmConfig(): org.amnezia.awg.config.Config { private fun buildAmConfig(): org.amnezia.awg.config.Config {
val peerList = buildAmPeerListFromProxyPeers() val peerList = buildAmPeerListFromProxyPeers()
val amInterface = buildAmInterfaceListFromProxyInterface() val amInterface = buildAmInterfaceListFromProxyInterface()
return org.amnezia.awg.config.Config.Builder().addPeers(peerList).setInterface(amInterface) return org.amnezia.awg.config.Config.Builder().addPeers(
peerList,
).setInterface(amInterface)
.build() .build()
} }
fun onSaveAllChanges(configType: ConfigType): Result<Unit> { fun onSaveAllChanges(configType: ConfigType): Result<Unit> {
return try { return try {
val wgQuick = buildConfig().toWgQuickString() val wgQuick = buildConfig().toWgQuickString()
val amQuick = if (configType == ConfigType.AMNEZIA) { val amQuick =
if (configType == ConfigType.AMNEZIA) {
buildAmConfig().toAwgQuickString() buildAmConfig().toAwgQuickString()
} else TunnelConfig.AM_QUICK_DEFAULT } else {
val tunnelConfig = when (uiState.value.tunnel) { TunnelConfig.AM_QUICK_DEFAULT
null -> TunnelConfig( }
val tunnelConfig =
when (uiState.value.tunnel) {
null ->
TunnelConfig(
name = _uiState.value.tunnelName, name = _uiState.value.tunnelName,
wgQuick = wgQuick, wgQuick = wgQuick,
amQuick = amQuick, amQuick = amQuick,
) )
else -> uiState.value.tunnel!!.copy( else ->
uiState.value.tunnel!!.copy(
name = _uiState.value.tunnelName, name = _uiState.value.tunnelName,
wgQuick = wgQuick, wgQuick = wgQuick,
amQuick = amQuick, amQuick = amQuick,
@@ -292,7 +322,8 @@ constructor(
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e) Timber.e(e)
val message = e.message?.substringAfter(":", missingDelimiterValue = "") val message = e.message?.substringAfter(":", missingDelimiterValue = "")
val stringValue = message?.let { val stringValue =
message?.let {
StringValue.DynamicString(message) StringValue.DynamicString(message)
} ?: StringValue.StringResource(R.string.unknown_error) } ?: StringValue.StringResource(R.string.unknown_error)
Result.failure(WgTunnelExceptions.ConfigParseError(stringValue)) Result.failure(WgTunnelExceptions.ConfigParseError(stringValue))
@@ -392,7 +423,6 @@ constructor(
interfaceProxy = _uiState.value.interfaceProxy.copy(addresses = value), interfaceProxy = _uiState.value.interfaceProxy.copy(addresses = value),
) )
} }
} }
fun onListenPortChanged(value: String) { fun onListenPortChanged(value: String) {
@@ -423,7 +453,6 @@ constructor(
interfaceProxy = _uiState.value.interfaceProxy.copy(publicKey = value), interfaceProxy = _uiState.value.interfaceProxy.copy(publicKey = value),
) )
} }
} }
fun onPrivateKeyChange(value: String) { fun onPrivateKeyChange(value: String) {
@@ -483,7 +512,10 @@ constructor(
fun onResponsePacketJunkSize(value: String) { fun onResponsePacketJunkSize(value: String) {
_uiState.update { _uiState.update {
it.copy( it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(responsePacketJunkSize = value), interfaceProxy =
_uiState.value.interfaceProxy.copy(
responsePacketJunkSize = value,
),
) )
} }
} }
@@ -491,7 +523,10 @@ constructor(
fun onInitPacketMagicHeader(value: String) { fun onInitPacketMagicHeader(value: String) {
_uiState.update { _uiState.update {
it.copy( it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(initPacketMagicHeader = value), interfaceProxy =
_uiState.value.interfaceProxy.copy(
initPacketMagicHeader = value,
),
) )
} }
} }
@@ -499,7 +534,10 @@ constructor(
fun onResponsePacketMagicHeader(value: String) { fun onResponsePacketMagicHeader(value: String) {
_uiState.update { _uiState.update {
it.copy( it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(responsePacketMagicHeader = value), interfaceProxy =
_uiState.value.interfaceProxy.copy(
responsePacketMagicHeader = value,
),
) )
} }
} }
@@ -507,7 +545,10 @@ constructor(
fun onTransportPacketMagicHeader(value: String) { fun onTransportPacketMagicHeader(value: String) {
_uiState.update { _uiState.update {
it.copy( it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(transportPacketMagicHeader = value), interfaceProxy =
_uiState.value.interfaceProxy.copy(
transportPacketMagicHeader = value,
),
) )
} }
} }
@@ -515,7 +556,10 @@ constructor(
fun onUnderloadPacketMagicHeader(value: String) { fun onUnderloadPacketMagicHeader(value: String) {
_uiState.update { _uiState.update {
it.copy( it.copy(
interfaceProxy = _uiState.value.interfaceProxy.copy(underloadPacketMagicHeader = value), interfaceProxy =
_uiState.value.interfaceProxy.copy(
underloadPacketMagicHeader = value,
),
) )
} }
} }
@@ -49,24 +49,69 @@ data class InterfaceProxy(
"" ""
}, },
mtu = if (i.mtu.isPresent) i.mtu.get().toString().trim() else "", mtu = if (i.mtu.isPresent) i.mtu.get().toString().trim() else "",
junkPacketCount = if (i.junkPacketCount.isPresent) i.junkPacketCount.get() junkPacketCount =
.toString() else "", if (i.junkPacketCount.isPresent) {
junkPacketMinSize = if (i.junkPacketMinSize.isPresent) i.junkPacketMinSize.get() i.junkPacketCount.get()
.toString() else "", .toString()
junkPacketMaxSize = if (i.junkPacketMaxSize.isPresent) i.junkPacketMaxSize.get() } else {
.toString() else "", ""
initPacketJunkSize = if (i.initPacketJunkSize.isPresent) i.initPacketJunkSize.get() },
.toString() else "", junkPacketMinSize =
responsePacketJunkSize = if (i.responsePacketJunkSize.isPresent) i.responsePacketJunkSize.get() if (i.junkPacketMinSize.isPresent) {
.toString() else "", i.junkPacketMinSize.get()
initPacketMagicHeader = if (i.initPacketMagicHeader.isPresent) i.initPacketMagicHeader.get() .toString()
.toString() else "", } else {
responsePacketMagicHeader = if (i.responsePacketMagicHeader.isPresent) i.responsePacketMagicHeader.get() ""
.toString() else "", },
transportPacketMagicHeader = if (i.transportPacketMagicHeader.isPresent) i.transportPacketMagicHeader.get() junkPacketMaxSize =
.toString() else "", if (i.junkPacketMaxSize.isPresent) {
underloadPacketMagicHeader = if (i.underloadPacketMagicHeader.isPresent) i.underloadPacketMagicHeader.get() i.junkPacketMaxSize.get()
.toString() else "", .toString()
} else {
""
},
initPacketJunkSize =
if (i.initPacketJunkSize.isPresent) {
i.initPacketJunkSize.get()
.toString()
} else {
""
},
responsePacketJunkSize =
if (i.responsePacketJunkSize.isPresent) {
i.responsePacketJunkSize.get()
.toString()
} else {
""
},
initPacketMagicHeader =
if (i.initPacketMagicHeader.isPresent) {
i.initPacketMagicHeader.get()
.toString()
} else {
""
},
responsePacketMagicHeader =
if (i.responsePacketMagicHeader.isPresent) {
i.responsePacketMagicHeader.get()
.toString()
} else {
""
},
transportPacketMagicHeader =
if (i.transportPacketMagicHeader.isPresent) {
i.transportPacketMagicHeader.get()
.toString()
} else {
""
},
underloadPacketMagicHeader =
if (i.underloadPacketMagicHeader.isPresent) {
i.underloadPacketMagicHeader.get()
.toString()
} else {
""
},
) )
} }
} }
@@ -7,7 +7,7 @@ data class PeerProxy(
val preSharedKey: String = "", val preSharedKey: String = "",
val persistentKeepalive: String = "", val persistentKeepalive: String = "",
val endpoint: String = "", val endpoint: String = "",
val allowedIps: String = IPV4_WILDCARD.joinToString(", ").trim() val allowedIps: String = IPV4_WILDCARD.joinToString(", ").trim(),
) { ) {
companion object { companion object {
fun from(peer: Peer): PeerProxy { fun from(peer: Peer): PeerProxy {
@@ -2,5 +2,5 @@ package com.zaneschepke.wireguardautotunnel.ui.screens.main
enum class ConfigType { enum class ConfigType {
AMNEZIA, AMNEZIA,
WIREGUARD WIREGUARD,
} }
@@ -43,7 +43,6 @@ import androidx.compose.material.icons.rounded.Info
import androidx.compose.material.icons.rounded.Settings import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material.icons.rounded.Smartphone import androidx.compose.material.icons.rounded.Smartphone
import androidx.compose.material.icons.rounded.Star import androidx.compose.material.icons.rounded.Star
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FabPosition import androidx.compose.material3.FabPosition
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
@@ -101,9 +100,9 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
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.TunnelState
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
import com.zaneschepke.wireguardautotunnel.ui.CaptureActivityPortrait
import com.zaneschepke.wireguardautotunnel.ui.Screen import com.zaneschepke.wireguardautotunnel.ui.Screen
import com.zaneschepke.wireguardautotunnel.ui.common.RowListItem import com.zaneschepke.wireguardautotunnel.ui.common.RowListItem
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.InfoDialog
import com.zaneschepke.wireguardautotunnel.ui.common.screen.LoadingScreen import com.zaneschepke.wireguardautotunnel.ui.common.screen.LoadingScreen
import com.zaneschepke.wireguardautotunnel.ui.theme.corn import com.zaneschepke.wireguardautotunnel.ui.theme.corn
import com.zaneschepke.wireguardautotunnel.ui.theme.mint import com.zaneschepke.wireguardautotunnel.ui.theme.mint
@@ -121,7 +120,7 @@ fun MainScreen(
viewModel: MainViewModel = hiltViewModel(), viewModel: MainViewModel = hiltViewModel(),
appViewModel: AppViewModel, appViewModel: AppViewModel,
focusRequester: FocusRequester, focusRequester: FocusRequester,
navController: NavController navController: NavController,
) { ) {
val haptic = LocalHapticFeedback.current val haptic = LocalHapticFeedback.current
val context = LocalContext.current val context = LocalContext.current
@@ -133,7 +132,8 @@ fun MainScreen(
var configType by remember { mutableStateOf(ConfigType.WIREGUARD) } var configType by remember { mutableStateOf(ConfigType.WIREGUARD) }
// Nested scroll for control FAB // Nested scroll for control FAB
val nestedScrollConnection = remember { val nestedScrollConnection =
remember {
object : NestedScrollConnection { object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
// Hide FAB // Hide FAB
@@ -150,7 +150,6 @@ fun MainScreen(
} }
} }
var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) } var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) }
var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) } var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) }
val uiState by viewModel.uiState.collectAsStateWithLifecycle() val uiState by viewModel.uiState.collectAsStateWithLifecycle()
@@ -191,7 +190,9 @@ fun MainScreen(
name.startsWith(Constants.ANDROID_TV_EXPLORER_STUB) name.startsWith(Constants.ANDROID_TV_EXPLORER_STUB)
} }
) { ) {
appViewModel.showSnackbarMessage(context.getString(R.string.error_no_file_explorer)) appViewModel.showSnackbarMessage(
context.getString(R.string.error_no_file_explorer),
)
} }
return intent return intent
} }
@@ -218,37 +219,31 @@ fun MainScreen(
}, },
) )
AnimatedVisibility(showDeleteTunnelAlertDialog) { if (showDeleteTunnelAlertDialog) {
AlertDialog( InfoDialog(
onDismissRequest = { showDeleteTunnelAlertDialog = false }, onDismiss = { showDeleteTunnelAlertDialog = false },
confirmButton = { onAttest = {
TextButton(
onClick = {
selectedTunnel?.let { viewModel.onDelete(it, context) } selectedTunnel?.let { viewModel.onDelete(it, context) }
showDeleteTunnelAlertDialog = false showDeleteTunnelAlertDialog = false
selectedTunnel = null selectedTunnel = null
}, },
) {
Text(text = stringResource(R.string.yes))
}
},
dismissButton = {
TextButton(onClick = { showDeleteTunnelAlertDialog = false }) {
Text(text = stringResource(R.string.cancel))
}
},
title = { Text(text = stringResource(R.string.delete_tunnel)) }, title = { Text(text = stringResource(R.string.delete_tunnel)) },
text = { Text(text = stringResource(R.string.delete_tunnel_message)) }, body = { Text(text = stringResource(R.string.delete_tunnel_message)) },
confirmText = { Text(text = stringResource(R.string.yes)) },
) )
} }
fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) { fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) {
if (appViewModel.isRequiredPermissionGranted()) { if (appViewModel.isRequiredPermissionGranted()) {
if (checked) viewModel.onTunnelStart(tunnel, context) else viewModel.onTunnelStop( if (checked) {
viewModel.onTunnelStart(tunnel, context)
} else {
viewModel.onTunnelStop(
context, context,
) )
} }
} }
}
if (uiState.loading) { if (uiState.loading) {
return LoadingScreen() return LoadingScreen()
@@ -262,8 +257,6 @@ fun MainScreen(
context.getString(R.string.scanning_qr), context.getString(R.string.scanning_qr),
) )
scanOptions.setBeepEnabled(false) scanOptions.setBeepEnabled(false)
scanOptions.captureActivity =
CaptureActivityPortrait::class.java
scanLauncher.launch(scanOptions) scanLauncher.launch(scanOptions)
} }
@@ -277,7 +270,6 @@ fun MainScreen(
}, },
) )
} }
}, },
floatingActionButtonPosition = FabPosition.End, floatingActionButtonPosition = FabPosition.End,
floatingActionButton = { floatingActionButton = {
@@ -285,7 +277,8 @@ fun MainScreen(
visible = isVisible.value, visible = isVisible.value,
enter = slideInVertically(initialOffsetY = { it * 2 }), enter = slideInVertically(initialOffsetY = { it * 2 }),
exit = slideOutVertically(targetOffsetY = { it * 2 }), exit = slideOutVertically(targetOffsetY = { it * 2 }),
modifier = Modifier modifier =
Modifier
.focusRequester(focusRequester) .focusRequester(focusRequester)
.focusGroup(), .focusGroup(),
) { ) {
@@ -296,16 +289,19 @@ fun MainScreen(
val fobIconColor = val fobIconColor =
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) Color.White else MaterialTheme.colorScheme.background if (WireGuardAutoTunnel.isRunningOnAndroidTv()) Color.White else MaterialTheme.colorScheme.background
MultiFloatingActionButton( MultiFloatingActionButton(
fabIcon = FabIcon( fabIcon =
FabIcon(
iconRes = R.drawable.add, iconRes = R.drawable.add,
iconResAfterRotate = R.drawable.close, iconResAfterRotate = R.drawable.close,
iconRotate = 180f, iconRotate = 180f,
), ),
fabOption = FabOption( fabOption =
FabOption(
iconTint = fobIconColor, iconTint = fobIconColor,
backgroundTint = fobColor, backgroundTint = fobColor,
), ),
itemsMultiFab = listOf( itemsMultiFab =
listOf(
MultiFabItem( MultiFabItem(
label = { label = {
Text( Text(
@@ -315,11 +311,13 @@ fun MainScreen(
modifier = Modifier.padding(end = 10.dp), modifier = Modifier.padding(end = 10.dp),
) )
}, },
modifier = Modifier modifier =
Modifier
.size(40.dp), .size(40.dp),
icon = R.drawable.add, icon = R.drawable.add,
value = ConfigType.AMNEZIA.name, value = ConfigType.AMNEZIA.name,
miniFabOption = FabOption( miniFabOption =
FabOption(
backgroundTint = fobColor, backgroundTint = fobColor,
fobIconColor, fobIconColor,
), ),
@@ -335,7 +333,8 @@ fun MainScreen(
}, },
icon = R.drawable.add, icon = R.drawable.add,
value = ConfigType.WIREGUARD.name, value = ConfigType.WIREGUARD.name,
miniFabOption = FabOption( miniFabOption =
FabOption(
backgroundTint = fobColor, backgroundTint = fobColor,
fobIconColor, fobIconColor,
), ),
@@ -354,7 +353,6 @@ fun MainScreen(
ModalBottomSheet( ModalBottomSheet(
onDismissRequest = { onDismissRequest = {
showBottomSheet = false showBottomSheet = false
}, },
sheetState = sheetState, sheetState = sheetState,
) { ) {
@@ -412,7 +410,7 @@ fun MainScreen(
.clickable { .clickable {
showBottomSheet = false showBottomSheet = false
navController.navigate( navController.navigate(
"${Screen.Config.route}/${Constants.MANUAL_TUNNEL_CONFIG_ID}?configType=${configType}", "${Screen.Config.route}/${Constants.MANUAL_TUNNEL_CONFIG_ID}?configType=$configType",
) )
} }
.padding(10.dp), .padding(10.dp),
@@ -445,23 +443,29 @@ fun MainScreen(
) { ) {
item { item {
AnimatedVisibility( AnimatedVisibility(
uiState.tunnels.isEmpty(), exit = fadeOut(), enter = fadeIn(), uiState.tunnels.isEmpty(),
exit = fadeOut(),
enter = fadeIn(),
) { ) {
Column( Column(
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center, verticalArrangement = Arrangement.Center,
modifier = Modifier modifier =
Modifier
.padding(top = 100.dp) .padding(top = 100.dp)
.fillMaxSize(), .fillMaxSize(),
) { ) {
val gettingStarted = buildAnnotatedString { val gettingStarted =
buildAnnotatedString {
append(stringResource(id = R.string.see_the)) append(stringResource(id = R.string.see_the))
append(" ") append(" ")
pushStringAnnotation( pushStringAnnotation(
tag = "gettingStarted", tag = "gettingStarted",
annotation = stringResource(id = R.string.getting_started_url), annotation = stringResource(id = R.string.getting_started_url),
) )
withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.primary)) { withStyle(
style = SpanStyle(color = MaterialTheme.colorScheme.primary),
) {
append(stringResource(id = R.string.getting_started_guide)) append(stringResource(id = R.string.getting_started_guide))
} }
pop() pop()
@@ -474,10 +478,12 @@ fun MainScreen(
fontStyle = FontStyle.Italic, fontStyle = FontStyle.Italic,
) )
ClickableText( ClickableText(
modifier = Modifier modifier =
Modifier
.padding(vertical = 10.dp, horizontal = 24.dp), .padding(vertical = 10.dp, horizontal = 24.dp),
text = gettingStarted, text = gettingStarted,
style = MaterialTheme.typography.bodyMedium.copy( style =
MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
), ),
@@ -492,49 +498,66 @@ fun MainScreen(
} }
item { item {
if (uiState.settings.isAutoTunnelEnabled) { if (uiState.settings.isAutoTunnelEnabled) {
val autoTunnelingLabel = buildAnnotatedString { val itemFocusRequester = remember { FocusRequester() }
val autoTunnelingLabel =
buildAnnotatedString {
append(stringResource(id = R.string.auto_tunneling)) append(stringResource(id = R.string.auto_tunneling))
append(": ") append(": ")
if (uiState.settings.isAutoTunnelPaused) append( if (uiState.settings.isAutoTunnelPaused) {
append(
stringResource(id = R.string.paused), stringResource(id = R.string.paused),
) else append( )
} else {
append(
stringResource(id = R.string.active), stringResource(id = R.string.active),
) )
} }
}
RowListItem( RowListItem(
icon = { icon = {
val icon = Icons.Rounded.Bolt val icon = Icons.Rounded.Bolt
Icon( Icon(
icon, icon,
icon.name, icon.name,
modifier = Modifier modifier =
Modifier
.padding(end = 8.5.dp) .padding(end = 8.5.dp)
.size(25.dp), .size(25.dp),
tint = tint =
if (uiState.settings.isAutoTunnelPaused) Color.Gray if (uiState.settings.isAutoTunnelPaused) {
else mint, Color.Gray
} else {
mint
},
) )
}, },
text = autoTunnelingLabel.text, text = autoTunnelingLabel.text,
rowButton = { rowButton = {
if (uiState.settings.isAutoTunnelPaused) { if (uiState.settings.isAutoTunnelPaused) {
TextButton( TextButton(
modifier = Modifier.focusRequester(itemFocusRequester),
onClick = { viewModel.resumeAutoTunneling() }, onClick = { viewModel.resumeAutoTunneling() },
) { ) {
Text(stringResource(id = R.string.resume)) Text(stringResource(id = R.string.resume))
} }
} else { } else {
TextButton( TextButton(
modifier = Modifier.focusRequester(itemFocusRequester),
onClick = { viewModel.pauseAutoTunneling() }, onClick = { viewModel.pauseAutoTunneling() },
) { ) {
Text(stringResource(id = R.string.pause)) Text(stringResource(id = R.string.pause))
} }
} }
}, },
onClick = {}, onClick = {
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
itemFocusRequester.requestFocus()
}
},
onHold = {}, onHold = {},
expanded = false, expanded = false,
statistics = null, statistics = null,
focusRequester = focusRequester,
) )
} }
} }
@@ -543,7 +566,8 @@ fun MainScreen(
key = { tunnel -> tunnel.id }, key = { tunnel -> tunnel.id },
) { tunnel -> ) { tunnel ->
val leadingIconColor = val leadingIconColor =
(if ( (
if (
uiState.vpnState.tunnelConfig?.name == tunnel.name && uiState.vpnState.tunnelConfig?.name == tunnel.name &&
uiState.vpnState.status == TunnelState.UP uiState.vpnState.status == TunnelState.UP
) { ) {
@@ -564,12 +588,15 @@ fun MainScreen(
} }
} else { } else {
Color.Gray Color.Gray
}) }
)
val itemFocusRequester = remember { FocusRequester() }
val expanded = remember { mutableStateOf(false) } val expanded = remember { mutableStateOf(false) }
RowListItem( RowListItem(
icon = { icon = {
val circleIcon = Icons.Rounded.Circle val circleIcon = Icons.Rounded.Circle
val icon = if (tunnel.isPrimaryTunnel) { val icon =
if (tunnel.isPrimaryTunnel) {
Icons.Rounded.Star Icons.Rounded.Star
} else if (tunnel.isMobileDataTunnel) { } else if (tunnel.isMobileDataTunnel) {
Icons.Rounded.Smartphone Icons.Rounded.Smartphone
@@ -580,7 +607,8 @@ fun MainScreen(
icon, icon,
icon.name, icon.name,
tint = leadingIconColor, tint = leadingIconColor,
modifier = Modifier modifier =
Modifier
.padding( .padding(
end = if (icon == circleIcon) 12.5.dp else 10.dp, end = if (icon == circleIcon) 12.5.dp else 10.dp,
start = if (icon == circleIcon) 2.5.dp else 0.dp, start = if (icon == circleIcon) 2.5.dp else 0.dp,
@@ -594,7 +622,9 @@ fun MainScreen(
(uiState.vpnState.status == TunnelState.UP) && (uiState.vpnState.status == TunnelState.UP) &&
(tunnel.name == uiState.vpnState.tunnelConfig?.name) (tunnel.name == uiState.vpnState.tunnelConfig?.name)
) { ) {
appViewModel.showSnackbarMessage(context.getString(R.string.turn_off_tunnel)) appViewModel.showSnackbarMessage(
context.getString(R.string.turn_off_tunnel),
)
return@RowListItem return@RowListItem
} }
haptic.performHapticFeedback(HapticFeedbackType.LongPress) haptic.performHapticFeedback(HapticFeedbackType.LongPress)
@@ -610,11 +640,12 @@ fun MainScreen(
} }
} else { } else {
selectedTunnel = tunnel selectedTunnel = tunnel
focusRequester.requestFocus() itemFocusRequester.requestFocus()
} }
}, },
statistics = uiState.vpnState.statistics, statistics = uiState.vpnState.statistics,
expanded = expanded.value, expanded = expanded.value,
focusRequester = focusRequester,
rowButton = { rowButton = {
if ( if (
tunnel.id == selectedTunnel?.id && tunnel.id == selectedTunnel?.id &&
@@ -661,16 +692,17 @@ fun MainScreen(
} else { } else {
val checked by remember { val checked by remember {
derivedStateOf { derivedStateOf {
(uiState.vpnState.status == TunnelState.UP && (
tunnel.name == uiState.vpnState.tunnelConfig?.name) uiState.vpnState.status == TunnelState.UP &&
tunnel.name == uiState.vpnState.tunnelConfig?.name
)
} }
} }
if (!checked) expanded.value = false if (!checked) expanded.value = false
@Composable @Composable
fun TunnelSwitch() = fun TunnelSwitch() = Switch(
Switch( modifier = Modifier.focusRequester(itemFocusRequester),
modifier = Modifier.focusRequester(focusRequester),
checked = checked, checked = checked,
onCheckedChange = { checked -> onCheckedChange = { checked ->
if (!checked) expanded.value = false if (!checked) expanded.value = false
@@ -681,7 +713,7 @@ fun MainScreen(
Row { Row {
IconButton( IconButton(
onClick = { onClick = {
if (uiState.settings.isAutoTunnelEnabled) { if (uiState.settings.isAutoTunnelEnabled && !uiState.settings.isAutoTunnelPaused) {
appViewModel.showSnackbarMessage( appViewModel.showSnackbarMessage(
context.getString(R.string.turn_off_auto), context.getString(R.string.turn_off_auto),
) )
@@ -8,5 +8,5 @@ data class MainUiState(
val settings: Settings = Settings(), val settings: Settings = Settings(),
val tunnels: TunnelConfigs = emptyList(), val tunnels: TunnelConfigs = emptyList(),
val vpnState: VpnState = VpnState(), val vpnState: VpnState = VpnState(),
val loading: Boolean = true val loading: Boolean = true,
) )
@@ -37,9 +37,8 @@ constructor(
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
private val serviceManager: ServiceManager, private val serviceManager: ServiceManager,
val vpnService: VpnService, val vpnService: VpnService,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : ViewModel() { ) : ViewModel() {
val uiState = val uiState =
combine( combine(
appDataRepository.settings.getSettingsFlow(), appDataRepository.settings.getSettingsFlow(),
@@ -80,8 +79,7 @@ constructor(
) )
} }
fun onTunnelStart(tunnelConfig: TunnelConfig, context: Context) = fun onTunnelStart(tunnelConfig: TunnelConfig, context: Context) = viewModelScope.launch {
viewModelScope.launch {
Timber.d("On start called!") Timber.d("On start called!")
serviceManager.startVpnService( serviceManager.startVpnService(
context, context,
@@ -90,9 +88,7 @@ constructor(
) )
} }
fun onTunnelStop(context: Context) = viewModelScope.launch {
fun onTunnelStop(context: Context) =
viewModelScope.launch {
Timber.i("Stopping active tunnel") Timber.i("Stopping active tunnel")
serviceManager.stopVpnService(context, isManualStop = true) serviceManager.stopVpnService(context, isManualStop = true)
} }
@@ -139,16 +135,26 @@ constructor(
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
try { try {
validateConfigString(result, configType) validateConfigString(result, configType)
val tunnelName = makeTunnelNameUnique(generateQrCodeTunnelName(result, configType)) val tunnelName =
val tunnelConfig = when (configType) { makeTunnelNameUnique(generateQrCodeTunnelName(result, configType))
val tunnelConfig =
when (configType) {
ConfigType.AMNEZIA -> { ConfigType.AMNEZIA -> {
TunnelConfig( TunnelConfig(
name = tunnelName, amQuick = result, name = tunnelName,
wgQuick = TunnelConfig.configFromAmQuick(result).toWgQuickString(), amQuick = result,
wgQuick =
TunnelConfig.configFromAmQuick(
result,
).toWgQuickString(),
) )
} }
ConfigType.WIREGUARD -> TunnelConfig(name = tunnelName, wgQuick = result) ConfigType.WIREGUARD ->
TunnelConfig(
name = tunnelName,
wgQuick = result,
)
} }
addTunnel(tunnelConfig) addTunnel(tunnelConfig)
Result.success(Unit) Result.success(Unit)
@@ -165,20 +171,17 @@ constructor(
var tunnelName = name var tunnelName = name
var num = 1 var num = 1
while (tunnels.any { it.name == tunnelName }) { while (tunnels.any { it.name == tunnelName }) {
tunnelName = name + "(${num})" tunnelName = name + "($num)"
num++ num++
} }
tunnelName tunnelName
} }
} }
private fun saveTunnelConfigFromStream( private fun saveTunnelConfigFromStream(stream: InputStream, fileName: String, type: ConfigType) {
stream: InputStream,
fileName: String,
type: ConfigType
) {
var amQuick: String? = null var amQuick: String? = null
val wgQuick = stream.use { val wgQuick =
stream.use {
when (type) { when (type) {
ConfigType.AMNEZIA -> { ConfigType.AMNEZIA -> {
val config = org.amnezia.awg.config.Config.parse(it) val config = org.amnezia.awg.config.Config.parse(it)
@@ -207,11 +210,7 @@ constructor(
return context.applicationContext.contentResolver.openInputStream(uri) return context.applicationContext.contentResolver.openInputStream(uri)
} }
suspend fun onTunnelFileSelected( suspend fun onTunnelFileSelected(uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
uri: Uri,
configType: ConfigType,
context: Context
): Result<Unit> {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
try { try {
if (isValidUriContentScheme(uri)) { if (isValidUriContentScheme(uri)) {
@@ -220,7 +219,8 @@ constructor(
Constants.CONF_FILE_EXTENSION -> Constants.CONF_FILE_EXTENSION ->
saveTunnelFromConfUri(fileName, uri, configType, context) saveTunnelFromConfUri(fileName, uri, configType, context)
Constants.ZIP_FILE_EXTENSION -> saveTunnelsFromZipUri( Constants.ZIP_FILE_EXTENSION ->
saveTunnelsFromZipUri(
uri, uri,
configType, configType,
context, context,
@@ -238,11 +238,7 @@ constructor(
} }
} }
private suspend fun saveTunnelsFromZipUri( private suspend fun saveTunnelsFromZipUri(uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
uri: Uri,
configType: ConfigType,
context: Context
): Result<Unit> {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
ZipInputStream(getInputStreamFromUri(uri, context)).use { zip -> ZipInputStream(getInputStreamFromUri(uri, context)).use { zip ->
generateSequence { zip.nextEntry } generateSequence { zip.nextEntry }
@@ -258,7 +254,10 @@ constructor(
val wgQuick = val wgQuick =
when (configType) { when (configType) {
ConfigType.AMNEZIA -> { ConfigType.AMNEZIA -> {
val config = org.amnezia.awg.config.Config.parse(zip) val config =
org.amnezia.awg.config.Config.parse(
zip,
)
amQuick = config.toAwgQuickString() amQuick = config.toAwgQuickString()
config.toWgQuickString() config.toWgQuickString()
} }
@@ -285,12 +284,7 @@ constructor(
} }
} }
private suspend fun saveTunnelFromConfUri( private suspend fun saveTunnelFromConfUri(name: String, uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
name: String,
uri: Uri,
configType: ConfigType,
context: Context
): Result<Unit> {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
val stream = getInputStreamFromUri(uri, context) val stream = getInputStreamFromUri(uri, context)
return@withContext if (stream != null) { return@withContext if (stream != null) {
@@ -312,15 +306,17 @@ constructor(
if (firstTunnel) WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate() if (firstTunnel) WireGuardAutoTunnel.requestTunnelTileServiceStateUpdate()
} }
fun pauseAutoTunneling() = fun pauseAutoTunneling() = viewModelScope.launch {
viewModelScope.launch { appDataRepository.settings.save(
appDataRepository.settings.save(uiState.value.settings.copy(isAutoTunnelPaused = true)) uiState.value.settings.copy(isAutoTunnelPaused = true),
)
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate() WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
} }
fun resumeAutoTunneling() = fun resumeAutoTunneling() = viewModelScope.launch {
viewModelScope.launch { appDataRepository.settings.save(
appDataRepository.settings.save(uiState.value.settings.copy(isAutoTunnelPaused = false)) uiState.value.settings.copy(isAutoTunnelPaused = false),
)
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate() WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
} }
@@ -349,8 +345,12 @@ constructor(
val index = getDisplayNameColumnIndex(cursor) val index = getDisplayNameColumnIndex(cursor)
if (index != null) { if (index != null) {
cursor.getString(index) cursor.getString(index)
} else null } else {
} else null null
}
} else {
null
}
} }
private fun isValidUriContentScheme(uri: Uri): Boolean { private fun isValidUriContentScheme(uri: Uri): Boolean {
@@ -374,9 +374,7 @@ constructor(
} }
} }
private fun saveSettings(settings: Settings) = private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
viewModelScope.launch { appDataRepository.settings.save(settings) }
fun onCopyTunnel(tunnel: TunnelConfig?) = viewModelScope.launch { fun onCopyTunnel(tunnel: TunnelConfig?) = viewModelScope.launch {
tunnel?.let { tunnel?.let {
@@ -81,7 +81,7 @@ fun OptionsScreen(
navController: NavController, navController: NavController,
appViewModel: AppViewModel, appViewModel: AppViewModel,
focusRequester: FocusRequester, focusRequester: FocusRequester,
tunnelId: String tunnelId: String,
) { ) {
val scrollState = rememberScrollState() val scrollState = rememberScrollState()
val uiState by optionsViewModel.uiState.collectAsStateWithLifecycle() val uiState by optionsViewModel.uiState.collectAsStateWithLifecycle()
@@ -127,21 +127,25 @@ fun OptionsScreen(
visible = true, visible = true,
enter = slideInVertically(initialOffsetY = { it * 2 }), enter = slideInVertically(initialOffsetY = { it * 2 }),
exit = slideOutVertically(targetOffsetY = { it * 2 }), exit = slideOutVertically(targetOffsetY = { it * 2 }),
modifier = Modifier modifier =
Modifier
.focusRequester(focusRequester) .focusRequester(focusRequester)
.focusGroup(), .focusGroup(),
) { ) {
MultiFloatingActionButton( MultiFloatingActionButton(
fabIcon = FabIcon( fabIcon =
FabIcon(
iconRes = R.drawable.edit, iconRes = R.drawable.edit,
iconResAfterRotate = R.drawable.close, iconResAfterRotate = R.drawable.close,
iconRotate = 180f, iconRotate = 180f,
), ),
fabOption = FabOption( fabOption =
FabOption(
iconTint = fobIconColor, iconTint = fobIconColor,
backgroundTint = fobColor, backgroundTint = fobColor,
), ),
itemsMultiFab = listOf( itemsMultiFab =
listOf(
MultiFabItem( MultiFabItem(
label = { label = {
Text( Text(
@@ -151,11 +155,13 @@ fun OptionsScreen(
modifier = Modifier.padding(end = 10.dp), modifier = Modifier.padding(end = 10.dp),
) )
}, },
modifier = Modifier modifier =
Modifier
.size(40.dp), .size(40.dp),
icon = R.drawable.edit, icon = R.drawable.edit,
value = ConfigType.AMNEZIA.name, value = ConfigType.AMNEZIA.name,
miniFabOption = FabOption( miniFabOption =
FabOption(
backgroundTint = fobColor, backgroundTint = fobColor,
fobIconColor, fobIconColor,
), ),
@@ -171,7 +177,8 @@ fun OptionsScreen(
}, },
icon = R.drawable.edit, icon = R.drawable.edit,
value = ConfigType.WIREGUARD.name, value = ConfigType.WIREGUARD.name,
miniFabOption = FabOption( miniFabOption =
FabOption(
backgroundTint = fobColor, backgroundTint = fobColor,
fobIconColor, fobIconColor,
), ),
@@ -180,7 +187,7 @@ fun OptionsScreen(
onFabItemClicked = { onFabItemClicked = {
val configType = ConfigType.valueOf(it.value) val configType = ConfigType.valueOf(it.value)
navController.navigate( navController.navigate(
"${Screen.Config.route}/${tunnelId}?configType=${configType.name}", "${Screen.Config.route}/$tunnelId?configType=${configType.name}",
) )
}, },
shape = RoundedCornerShape(16.dp), shape = RoundedCornerShape(16.dp),
@@ -208,7 +215,8 @@ fun OptionsScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.height(IntrinsicSize.Min) .height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
@@ -217,7 +225,8 @@ fun OptionsScreen(
Modifier Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp) .padding(top = 20.dp)
}) }
)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Column( Column(
@@ -233,7 +242,8 @@ fun OptionsScreen(
stringResource(R.string.set_primary_tunnel), stringResource(R.string.set_primary_tunnel),
enabled = true, enabled = true,
checked = uiState.isDefaultTunnel, checked = uiState.isDefaultTunnel,
modifier = Modifier modifier =
Modifier
.focusRequester(focusRequester), .focusRequester(focusRequester),
padding = screenPadding, padding = screenPadding,
onCheckChanged = { optionsViewModel.onTogglePrimaryTunnel() }, onCheckChanged = { optionsViewModel.onTogglePrimaryTunnel() },
@@ -246,7 +256,8 @@ fun OptionsScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.height(IntrinsicSize.Min) .height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
@@ -255,7 +266,8 @@ fun OptionsScreen(
Modifier Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp) .padding(top = 20.dp)
}) }
)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Column( Column(
@@ -276,7 +288,8 @@ fun OptionsScreen(
) )
Column { Column {
FlowRow( FlowRow(
modifier = Modifier modifier =
Modifier
.padding(screenPadding) .padding(screenPadding)
.fillMaxWidth(), .fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(5.dp), horizontalArrangement = Arrangement.spacedBy(5.dp),
@@ -292,7 +305,6 @@ fun OptionsScreen(
onIconClick = { onIconClick = {
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus() if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus()
optionsViewModel.onDeleteRunSSID(ssid) optionsViewModel.onDeleteRunSSID(ssid)
}, },
text = ssid, text = ssid,
icon = Icons.Filled.Close, icon = Icons.Filled.Close,
@@ -5,5 +5,5 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
data class OptionsUiState( data class OptionsUiState(
val id: String? = null, val id: String? = null,
val tunnel: TunnelConfig? = null, val tunnel: TunnelConfig? = null,
val isDefaultTunnel: Boolean = false val isDefaultTunnel: Boolean = false,
) )
@@ -19,14 +19,15 @@ import kotlinx.coroutines.withContext
import javax.inject.Inject import javax.inject.Inject
@HiltViewModel @HiltViewModel
class OptionsViewModel @Inject class OptionsViewModel
@Inject
constructor( constructor(
private val appDataRepository: AppDataRepository private val appDataRepository: AppDataRepository,
) : ViewModel() { ) : ViewModel() {
private val _optionState = MutableStateFlow(OptionsUiState()) private val _optionState = MutableStateFlow(OptionsUiState())
val uiState = combine( val uiState =
combine(
appDataRepository.tunnels.getTunnelConfigsFlow(), appDataRepository.tunnels.getTunnelConfigsFlow(),
_optionState, _optionState,
) { tunnels, optionState -> ) { tunnels, optionState ->
@@ -34,7 +35,9 @@ constructor(
val tunnelConfig = tunnels.fastFirstOrNull { it.id.toString() == optionState.id } val tunnelConfig = tunnels.fastFirstOrNull { it.id.toString() == optionState.id }
val isPrimaryTunnel = tunnelConfig?.isPrimaryTunnel == true val isPrimaryTunnel = tunnelConfig?.isPrimaryTunnel == true
OptionsUiState(optionState.id, tunnelConfig, isPrimaryTunnel) OptionsUiState(optionState.id, tunnelConfig, isPrimaryTunnel)
} else OptionsUiState() } else {
OptionsUiState()
}
}.stateIn( }.stateIn(
viewModelScope, viewModelScope,
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT), SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
@@ -52,7 +55,8 @@ constructor(
fun onDeleteRunSSID(ssid: String) = viewModelScope.launch { fun onDeleteRunSSID(ssid: String) = viewModelScope.launch {
uiState.value.tunnel?.let { uiState.value.tunnel?.let {
appDataRepository.tunnels.save( appDataRepository.tunnels.save(
tunnelConfig = it.copy( tunnelConfig =
it.copy(
tunnelNetworks = (uiState.value.tunnel!!.tunnelNetworks - ssid).toMutableList(), tunnelNetworks = (uiState.value.tunnel!!.tunnelNetworks - ssid).toMutableList(),
), ),
) )
@@ -67,11 +71,13 @@ constructor(
suspend fun onSaveRunSSID(ssid: String): Result<Unit> { suspend fun onSaveRunSSID(ssid: String): Result<Unit> {
val trimmed = ssid.trim() val trimmed = ssid.trim()
val tunnelsWithName = withContext(viewModelScope.coroutineContext) { val tunnelsWithName =
withContext(viewModelScope.coroutineContext) {
appDataRepository.tunnels.findByTunnelNetworksName(trimmed) appDataRepository.tunnels.findByTunnelNetworksName(trimmed)
} }
return if (uiState.value.tunnel?.tunnelNetworks?.contains(trimmed) != true && return if (uiState.value.tunnel?.tunnelNetworks?.contains(trimmed) != true &&
tunnelsWithName.isEmpty()) { tunnelsWithName.isEmpty()
) {
uiState.value.tunnel?.tunnelNetworks?.add(trimmed) uiState.value.tunnel?.tunnelNetworks?.add(trimmed)
saveTunnel(uiState.value.tunnel) saveTunnel(uiState.value.tunnel)
Result.success(Unit) Result.success(Unit)
@@ -84,7 +90,9 @@ constructor(
uiState.value.tunnel?.let { uiState.value.tunnel?.let {
if (it.isMobileDataTunnel) { if (it.isMobileDataTunnel) {
appDataRepository.tunnels.updateMobileDataTunnel(null) appDataRepository.tunnels.updateMobileDataTunnel(null)
} else appDataRepository.tunnels.updateMobileDataTunnel(it) } else {
appDataRepository.tunnels.updateMobileDataTunnel(it)
}
} }
} }
@@ -19,9 +19,14 @@ fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
PinLock( PinLock(
title = { pinExists -> title = { pinExists ->
Text( Text(
text = if (pinExists) stringResource(id = R.string.enter_pin) else stringResource( text =
if (pinExists) {
stringResource(id = R.string.enter_pin)
} else {
stringResource(
id = R.string.create_pin, id = R.string.create_pin,
), )
},
) )
}, },
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
@@ -35,7 +40,6 @@ fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
navController.navigate(Screen.Main.route) navController.navigate(Screen.Main.route)
} }
} }
}, },
onPinIncorrect = { onPinIncorrect = {
// pin is incorrect, show error // pin is incorrect, show error
@@ -84,7 +84,6 @@ import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
import com.zaneschepke.wireguardautotunnel.util.getMessage import com.zaneschepke.wireguardautotunnel.util.getMessage
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import xyz.teamgravity.pin_lock_compose.PinManager
import java.io.File import java.io.File
@OptIn( @OptIn(
@@ -103,7 +102,6 @@ fun SettingsScreen(
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val scrollState = rememberScrollState() val scrollState = rememberScrollState()
val interactionSource = remember { MutableInteractionSource() } val interactionSource = remember { MutableInteractionSource() }
//val pinExists = remember { mutableStateOf(PinManager.pinExists()) }
val uiState by viewModel.uiState.collectAsStateWithLifecycle() val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val kernelSupport by viewModel.kernelSupport.collectAsStateWithLifecycle() val kernelSupport by viewModel.kernelSupport.collectAsStateWithLifecycle()
@@ -123,7 +121,9 @@ fun SettingsScreen(
} }
val startForResult = val startForResult =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) { if (result.resultCode == Activity.RESULT_OK) {
result.data result.data
// Handle the Intent // Handle the Intent
@@ -133,28 +133,34 @@ fun SettingsScreen(
fun exportAllConfigs() { fun exportAllConfigs() {
try { try {
val wgFiles = uiState.tunnels.map { config -> val wgFiles =
uiState.tunnels.map { config ->
val file = File(context.cacheDir, "${config.name}-wg.conf") val file = File(context.cacheDir, "${config.name}-wg.conf")
file.outputStream().use { file.outputStream().use {
it.write(config.wgQuick.toByteArray()) it.write(config.wgQuick.toByteArray())
} }
file file
} }
val amFiles = uiState.tunnels.mapNotNull { config -> val amFiles =
uiState.tunnels.mapNotNull { config ->
if (config.amQuick != TunnelConfig.AM_QUICK_DEFAULT) { if (config.amQuick != TunnelConfig.AM_QUICK_DEFAULT) {
val file = File(context.cacheDir, "${config.name}-am.conf") val file = File(context.cacheDir, "${config.name}-am.conf")
file.outputStream().use { file.outputStream().use {
it.write(config.amQuick.toByteArray()) it.write(config.amQuick.toByteArray())
} }
file file
} else null } else {
null
}
} }
scope.launch { scope.launch {
viewModel.onExportTunnels(wgFiles + amFiles).onFailure { viewModel.onExportTunnels(wgFiles + amFiles).onFailure {
appViewModel.showSnackbarMessage(it.getMessage(context)) appViewModel.showSnackbarMessage(it.getMessage(context))
}.onSuccess { }.onSuccess {
didExportFiles = true didExportFiles = true
appViewModel.showSnackbarMessage(context.getString(R.string.exported_configs_message)) appViewModel.showSnackbarMessage(
context.getString(R.string.exported_configs_message),
)
} }
} }
} catch (e: Exception) { } catch (e: Exception) {
@@ -262,14 +268,16 @@ fun SettingsScreen(
Column( Column(
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top, verticalArrangement = Arrangement.Top,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.verticalScroll(scrollState), .verticalScroll(scrollState),
) { ) {
Icon( Icon(
Icons.Rounded.LocationOff, Icons.Rounded.LocationOff,
contentDescription = stringResource(id = R.string.map), contentDescription = stringResource(id = R.string.map),
modifier = Modifier modifier =
Modifier
.padding(30.dp) .padding(30.dp)
.size(128.dp), .size(128.dp),
) )
@@ -323,11 +331,15 @@ fun SettingsScreen(
}, },
onError = { _ -> onError = { _ ->
showAuthPrompt = false showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authentication_failed)) appViewModel.showSnackbarMessage(
context.getString(R.string.error_authentication_failed),
)
}, },
onFailure = { onFailure = {
showAuthPrompt = false showAuthPrompt = false
appViewModel.showSnackbarMessage(context.getString(R.string.error_authorization_failed)) appViewModel.showSnackbarMessage(
context.getString(R.string.error_authorization_failed),
)
}, },
) )
} }
@@ -367,7 +379,8 @@ fun SettingsScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.height(IntrinsicSize.Min) .height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
@@ -376,7 +389,8 @@ fun SettingsScreen(
Modifier Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp) .padding(top = 20.dp)
}) }
)
.padding(bottom = 10.dp), .padding(bottom = 10.dp),
) { ) {
Column( Column(
@@ -391,21 +405,26 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(id = R.string.tunnel_on_wifi), stringResource(id = R.string.tunnel_on_wifi),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isTunnelOnWifiEnabled, checked = uiState.settings.isTunnelOnWifiEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { viewModel.onToggleTunnelOnWifi() }, onCheckChanged = { viewModel.onToggleTunnelOnWifi() },
modifier = modifier =
if (uiState.settings.isAutoTunnelEnabled) Modifier if (uiState.settings.isAutoTunnelEnabled) {
else
Modifier Modifier
.focusRequester(focusRequester), } else {
Modifier
.focusRequester(focusRequester)
},
) )
AnimatedVisibility(visible = uiState.settings.isTunnelOnWifiEnabled) { AnimatedVisibility(visible = uiState.settings.isTunnelOnWifiEnabled) {
Column { Column {
FlowRow( FlowRow(
modifier = Modifier modifier =
Modifier
.padding(screenPadding) .padding(screenPadding)
.fillMaxWidth(), .fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(5.dp), horizontalArrangement = Arrangement.spacedBy(5.dp),
@@ -421,13 +440,14 @@ fun SettingsScreen(
onIconClick = { onIconClick = {
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus() if (WireGuardAutoTunnel.isRunningOnAndroidTv()) focusRequester.requestFocus()
viewModel.onDeleteTrustedSSID(ssid) viewModel.onDeleteTrustedSSID(ssid)
}, },
text = ssid, text = ssid,
icon = Icons.Filled.Close, icon = Icons.Filled.Close,
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
) )
} }
if (uiState.settings.trustedNetworkSSIDs.isEmpty()) { if (uiState.settings.trustedNetworkSSIDs.isEmpty()) {
@@ -440,8 +460,10 @@ fun SettingsScreen(
} }
OutlinedTextField( OutlinedTextField(
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
value = currentText, value = currentText,
onValueChange = { currentText = it }, onValueChange = { currentText = it },
label = { Text(stringResource(R.string.add_trusted_ssid)) }, label = { Text(stringResource(R.string.add_trusted_ssid)) },
@@ -489,8 +511,10 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(R.string.tunnel_mobile_data), stringResource(R.string.tunnel_mobile_data),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isTunnelOnMobileDataEnabled, checked = uiState.settings.isTunnelOnMobileDataEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { viewModel.onToggleTunnelOnMobileData() }, onCheckChanged = { viewModel.onToggleTunnelOnMobileData() },
@@ -498,8 +522,10 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(id = R.string.tunnel_on_ethernet), stringResource(id = R.string.tunnel_on_ethernet),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isTunnelOnEthernetEnabled, checked = uiState.settings.isTunnelOnEthernetEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { viewModel.onToggleTunnelOnEthernet() }, onCheckChanged = { viewModel.onToggleTunnelOnEthernet() },
@@ -507,8 +533,10 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(R.string.restart_on_ping), stringResource(R.string.restart_on_ping),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAlwaysOnVpnEnabled), uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled
),
checked = uiState.settings.isPingEnabled, checked = uiState.settings.isPingEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { viewModel.onToggleRestartOnPing() }, onCheckChanged = { viewModel.onToggleRestartOnPing() },
@@ -516,11 +544,15 @@ fun SettingsScreen(
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = modifier =
(if (!uiState.settings.isAutoTunnelEnabled) Modifier (
else if (!uiState.settings.isAutoTunnelEnabled) {
Modifier
} else {
Modifier.focusRequester( Modifier.focusRequester(
focusRequester, focusRequester,
)) )
}
)
.fillMaxSize() .fillMaxSize()
.padding(top = 5.dp), .padding(top = 5.dp),
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
@@ -535,12 +567,16 @@ fun SettingsScreen(
when (false) { when (false) {
isBackgroundLocationGranted -> isBackgroundLocationGranted ->
appViewModel.showSnackbarMessage( appViewModel.showSnackbarMessage(
context.getString(R.string.background_location_required), context.getString(
R.string.background_location_required,
),
) )
fineLocationState.status.isGranted -> fineLocationState.status.isGranted ->
appViewModel.showSnackbarMessage( appViewModel.showSnackbarMessage(
context.getString(R.string.precise_location_required), context.getString(
R.string.precise_location_required,
),
) )
viewModel.isLocationEnabled(context) -> viewModel.isLocationEnabled(context) ->
@@ -571,7 +607,8 @@ fun SettingsScreen(
shadowElevation = 2.dp, shadowElevation = 2.dp,
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = Modifier modifier =
Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(vertical = 10.dp), .padding(vertical = 10.dp),
) { ) {
@@ -587,9 +624,11 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(R.string.use_amnezia), stringResource(R.string.use_amnezia),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled || uiState.settings.isAlwaysOnVpnEnabled ||
(uiState.vpnState.status == TunnelState.UP) || uiState.settings.isKernelEnabled), (uiState.vpnState.status == TunnelState.UP) || uiState.settings.isKernelEnabled
),
checked = uiState.settings.isAmneziaEnabled, checked = uiState.settings.isAmneziaEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { onCheckChanged = {
@@ -600,9 +639,11 @@ fun SettingsScreen(
ConfigurationToggle( ConfigurationToggle(
stringResource(R.string.use_kernel), stringResource(R.string.use_kernel),
enabled = enabled =
!(uiState.settings.isAutoTunnelEnabled || !(
uiState.settings.isAutoTunnelEnabled ||
uiState.settings.isAlwaysOnVpnEnabled || uiState.settings.isAlwaysOnVpnEnabled ||
(uiState.vpnState.status == TunnelState.UP)), (uiState.vpnState.status == TunnelState.UP)
),
checked = uiState.settings.isKernelEnabled, checked = uiState.settings.isKernelEnabled,
padding = screenPadding, padding = screenPadding,
onCheckChanged = { onCheckChanged = {
@@ -652,25 +693,34 @@ fun SettingsScreen(
onCheckChanged = { viewModel.onToggleShortcutsEnabled() }, onCheckChanged = { viewModel.onToggleShortcutsEnabled() },
) )
} }
// TODO disable for now ConfigurationToggle(
// ConfigurationToggle( stringResource(R.string.restart_at_boot),
// stringResource(R.string.enable_app_lock), enabled = true,
// enabled = true, checked = uiState.settings.isRestoreOnBootEnabled,
// checked = pinExists.value, padding = screenPadding,
// padding = screenPadding, onCheckChanged = {
// onCheckChanged = { viewModel.onToggleRestartAtBoot()
// if (pinExists.value) { },
// PinManager.clearPin() )
// pinExists.value = PinManager.pinExists() ConfigurationToggle(
// } else { stringResource(R.string.enable_app_lock),
// navController.navigate(Screen.Lock.route) enabled = true,
// } checked = uiState.isPinLockEnabled,
// }, padding = screenPadding,
// ) onCheckChanged = {
if (uiState.isPinLockEnabled) {
viewModel.onPinLockDisabled()
} else {
viewModel.onPinLockEnabled()
navController.navigate(Screen.Lock.route)
}
},
)
if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) { if (!WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(top = 5.dp), .padding(top = 5.dp),
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
@@ -10,4 +10,5 @@ data class SettingsUiState(
val vpnState: VpnState = VpnState(), val vpnState: VpnState = VpnState(),
val isLocationDisclosureShown: Boolean = true, val isLocationDisclosureShown: Boolean = true,
val isBatteryOptimizeDisableShown: Boolean = false, val isBatteryOptimizeDisableShown: Boolean = false,
val isPinLockEnabled: Boolean = false,
) )
@@ -27,6 +27,7 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
import xyz.teamgravity.pin_lock_compose.PinManager
import java.io.File import java.io.File
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Provider import javax.inject.Provider
@@ -40,9 +41,8 @@ constructor(
private val rootShell: Provider<RootShell>, private val rootShell: Provider<RootShell>,
private val fileUtils: FileUtils, private val fileUtils: FileUtils,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
vpnService: VpnService vpnService: VpnService,
) : ViewModel() { ) : ViewModel() {
private val _kernelSupport = MutableStateFlow(false) private val _kernelSupport = MutableStateFlow(false)
val kernelSupport = _kernelSupport.asStateFlow() val kernelSupport = _kernelSupport.asStateFlow()
@@ -57,8 +57,9 @@ constructor(
settings, settings,
tunnels, tunnels,
tunnelState, tunnelState,
generalState.locationDisclosureShown, generalState.isLocationDisclosureShown,
generalState.batteryOptimizationDisableShown, generalState.isBatteryOptimizationDisableShown,
generalState.isPinLockEnabled,
) )
} }
.stateIn( .stateIn(
@@ -78,13 +79,11 @@ constructor(
} }
} }
fun setLocationDisclosureShown() = fun setLocationDisclosureShown() = viewModelScope.launch {
viewModelScope.launch {
appDataRepository.appState.setLocationDisclosureShown(true) appDataRepository.appState.setLocationDisclosureShown(true)
} }
fun setBatteryOptimizeDisableShown() = fun setBatteryOptimizeDisableShown() = viewModelScope.launch {
viewModelScope.launch {
appDataRepository.appState.setBatteryOptimizationDisableShown(true) appDataRepository.appState.setBatteryOptimizationDisableShown(true)
} }
@@ -109,8 +108,7 @@ constructor(
return fileUtils.saveFilesToZip(files) return fileUtils.saveFilesToZip(files)
} }
fun onToggleAutoTunnel(context: Context) = fun onToggleAutoTunnel(context: Context) = viewModelScope.launch {
viewModelScope.launch {
val isAutoTunnelEnabled = uiState.value.settings.isAutoTunnelEnabled val isAutoTunnelEnabled = uiState.value.settings.isAutoTunnelEnabled
var isAutoTunnelPaused = uiState.value.settings.isAutoTunnelPaused var isAutoTunnelPaused = uiState.value.settings.isAutoTunnelPaused
@@ -129,8 +127,7 @@ constructor(
WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate() WireGuardAutoTunnel.requestAutoTunnelTileServiceUpdate()
} }
fun onToggleAlwaysOnVPN() = fun onToggleAlwaysOnVPN() = viewModelScope.launch {
viewModelScope.launch {
saveSettings( saveSettings(
uiState.value.settings.copy( uiState.value.settings.copy(
isAlwaysOnVpnEnabled = !uiState.value.settings.isAlwaysOnVpnEnabled, isAlwaysOnVpnEnabled = !uiState.value.settings.isAlwaysOnVpnEnabled,
@@ -138,8 +135,7 @@ constructor(
) )
} }
private fun saveSettings(settings: Settings) = private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
viewModelScope.launch { appDataRepository.settings.save(settings) }
fun onToggleTunnelOnEthernet() { fun onToggleTunnelOnEthernet() {
saveSettings( saveSettings(
@@ -150,7 +146,10 @@ constructor(
} }
fun isLocationEnabled(context: Context): Boolean { fun isLocationEnabled(context: Context): Boolean {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager val locationManager =
context.getSystemService(
Context.LOCATION_SERVICE,
) as LocationManager
return LocationManagerCompat.isLocationEnabled(locationManager) return LocationManagerCompat.isLocationEnabled(locationManager)
} }
@@ -205,7 +204,6 @@ constructor(
isAmneziaEnabled = false, isAmneziaEnabled = false,
), ),
) )
} catch (e: RootShell.RootShellException) { } catch (e: RootShell.RootShellException) {
Timber.e(e) Timber.e(e)
saveKernelMode(on = false) saveKernelMode(on = false)
@@ -227,11 +225,30 @@ constructor(
} }
fun checkKernelSupport() = viewModelScope.launch { fun checkKernelSupport() = viewModelScope.launch {
val kernelSupport = withContext(ioDispatcher) { val kernelSupport =
withContext(ioDispatcher) {
WgQuickBackend.hasKernelSupport() WgQuickBackend.hasKernelSupport()
} }
_kernelSupport.update { _kernelSupport.update {
kernelSupport kernelSupport
} }
} }
fun onPinLockDisabled() = viewModelScope.launch {
PinManager.clearPin()
appDataRepository.appState.setPinLockEnabled(false)
}
fun onPinLockEnabled() = viewModelScope.launch {
PinManager.initialize(WireGuardAutoTunnel.instance)
appDataRepository.appState.setPinLockEnabled(true)
}
fun onToggleRestartAtBoot() = viewModelScope.launch {
saveSettings(
uiState.value.settings.copy(
isRestoreOnBootEnabled = !uiState.value.settings.isRestoreOnBootEnabled,
),
)
}
} }
@@ -57,7 +57,7 @@ fun SupportScreen(
viewModel: SupportViewModel = hiltViewModel(), viewModel: SupportViewModel = hiltViewModel(),
appViewModel: AppViewModel, appViewModel: AppViewModel,
navController: NavController, navController: NavController,
focusRequester: FocusRequester focusRequester: FocusRequester,
) { ) {
val context = LocalContext.current val context = LocalContext.current
val fillMaxWidth = .85f val fillMaxWidth = .85f
@@ -79,7 +79,8 @@ fun SupportScreen(
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface, color = MaterialTheme.colorScheme.surface,
modifier = modifier =
(if (WireGuardAutoTunnel.isRunningOnAndroidTv()) { (
if (WireGuardAutoTunnel.isRunningOnAndroidTv()) {
Modifier Modifier
.height(IntrinsicSize.Min) .height(IntrinsicSize.Min)
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
@@ -88,7 +89,8 @@ fun SupportScreen(
Modifier Modifier
.fillMaxWidth(fillMaxWidth) .fillMaxWidth(fillMaxWidth)
.padding(top = 20.dp) .padding(top = 20.dp)
}) }
)
.padding(bottom = 25.dp), .padding(bottom = 25.dp),
) { ) {
Column(modifier = Modifier.padding(20.dp)) { Column(modifier = Modifier.padding(20.dp)) {
@@ -113,7 +115,8 @@ fun SupportScreen(
context, context,
) )
}, },
modifier = Modifier modifier =
Modifier
.padding(vertical = 5.dp) .padding(vertical = 5.dp)
.focusRequester(focusRequester), .focusRequester(focusRequester),
) { ) {
@@ -128,7 +131,8 @@ fun SupportScreen(
Text( Text(
stringResource(id = R.string.docs_description), stringResource(id = R.string.docs_description),
textAlign = TextAlign.Justify, textAlign = TextAlign.Justify,
modifier = Modifier modifier =
Modifier
.padding(start = 10.dp) .padding(start = 10.dp)
.weight( .weight(
weight = 1.0f, weight = 1.0f,
@@ -295,12 +299,14 @@ fun SupportScreen(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(25.dp), modifier = Modifier.padding(25.dp),
) { ) {
val version = buildAnnotatedString { val version =
buildAnnotatedString {
append(stringResource(id = R.string.version)) append(stringResource(id = R.string.version))
append(": ") append(": ")
append(BuildConfig.VERSION_NAME) append(BuildConfig.VERSION_NAME)
} }
val mode = buildAnnotatedString { val mode =
buildAnnotatedString {
append(stringResource(R.string.mode)) append(stringResource(R.string.mode))
append(": ") append(": ")
when (uiState.settings.isKernelEnabled) { when (uiState.settings.isKernelEnabled) {
@@ -11,9 +11,10 @@ import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject import javax.inject.Inject
@HiltViewModel @HiltViewModel
class SupportViewModel @Inject constructor(settingsRepository: SettingsRepository) : class SupportViewModel
@Inject
constructor(settingsRepository: SettingsRepository) :
ViewModel() { ViewModel() {
val uiState = val uiState =
settingsRepository settingsRepository
.getSettingsFlow() .getSettingsFlow()
@@ -42,7 +42,6 @@ import kotlinx.coroutines.launch
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable @Composable
fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) { fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
val logs = viewModel.logs val logs = viewModel.logs
val context = LocalContext.current val context = LocalContext.current
@@ -87,7 +86,8 @@ fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.Top), verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.Top),
state = lazyColumnListState, state = lazyColumnListState,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.padding(horizontal = 24.dp), .padding(horizontal = 24.dp),
) { ) {
@@ -99,13 +99,16 @@ fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
Row( Row(
horizontalArrangement = Arrangement.spacedBy(5.dp, Alignment.Start), horizontalArrangement = Arrangement.spacedBy(5.dp, Alignment.Start),
verticalAlignment = Alignment.Top, verticalAlignment = Alignment.Top,
modifier = Modifier modifier =
Modifier
.fillMaxSize() .fillMaxSize()
.clickable( .clickable(
interactionSource = remember { MutableInteractionSource() }, interactionSource = remember { MutableInteractionSource() },
indication = null, indication = null,
onClick = { onClick = {
clipboardManager.setText(annotatedString = AnnotatedString(it.toString())) clipboardManager.setText(
annotatedString = AnnotatedString(it.toString()),
)
}, },
), ),
) { ) {
@@ -20,13 +20,13 @@ import javax.inject.Inject
@HiltViewModel @HiltViewModel
class LogsViewModel class LogsViewModel
@Inject constructor( @Inject
constructor(
private val localLogCollector: LocalLogCollector, private val localLogCollector: LocalLogCollector,
private val fileUtils: FileUtils, private val fileUtils: FileUtils,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
@MainDispatcher private val mainDispatcher: CoroutineDispatcher @MainDispatcher private val mainDispatcher: CoroutineDispatcher,
) : ViewModel() { ) : ViewModel() {
val logs = mutableStateListOf<LogMessage>() val logs = mutableStateListOf<LogMessage>()
init { init {
@@ -45,7 +45,8 @@ class LogsViewModel
} }
suspend fun saveLogsToFile(): Result<Unit> { suspend fun saveLogsToFile(): Result<Unit> {
val file = localLogCollector.getLogFile().getOrElse { val file =
localLogCollector.getLogFile().getOrElse {
return Result.failure(it) return Result.failure(it)
} }
val fileContent = fileUtils.readBytesFromFile(file) val fileContent = fileUtils.readBytesFromFile(file)
@@ -49,7 +49,7 @@ fun WireguardAutoTunnelTheme(
// Dynamic color is available on Android 12+ // Dynamic color is available on Android 12+
// turning off dynamic color for now // turning off dynamic color for now
dynamicColor: Boolean = false, dynamicColor: Boolean = false,
content: @Composable () -> Unit content: @Composable () -> Unit,
) { ) {
val colorScheme = val colorScheme =
when { when {
@@ -1,7 +1,6 @@
package com.zaneschepke.wireguardautotunnel.util package com.zaneschepke.wireguardautotunnel.util
object Constants { object Constants {
const val BASE_LOG_FILE_NAME = "wg_tunnel_logs" const val BASE_LOG_FILE_NAME = "wg_tunnel_logs"
const val LOG_BUFFER_SIZE = 3_000L const val LOG_BUFFER_SIZE = 3_000L
@@ -32,13 +31,10 @@ object Constants {
const val PING_INTERVAL = 60_000L const val PING_INTERVAL = 60_000L
const val PING_COOLDOWN = PING_INTERVAL * 60 // one hour const val PING_COOLDOWN = PING_INTERVAL * 60 // one hour
const val ALLOWED_DISPLAY_NAME_LENGTH = 20
const val TUNNEL_EXTRA_KEY = "tunnelId" const val TUNNEL_EXTRA_KEY = "tunnelId"
const val UNREADABLE_SSID = "<unknown ssid>" const val UNREADABLE_SSID = "<unknown ssid>"
val amneziaProperties = listOf("Jc", "Jmin", "Jmax", "S1", "S2", "H1", "H2", "H3", "H4") val amneziaProperties = listOf("Jc", "Jmin", "Jmax", "S1", "S2", "H1", "H2", "H3", "H4")
const val QR_CODE_NAME_PROPERTY = "# Name =" const val QR_CODE_NAME_PROPERTY = "# Name ="
} }
@@ -1,6 +1,5 @@
package com.zaneschepke.wireguardautotunnel.util package com.zaneschepke.wireguardautotunnel.util
import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.pm.PackageInfo import android.content.pm.PackageInfo
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
@@ -10,7 +9,6 @@ import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStati
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.channels.ClosedReceiveChannelException import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.ReceiveChannel
@@ -19,7 +17,6 @@ import kotlinx.coroutines.channels.ticker
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.whileSelect import kotlinx.coroutines.selects.whileSelect
import org.amnezia.awg.config.Config import org.amnezia.awg.config.Config
import timber.log.Timber import timber.log.Timber
@@ -27,25 +24,8 @@ import java.math.BigDecimal
import java.text.DecimalFormat import java.text.DecimalFormat
import java.time.Duration import java.time.Duration
import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.cancellation.CancellationException import kotlin.coroutines.cancellation.CancellationException
fun BroadcastReceiver.goAsync(
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> Unit
) {
val pendingResult = goAsync()
@OptIn(DelicateCoroutinesApi::class) // Must run globally; there's no teardown callback.
GlobalScope.launch(context) {
try {
block()
} finally {
pendingResult.finish()
}
}
}
fun BigDecimal.toThreeDecimalPlaceString(): String { fun BigDecimal.toThreeDecimalPlaceString(): String {
val df = DecimalFormat("#.###") val df = DecimalFormat("#.###")
return df.format(this) return df.format(this)
@@ -109,8 +89,7 @@ fun Throwable.getMessage(context: Context): String {
* Borrowed from this [Stack Overflow question](https://stackoverflow.com/questions/51022533/kotlin-chunk-sequence-based-on-size-and-time). * Borrowed from this [Stack Overflow question](https://stackoverflow.com/questions/51022533/kotlin-chunk-sequence-based-on-size-and-time).
*/ */
@OptIn(ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class) @OptIn(ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class)
fun <T> ReceiveChannel<T>.chunked(scope: CoroutineScope, size: Int, time: Duration) = fun <T> ReceiveChannel<T>.chunked(scope: CoroutineScope, size: Int, time: Duration) = scope.produce<List<T>> {
scope.produce<List<T>> {
while (true) { // this loop goes over each chunk while (true) { // this loop goes over each chunk
val chunk = ConcurrentLinkedQueue<T>() // current chunk val chunk = ConcurrentLinkedQueue<T>() // current chunk
val ticker = ticker(time.toMillis()) // time-limit for this chunk val ticker = ticker(time.toMillis()) // time-limit for this chunk
@@ -163,6 +142,3 @@ fun <T> CoroutineScope.asChannel(flow: Flow<T>): ReceiveChannel<T> = produce {
channel.send(value) channel.send(value)
} }
} }
@@ -21,7 +21,6 @@ class FileUtils(
private val context: Context, private val context: Context,
private val ioDispatcher: CoroutineDispatcher, private val ioDispatcher: CoroutineDispatcher,
) { ) {
suspend fun readBytesFromFile(file: File): ByteArray { suspend fun readBytesFromFile(file: File): ByteArray {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
FileInputStream(file).use { FileInputStream(file).use {
@@ -61,7 +60,9 @@ class FileUtils(
} else { } else {
val target = val target =
File( File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS,
),
fileName, fileName,
) )
FileOutputStream(target).use { output -> FileOutputStream(target).use { output ->
@@ -101,10 +102,7 @@ class FileUtils(
} }
// TODO issue with android 9 // TODO issue with android 9
private fun createDownloadsFileOutputStream( private fun createDownloadsFileOutputStream(fileName: String, mimeType: String = Constants.ALLOWED_FILE_TYPES): OutputStream? {
fileName: String,
mimeType: String = Constants.ALLOWED_FILE_TYPES
): OutputStream? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val resolver = context.contentResolver val resolver = context.contentResolver
val contentValues = val contentValues =
@@ -4,14 +4,13 @@ import android.content.Context
import androidx.annotation.StringRes import androidx.annotation.StringRes
sealed class StringValue { sealed class StringValue {
data class DynamicString(val value: String) : StringValue() data class DynamicString(val value: String) : StringValue()
data object Empty : StringValue() data object Empty : StringValue()
class StringResource( class StringResource(
@StringRes val resId: Int, @StringRes val resId: Int,
vararg val args: Any vararg val args: Any,
) : StringValue() ) : StringValue()
fun asString(context: Context?): String { fun asString(context: Context?): String {
@@ -5,13 +5,19 @@ import com.zaneschepke.wireguardautotunnel.R
sealed class WgTunnelExceptions : Exception() { sealed class WgTunnelExceptions : Exception() {
abstract fun getMessage(context: Context): String abstract fun getMessage(context: Context): String
data class General(private val userMessage: StringValue) : WgTunnelExceptions() { data class General(private val userMessage: StringValue) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
} }
} }
data class SsidConflict(private val userMessage: StringValue = StringValue.StringResource(R.string.error_ssid_exists)) : data class SsidConflict(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_ssid_exists,
),
) :
WgTunnelExceptions() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -19,9 +25,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class ConfigExportFailed( data class ConfigExportFailed(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.export_configs_failed, R.string.export_configs_failed,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -32,18 +39,29 @@ sealed class WgTunnelExceptions : Exception() {
WgTunnelExceptions() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return StringValue.StringResource(R.string.config_parse_error).asString(context) + ( return StringValue.StringResource(R.string.config_parse_error).asString(context) + (
if (appendMessage != StringValue.Empty) ": ${appendMessage.asString(context)}" else "") if (appendMessage != StringValue.Empty) ": ${appendMessage.asString(context)}" else ""
)
} }
} }
data class RootDenied(private val userMessage: StringValue = StringValue.StringResource(R.string.error_root_denied)) : data class RootDenied(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_root_denied,
),
) :
WgTunnelExceptions() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
} }
} }
data class InvalidQrCode(private val userMessage: StringValue = StringValue.StringResource(R.string.error_invalid_code)) : data class InvalidQrCode(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_invalid_code,
),
) :
WgTunnelExceptions() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -51,16 +69,22 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class InvalidFileExtension( data class InvalidFileExtension(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_file_extension, R.string.error_file_extension,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
} }
} }
data class FileReadFailed(private val userMessage: StringValue = StringValue.StringResource(R.string.error_file_format)) : data class FileReadFailed(
private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_file_format,
),
) :
WgTunnelExceptions() { WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -68,9 +92,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class AuthenticationFailed( data class AuthenticationFailed(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_authentication_failed, R.string.error_authentication_failed,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -78,9 +103,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class AuthorizationFailed( data class AuthorizationFailed(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_authorization_failed, R.string.error_authorization_failed,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -88,9 +114,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class BackgroundLocationRequired( data class BackgroundLocationRequired(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.background_location_required, R.string.background_location_required,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -98,9 +125,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class LocationServicesRequired( data class LocationServicesRequired(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.location_services_required, R.string.location_services_required,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -108,9 +136,10 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class PreciseLocationRequired( data class PreciseLocationRequired(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.precise_location_required, R.string.precise_location_required,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
@@ -118,13 +147,13 @@ sealed class WgTunnelExceptions : Exception() {
} }
data class FileExplorerRequired( data class FileExplorerRequired(
private val userMessage: StringValue = StringValue.StringResource( private val userMessage: StringValue =
StringValue.StringResource(
R.string.error_no_file_explorer, R.string.error_no_file_explorer,
) ),
) : WgTunnelExceptions() { ) : WgTunnelExceptions() {
override fun getMessage(context: Context): String { override fun getMessage(context: Context): String {
return userMessage.asString(context) return userMessage.asString(context)
} }
} }
} }
+7
View File
@@ -144,4 +144,11 @@
<string name="general">Obecné</string> <string name="general">Obecné</string>
<string name="settings">Nastavení</string> <string name="settings">Nastavení</string>
<string name="support">Podpora</string> <string name="support">Podpora</string>
<string name="app_name">WG Tunnel</string>
<string name="mtu">MTU</string>
<string name="db_name">wg-tunnel-db</string>
<string name="listen_port">Naslouchací port</string>
<string name="auto">(automaticky)</string>
<string name="kernel">Kernel</string>
<string name="backend">Backend</string>
</resources> </resources>
+6 -1
View File
@@ -135,7 +135,7 @@
<string name="pin_created">Pin creado con éxito</string> <string name="pin_created">Pin creado con éxito</string>
<string name="enter_pin">Introduce tu pin</string> <string name="enter_pin">Introduce tu pin</string>
<string name="create_pin">Crear pin</string> <string name="create_pin">Crear pin</string>
<string name="enable_app_lock">Bloqueo de app activado</string> <string name="enable_app_lock">Activar el bloqueo de aplicaciones</string>
<string name="restart_on_ping">Reiniciar al fallar ping (beta)</string> <string name="restart_on_ping">Reiniciar al fallar ping (beta)</string>
<string name="set_primary_tunnel">Establecer como túnel Principal</string> <string name="set_primary_tunnel">Establecer como túnel Principal</string>
<string name="no_wifi_names_configured">No hay nombres Wi-Fi configurados para este túnel</string> <string name="no_wifi_names_configured">No hay nombres Wi-Fi configurados para este túnel</string>
@@ -152,4 +152,9 @@
<string name="watcher_channel_id">Canal del obvervador</string> <string name="watcher_channel_id">Canal del obvervador</string>
<string name="watcher_channel_name">Canal de notificación del obvervador</string> <string name="watcher_channel_name">Canal de notificación del obvervador</string>
<string name="prominent_background_location_message">La monitorización SSID Wi-Fi necesita de permiso de ubicación en segundo plano incluso si la app está cerrada. Mira el enlace a la Política de Privacidad en la pantalla de ayuda para más detalles.</string> <string name="prominent_background_location_message">La monitorización SSID Wi-Fi necesita de permiso de ubicación en segundo plano incluso si la app está cerrada. Mira el enlace a la Política de Privacidad en la pantalla de ayuda para más detalles.</string>
<string name="export_configs_failed">Error al exportar la configuración</string>
<string name="use_amnezia">"Utilizar el entorno de usuario de Amnezia "</string>
<string name="junk_packet_count">Recuento de paquetes basura</string>
<string name="backend">Backend</string>
<string name="junk_packet_minimum_size">Tamaño mínimo del paquete basura</string>
</resources> </resources>
+162
View File
@@ -0,0 +1,162 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="watcher_notification_text_active">Monitoramento de mudanças do estado da rede: Ativo</string>
<string name="watcher_notification_text_paused">Monitoramento de mudanças do estado da rede: pausado</string>
<string name="tunnel_start_title">VPN conectada</string>
<string name="tunnel_on_ethernet">Túnel na ethernet</string>
<string name="save_changes">Salvar</string>
<string name="public_key">Chave pública</string>
<string name="addresses">Endereços</string>
<string name="dns_servers">Servidores DNS</string>
<string name="endpoint">Endpoint</string>
<string name="name">Nome</string>
<string name="restart">Reiniciar Túnel</string>
<string name="create_import">Criar do zero</string>
<string name="turn_off_auto">Esta ação precisa do auto-túnel desativado ou pausado</string>
<string name="rotate_keys">Revezar chaves</string>
<string name="private_key">Chave privada</string>
<string name="base64_key">Chave base64</string>
<string name="optional_no_recommend">(opcional, não recomendado)</string>
<string name="preshared_key">Chave pré-compartilhada</string>
<string name="seconds">segundos</string>
<string name="export_configs">Exportar configurações</string>
<string name="export_configs_failed">Falhou ao exportar configurações</string>
<string name="go">ir</string>
<string name="error_no_file_explorer">Nenhum explorador de arquivos instalado</string>
<string name="error_invalid_code">Código QR inválido</string>
<string name="auto_tunnel_title">Serviço de Auto-túnel</string>
<string name="excluded">excluído</string>
<string name="all">todos</string>
<string name="enter_pin">Digite seu pin</string>
<string name="use_tunnel_on_wifi_name">Usar túnel em wifi com nome</string>
<string name="auto_tun_on">Continuar auto-túnel</string>
<string name="auto_tun_off">Pausar auto-túnel</string>
<string name="version">Versão</string>
<string name="mode">Modo</string>
<string name="use_amnezia">"Usar Amnezia em modo usuário "</string>
<string name="junk_packet_count">Número de pacotes-lixo</string>
<string name="junk_packet_minimum_size">Tamanho mínimo de pacote-lixo</string>
<string name="junk_packet_maximum_size">Tamanho máximo de pacote-lixo</string>
<string name="init_packet_junk_size">Tamanho de pacote-lixo inicial</string>
<string name="response_packet_junk_size">Tamanho de resposta de pacote-lixo</string>
<string name="app_name">WG Tunnel</string>
<string name="no_tunnels">Nenhum túnel foi adicionado!</string>
<string name="error_file_extension">O arquivo não é .conf ou .zip</string>
<string name="prominent_background_location_message">Este recurso precisa de permissões de localização em segundo plano para habilitar o monitoramento do SSID da rede Wi-Fi mesmo quando o aplicativo está fechado. Para mais detalhes, por favor veja a Política de Privacidade na tela de Suporte.</string>
<string name="turn_off_tunnel">Esta ação só é possível com o túnel inativo</string>
<string name="enabled_app_shortcuts">Habilitar atalhos do aplicativo</string>
<string name="notification_permission_required">Necessita permissões de notificação.</string>
<string name="add_trusted_ssid">Adicionar nome de Wi-Fi confiável</string>
<string name="enable_auto_tunnel">Iniciar auto-túnel</string>
<string name="tunnels">Túneis</string>
<string name="disable_auto_tunnel">Parar auto-túnel</string>
<string name="tunnel_start_text">Conectado ao túnel</string>
<string name="trusted_ssid_empty_description">Digite o SSID</string>
<string name="no_thanks">Não, obrigado</string>
<string name="privacy_policy">Ver a Política de Privacidade</string>
<string name="okay">OK</string>
<string name="tunnel_mobile_data">Túnel em dados móveis</string>
<string name="one_tunnel_required">Pelo menos um túnel é necessário para usar este recurso</string>
<string name="prominent_background_location_title">Revelar a localização em segundo plano</string>
<string name="thank_you">Obrigado por usar o WG Tunnel!</string>
<string name="trusted_ssid_value_description">Envie o SSID</string>
<string name="open_file">Abrir Arquivo</string>
<string name="add_from_qr">Adicionar a partir de código QR</string>
<string name="add_tunnels_text">Adicionar a partir de arquivo ou zip</string>
<string name="tunnel_all">Todos os aplicativos pelo túnel</string>
<string name="icon">Ícone</string>
<string name="turn_on">Ligar</string>
<string name="qr_scan">Escanear o código QR</string>
<string name="tunnel_name">Nome do Túnel</string>
<string name="add_tunnel">Adicionar Túnel</string>
<string name="config_changes_saved">Mudanças nas configurações salvas.</string>
<string name="exclude">Excluir</string>
<string name="include">Incluir</string>
<string name="map">Mapa</string>
<string name="vpn_connection_failed">Falha na conexão</string>
<string name="mtu">MTU</string>
<string name="always_on_vpn_support">Permitir VPN sempre ligada</string>
<string name="allowed_ips">IPs Permitidos</string>
<string name="attempt_connection">Tentando conexão..</string>
<string name="peer">Par</string>
<string name="location_services_not_detected">Serviço de localização não foi detectado</string>
<string name="hint_search_packages">Procurar pacotes</string>
<string name="vpn_starting">Iniciando VPN</string>
<string name="other">Outro</string>
<string name="scanning_qr">Escaneando código QR</string>
<string name="none">Nenhum nome de Wi-Fi confiável</string>
<string name="auto_tunneling">Auto-túnel</string>
<string name="default_vpn_on">VPN Principal ligada</string>
<string name="vpn_on">VPN ligada</string>
<string name="vpn_off">VPN desligada</string>
<string name="listen_port">Porta de escuta</string>
<string name="default_vpn_off">VPN Principal desligada</string>
<string name="turn_on_tunnel">Esta ação precisa um túnel ativo</string>
<string name="done">Feito</string>
<string name="add_peer">Adicionar par</string>
<string name="interface_">Interface</string>
<string name="copy_public_key">Copiar chave pública</string>
<string name="comma_separated_list">Lista separada por vírgulas</string>
<string name="optional">(opcional)</string>
<string name="random">(aleatório)</string>
<string name="persistent_keepalive">Manter a conexão persistente (keepalive)</string>
<string name="cancel">Cancelar</string>
<string name="error_authentication_failed">Autenticação falhou</string>
<string name="error_authorization_failed">Autorização falhou</string>
<string name="restart_on_ping">Reiniciar em falha de ping (beta)</string>
<string name="background_location_required">Necessita a localização em segundo plano</string>
<string name="location_services_required">Necessita dos serviços de localização</string>
<string name="email_description">Me envie um email</string>
<string name="error_ssid_exists">SSID já existe</string>
<string name="delete_tunnel_message">Tem certeza que você quer apagar este túnel?</string>
<string name="yes">Sim</string>
<string name="precise_location_required">Necessita da localização precisa</string>
<string name="exported_configs_message">Configurações exportadas para downloads</string>
<string name="unknown_error">Ocorreu um erro desconhecido</string>
<string name="email_subject">Suporte para o WG Tunnel</string>
<string name="tunnel_on_wifi">Túnel em Wi-Fi não confiável</string>
<string name="error_none">Nenhum erro</string>
<string name="delete_tunnel">Apagar túnel</string>
<string name="email_chooser">Enviar um email…</string>
<string name="use_kernel">Usar o módulo do kernel</string>
<string name="discord_description">Juntar-se à comunidade</string>
<string name="docs_description">Ler a documentação</string>
<string name="support_help_text">Se você enfrentar problemas, tiver ideias para melhorias ou apenas quiser participar, os seguintes recursos estão disponíveis:</string>
<string name="error_root_denied">Shell Root negado</string>
<string name="location_services_missing_message">O aplicativo não detectou o serviço de localização habilitado no seu dispositivo. Dependendo do dispositivo, isto pode causar que a função de Wi-Fi não confiável falhe em ler o nome do Wi-Fi. Quer continuar mesmo assim?</string>
<string name="paused">pausado</string>
<string name="included">incluso</string>
<string name="resume">Continuar</string>
<string name="pause">Pausar</string>
<string name="active">ativo</string>
<string name="always_on_disabled">VPN sempre ligada tentou iniciar um túnel, mas este recurso está desligado nas configurações.</string>
<string name="open_issue">Abrir um problema</string>
<string name="tunneling_apps">Aplicativos em túnel</string>
<string name="no_email_detected">Nenhum aplicativo de email detectado</string>
<string name="no_browser_detected">Nenhum navegador detectado</string>
<string name="logs_saved">Registros salvos em downloads</string>
<string name="incorrect_pin">O Pin está errado</string>
<string name="auto">(automático)</string>
<string name="disabled">desligado</string>
<string name="read_logs">Ler os registros</string>
<string name="config_parse_error">Falha na interpretação das configurações</string>
<string name="pin_created">Pin criado com sucesso</string>
<string name="auto_on">Continuar auto-túnel</string>
<string name="create_pin">Criar um pin</string>
<string name="enable_app_lock">Ligar trava de aplicativo</string>
<string name="no_wifi_names_configured">Nenhum Wi-Fi configurado para este túnel</string>
<string name="edit_tunnel">Editar túnel</string>
<string name="mobile_data_tunnel">Selecionar como túnel em dados móveis</string>
<string name="set_primary_tunnel">Selecionar como túnel principal</string>
<string name="general">Geral</string>
<string name="userspace">Modo usuário</string>
<string name="support">Suporte</string>
<string name="kernel">Kernel</string>
<string name="auto_off">Pausar auto-túnel</string>
<string name="backend">Backend</string>
<string name="settings">Configurações</string>
<string name="unsure_how">se não tiver certeza em como continuar</string>
<string name="see_the">Veja o</string>
<string name="getting_started_guide">guia de início rápido</string>
<string name="error_file_format">Formato de arquivo de configuração inválido</string>
</resources>
+1 -1
View File
@@ -59,7 +59,7 @@
<string name="cancel">Отмена</string> <string name="cancel">Отмена</string>
<string name="docs_description">Посмотреть документацию</string> <string name="docs_description">Посмотреть документацию</string>
<string name="discord_description">Присоединиться к сообществу</string> <string name="discord_description">Присоединиться к сообществу</string>
<string name="email_chooser">Отправить письмо</string> <string name="email_chooser">Отправить письмо</string>
<string name="add_trusted_ssid">Добавить доверенное имя сети Wi-Fi</string> <string name="add_trusted_ssid">Добавить доверенное имя сети Wi-Fi</string>
<string name="included">включено</string> <string name="included">включено</string>
<string name="vpn_starting">Идёт запуск VPN</string> <string name="vpn_starting">Идёт запуск VPN</string>
+87 -67
View File
@@ -1,4 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string name="app_name">WG Tunnel</string> <string name="app_name">WG Tunnel</string>
<string name="vpn_channel_id">VPN Kanalı</string> <string name="vpn_channel_id">VPN Kanalı</string>
@@ -8,38 +7,38 @@
<string name="github_url" translatable="false">https://github.com/zaneschepke/wgtunnel/issues</string> <string name="github_url" translatable="false">https://github.com/zaneschepke/wgtunnel/issues</string>
<string name="docs_url" translatable="false">https://zaneschepke.com/wgtunnel-docs/overview.html</string> <string name="docs_url" translatable="false">https://zaneschepke.com/wgtunnel-docs/overview.html</string>
<string name="privacy_policy_url" translatable="false">https://zaneschepke.com/wgtunnel-docs/privacypolicy.html</string> <string name="privacy_policy_url" translatable="false">https://zaneschepke.com/wgtunnel-docs/privacypolicy.html</string>
<string name="error_file_extension">Dosya bir .conf veya .zip değil</string> <string name="error_file_extension">Dosya .conf veya .zip değil</string>
<string name="turn_off_tunnel">Eylem tünelin kapalı olmasını gerektiriyor</string> <string name="turn_off_tunnel">İşlem için tünelin kapalı olması gerekiyor</string>
<string name="no_tunnels">Henüz bir tünel ekli değil!</string> <string name="no_tunnels">Henüz tünel eklenmedi!</string>
<string name="discord_url" translatable="false">https://discord.gg/rbRRNh6H7V</string> <string name="discord_url" translatable="false">https://discord.gg/rbRRNh6H7V</string>
<string name="watcher_notification_text_active">Ağ durumu değişikliklerini izleme: etkin</string> <string name="watcher_notification_text_active">Ağ durum değişiklikleri izleniyor: aktif</string>
<string name="watcher_notification_text_paused">Ağ durumu değişikliklerini izleme: duraklatıldı</string> <string name="watcher_notification_text_paused">Ağ durum değişiklikleri izleniyor: duraklatıldı</string>
<string name="tunnel_start_title">VPN bağlandı</string> <string name="tunnel_start_title">VPN bağlandı</string>
<string name="tunnel_start_text">Tünele bağlı</string> <string name="tunnel_start_text">Tünele bağlandı</string>
<string name="notification_permission_required">Bildirim izni gerekli.</string> <string name="notification_permission_required">Bildirim izni gerekli.</string>
<string name="add_trusted_ssid">Güvenilir Wi-Fi adı ekle</string> <string name="add_trusted_ssid">Güvenilir wifi adı ekle</string>
<string name="tunnels">Tüneller</string> <string name="tunnels">Tüneller</string>
<string name="enable_auto_tunnel">Otomatik tünellemeyi başlat</string> <string name="enable_auto_tunnel">Otomatik tünellemeyi başlat</string>
<string name="disable_auto_tunnel">Otomatik tünellemeyi durdur</string> <string name="disable_auto_tunnel">Otomatik tünellemeyi durdur</string>
<string name="tunnel_mobile_data">Mobil veri üzerinde tünel</string> <string name="tunnel_mobile_data">Mobil veride tünel</string>
<string name="one_tunnel_required">Bu özelliği kullanabilmek için en az bir tünel gereklidir.</string> <string name="one_tunnel_required">Bu özelliği kullanmak için en az bir tünel gerekli</string>
<string name="privacy_policy">Gizlilik Politikası</string> <string name="privacy_policy">Gizlilik Politikasını Görüntüle</string>
<string name="okay">Tamam</string> <string name="okay">Tamam</string>
<string name="tunnel_on_ethernet">Ethernet üzerinde tünel</string> <string name="tunnel_on_ethernet">Ethernet\'te tünel</string>
<string name="prominent_background_location_message">Bu özellik, uygulama kapalıyken bile Wi-Fi SSID izlemesini etkinleştirmek için arka plan konumu izni gerektirir. Daha fazla bilgi için lütfen Destek ekranında bağlantısı verilen Gizlilik Politikasına bakın.</string> <string name="prominent_background_location_message">Bu özellik, uygulama kapalıyken bile Wi-Fi SSID izlemesini etkinleştirmek için arka plan konum iznine ihtiyaç duyar. Daha fazla ayrıntı için lütfen Destek ekranında bağlantısı verilen Gizlilik Politikasına bakın.</string>
<string name="prominent_background_location_title">Arka Plan Konum Açıklaması</string> <string name="prominent_background_location_title">Arka Plan Konum Açıklaması</string>
<string name="thank_you">WG Tunnel\'i kullandığınız için teşekkür ederiz!</string> <string name="thank_you">WG Tunnel\'ı kullandığınız için teşekkürler!</string>
<string name="trusted_ssid_empty_description">SSID\'yi gir</string> <string name="trusted_ssid_empty_description">SSID girin</string>
<string name="trusted_ssid_value_description">SSID\'yi gönder</string> <string name="trusted_ssid_value_description">SSID\'yi gönder</string>
<string name="add_tunnels_text">Dosyadan veya ZIP\'ten ekle</string> <string name="add_tunnels_text">Dosyadan veya zip\'ten ekle</string>
<string name="open_file">Dosya Aç</string> <string name="open_file">Dosya Aç</string>
<string name="add_from_qr">QR kodundan ekle</string> <string name="add_from_qr">QR kodundan ekle</string>
<string name="qr_scan">QR kodu tarat</string> <string name="qr_scan">QR Tarama</string>
<string name="tunnel_name">Tünel adı</string> <string name="tunnel_name">Tünel Adı</string>
<string name="add_tunnel">Tünel ekle</string> <string name="add_tunnel">Tünel Ekle</string>
<string name="exclude">Hariç tut</string> <string name="exclude">Hariç tut</string>
<string name="include">Dahil et</string> <string name="include">Dahil et</string>
<string name="tunnel_all">Tüm uygulamaları dahil et</string> <string name="tunnel_all">Tüm uygulamaları tünelle</string>
<string name="config_changes_saved">Yapılandırma değişiklikleri kaydedildi.</string> <string name="config_changes_saved">Yapılandırma değişiklikleri kaydedildi.</string>
<string name="save_changes">Kaydet</string> <string name="save_changes">Kaydet</string>
<string name="icon">Simge</string> <string name="icon">Simge</string>
@@ -55,15 +54,15 @@
<string name="endpoint">Uç nokta (endpoint)</string> <string name="endpoint">Uç nokta (endpoint)</string>
<string name="name">Ad</string> <string name="name">Ad</string>
<string name="restart">Tüneli Yeniden Başlat</string> <string name="restart">Tüneli Yeniden Başlat</string>
<string name="vpn_connection_failed">Bağlantı kurulamadı</string> <string name="vpn_connection_failed">Bağlantı başarısız</string>
<string name="always_on_vpn_support">Her Zaman Açık VPN\'e İzin Ver</string> <string name="always_on_vpn_support">Her Zaman Açık VPN\'e İzin Ver</string>
<string name="location_services_not_detected">Konum Hizmetleri Algılanmadı</string> <string name="location_services_not_detected">Konum Hizmetleri Algılanmadı</string>
<string name="hint_search_packages">Uygulama arayın</string> <string name="hint_search_packages">Paketlerde ara</string>
<string name="attempt_connection">Bağlantı kurulmaya çalışılıyor..</string> <string name="attempt_connection">Bağlantı deneniyor..</string>
<string name="vpn_starting">VPN başlatılıyor</string> <string name="vpn_starting">VPN başlatılıyor</string>
<string name="db_name">wg-tunnel-db</string> <string name="db_name">wg-tunnel-db</string>
<string name="scanning_qr">QR taranıyor</string> <string name="scanning_qr">QR için taranıyor</string>
<string name="none">Güvenilir Wi-Fi adı yok</string> <string name="none">Güvenilir wifi adı yok</string>
<string name="other">Diğer</string> <string name="other">Diğer</string>
<string name="auto_tunneling">Otomatik tünelleme</string> <string name="auto_tunneling">Otomatik tünelleme</string>
<string name="vpn_on">VPN açık</string> <string name="vpn_on">VPN açık</string>
@@ -71,50 +70,50 @@
<string name="default_vpn_on">Birincil VPN açık</string> <string name="default_vpn_on">Birincil VPN açık</string>
<string name="default_vpn_off">Birincil VPN kapalı</string> <string name="default_vpn_off">Birincil VPN kapalı</string>
<string name="create_import">Sıfırdan oluştur</string> <string name="create_import">Sıfırdan oluştur</string>
<string name="turn_off_auto">Eylem, otomatik tünelin devre dışı bırakılmasını veya duraklatılmasını gerektirir</string> <string name="turn_off_auto">İşlem için otomatik tünelin devre dışı veya duraklatılmış olması gerekiyor</string>
<string name="turn_on_tunnel">Eylem aktif tünel gerektirir</string> <string name="turn_on_tunnel">İşlem için aktif tünel gerekiyor</string>
<string name="add_peer"> (peer) ekle</string> <string name="add_peer">Eş ekle</string>
<string name="done">Tamam</string> <string name="done">Tamam</string>
<string name="interface_">Arayüz</string> <string name="interface_">Arayüz</string>
<string name="rotate_keys">Tuşları döndür</string> <string name="rotate_keys">Anahtarları döndür</string>
<string name="private_key">Özel anahtar</string> <string name="private_key">Özel anahtar</string>
<string name="copy_public_key">Genel anahtarı kopyala</string> <string name="copy_public_key">Genel anahtarı kopyala</string>
<string name="base64_key">Base64 anahtarı</string> <string name="base64_key">base64 anahtar</string>
<string name="comma_separated_list">Virgül ile ayrılmış liste ekleyin</string> <string name="comma_separated_list">virgülle ayrılmış liste</string>
<string name="listen_port">Bağlantı noktası</string> <string name="listen_port">Dinleme portu</string>
<string name="random">(Rastgele)</string> <string name="random">(rastgele)</string>
<string name="optional">(İsteğe bağlı)</string> <string name="optional">(isteğe bağlı)</string>
<string name="optional_no_recommend">(İsteğe bağlı, önerilmez)</string> <string name="optional_no_recommend">(isteğe bağlı, önerilmez)</string>
<string name="preshared_key">Ön paylaşımlı anahtar</string> <string name="preshared_key">Önceden paylaşılmış anahtar</string>
<string name="seconds">saniye</string> <string name="seconds">saniye</string>
<string name="persistent_keepalive">Kalıcı olarak canlı tutma</string> <string name="persistent_keepalive">Kalıcı canlı tutma</string>
<string name="cancel">İptal</string> <string name="cancel">İptal</string>
<string name="error_authentication_failed">Kimlik doğrulama başarısız oldu</string> <string name="error_authentication_failed">Kimlik doğrulama başarısız oldu</string>
<string name="error_authorization_failed">Yetkilendirilemedi</string> <string name="error_authorization_failed">Yetkilendirme başarısız oldu</string>
<string name="enabled_app_shortcuts">Uygulama kısayollarını etkinleştir</string> <string name="enabled_app_shortcuts">Uygulama kısayollarını etkinleştir</string>
<string name="export_configs">Yapılandırmaları dışa aktar</string> <string name="export_configs">Yapılandırmaları dışa aktar</string>
<string name="location_services_required">Gerekli konum hizmetleri</string> <string name="export_configs_failed">Yapılandırmaları dışa aktarma başarısız oldu</string>
<string name="location_services_required">Konum hizmetleri gerekli</string>
<string name="background_location_required">Arka plan konumu gerekli</string> <string name="background_location_required">Arka plan konumu gerekli</string>
<string name="precise_location_required">Kesin konum gerekli</string> <string name="precise_location_required">Hassas konum gerekli</string>
<string name="unknown_error">Bilinmeyen bir hata oluştu</string> <string name="unknown_error">Bilinmeyen bir hata oluştu</string>
<string name="exported_configs_message">Yapılandırmalar indirilenler\'e aktarıldı</string> <string name="exported_configs_message">Yapılandırmalar indirilenler klasörüne aktarıldı</string>
<string name="tunnel_on_wifi">Güvenilmeyen kablosuz internet bağlantısında tünel</string> <string name="tunnel_on_wifi">Güvenilmeyen wifi\'da tünel</string>
<string name="my_email" translatable="false">support@zaneschepke.com</string> <string name="my_email" translatable="false">support@zaneschepke.com</string>
<string name="email_subject">WG Tunnel Desteği</string> <string name="email_subject">WG Tunnel Desteği</string>
<string name="email_chooser">Bir e-posta gönderin</string> <string name="email_chooser">E-posta gönder…</string>
<string name="go">git</string> <string name="go">git</string>
<string name="docs_description">Belgeleri oku</string> <string name="docs_description">Belgeleri oku</string>
<string name="discord_description">Topluluğa katıl</string> <string name="discord_description">Topluluğa katıl</string>
<string name="email_description">Bana e-posta gönder</string> <string name="email_description">Bana e-posta gönder</string>
<string name="support_help_text">Sorun yaşıyorsanız, iyileştirme fikirleriniz varsa veya sadece etkileşimde bulunmak istiyorsanız, aşağıdaki kaynaklar mevcuttur:</string> <string name="support_help_text">Sorun yaşıyorsanız, iyileştirme fikirleriniz varsa veya sadece iletişime geçmek istiyorsanız, aşağıdaki kaynaklar mevcuttur:</string>
<string name="kernel">Çekirdek</string> <string name="use_kernel">Kernel modülünü kullan</string>
<string name="use_kernel">Çekirdek modülünü kullan</string> <string name="error_ssid_exists">SSID zaten mevcut</string>
<string name="error_ssid_exists">SSID zaten var</string> <string name="error_root_denied">Root kabuğu reddedildi</string>
<string name="error_root_denied">Kök kabuğu reddedildi</string> <string name="error_no_file_explorer">Dosya gezgini yüklü değil</string>
<string name="error_no_file_explorer">Yüklü dosya gezgini yok</string>
<string name="error_invalid_code">Geçersiz QR kodu</string> <string name="error_invalid_code">Geçersiz QR kodu</string>
<string name="error_none">Hata yok</string> <string name="error_none">Hata yok</string>
<string name="location_services_missing_message">Uygulama, cihazınızda etkinleştirilen herhangi bir konum hizmeti algılamıyor. Cihaza bağlı olarak bu, güvenilmeyen Wi-Fi özelliğinin Wi-Fi adını okuyamamasına neden olabilir. Yine de devam etmek ister misiniz?</string> <string name="location_services_missing_message">Uygulama, cihazınızda etkinleştirilmiş herhangi bir konum hizmeti algılamıyor. Cihaza bağlı olarak, bu durum güvenilmeyen wifi özelliğinin wifi adını okumasını engelleyebilir. Yine de devam etmek istiyor musunuz?</string>
<string name="auto_tunnel_title">Otomatik Tünel Hizmeti</string> <string name="auto_tunnel_title">Otomatik Tünel Hizmeti</string>
<string name="delete_tunnel">Tüneli sil</string> <string name="delete_tunnel">Tüneli sil</string>
<string name="delete_tunnel_message">Bu tüneli silmek istediğinizden emin misiniz?</string> <string name="delete_tunnel_message">Bu tüneli silmek istediğinizden emin misiniz?</string>
@@ -124,37 +123,58 @@
<string name="paused">duraklatıldı</string> <string name="paused">duraklatıldı</string>
<string name="active">aktif</string> <string name="active">aktif</string>
<string name="tunneling_apps">Tünellenen uygulamalar</string> <string name="tunneling_apps">Tünellenen uygulamalar</string>
<string name="included">dahil edildi</string> <string name="included">dahil</string>
<string name="excluded">hariç tutuldu</string> <string name="excluded">hariç</string>
<string name="all">tümü</string> <string name="all">tümü</string>
<string name="always_on_disabled">Her zaman açık VPN bir tünel başlatmaya çalıştı, ancak bu özellik ayarlarda devre dışı bırakıldı.</string> <string name="always_on_disabled">Her Zaman Açık VPN bir tüneli başlatmaya çalıştı, ancak bu özellik ayarlarda devre dışı bırakılmış.</string>
<string name="no_email_detected">E-posta uygulaması algılanmadı</string> <string name="no_email_detected">E-posta uygulaması algılanmadı</string>
<string name="no_browser_detected">Tarayıcı algılanmadı</string> <string name="no_browser_detected">Tarayıcı algılanmadı</string>
<string name="logs_saved">İndirilenlere kaydedilen günlükler</string> <string name="logs_saved">Günlükler indirilenler klasörüne kaydedildi</string>
<string name="open_issue">Bir sorun bildir</string> <string name="open_issue">Sorun bildir</string>
<string name="read_logs">Günlükleri oku</string> <string name="read_logs">Günlükleri oku</string>
<string name="auto">(Otomatik)</string> <string name="auto">(otomatik)</string>
<string name="config_parse_error">Yapılandırma kaydedilemedi</string> <string name="config_parse_error">Yapılandırma ayrıştırılamadı</string>
<string name="incorrect_pin">PIN kodu yanlış</string> <string name="incorrect_pin">PIN yanlış</string>
<string name="pin_created">Pin başarıyla oluşturuldu</string> <string name="pin_created">PIN başarıyla oluşturuldu</string>
<string name="enter_pin">PIN kodunuzu girin</string> <string name="enter_pin">PIN\'inizi girin</string>
<string name="create_pin">PIN kodu oluştur</string> <string name="create_pin">PIN oluştur</string>
<string name="enable_app_lock">Uygulama kilidini etkinleştir</string> <string name="enable_app_lock">Uygulama kilidini etkinleştir</string>
<string name="restart_on_ping">Ping başarısız olduğunda yeniden başlat (beta)</string> <string name="restart_on_ping">Ping başarısız olduğunda yeniden başlat (beta)</string>
<string name="mobile_data_tunnel">Mobil veri tüneli olarak ayarla</string> <string name="mobile_data_tunnel">Mobil veri tüneli olarak ayarla</string>
<string name="set_primary_tunnel">Birincil tünel olarak ayarla</string> <string name="set_primary_tunnel">Birincil tünel olarak ayarla</string>
<string name="use_tunnel_on_wifi_name">Wi-Fi adında tünel kullan</string> <string name="use_tunnel_on_wifi_name">Wifi adında tünel kullan</string>
<string name="no_wifi_names_configured">Bu tünel için yapılandırılmış Wi-Fi adı yok</string> <string name="no_wifi_names_configured">Bu tünel için yapılandırılmış wifi adı yok</string>
<string name="general">Genel</string> <string name="general">Genel</string>
<string name="edit_tunnel">Tüneli düzenle</string> <string name="edit_tunnel">Tüneli düzenle</string>
<string name="disabled">Devre dışı</string> <string name="disabled">devre dışı</string>
<string name="auto_on">Otomatik ayarlamayı sürdür</string> <string name="auto_on">Otomatik tüneli devam ettir</string>
<string name="auto_off">Otomatik ayarlamayı duraklat</string> <string name="auto_off">Otomatik tüneli duraklat</string>
<string name="auto_tun_on">Otomatik tüneli sürdür</string> <string name="auto_tun_on">Otomatik tüneli devam ettir</string>
<string name="auto_tun_off">Otomatik tüneli duraklat</string> <string name="auto_tun_off">Otomatik tüneli duraklat</string>
<string name="version">Sürüm</string> <string name="version">Sürüm</string>
<string name="mode">Mod</string> <string name="mode">Mod</string>
<string name="userspace">Kullanıcı alanı</string> <string name="userspace">Kullanıcı alanı</string>
<string name="settings">Ayarlar</string> <string name="settings">Ayarlar</string>
<string name="support">Destek</string> <string name="support">Destek</string>
<string name="backend">Arka uç</string>
<string name="kernel">Çekirdek</string>
<string name="use_amnezia">"Amnezia kullanıcı alanını kullan "</string>
<string name="junk_packet_count">Gereksiz paket sayısı</string>
<string name="junk_packet_minimum_size">Gereksiz paket minimum boyutu</string>
<string name="junk_packet_maximum_size">Gereksiz paket maksimum boyutu</string>
<string name="init_packet_junk_size">Başlatma paketi gereksiz boyutu</string>
<string name="response_packet_junk_size">Yanıt paketi gereksiz boyutu</string>
<string name="init_packet_magic_header">Başlatma paketi sihirli başlığı</string>
<string name="response_packet_magic_header">Yanıt paketi sihirli başlığı</string>
<string name="transport_packet_magic_header">Taşıma paketi sihirli başlığı</string>
<string name="underload_packet_magic_header">Düşük yük paketi sihirli başlığı</string>
<string name="telegram_url" translatable="false">https://t.me/wgtunnel</string>
<string name="unsure_how">nasıl devam edeceğinizden emin değilseniz</string>
<string name="see_the">Bakın:</string>
<string name="getting_started_url" translatable="false">https://zaneschepke.com/wgtunnel-docs/getting-started.html</string>
<string name="getting_started_guide">başlangıç kılavuzu</string>
<string name="amnezia" translatable="false">Amnezia</string>
<string name="wireguard" translatable="false">WireGuard</string>
<string name="error_file_format">Geçersiz tünel yapılandırma formatı</string>
<string name="restart_at_boot">Önyüklemede yeniden başlat</string>
</resources> </resources>
+169
View File
@@ -0,0 +1,169 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="comma_separated_list">список розділений комами</string>
<string name="no_tunnels">Тунелі ще не додані!</string>
<string name="app_name">WG Tunnel</string>
<string name="add_trusted_ssid">Додати ім\'я довіреної мережі Wi-Fi</string>
<string name="tunnels">Тунелі</string>
<string name="enable_auto_tunnel">Запустити авто-тунелі</string>
<string name="disable_auto_tunnel">Зупинити авто-тунелі</string>
<string name="okay">ОК</string>
<string name="tunnel_on_ethernet">Тунелювати Ethernet</string>
<string name="prominent_background_location_title">Фонова передача місцезнаходження</string>
<string name="trusted_ssid_value_description">Підтвердити SSID</string>
<string name="qr_scan">Сканувати QR</string>
<string name="tunnel_name">Ім\'я тунелю</string>
<string name="add_tunnel">Додати тунель</string>
<string name="include">Включити</string>
<string name="tunnel_all">Тунель для всіх додатків</string>
<string name="config_changes_saved">Зміни налаштувань збережено.</string>
<string name="icon">Іконка</string>
<string name="no_thanks">Ні, дякую</string>
<string name="default_vpn_off">Основний VPN вимк.</string>
<string name="turn_on_tunnel">Дія потребує активного тунелю</string>
<string name="rotate_keys">Оновити ключі</string>
<string name="private_key">Закритий ключ</string>
<string name="base64_key">Ключ в base64</string>
<string name="random">(випадково)</string>
<string name="optional">(необов\'язково)</string>
<string name="optional_no_recommend">(необов\'язково, не рекомендується)</string>
<string name="cancel">Скасувати</string>
<string name="export_configs_failed">Помилка експорту конфігурації</string>
<string name="location_services_required">Необхідно сервіси місцезнаходження</string>
<string name="precise_location_required">Необхідно доступ до точного місцезнаходження</string>
<string name="exported_configs_message">Експорт конфігурації в Завантаження</string>
<string name="email_chooser">Надіслати E-Mail…</string>
<string name="error_root_denied">Root доступ заборонено</string>
<string name="error_invalid_code">Некоректний QR-код</string>
<string name="error_none">Нема помилок</string>
<string name="logs_saved">Логи збережено в Завантаженнях</string>
<string name="config_parse_error">Помилка аналізу файлу конфігурації</string>
<string name="incorrect_pin">Невірний PIN-код</string>
<string name="use_tunnel_on_wifi_name">Використовувати тунель в мережі Wi-Fi</string>
<string name="disabled">відключено</string>
<string name="version">Версія</string>
<string name="mode">Режим</string>
<string name="transport_packet_magic_header">Заголовок транспортного пакету</string>
<string name="getting_started_guide">інструкція щодо початку роботи</string>
<string name="error_file_format">некоректний формат конфігурації тунелю</string>
<string name="watcher_notification_text_active">Моніторинг стану мережі: активний</string>
<string name="vpn_channel_name">Канал сповіщення VPN</string>
<string name="vpn_channel_id">Канал VPN</string>
<string name="error_file_extension">Файл не є .conf або .zip файлом</string>
<string name="turn_off_tunnel">Дія потребує вимкнення тунелю</string>
<string name="watcher_notification_text_paused">Моніторинг стану мережі: призупинено</string>
<string name="tunnel_start_text">Підключення до тунелю</string>
<string name="tunnel_start_title">VPN підключено</string>
<string name="notification_permission_required">Потрібен дозвіл на відображення сповіщень.</string>
<string name="tunnel_mobile_data">Тунелювати мобільні дані</string>
<string name="one_tunnel_required">Для використання даної функції потрібно налаштувати мінімум один тунель</string>
<string name="privacy_policy">Переглянути політику конфіденційності</string>
<string name="thank_you">Спасибі за використання WG Tunnel!</string>
<string name="prominent_background_location_message">Дана функція потребує фоновий доступ до служби місцезнаходження для моніторингу назви мереж Wi-Fi навіть коли додаток закрито. Для отримання додаткової інформації прочитайте політику приватності на екрані Підтримки.</string>
<string name="trusted_ssid_empty_description">Введіть SSID</string>
<string name="add_tunnels_text">Додати з файлу або архіву</string>
<string name="open_file">Відкрити файл</string>
<string name="exclude">Виключити</string>
<string name="add_from_qr">Додати з QR коду</string>
<string name="save_changes">Зберегти</string>
<string name="turn_on">Увімкнути</string>
<string name="map">Карта</string>
<string name="public_key">Публічний ключ</string>
<string name="addresses">Адреса</string>
<string name="allowed_ips">Дозволені IP</string>
<string name="dns_servers">DNS-сервери</string>
<string name="mtu">MTU</string>
<string name="peer">Пір</string>
<string name="endpoint">Кінцева точка</string>
<string name="hint_search_packages">Пошук програм</string>
<string name="name">Ім\'я</string>
<string name="vpn_connection_failed">Помилка з\'єднання</string>
<string name="restart">Перезапустити тунель</string>
<string name="always_on_vpn_support">Дозволили Always-ON VPN</string>
<string name="location_services_not_detected">Сервіси місце знаходження не знайдено</string>
<string name="db_name">wg-tunnel-db</string>
<string name="scanning_qr">Сканування QR коду</string>
<string name="attempt_connection">Спроба з\'єднання...</string>
<string name="other">Інше</string>
<string name="vpn_starting">Запуск VPN</string>
<string name="auto_tunneling">Авто-тунелювання</string>
<string name="none">Нема довірених мереж Wi-Fi</string>
<string name="vpn_on">VPN увімк.</string>
<string name="vpn_off">VPN вимк.</string>
<string name="default_vpn_on">Основний VPN увімк.</string>
<string name="create_import">Створити з нуля</string>
<string name="turn_off_auto">Необхідно вимкнути або призупинити авто-тунелювання</string>
<string name="add_peer">Додати peer</string>
<string name="done">Готово</string>
<string name="interface_">Інтерфейс</string>
<string name="copy_public_key">Копіювати відкритий ключ</string>
<string name="listen_port">Слухати порт</string>
<string name="preshared_key">Pre-shared key</string>
<string name="seconds">секунд</string>
<string name="persistent_keepalive">Persistent keepalive</string>
<string name="error_authorization_failed">Не вдалося авторизуватися</string>
<string name="enabled_app_shortcuts">Дозволити ярлики</string>
<string name="error_authentication_failed">Помилка автентифікації</string>
<string name="export_configs">Експорт конфігурації</string>
<string name="background_location_required">Необхідний фоновий доступ до місцезнаходження</string>
<string name="unknown_error">Невідома помилка</string>
<string name="tunnel_on_wifi">Тунелювати недовірені мережі Wi-Fi</string>
<string name="email_subject">Підтримка WG-Tunnel</string>
<string name="go">вперед</string>
<string name="docs_description">Переглянути документацію</string>
<string name="email_description">Відправити email автору</string>
<string name="discord_description">Приєднатися до спільноти</string>
<string name="support_help_text">Якщо у вас виникли проблеми, є ідеї щодо покращення, чи бажання долучитися, скористайтесь наступними ресурсами:</string>
<string name="use_kernel">Використовувати модуль режиму ядра</string>
<string name="error_ssid_exists">SSID вже існує</string>
<string name="error_no_file_explorer">Не знайдено файловий менеджер</string>
<string name="auto_tunnel_title">Сервіс авто-тунелювання</string>
<string name="delete_tunnel">Видалити тунель</string>
<string name="location_services_missing_message">Додаток не знайшов служб місце знаходження на вашому пристрої. На деяких пристроях це може привести до неможливості визначення назви мережі Wi-Fi і помилок функції недовірених Wi-Fi мереж. Все рівно хочете продовжити?</string>
<string name="included">включено</string>
<string name="delete_tunnel_message">Ви дійсно хочете видалити цей тунель?</string>
<string name="yes">Так</string>
<string name="active">активно</string>
<string name="resume">Відновити</string>
<string name="pause">Призупинити</string>
<string name="paused">призупинено</string>
<string name="tunneling_apps">Тунельовані додатки</string>
<string name="excluded">виключено</string>
<string name="always_on_disabled">Функція Always-on VPN спробувала запустити тунель, але функція вимкнена в налаштуваннях.</string>
<string name="auto">(авто)</string>
<string name="all">всі</string>
<string name="no_email_detected">Програми для надсилання email не знайдено</string>
<string name="open_issue">Повідомити про проблему</string>
<string name="read_logs">Переглянути логи</string>
<string name="no_browser_detected">Веб браузер не знайдено</string>
<string name="pin_created">PIN-код створено успішно</string>
<string name="enter_pin">Введіть PIN-код</string>
<string name="create_pin">Створити PINhкод</string>
<string name="enable_app_lock">Увімкнути блокування додатку</string>
<string name="edit_tunnel">Редагувати тунель</string>
<string name="auto_on">Відновити авто-тунель</string>
<string name="restart_on_ping">Перезапуск при помилці ping (бета)</string>
<string name="mobile_data_tunnel">Встановити як тунель для мобільних даних</string>
<string name="set_primary_tunnel">Встановити як основний тунель</string>
<string name="no_wifi_names_configured">Імена мереж Wi-Fi не налаштовано для цього тунелю</string>
<string name="general">Загальне</string>
<string name="auto_tun_off">Призупинити авто-тунель</string>
<string name="auto_off">Призупинити авто-тунель</string>
<string name="auto_tun_on">Відновити авто-тунель</string>
<string name="userspace">Користувача</string>
<string name="support">Підтримка</string>
<string name="settings">Налаштування</string>
<string name="use_amnezia">"Використовувати модуль Amnezia режиму користувача "</string>
<string name="backend">Модуль</string>
<string name="kernel">Модуль ядра</string>
<string name="junk_packet_count">Кількість «сміттєвих» пакетів</string>
<string name="junk_packet_minimum_size">Мінімальний розмір «сміттєвого» пакету</string>
<string name="junk_packet_maximum_size">Максимальний розмір «сміттєвого» пакету</string>
<string name="init_packet_junk_size">Початковий розмір «сміттєвого» пакету</string>
<string name="response_packet_junk_size">Розмір відповіді «сміттєвого» пакету</string>
<string name="init_packet_magic_header">Заголовок пакету ініціалізації</string>
<string name="underload_packet_magic_header">Заголовок пакету під навантаженням</string>
<string name="response_packet_magic_header">Заголовок пакету відповіді</string>
<string name="unsure_how">, якщо не впевнені що робити далі</string>
<string name="see_the">Дивіться</string>
</resources>
+4
View File
@@ -176,4 +176,8 @@
<string name="amnezia" translatable="false">Amnezia</string> <string name="amnezia" translatable="false">Amnezia</string>
<string name="wireguard" translatable="false">WireGuard</string> <string name="wireguard" translatable="false">WireGuard</string>
<string name="error_file_format">Invalid tunnel config format</string> <string name="error_file_format">Invalid tunnel config format</string>
<string name="restart_at_boot">Restart on boot</string>
<string name="vpn_denied_dialog_title">Permission Denied</string>
<string name="vpn_denied_dialog_message">Permission to start the VPN has either been explicitly denied or is being blocked by the system.</string>
<string name="vpn_denied_dialog_message2">If VPN permission is being blocked by the system, please confirm no other app is using the Always-on VPN feature and try again.</string>
</resources> </resources>
+8
View File
@@ -4,4 +4,12 @@
<style name="Theme.WireguardAutoTunnel" parent="@style/Theme.AppCompat.NoActionBar"> <style name="Theme.WireguardAutoTunnel" parent="@style/Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@color/black_background</item> <item name="android:windowBackground">@color/black_background</item>
</style> </style>
<style name="Theme.AppSplashScreen" parent="Theme.SplashScreen">
<!--<item name="windowSplashScreenBackground">@color/white</item>-->
<!-- icon has to be a circle -->
<item name="windowSplashScreenAnimatedIcon">@mipmap/ic_launcher</item>
<item name="windowSplashScreenAnimationDuration">500</item>
<item name="postSplashScreenTheme">@style/Theme.WireguardAutoTunnel</item>
</style>
</resources> </resources>
+17
View File
@@ -5,4 +5,21 @@ plugins {
alias(libs.plugins.kotlinxSerialization) apply false alias(libs.plugins.kotlinxSerialization) apply false
alias(libs.plugins.ksp) apply false alias(libs.plugins.ksp) apply false
alias(libs.plugins.androidLibrary) apply false alias(libs.plugins.androidLibrary) apply false
alias(libs.plugins.compose.compiler) apply false
alias(libs.plugins.ktlint)
}
subprojects {
apply {
plugin(rootProject.libs.plugins.ktlint.get().pluginId)
}
ktlint {
debug.set(false)
verbose.set(true)
android.set(true)
outputToConsole.set(true)
ignoreFailures.set(false)
enableExperimentalRules.set(true)
}
} }
-47
View File
@@ -1,47 +0,0 @@
import org.gradle.api.invocation.Gradle
import java.io.File
object BuildHelper {
private fun getCurrentFlavor(gradle: Gradle): String {
val taskRequestsStr = gradle.startParameter.taskRequests.toString()
val pattern: java.util.regex.Pattern =
if (taskRequestsStr.contains("assemble")) {
java.util.regex.Pattern.compile("assemble(\\w+)(Release|Debug)")
} else {
java.util.regex.Pattern.compile("bundle(\\w+)(Release|Debug)")
}
val matcher = pattern.matcher(taskRequestsStr)
val flavor =
if (matcher.find()) {
matcher.group(1).lowercase()
} else {
print("NO FLAVOR FOUND")
""
}
return flavor
}
fun getLocalProperty(key: String, file: String = "local.properties"): String? {
val properties = java.util.Properties()
val localProperties = File(file)
if (localProperties.isFile) {
java.io.InputStreamReader(java.io.FileInputStream(localProperties), Charsets.UTF_8)
.use { reader ->
properties.load(reader)
}
} else return null
return properties.getProperty(key)
}
fun isGeneralFlavor(gradle: Gradle): Boolean {
return getCurrentFlavor(gradle) == "general"
}
fun isReleaseBuild(gradle: Gradle): Boolean {
return (gradle.startParameter.taskNames.size > 0 &&
gradle.startParameter.taskNames[0].contains(
"Release",
))
}
}
+8 -4
View File
@@ -1,13 +1,11 @@
object Constants { object Constants {
const val VERSION_NAME = "3.4.6" const val VERSION_NAME = "3.4.8"
const val JVM_TARGET = "17" const val JVM_TARGET = "17"
const val VERSION_CODE = 34600 const val VERSION_CODE = 34800
const val TARGET_SDK = 34 const val TARGET_SDK = 34
const val MIN_SDK = 26 const val MIN_SDK = 26
const val APP_ID = "com.zaneschepke.wireguardautotunnel" const val APP_ID = "com.zaneschepke.wireguardautotunnel"
const val APP_NAME = "wgtunnel" const val APP_NAME = "wgtunnel"
const val COMPOSE_COMPILER_EXTENSION_VERSION = "1.5.14"
const val STORE_PASS_VAR = "SIGNING_STORE_PASSWORD" const val STORE_PASS_VAR = "SIGNING_STORE_PASSWORD"
const val KEY_ALIAS_VAR = "SIGNING_KEY_ALIAS" const val KEY_ALIAS_VAR = "SIGNING_KEY_ALIAS"
@@ -15,5 +13,11 @@ object Constants {
const val KEY_STORE_PATH_VAR = "KEY_STORE_PATH" const val KEY_STORE_PATH_VAR = "KEY_STORE_PATH"
const val RELEASE = "release" const val RELEASE = "release"
const val NIGHTLY = "nightly"
const val PRERELEASE = "prerelease"
const val DEBUG = "debug"
const val TYPE = "type" const val TYPE = "type"
const val NIGHTLY_CODE = 42
const val PRERELEASE_CODE = 99
} }
+78
View File
@@ -0,0 +1,78 @@
import org.gradle.api.Project
import org.gradle.api.invocation.Gradle
import java.io.File
import java.util.Properties
fun Project.getCurrentFlavor(): String {
val taskRequestsStr = gradle.startParameter.taskRequests.toString()
val pattern: java.util.regex.Pattern =
if (taskRequestsStr.contains(":app:assemble")) {
java.util.regex.Pattern.compile(":app:assemble(\\w+)(Release|Debug)")
} else {
java.util.regex.Pattern.compile(":app:bundle(\\w+)(Release|Debug)")
}
val matcher = pattern.matcher(taskRequestsStr)
val flavor =
if (matcher.find()) {
matcher.group(1).lowercase()
} else {
print("NO FLAVOR FOUND")
""
}
return flavor
}
fun Project.getBuildTaskName(): String {
val taskRequestsStr = gradle.startParameter.taskRequests[0].toString()
return taskRequestsStr.also {
project.logger.lifecycle("Build task: $it")
}
}
fun getLocalProperty(key: String, file: String = "local.properties"): String? {
val properties = Properties()
val localProperties = File(file)
if (localProperties.isFile) {
java.io.InputStreamReader(java.io.FileInputStream(localProperties), Charsets.UTF_8)
.use { reader ->
properties.load(reader)
}
} else return null
return properties.getProperty(key)
}
fun Project.getSigningProperties(): Properties {
return Properties().apply {
// created local file for signing details
try {
load(file("signing.properties").reader())
} catch (_: Exception) {
load(file("signing_template.properties").reader())
}
}
}
fun Project.getStoreFile(): File {
return file(
System.getenv()
.getOrDefault(
Constants.KEY_STORE_PATH_VAR,
getSigningProperties().getProperty(Constants.KEY_STORE_PATH_VAR),
),
)
}
fun Project.getSigningProperty(property: String): String {
// try to get secrets from env first for pipeline build, then properties file for local
return System.getenv()
.getOrDefault(
property,
getSigningProperties().getProperty(property),
)
}
@@ -1,5 +1,5 @@
Verbesserungen: Verbesserungen:
- Unterstützung für Tunnelung nur bei Verwendung von Mobilen Daten - Unterstützung für Auto-Tunneln nur bei Verwendung von Mobilen Daten
- Verbesserungen der Support Oberfläche - Verbesserungen der Support Oberfläche
- Aktualisierung der Ressourcenlinks - Aktualisierung der Ressourcenlinks
- Verschiedene andere Fehlerbehebungen - Verschiedene andere Fehlerbehebungen
@@ -0,0 +1,5 @@
Was ist neu?
- Zusätzliche Sprachunterstützung
- Fehler beim automatischen Tunneln von mobilen Daten behoben
- AndroidTV-Schaltfläche für schwebende Aktionen behoben
- Weitere Optimierungen und Erweiterungen
@@ -0,0 +1,4 @@
Was ist neu?
- Behebt Auto-Tunneling-Fehler
- Behebt Android-Backup-Fehler
- Versionen erhöhen
@@ -0,0 +1,6 @@
What's new:
- Fix crashing issues
- Improve tile performance
- Re-enable pin lock
- Make restart on boot a setting
- Various performance and bug fixes

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