mirror of
https://github.com/wgtunnel/android.git
synced 2026-06-02 08:33:40 +02:00
Compare commits
68 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fb33b8996f | |||
| ec3a5dcd65 | |||
| 7b443add3a | |||
| d70ef658e2 | |||
| c01b045022 | |||
| d3ea75869a | |||
| 0784c96011 | |||
| 553279ea76 | |||
| 89f6dec357 | |||
| ab7499a616 | |||
| 105c753c66 | |||
| d9f0de2dd4 | |||
| 82280091ad | |||
| b97b7cf989 | |||
| f83e40f6cc | |||
| 1fab9dfdf2 | |||
| a670931b06 | |||
| 2c0c88baf2 | |||
| 05e7cb7c04 | |||
| bc811f74ef | |||
| 09b669f54b | |||
| f08d73cbb7 | |||
| 7ca23d3ef5 | |||
| 7fdd95ea51 | |||
| e11f0f794a | |||
| fea31437cd | |||
| 1306fdc8b2 | |||
| d2e5d6d3bc | |||
| 960af02beb | |||
| 3f1ff22488 | |||
| d6b032845b | |||
| ffad6b331f | |||
| 1fb953e2fe | |||
| 893a03d3b1 | |||
| 30b577a03d | |||
| 47f619ff07 | |||
| 791b532d85 | |||
| 57d096ebb1 | |||
| cfb4f85ded | |||
| d330fa4c28 | |||
| a362327fa3 | |||
| 9c72390398 | |||
| d1d59aaf5c | |||
| 03fdb82c24 | |||
| 4355e2e9ce | |||
| d7b4fbecb9 | |||
| 7fee0b3768 | |||
| bd76ee5392 | |||
| 911ed140e0 | |||
| a9d7648425 | |||
| 230f505806 | |||
| e58dad00ea | |||
| 8ddf5cf537 | |||
| d86fa782cc | |||
| fe7b9072d6 | |||
| 9895ed1061 | |||
| 34066ea182 | |||
| b99b116fdb | |||
| 9d42e7299b | |||
| b782cdeb35 | |||
| e40515c138 | |||
| d62df80682 | |||
| 71284b5a9c | |||
| 0a730b7a1a | |||
| 753d7eb22a | |||
| 6e961e0994 | |||
| 6bea44269f | |||
| b2a2b9fcf4 |
+2
-1
@@ -1,2 +1,3 @@
|
||||
ko_fi: zaneschepke
|
||||
liberapay: zaneschepke
|
||||
liberapay: zaneschepke
|
||||
github: zaneschepke
|
||||
|
||||
@@ -15,6 +15,7 @@ A clear and concise description of what the bug is.
|
||||
- Device: [e.g. Pixel 4a]
|
||||
- Android Version: [e.g. Android 13]
|
||||
- App Version [e.g. 3.3.3]
|
||||
- Backend: [e.g. Kernel, Userspace]
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Issue Updates Workflow
|
||||
name: on-issue
|
||||
|
||||
on:
|
||||
issues:
|
||||
@@ -7,8 +7,8 @@ on:
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
name: Build
|
||||
on-issue:
|
||||
name: On new issue
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Send Telegram Message
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Release Updates Workflow
|
||||
name: on-publish
|
||||
|
||||
on:
|
||||
release:
|
||||
@@ -7,8 +7,8 @@ on:
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
name: Build
|
||||
on-publish:
|
||||
name: On publish
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Send Telegram Message
|
||||
@@ -2,7 +2,7 @@ name: release-android
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "4 3 * * *"
|
||||
- cron: "4 3 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
track:
|
||||
@@ -14,7 +14,7 @@ on:
|
||||
- alpha
|
||||
- beta
|
||||
- production
|
||||
default: alpha
|
||||
default: none
|
||||
required: true
|
||||
release_type:
|
||||
type: choice
|
||||
@@ -30,13 +30,34 @@ on:
|
||||
description: "Tag name for release"
|
||||
required: false
|
||||
default: nightly
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build Signed APK
|
||||
if: ${{ inputs.release_type != 'none' }}
|
||||
check_commits:
|
||||
name: Check for New Commits
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
has_new_commits: ${{ steps.check.outputs.new_commits }}
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0 # This fetches all history so we can check commits
|
||||
|
||||
- name: Check for new commits
|
||||
id: check
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
# This script checks for commits newer than 23 hours ago
|
||||
NEW_COMMITS=$(git rev-list --count --after="$(date -Iseconds -d '23 hours ago')" ${{ github.sha }})
|
||||
echo "new_commits=$NEW_COMMITS" >> $GITHUB_OUTPUT
|
||||
build:
|
||||
needs: check_commits
|
||||
if: ${{ needs.check_commits.outputs.has_new_commits > 0 && inputs.release_type != 'none' }}
|
||||
name: Build Signed APK
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
|
||||
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
|
||||
@@ -110,9 +131,24 @@ jobs:
|
||||
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
|
||||
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
|
||||
|
||||
- name: Commit and push versionCode changes
|
||||
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' || inputs.release_type == 'prerelease' }}
|
||||
run: |
|
||||
git config --global user.name 'GitHub Actions'
|
||||
git config --global user.email 'actions@github.com'
|
||||
git add versionCode.txt
|
||||
git commit -m "Automated build update"
|
||||
|
||||
- name: Push changes
|
||||
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' || inputs.release_type == 'prerelease' }}
|
||||
uses: ad-m/github-push-action@master
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
branch: ${{ github.ref }}
|
||||
|
||||
# Save the APK after the Build job is complete to publish it as a Github release in the next job
|
||||
- name: Upload APK
|
||||
uses: actions/upload-artifact@v4.3.6
|
||||
uses: actions/upload-artifact@v4.4.3
|
||||
with:
|
||||
name: wgtunnel
|
||||
path: ${{ env.APK_PATH }}
|
||||
@@ -149,6 +185,7 @@ jobs:
|
||||
run: |
|
||||
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
|
||||
gh release delete nightly --yes || true
|
||||
git push origin :nightly || true
|
||||
|
||||
- name: On prerelease release notes
|
||||
if: ${{ inputs.release_type == 'prerelease' }}
|
||||
|
||||
+39
-15
@@ -8,6 +8,21 @@ plugins {
|
||||
alias(libs.plugins.grgit)
|
||||
}
|
||||
|
||||
val versionFile = file("$rootDir/versionCode.txt")
|
||||
|
||||
val versionCodeIncrement = with(getBuildTaskName().lowercase()) {
|
||||
when {
|
||||
this.contains(Constants.NIGHTLY) || this.contains(Constants.PRERELEASE) -> {
|
||||
if (versionFile.exists()) {
|
||||
versionFile.readText().toInt() + 1
|
||||
} else {
|
||||
1
|
||||
}
|
||||
}
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = Constants.APP_ID
|
||||
compileSdk = Constants.TARGET_SDK
|
||||
@@ -20,7 +35,7 @@ android {
|
||||
applicationId = Constants.APP_ID
|
||||
minSdk = Constants.MIN_SDK
|
||||
targetSdk = Constants.TARGET_SDK
|
||||
versionCode = determineVersionCode()
|
||||
versionCode = Constants.VERSION_CODE + versionCodeIncrement
|
||||
versionName = determineVersionName()
|
||||
|
||||
ksp { arg("room.schemaLocation", "$projectDir/schemas") }
|
||||
@@ -29,6 +44,8 @@ android {
|
||||
getByName("debug").assets.srcDirs(files("$projectDir/schemas")) // Room
|
||||
}
|
||||
|
||||
buildConfigField("String[]", "LANGUAGES", "new String[]{ ${languageList().joinToString(separator = ", ") { "\"$it\"" }} }")
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables { useSupportLibrary = true }
|
||||
}
|
||||
@@ -57,12 +74,14 @@ android {
|
||||
"proguard-rules.pro",
|
||||
)
|
||||
signingConfig = signingConfigs.getByName(Constants.RELEASE)
|
||||
resValue("string", "provider", "\"${Constants.APP_NAME}.provider\"")
|
||||
}
|
||||
debug {
|
||||
applicationIdSuffix = ".debug"
|
||||
versionNameSuffix = "-debug"
|
||||
resValue("string", "app_name", "WG Tunnel - Debug")
|
||||
isDebuggable = true
|
||||
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.debug\"")
|
||||
}
|
||||
|
||||
create(Constants.PRERELEASE) {
|
||||
@@ -70,6 +89,7 @@ android {
|
||||
applicationIdSuffix = ".prerelease"
|
||||
versionNameSuffix = "-pre"
|
||||
resValue("string", "app_name", "WG Tunnel - Pre")
|
||||
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.pre\"")
|
||||
}
|
||||
|
||||
create(Constants.NIGHTLY) {
|
||||
@@ -77,6 +97,7 @@ android {
|
||||
applicationIdSuffix = ".nightly"
|
||||
versionNameSuffix = "-nightly"
|
||||
resValue("string", "app_name", "WG Tunnel - Nightly")
|
||||
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.nightly\"")
|
||||
}
|
||||
|
||||
applicationVariants.all {
|
||||
@@ -114,8 +135,6 @@ android {
|
||||
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
|
||||
}
|
||||
|
||||
val generalImplementation by configurations
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation(project(":logcatter"))
|
||||
@@ -132,6 +151,7 @@ dependencies {
|
||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||
implementation(libs.androidx.material3)
|
||||
implementation(libs.androidx.appcompat)
|
||||
implementation(libs.material)
|
||||
|
||||
// test
|
||||
testImplementation(libs.junit)
|
||||
@@ -157,8 +177,6 @@ dependencies {
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
implementation(libs.androidx.hilt.navigation.compose)
|
||||
|
||||
implementation(libs.zaneschepke.multifab)
|
||||
|
||||
// hilt
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.android.compiler)
|
||||
@@ -199,16 +217,6 @@ dependencies {
|
||||
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 {
|
||||
@@ -219,3 +227,19 @@ fun determineVersionName(): String {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val incrementVersionCode by tasks.registering {
|
||||
doLast {
|
||||
val versionFile = file("$rootDir/versionCode.txt")
|
||||
if (versionFile.exists()) {
|
||||
versionFile.writeText(versionCodeIncrement.toString())
|
||||
println("Incremented versionCode to $versionCodeIncrement")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.whenTaskAdded {
|
||||
if (name.startsWith("assemble") && !name.lowercase().contains("debug")) {
|
||||
dependsOn(incrementVersionCode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 10,
|
||||
"identityHash": "c8621055524f90b4d1972f6171f59e80",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "Settings",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_auto_tunnel_paused` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAutoTunnelEnabled",
|
||||
"columnName": "is_tunnel_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isTunnelOnMobileDataEnabled",
|
||||
"columnName": "is_tunnel_on_mobile_data_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "trustedNetworkSSIDs",
|
||||
"columnName": "trusted_network_ssids",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAlwaysOnVpnEnabled",
|
||||
"columnName": "is_always_on_vpn_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isTunnelOnEthernetEnabled",
|
||||
"columnName": "is_tunnel_on_ethernet_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isShortcutsEnabled",
|
||||
"columnName": "is_shortcuts_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isTunnelOnWifiEnabled",
|
||||
"columnName": "is_tunnel_on_wifi_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isKernelEnabled",
|
||||
"columnName": "is_kernel_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isRestoreOnBootEnabled",
|
||||
"columnName": "is_restore_on_boot_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isMultiTunnelEnabled",
|
||||
"columnName": "is_multi_tunnel_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAutoTunnelPaused",
|
||||
"columnName": "is_auto_tunnel_paused",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPingEnabled",
|
||||
"columnName": "is_ping_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAmneziaEnabled",
|
||||
"columnName": "is_amnezia_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "TunnelConfig",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '', `is_Active` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `ping_interval` INTEGER DEFAULT null, `ping_cooldown` INTEGER DEFAULT null, `ping_ip` TEXT DEFAULT null)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wgQuick",
|
||||
"columnName": "wg_quick",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "tunnelNetworks",
|
||||
"columnName": "tunnel_networks",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true,
|
||||
"defaultValue": "''"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isMobileDataTunnel",
|
||||
"columnName": "is_mobile_data_tunnel",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPrimaryTunnel",
|
||||
"columnName": "is_primary_tunnel",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "amQuick",
|
||||
"columnName": "am_quick",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true,
|
||||
"defaultValue": "''"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isActive",
|
||||
"columnName": "is_Active",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPingEnabled",
|
||||
"columnName": "is_ping_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pingInterval",
|
||||
"columnName": "ping_interval",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false,
|
||||
"defaultValue": "null"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pingCooldown",
|
||||
"columnName": "ping_cooldown",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false,
|
||||
"defaultValue": "null"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pingIp",
|
||||
"columnName": "ping_ip",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false,
|
||||
"defaultValue": "null"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_TunnelConfig_name",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"name"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
}
|
||||
],
|
||||
"views": [],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'c8621055524f90b4d1972f6171f59e80')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 11,
|
||||
"identityHash": "4c9418386f72dfac5d28ab96c1e5ea0b",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "Settings",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_wifi_by_shell_enabled` INTEGER NOT NULL DEFAULT false)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAutoTunnelEnabled",
|
||||
"columnName": "is_tunnel_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isTunnelOnMobileDataEnabled",
|
||||
"columnName": "is_tunnel_on_mobile_data_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "trustedNetworkSSIDs",
|
||||
"columnName": "trusted_network_ssids",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAlwaysOnVpnEnabled",
|
||||
"columnName": "is_always_on_vpn_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isTunnelOnEthernetEnabled",
|
||||
"columnName": "is_tunnel_on_ethernet_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isShortcutsEnabled",
|
||||
"columnName": "is_shortcuts_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isTunnelOnWifiEnabled",
|
||||
"columnName": "is_tunnel_on_wifi_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isKernelEnabled",
|
||||
"columnName": "is_kernel_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isRestoreOnBootEnabled",
|
||||
"columnName": "is_restore_on_boot_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isMultiTunnelEnabled",
|
||||
"columnName": "is_multi_tunnel_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPingEnabled",
|
||||
"columnName": "is_ping_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAmneziaEnabled",
|
||||
"columnName": "is_amnezia_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isWildcardsEnabled",
|
||||
"columnName": "is_wildcards_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isWifiNameByShellEnabled",
|
||||
"columnName": "is_wifi_by_shell_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "TunnelConfig",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '', `is_Active` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `ping_interval` INTEGER DEFAULT null, `ping_cooldown` INTEGER DEFAULT null, `ping_ip` TEXT DEFAULT null)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wgQuick",
|
||||
"columnName": "wg_quick",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "tunnelNetworks",
|
||||
"columnName": "tunnel_networks",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true,
|
||||
"defaultValue": "''"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isMobileDataTunnel",
|
||||
"columnName": "is_mobile_data_tunnel",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPrimaryTunnel",
|
||||
"columnName": "is_primary_tunnel",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "amQuick",
|
||||
"columnName": "am_quick",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true,
|
||||
"defaultValue": "''"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isActive",
|
||||
"columnName": "is_Active",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPingEnabled",
|
||||
"columnName": "is_ping_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pingInterval",
|
||||
"columnName": "ping_interval",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false,
|
||||
"defaultValue": "null"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pingCooldown",
|
||||
"columnName": "ping_cooldown",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false,
|
||||
"defaultValue": "null"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pingIp",
|
||||
"columnName": "ping_ip",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false,
|
||||
"defaultValue": "null"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_TunnelConfig_name",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"name"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
}
|
||||
],
|
||||
"views": [],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '4c9418386f72dfac5d28ab96c1e5ea0b')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -3,17 +3,7 @@
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32" />
|
||||
<uses-permission
|
||||
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32"
|
||||
tools:ignore="ScopedStorage" />
|
||||
<uses-permission
|
||||
android:name="android.permission.ACCESS_WIFI_STATE"
|
||||
android:maxSdkVersion="30"
|
||||
tools:ignore="LeanbackUsesWifi" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
@@ -22,7 +12,8 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
|
||||
<!--foreground service exempt android 14-->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
|
||||
<!--foreground service permissions-->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
@@ -49,6 +40,12 @@
|
||||
<uses-feature
|
||||
android:name="android.hardware.screen.portrait"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.hardware.gamepad"
|
||||
android:required="false"/>
|
||||
|
||||
<uses-feature android:name="android.hardware.wifi"
|
||||
android:required="false"/>
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
@@ -66,12 +63,12 @@
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.AppSplashScreen"
|
||||
android:theme="@style/Theme.App.Start"
|
||||
tools:targetApi="tiramisu">
|
||||
<activity
|
||||
android:name=".ui.SplashActivity"
|
||||
android:name=".ui.MainActivity"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.AppSplashScreen">
|
||||
android:theme="@style/Theme.WireguardAutoTunnel">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
@@ -83,11 +80,6 @@
|
||||
android:name="android.app.shortcuts"
|
||||
android:resource="@xml/shortcuts" />
|
||||
</activity>
|
||||
<activity
|
||||
android:name=".ui.MainActivity"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.WireguardAutoTunnel">
|
||||
</activity>
|
||||
<activity
|
||||
android:name="com.journeyapps.barcodescanner.CaptureActivity"
|
||||
android:screenOrientation="portrait"
|
||||
@@ -103,12 +95,16 @@
|
||||
android:launchMode="singleInstance"
|
||||
android:theme="@android:style/Theme.NoDisplay" />
|
||||
|
||||
<service
|
||||
android:name=".service.foreground.ForegroundService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="systemExempted"
|
||||
tools:node="merge" />
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="@string/provider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
|
||||
<service
|
||||
android:name=".service.tile.TunnelControlTile"
|
||||
android:exported="true"
|
||||
@@ -170,6 +166,7 @@
|
||||
<service
|
||||
android:name=".service.foreground.TunnelBackgroundService"
|
||||
android:exported="false"
|
||||
android:persistent="true"
|
||||
android:foregroundServiceType="systemExempted"
|
||||
android:permission="android.permission.BIND_VPN_SERVICE">
|
||||
<intent-filter>
|
||||
@@ -190,10 +187,6 @@
|
||||
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".receiver.BackgroundActionReceiver"
|
||||
android:enabled="true"
|
||||
android:exported="false"/>
|
||||
<receiver
|
||||
android:name=".receiver.AppUpdateReceiver"
|
||||
android:exported="false">
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package com.zaneschepke.wireguardautotunnel
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.os.StrictMode
|
||||
import android.os.StrictMode.ThreadPolicy
|
||||
import com.zaneschepke.logcatter.LocalLogCollector
|
||||
import com.zaneschepke.logcatter.LogReader
|
||||
import com.zaneschepke.wireguardautotunnel.data.datastore.LocaleStorage
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
@@ -18,12 +21,16 @@ import javax.inject.Inject
|
||||
@HiltAndroidApp
|
||||
class WireGuardAutoTunnel : Application() {
|
||||
|
||||
val localeStorage: LocaleStorage by lazy {
|
||||
LocaleStorage(this)
|
||||
}
|
||||
|
||||
@Inject
|
||||
@ApplicationScope
|
||||
lateinit var applicationScope: CoroutineScope
|
||||
|
||||
@Inject
|
||||
lateinit var localLogCollector: LocalLogCollector
|
||||
lateinit var logReader: LogReader
|
||||
|
||||
@Inject
|
||||
@IoDispatcher
|
||||
@@ -47,11 +54,15 @@ class WireGuardAutoTunnel : Application() {
|
||||
}
|
||||
if (!isRunningOnTv()) {
|
||||
applicationScope.launch(ioDispatcher) {
|
||||
localLogCollector.start()
|
||||
logReader.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun attachBaseContext(base: Context) {
|
||||
super.attachBaseContext(LocaleUtil.getLocalizedContext(base, LocaleStorage(base).getPreferredLocale()))
|
||||
}
|
||||
|
||||
companion object {
|
||||
lateinit var instance: WireGuardAutoTunnel
|
||||
private set
|
||||
|
||||
@@ -11,7 +11,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
|
||||
@Database(
|
||||
entities = [Settings::class, TunnelConfig::class],
|
||||
version = 9,
|
||||
version = 11,
|
||||
autoMigrations =
|
||||
[
|
||||
AutoMigration(from = 1, to = 2),
|
||||
@@ -35,6 +35,12 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
),
|
||||
AutoMigration(7, 8),
|
||||
AutoMigration(8, 9),
|
||||
AutoMigration(9, 10),
|
||||
AutoMigration(
|
||||
from = 10,
|
||||
to = 11,
|
||||
spec = RemoveTunnelPauseMigration::class,
|
||||
),
|
||||
],
|
||||
exportSchema = true,
|
||||
)
|
||||
@@ -54,3 +60,9 @@ abstract class AppDatabase : RoomDatabase() {
|
||||
columnName = "is_battery_saver_enabled",
|
||||
)
|
||||
class RemoveLegacySettingColumnsMigration : AutoMigrationSpec
|
||||
|
||||
@DeleteColumn(
|
||||
tableName = "Settings",
|
||||
columnName = "is_auto_tunnel_paused",
|
||||
)
|
||||
class RemoveTunnelPauseMigration : AutoMigrationSpec
|
||||
|
||||
+18
-6
@@ -4,7 +4,6 @@ import android.content.Context
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
@@ -22,11 +21,12 @@ class DataStoreManager(
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
) {
|
||||
companion object {
|
||||
val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
|
||||
val BATTERY_OPTIMIZE_DISABLE_SHOWN = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
||||
val LAST_ACTIVE_TUNNEL = intPreferencesKey("LAST_ACTIVE_TUNNEL")
|
||||
val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
|
||||
val IS_PIN_LOCK_ENABLED = booleanPreferencesKey("PIN_LOCK_ENABLED")
|
||||
val locationDisclosureShown = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
|
||||
val batteryDisableShown = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
||||
val currentSSID = stringPreferencesKey("CURRENT_SSID")
|
||||
val pinLockEnabled = booleanPreferencesKey("PIN_LOCK_ENABLED")
|
||||
val tunnelStatsExpanded = booleanPreferencesKey("TUNNEL_STATS_EXPANDED")
|
||||
val theme = stringPreferencesKey("THEME")
|
||||
}
|
||||
|
||||
// preferences
|
||||
@@ -58,6 +58,18 @@ class DataStoreManager(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun <T> removeFromDataStore(key: Preferences.Key<T>) {
|
||||
withContext(ioDispatcher) {
|
||||
try {
|
||||
context.dataStore.edit { it.remove(key) }
|
||||
} catch (e: IOException) {
|
||||
Timber.e(e)
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> getFromStoreFlow(key: Preferences.Key<T>) = context.dataStore.data.map { it[key] }
|
||||
|
||||
suspend fun <T> getFromStore(key: Preferences.Key<T>): T? {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.zaneschepke.wireguardautotunnel.data.datastore
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||
|
||||
class LocaleStorage(context: Context) {
|
||||
private var preferences: SharedPreferences = context.getSharedPreferences("sp", Context.MODE_PRIVATE)
|
||||
|
||||
fun getPreferredLocale(): String {
|
||||
return preferences.getString("preferred_locale", LocaleUtil.OPTION_PHONE_LANGUAGE)!!
|
||||
}
|
||||
|
||||
fun setPreferredLocale(localeCode: String) {
|
||||
preferences.edit().putString("preferred_locale", localeCode).apply()
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
package com.zaneschepke.wireguardautotunnel.data.domain
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
|
||||
data class GeneralState(
|
||||
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
||||
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
||||
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
|
||||
val lastActiveTunnelId: Int? = null,
|
||||
val isTunnelStatsExpanded: Boolean = IS_TUNNEL_STATS_EXPANDED,
|
||||
val theme: Theme = Theme.AUTOMATIC,
|
||||
) {
|
||||
companion object {
|
||||
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
|
||||
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
|
||||
const val PIN_LOCK_ENABLED_DEFAULT = false
|
||||
const val IS_TUNNEL_STATS_EXPANDED = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,11 +40,6 @@ data class Settings(
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isMultiTunnelEnabled: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "is_auto_tunnel_paused",
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isAutoTunnelPaused: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "is_ping_enabled",
|
||||
defaultValue = "false",
|
||||
@@ -55,4 +50,14 @@ data class Settings(
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isAmneziaEnabled: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "is_wildcards_enabled",
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isWildcardsEnabled: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "is_wifi_by_shell_enabled",
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isWifiNameByShellEnabled: Boolean = false,
|
||||
)
|
||||
|
||||
@@ -37,11 +37,33 @@ data class TunnelConfig(
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isActive: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "is_ping_enabled",
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isPingEnabled: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "ping_interval",
|
||||
defaultValue = "null",
|
||||
)
|
||||
val pingInterval: Long? = null,
|
||||
@ColumnInfo(
|
||||
name = "ping_cooldown",
|
||||
defaultValue = "null",
|
||||
)
|
||||
val pingCooldown: Long? = null,
|
||||
@ColumnInfo(
|
||||
name = "ping_ip",
|
||||
defaultValue = "null",
|
||||
)
|
||||
var pingIp: String? = null,
|
||||
) {
|
||||
|
||||
fun toAmConfig(): org.amnezia.awg.config.Config {
|
||||
return configFromAmQuick(if (amQuick != "") amQuick else wgQuick)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun findDefault(tunnels: List<TunnelConfig>): TunnelConfig? {
|
||||
return tunnels.find { it.isPrimaryTunnel } ?: tunnels.firstOrNull()
|
||||
}
|
||||
|
||||
fun configFromWgQuick(wgQuick: String): Config {
|
||||
val inputStream: InputStream = wgQuick.byteInputStream()
|
||||
|
||||
+4
-3
@@ -15,8 +15,9 @@ constructor(
|
||||
}
|
||||
|
||||
override suspend fun getStartTunnelConfig(): TunnelConfig? {
|
||||
return appState.getLastActiveTunnelId()?.let {
|
||||
tunnels.getById(it)
|
||||
} ?: getPrimaryOrFirstTunnel()
|
||||
tunnels.getActive().let {
|
||||
if (it.isNotEmpty()) return it.first()
|
||||
return getPrimaryOrFirstTunnel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-4
@@ -1,6 +1,7 @@
|
||||
package com.zaneschepke.wireguardautotunnel.data.repository
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface AppStateRepository {
|
||||
@@ -16,13 +17,17 @@ interface AppStateRepository {
|
||||
|
||||
suspend fun setBatteryOptimizationDisableShown(shown: Boolean)
|
||||
|
||||
suspend fun getLastActiveTunnelId(): Int?
|
||||
|
||||
suspend fun setLastActiveTunnelId(id: Int)
|
||||
|
||||
suspend fun getCurrentSsid(): String?
|
||||
|
||||
suspend fun setCurrentSsid(ssid: String)
|
||||
|
||||
suspend fun isTunnelStatsExpanded(): Boolean
|
||||
|
||||
suspend fun setTunnelStatsExpanded(expanded: Boolean)
|
||||
|
||||
suspend fun setTheme(theme: Theme)
|
||||
|
||||
suspend fun getTheme(): Theme
|
||||
|
||||
val generalStateFlow: Flow<GeneralState>
|
||||
}
|
||||
|
||||
+40
-33
@@ -2,65 +2,71 @@ package com.zaneschepke.wireguardautotunnel.data.repository
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.withContext
|
||||
import timber.log.Timber
|
||||
|
||||
class DataStoreAppStateRepository(
|
||||
private val dataStoreManager: DataStoreManager,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
) :
|
||||
AppStateRepository {
|
||||
override suspend fun isLocationDisclosureShown(): Boolean {
|
||||
return withContext(ioDispatcher) {
|
||||
dataStoreManager.getFromStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN)
|
||||
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT
|
||||
}
|
||||
return dataStoreManager.getFromStore(DataStoreManager.locationDisclosureShown)
|
||||
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT
|
||||
}
|
||||
|
||||
override suspend fun setLocationDisclosureShown(shown: Boolean) {
|
||||
withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown) }
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.locationDisclosureShown, shown)
|
||||
}
|
||||
|
||||
override suspend fun isPinLockEnabled(): Boolean {
|
||||
return withContext(ioDispatcher) {
|
||||
dataStoreManager.getFromStore(DataStoreManager.IS_PIN_LOCK_ENABLED)
|
||||
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT
|
||||
}
|
||||
return dataStoreManager.getFromStore(DataStoreManager.pinLockEnabled)
|
||||
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT
|
||||
}
|
||||
|
||||
override suspend fun setPinLockEnabled(enabled: Boolean) {
|
||||
withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.IS_PIN_LOCK_ENABLED, enabled) }
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.pinLockEnabled, enabled)
|
||||
}
|
||||
|
||||
override suspend fun isBatteryOptimizationDisableShown(): Boolean {
|
||||
return withContext(ioDispatcher) {
|
||||
dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN)
|
||||
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
|
||||
}
|
||||
return dataStoreManager.getFromStore(DataStoreManager.batteryDisableShown)
|
||||
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
|
||||
}
|
||||
|
||||
override suspend fun setBatteryOptimizationDisableShown(shown: Boolean) {
|
||||
withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN, shown) }
|
||||
}
|
||||
|
||||
override suspend fun getLastActiveTunnelId(): Int? {
|
||||
return withContext(ioDispatcher) { dataStoreManager.getFromStore(DataStoreManager.LAST_ACTIVE_TUNNEL) }
|
||||
}
|
||||
|
||||
override suspend fun setLastActiveTunnelId(id: Int) {
|
||||
return withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.LAST_ACTIVE_TUNNEL, id) }
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.batteryDisableShown, shown)
|
||||
}
|
||||
|
||||
override suspend fun getCurrentSsid(): String? {
|
||||
return withContext(ioDispatcher) { dataStoreManager.getFromStore(DataStoreManager.CURRENT_SSID) }
|
||||
return dataStoreManager.getFromStore(DataStoreManager.currentSSID)
|
||||
}
|
||||
|
||||
override suspend fun setCurrentSsid(ssid: String) {
|
||||
withContext(ioDispatcher) { dataStoreManager.saveToDataStore(DataStoreManager.CURRENT_SSID, ssid) }
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.currentSSID, ssid)
|
||||
}
|
||||
|
||||
override suspend fun isTunnelStatsExpanded(): Boolean {
|
||||
return dataStoreManager.getFromStore(DataStoreManager.tunnelStatsExpanded)
|
||||
?: GeneralState.IS_TUNNEL_STATS_EXPANDED
|
||||
}
|
||||
|
||||
override suspend fun setTunnelStatsExpanded(expanded: Boolean) {
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.tunnelStatsExpanded, expanded)
|
||||
}
|
||||
|
||||
override suspend fun setTheme(theme: Theme) {
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.theme, theme.name)
|
||||
}
|
||||
|
||||
override suspend fun getTheme(): Theme {
|
||||
return dataStoreManager.getFromStore(DataStoreManager.theme)?.let {
|
||||
try {
|
||||
Theme.valueOf(it)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
Theme.AUTOMATIC
|
||||
}
|
||||
} ?: Theme.AUTOMATIC
|
||||
}
|
||||
|
||||
override val generalStateFlow: Flow<GeneralState> =
|
||||
@@ -69,15 +75,16 @@ class DataStoreAppStateRepository(
|
||||
try {
|
||||
GeneralState(
|
||||
isLocationDisclosureShown =
|
||||
pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
|
||||
pref[DataStoreManager.locationDisclosureShown]
|
||||
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
||||
isBatteryOptimizationDisableShown =
|
||||
pref[DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN]
|
||||
pref[DataStoreManager.batteryDisableShown]
|
||||
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
||||
isPinLockEnabled =
|
||||
pref[DataStoreManager.IS_PIN_LOCK_ENABLED]
|
||||
pref[DataStoreManager.pinLockEnabled]
|
||||
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT,
|
||||
lastActiveTunnelId = pref[DataStoreManager.LAST_ACTIVE_TUNNEL],
|
||||
isTunnelStatsExpanded = pref[DataStoreManager.tunnelStatsExpanded] ?: GeneralState.IS_TUNNEL_STATS_EXPANDED,
|
||||
theme = getTheme(),
|
||||
)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Timber.e(e)
|
||||
|
||||
-6
@@ -1,11 +1,9 @@
|
||||
package com.zaneschepke.wireguardautotunnel.data.repository
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -26,8 +24,6 @@ class RoomTunnelConfigRepository(
|
||||
override suspend fun save(tunnelConfig: TunnelConfig) {
|
||||
withContext(ioDispatcher) {
|
||||
tunnelConfigDao.save(tunnelConfig)
|
||||
}.also {
|
||||
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,8 +56,6 @@ class RoomTunnelConfigRepository(
|
||||
override suspend fun delete(tunnelConfig: TunnelConfig) {
|
||||
withContext(ioDispatcher) {
|
||||
tunnelConfigDao.delete(tunnelConfig)
|
||||
}.also {
|
||||
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.zaneschepke.wireguardautotunnel.module
|
||||
|
||||
import android.content.Context
|
||||
import com.zaneschepke.logcatter.LocalLogCollector
|
||||
import com.zaneschepke.logcatter.LogcatUtil
|
||||
import com.zaneschepke.logcatter.LogReader
|
||||
import com.zaneschepke.logcatter.LogcatCollector
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
@@ -24,7 +24,7 @@ class AppModule {
|
||||
|
||||
@Singleton
|
||||
@Provides
|
||||
fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector {
|
||||
return LogcatUtil.init(context = context)
|
||||
fun provideLogCollect(@ApplicationContext context: Context): LogReader {
|
||||
return LogcatCollector.init(context = context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,8 +72,8 @@ class RepositoryModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideGeneralStateRepository(dataStoreManager: DataStoreManager, @IoDispatcher ioDispatcher: CoroutineDispatcher): AppStateRepository {
|
||||
return DataStoreAppStateRepository(dataStoreManager, ioDispatcher)
|
||||
fun provideGeneralStateRepository(dataStoreManager: DataStoreManager): AppStateRepository {
|
||||
return DataStoreAppStateRepository(dataStoreManager)
|
||||
}
|
||||
|
||||
@Provides
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.wireguard.android.backend.WgQuickBackend
|
||||
import com.wireguard.android.util.RootShell
|
||||
import com.wireguard.android.util.ToolsInstaller
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.TunnelConfigRepository
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.WireGuardTunnel
|
||||
@@ -60,25 +61,27 @@ class TunnelModule {
|
||||
@Singleton
|
||||
fun provideVpnService(
|
||||
amneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
||||
@Userspace userspaceBackend: Provider<Backend>,
|
||||
@Kernel kernelBackend: Provider<Backend>,
|
||||
appDataRepository: AppDataRepository,
|
||||
tunnelConfigRepository: TunnelConfigRepository,
|
||||
@ApplicationScope applicationScope: CoroutineScope,
|
||||
@IoDispatcher ioDispatcher: CoroutineDispatcher,
|
||||
serviceManager: ServiceManager,
|
||||
): TunnelService {
|
||||
return WireGuardTunnel(
|
||||
amneziaBackend,
|
||||
userspaceBackend,
|
||||
tunnelConfigRepository,
|
||||
kernelBackend,
|
||||
appDataRepository,
|
||||
applicationScope,
|
||||
ioDispatcher,
|
||||
serviceManager,
|
||||
)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideServiceManager(): ServiceManager {
|
||||
return ServiceManager()
|
||||
@Provides
|
||||
fun provideServiceManager(@ApplicationContext context: Context): ServiceManager {
|
||||
return ServiceManager(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@ import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@AndroidEntryPoint
|
||||
class AppUpdateReceiver : BroadcastReceiver() {
|
||||
@@ -25,10 +25,10 @@ class AppUpdateReceiver : BroadcastReceiver() {
|
||||
lateinit var appDataRepository: AppDataRepository
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
lateinit var tunnelService: Provider<TunnelService>
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelService: TunnelService
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
|
||||
@@ -36,11 +36,11 @@ class AppUpdateReceiver : BroadcastReceiver() {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isAutoTunnelEnabled) {
|
||||
Timber.i("Restarting services after upgrade")
|
||||
serviceManager.startWatcherServiceForeground(context)
|
||||
serviceManager.startAutoTunnel(true)
|
||||
}
|
||||
if (!settings.isAutoTunnelEnabled || settings.isAutoTunnelPaused) {
|
||||
if (!settings.isAutoTunnelEnabled) {
|
||||
val tunnels = appDataRepository.tunnels.getAll().filter { it.isActive }
|
||||
if (tunnels.isNotEmpty()) context.startTunnelBackground(tunnels.first().id)
|
||||
if (tunnels.isNotEmpty()) tunnelService.get().startTunnel(tunnels.first(), true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.receiver
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.TunnelConfigRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@AndroidEntryPoint
|
||||
class BackgroundActionReceiver : BroadcastReceiver() {
|
||||
|
||||
@Inject
|
||||
@ApplicationScope
|
||||
lateinit var applicationScope: CoroutineScope
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelService: Provider<TunnelService>
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelConfigRepository: TunnelConfigRepository
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val id = intent.getIntExtra(TUNNEL_ID_EXTRA_KEY, 0)
|
||||
if (id == 0) return
|
||||
when (intent.action) {
|
||||
ACTION_CONNECT -> {
|
||||
Timber.d("Connect actions")
|
||||
applicationScope.launch {
|
||||
val tunnel = tunnelConfigRepository.getById(id)
|
||||
tunnel?.let {
|
||||
serviceManager.startTunnelBackgroundService(context)
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
ACTION_DISCONNECT -> {
|
||||
applicationScope.launch {
|
||||
val tunnel = tunnelConfigRepository.getById(id)
|
||||
tunnel?.let {
|
||||
serviceManager.stopTunnelBackgroundService(context)
|
||||
tunnelService.get().stopTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ACTION_CONNECT = "ACTION_CONNECT"
|
||||
const val ACTION_DISCONNECT = "ACTION_DISCONNECT"
|
||||
const val TUNNEL_ID_EXTRA_KEY = "tunnelId"
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -23,26 +23,30 @@ class BootReceiver : BroadcastReceiver() {
|
||||
@Inject
|
||||
lateinit var tunnelService: Provider<TunnelService>
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
@Inject
|
||||
@ApplicationScope
|
||||
lateinit var applicationScope: CoroutineScope
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (Intent.ACTION_BOOT_COMPLETED != intent.action) return
|
||||
applicationScope.launch {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isRestoreOnBootEnabled) {
|
||||
appDataRepository.getStartTunnelConfig()?.let {
|
||||
context.startTunnelBackground(it.id)
|
||||
with(appDataRepository.settings.getSettings()) {
|
||||
if (isRestoreOnBootEnabled) {
|
||||
val activeTunnels = appDataRepository.tunnels.getActive()
|
||||
val tunState = tunnelService.get().vpnState.value.status
|
||||
if (activeTunnels.isNotEmpty() && tunState != TunnelState.UP) {
|
||||
Timber.i("Starting previously active tunnel")
|
||||
tunnelService.get().startTunnel(activeTunnels.first(), true)
|
||||
}
|
||||
if (isAutoTunnelEnabled) {
|
||||
Timber.i("Starting watcher service from boot")
|
||||
serviceManager.startAutoTunnel(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (settings.isAutoTunnelEnabled) {
|
||||
Timber.i("Starting watcher service from boot")
|
||||
serviceManager.startWatcherServiceForeground(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+303
-214
@@ -1,11 +1,16 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.content.Intent
|
||||
import android.net.NetworkCapabilities
|
||||
import android.os.IBinder
|
||||
import android.os.PowerManager
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.wireguard.android.util.RootShell
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
@@ -19,11 +24,20 @@ import com.zaneschepke.wireguardautotunnel.service.notification.NotificationServ
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.cancelWithMessage
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.getCurrentWifiName
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isDown
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isReachable
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.onNotRunning
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -33,9 +47,12 @@ import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@AndroidEntryPoint
|
||||
class AutoTunnelService : ForegroundService() {
|
||||
class AutoTunnelService : LifecycleService() {
|
||||
private val foregroundId = 122
|
||||
|
||||
@Inject
|
||||
lateinit var rootShell: Provider<RootShell>
|
||||
|
||||
@Inject
|
||||
lateinit var wifiService: NetworkService<WifiService>
|
||||
|
||||
@@ -58,57 +75,73 @@ class AutoTunnelService : ForegroundService() {
|
||||
@IoDispatcher
|
||||
lateinit var ioDispatcher: CoroutineDispatcher
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
@Inject
|
||||
@MainImmediateDispatcher
|
||||
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
||||
|
||||
private val networkEventsFlow = MutableStateFlow(AutoTunnelState())
|
||||
private val autoTunnelStateFlow = MutableStateFlow(AutoTunnelState())
|
||||
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
private val tag = this.javaClass.name
|
||||
|
||||
private var running: Boolean = false
|
||||
private var wifiJob: Job? = null
|
||||
private var mobileDataJob: Job? = null
|
||||
private var ethernetJob: Job? = null
|
||||
private var pingJob: Job? = null
|
||||
private var networkEventJob: Job? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||
kotlin.runCatching {
|
||||
launchNotification()
|
||||
launchWatcherNotification()
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun launchNotification() {
|
||||
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
|
||||
launchWatcherPausedNotification()
|
||||
} else {
|
||||
launchWatcherNotification()
|
||||
}
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
super.onBind(intent)
|
||||
// We don't provide binding, so return null
|
||||
return null
|
||||
}
|
||||
|
||||
override fun startService(extras: Bundle?) {
|
||||
super.startService(extras)
|
||||
if (running) return
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
Timber.d("onStartCommand executed with startId: $startId")
|
||||
serviceManager.autoTunnelService.complete(this)
|
||||
return super.onStartCommand(intent, flags, startId)
|
||||
}
|
||||
|
||||
fun start() {
|
||||
kotlin.runCatching {
|
||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||
launchNotification()
|
||||
launchWatcherNotification()
|
||||
initWakeLock()
|
||||
}
|
||||
startWatcherJob()
|
||||
startSettingsJob()
|
||||
startVpnStateJob()
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
|
||||
override fun stopService() {
|
||||
super.stopService()
|
||||
fun stop() {
|
||||
wakeLock?.let {
|
||||
if (it.isHeld) {
|
||||
it.release()
|
||||
}
|
||||
}
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
cancelAndResetNetworkJobs()
|
||||
cancelAndResetPingJob()
|
||||
serviceManager.autoTunnelService = CompletableDeferred()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun launchWatcherNotification(description: String = getString(R.string.watcher_notification_text_active)) {
|
||||
@@ -127,13 +160,10 @@ class AutoTunnelService : ForegroundService() {
|
||||
)
|
||||
}
|
||||
|
||||
private fun launchWatcherPausedNotification() {
|
||||
launchWatcherNotification(getString(R.string.watcher_notification_text_paused))
|
||||
}
|
||||
|
||||
private fun initWakeLock() {
|
||||
wakeLock =
|
||||
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
|
||||
val tag = this.javaClass.name
|
||||
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply {
|
||||
try {
|
||||
Timber.i("Initiating wakelock with 10 min timeout")
|
||||
@@ -145,48 +175,42 @@ class AutoTunnelService : ForegroundService() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun startWatcherJob() = lifecycleScope.launch {
|
||||
val setting = appDataRepository.settings.getSettings()
|
||||
launch {
|
||||
Timber.i("Starting wifi watcher")
|
||||
watchForWifiConnectivityChanges()
|
||||
}
|
||||
if (setting.isTunnelOnMobileDataEnabled) {
|
||||
launch {
|
||||
Timber.i("Starting mobile data watcher")
|
||||
watchForMobileDataConnectivityChanges()
|
||||
}
|
||||
}
|
||||
if (setting.isTunnelOnEthernetEnabled) {
|
||||
launch {
|
||||
Timber.i("Starting ethernet data watcher")
|
||||
watchForEthernetConnectivityChanges()
|
||||
}
|
||||
}
|
||||
launch {
|
||||
Timber.i("Starting settings watcher")
|
||||
watchForSettingsChanges()
|
||||
}
|
||||
if (setting.isPingEnabled) {
|
||||
launch {
|
||||
Timber.i("Starting ping watcher")
|
||||
watchForPingFailure()
|
||||
}
|
||||
}
|
||||
launch {
|
||||
Timber.i("Starting management watcher")
|
||||
manageVpn()
|
||||
}
|
||||
running = true
|
||||
private fun startSettingsJob() = lifecycleScope.launch {
|
||||
watchForSettingsChanges()
|
||||
}
|
||||
|
||||
private fun startVpnStateJob() = lifecycleScope.launch {
|
||||
watchForVpnStateChanges()
|
||||
}
|
||||
|
||||
private fun startWifiJob() = lifecycleScope.launch {
|
||||
watchForWifiConnectivityChanges()
|
||||
}
|
||||
|
||||
private fun startMobileDataJob() = lifecycleScope.launch {
|
||||
watchForMobileDataConnectivityChanges()
|
||||
}
|
||||
|
||||
private fun startEthernetJob() = lifecycleScope.launch {
|
||||
watchForEthernetConnectivityChanges()
|
||||
}
|
||||
|
||||
private fun startPingJob() = lifecycleScope.launch {
|
||||
watchForPingFailure()
|
||||
}
|
||||
|
||||
private fun startNetworkEventJob() = lifecycleScope.launch {
|
||||
handleNetworkEventChanges()
|
||||
}
|
||||
|
||||
private suspend fun watchForMobileDataConnectivityChanges() {
|
||||
withContext(ioDispatcher) {
|
||||
Timber.i("Starting mobile data watcher")
|
||||
mobileDataService.networkStatus.collect { status ->
|
||||
when (status) {
|
||||
is NetworkStatus.Available -> {
|
||||
Timber.i("Gained Mobile data connection")
|
||||
networkEventsFlow.update {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isMobileDataConnected = true,
|
||||
)
|
||||
@@ -194,7 +218,7 @@ class AutoTunnelService : ForegroundService() {
|
||||
}
|
||||
|
||||
is NetworkStatus.CapabilitiesChanged -> {
|
||||
networkEventsFlow.update {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isMobileDataConnected = true,
|
||||
)
|
||||
@@ -203,7 +227,7 @@ class AutoTunnelService : ForegroundService() {
|
||||
}
|
||||
|
||||
is NetworkStatus.Unavailable -> {
|
||||
networkEventsFlow.update {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isMobileDataConnected = false,
|
||||
)
|
||||
@@ -217,92 +241,166 @@ class AutoTunnelService : ForegroundService() {
|
||||
|
||||
private suspend fun watchForPingFailure() {
|
||||
withContext(ioDispatcher) {
|
||||
try {
|
||||
Timber.i("Starting ping watcher")
|
||||
runCatching {
|
||||
do {
|
||||
if (tunnelService.get().vpnState.value.status == TunnelState.UP) {
|
||||
val tunnelConfig = tunnelService.get().vpnState.value.tunnelConfig
|
||||
tunnelConfig?.let {
|
||||
val config = TunnelConfig.configFromWgQuick(it.wgQuick)
|
||||
val results =
|
||||
val vpnState = tunnelService.get().vpnState.value
|
||||
if (vpnState.status == TunnelState.UP) {
|
||||
if (vpnState.tunnelConfig != null) {
|
||||
val config = TunnelConfig.configFromWgQuick(vpnState.tunnelConfig.wgQuick)
|
||||
val results = if (vpnState.tunnelConfig.pingIp != null) {
|
||||
Timber.d("Pinging custom ip : ${vpnState.tunnelConfig.pingIp}")
|
||||
listOf(InetAddress.getByName(vpnState.tunnelConfig.pingIp).isReachable(Constants.PING_TIMEOUT.toInt()))
|
||||
} else {
|
||||
Timber.d("Pinging all peers")
|
||||
config.peers.map { peer ->
|
||||
val host =
|
||||
if (peer.endpoint.isPresent &&
|
||||
peer.endpoint.get().resolved.isPresent
|
||||
) {
|
||||
peer.endpoint.get().resolved.get().host
|
||||
} else {
|
||||
Constants.DEFAULT_PING_IP
|
||||
}
|
||||
Timber.i("Checking reachability of: $host")
|
||||
val reachable =
|
||||
InetAddress.getByName(host)
|
||||
.isReachable(Constants.PING_TIMEOUT.toInt())
|
||||
Timber.i("Result: reachable - $reachable")
|
||||
reachable
|
||||
peer.isReachable()
|
||||
}
|
||||
}
|
||||
Timber.i("Ping results reachable: $results")
|
||||
if (results.contains(false)) {
|
||||
Timber.i("Restarting VPN for ping failure")
|
||||
tunnelService.get().stopTunnel(it)
|
||||
delay(Constants.VPN_RESTART_DELAY)
|
||||
tunnelService.get().startTunnel(it)
|
||||
delay(Constants.PING_COOLDOWN)
|
||||
val cooldown = vpnState.tunnelConfig.pingCooldown
|
||||
tunnelService.get().bounceTunnel(vpnState.tunnelConfig)
|
||||
delay(cooldown ?: Constants.PING_COOLDOWN)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
delay(Constants.PING_INTERVAL)
|
||||
delay(vpnState.tunnelConfig?.pingInterval ?: Constants.PING_INTERVAL)
|
||||
} while (true)
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e)
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun watchForSettingsChanges() {
|
||||
appDataRepository.settings.getSettingsFlow().collect { settings ->
|
||||
if (networkEventsFlow.value.settings.isAutoTunnelPaused
|
||||
!= settings.isAutoTunnelPaused
|
||||
) {
|
||||
when (settings.isAutoTunnelPaused) {
|
||||
true -> launchWatcherPausedNotification()
|
||||
false -> launchWatcherNotification()
|
||||
Timber.i("Starting settings watcher")
|
||||
withContext(ioDispatcher) {
|
||||
appDataRepository.settings.getSettingsFlow().combine(
|
||||
// ignore isActive changes to allow manual tunnel overrides
|
||||
appDataRepository.tunnels.getTunnelConfigsFlow().distinctUntilChanged { old, new ->
|
||||
old.map { it.isActive } != new.map { it.isActive }
|
||||
},
|
||||
) { settings, tunnels ->
|
||||
autoTunnelStateFlow.value.copy(
|
||||
settings = settings,
|
||||
tunnels = tunnels,
|
||||
)
|
||||
}.collect {
|
||||
Timber.d("got new settings: ${it.settings}")
|
||||
manageJobsBySettings(it.settings)
|
||||
autoTunnelStateFlow.emit(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun watchForVpnStateChanges() {
|
||||
Timber.i("Starting vpn state watcher")
|
||||
withContext(ioDispatcher) {
|
||||
tunnelService.get().vpnState.distinctUntilChanged { old, new ->
|
||||
old.tunnelConfig == new.tunnelConfig && old.status == new.status
|
||||
}.collect { state ->
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(vpnState = state)
|
||||
}
|
||||
state.tunnelConfig?.let {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (it.isPingEnabled && !settings.isPingEnabled) {
|
||||
pingJob.onNotRunning { pingJob = startPingJob() }
|
||||
}
|
||||
if (!it.isPingEnabled && !settings.isPingEnabled) {
|
||||
cancelAndResetPingJob()
|
||||
}
|
||||
}
|
||||
}
|
||||
networkEventsFlow.update {
|
||||
it.copy(
|
||||
settings = settings,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun manageJobsBySettings(settings: Settings) {
|
||||
with(settings) {
|
||||
if (isPingEnabled) {
|
||||
pingJob.onNotRunning { pingJob = startPingJob() }
|
||||
} else {
|
||||
cancelAndResetPingJob()
|
||||
}
|
||||
if (isTunnelOnWifiEnabled || isTunnelOnEthernetEnabled || isTunnelOnMobileDataEnabled) {
|
||||
startNetworkJobs()
|
||||
} else {
|
||||
cancelAndResetNetworkJobs()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun startNetworkJobs() {
|
||||
wifiJob.onNotRunning {
|
||||
Timber.i("Wifi job starting")
|
||||
wifiJob = startWifiJob()
|
||||
}
|
||||
ethernetJob.onNotRunning {
|
||||
ethernetJob = startEthernetJob()
|
||||
Timber.i("Ethernet job starting")
|
||||
}
|
||||
mobileDataJob.onNotRunning {
|
||||
mobileDataJob = startMobileDataJob()
|
||||
Timber.i("Mobile data job starting")
|
||||
}
|
||||
networkEventJob.onNotRunning {
|
||||
Timber.i("Network event job starting")
|
||||
networkEventJob = startNetworkEventJob()
|
||||
}
|
||||
}
|
||||
|
||||
private fun cancelAndResetPingJob() {
|
||||
pingJob?.cancelWithMessage("Ping job canceled")
|
||||
pingJob = null
|
||||
}
|
||||
|
||||
private fun cancelAndResetNetworkJobs() {
|
||||
networkEventJob?.cancelWithMessage("Network event job canceled")
|
||||
wifiJob?.cancelWithMessage("Wifi job canceled")
|
||||
ethernetJob?.cancelWithMessage("Ethernet job canceled")
|
||||
mobileDataJob?.cancelWithMessage("Mobile data job canceled")
|
||||
networkEventJob = null
|
||||
wifiJob = null
|
||||
ethernetJob = null
|
||||
mobileDataJob = null
|
||||
}
|
||||
|
||||
private fun updateEthernet(connected: Boolean) {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isEthernetConnected = connected,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateWifi(connected: Boolean) {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isWifiConnected = connected,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun watchForEthernetConnectivityChanges() {
|
||||
withContext(ioDispatcher) {
|
||||
Timber.i("Starting ethernet data watcher")
|
||||
ethernetService.networkStatus.collect { status ->
|
||||
when (status) {
|
||||
is NetworkStatus.Available -> {
|
||||
Timber.i("Gained Ethernet connection")
|
||||
networkEventsFlow.update {
|
||||
it.copy(
|
||||
isEthernetConnected = true,
|
||||
)
|
||||
}
|
||||
updateEthernet(true)
|
||||
}
|
||||
|
||||
is NetworkStatus.CapabilitiesChanged -> {
|
||||
Timber.i("Ethernet capabilities changed")
|
||||
networkEventsFlow.update {
|
||||
it.copy(
|
||||
isEthernetConnected = true,
|
||||
)
|
||||
}
|
||||
updateEthernet(true)
|
||||
}
|
||||
|
||||
is NetworkStatus.Unavailable -> {
|
||||
networkEventsFlow.update {
|
||||
it.copy(
|
||||
isEthernetConnected = false,
|
||||
)
|
||||
}
|
||||
updateEthernet(false)
|
||||
Timber.i("Lost Ethernet connection")
|
||||
}
|
||||
}
|
||||
@@ -312,25 +410,18 @@ class AutoTunnelService : ForegroundService() {
|
||||
|
||||
private suspend fun watchForWifiConnectivityChanges() {
|
||||
withContext(ioDispatcher) {
|
||||
Timber.i("Starting wifi watcher")
|
||||
wifiService.networkStatus.collect { status ->
|
||||
when (status) {
|
||||
is NetworkStatus.Available -> {
|
||||
Timber.i("Gained Wi-Fi connection")
|
||||
networkEventsFlow.update {
|
||||
it.copy(
|
||||
isWifiConnected = true,
|
||||
)
|
||||
}
|
||||
updateWifi(true)
|
||||
}
|
||||
|
||||
is NetworkStatus.CapabilitiesChanged -> {
|
||||
Timber.i("Wifi capabilities changed")
|
||||
networkEventsFlow.update {
|
||||
it.copy(
|
||||
isWifiConnected = true,
|
||||
)
|
||||
}
|
||||
val ssid = wifiService.getNetworkName(status.networkCapabilities)
|
||||
updateWifi(true)
|
||||
val ssid = getWifiSSID(status.networkCapabilities)
|
||||
ssid?.let { name ->
|
||||
if (name.contains(Constants.UNREADABLE_SSID)) {
|
||||
Timber.w("SSID unreadable: missing permissions")
|
||||
@@ -338,7 +429,7 @@ class AutoTunnelService : ForegroundService() {
|
||||
Timber.i("Detected valid SSID")
|
||||
}
|
||||
appDataRepository.appState.setCurrentSsid(name)
|
||||
networkEventsFlow.update {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
currentNetworkSSID = name,
|
||||
)
|
||||
@@ -347,11 +438,7 @@ class AutoTunnelService : ForegroundService() {
|
||||
}
|
||||
|
||||
is NetworkStatus.Unavailable -> {
|
||||
networkEventsFlow.update {
|
||||
it.copy(
|
||||
isWifiConnected = false,
|
||||
)
|
||||
}
|
||||
updateWifi(false)
|
||||
Timber.i("Lost Wi-Fi connection")
|
||||
}
|
||||
}
|
||||
@@ -359,106 +446,108 @@ class AutoTunnelService : ForegroundService() {
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getWifiSSID(networkCapabilities: NetworkCapabilities): String? {
|
||||
return withContext(ioDispatcher) {
|
||||
with(autoTunnelStateFlow.value.settings) {
|
||||
if (isWifiNameByShellEnabled) return@withContext rootShell.get().getCurrentWifiName()
|
||||
wifiService.getNetworkName(networkCapabilities)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getMobileDataTunnel(): TunnelConfig? {
|
||||
return appDataRepository.tunnels.findByMobileDataTunnel().firstOrNull()
|
||||
}
|
||||
|
||||
private suspend fun getSsidTunnel(ssid: String): TunnelConfig? {
|
||||
return appDataRepository.tunnels.findByTunnelNetworksName(ssid).firstOrNull()
|
||||
}
|
||||
|
||||
private fun isTunnelDown(): Boolean {
|
||||
return tunnelService.get().vpnState.value.status == TunnelState.DOWN
|
||||
}
|
||||
|
||||
private suspend fun manageVpn() {
|
||||
private suspend fun handleNetworkEventChanges() {
|
||||
withContext(ioDispatcher) {
|
||||
networkEventsFlow.collectLatest { watcherState ->
|
||||
Timber.i("Starting network event watcher")
|
||||
autoTunnelStateFlow.collectLatest { watcherState ->
|
||||
val autoTunnel = "Auto-tunnel watcher"
|
||||
if (!watcherState.settings.isAutoTunnelPaused) {
|
||||
// delay for rapid network state changes and then collect latest
|
||||
delay(Constants.WATCHER_COLLECTION_DELAY)
|
||||
val activeTunnel = tunnelService.get().vpnState.value.tunnelConfig
|
||||
val defaultTunnel = appDataRepository.getPrimaryOrFirstTunnel()
|
||||
when {
|
||||
watcherState.isEthernetConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
|
||||
if (isTunnelDown()) {
|
||||
defaultTunnel?.let {
|
||||
Timber.d("New watcher state!")
|
||||
// delay for rapid network state changes and then collect latest
|
||||
delay(Constants.WATCHER_COLLECTION_DELAY)
|
||||
val activeTunnel = watcherState.vpnState.tunnelConfig
|
||||
val defaultTunnel = appDataRepository.getPrimaryOrFirstTunnel()
|
||||
when {
|
||||
watcherState.isEthernetConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
|
||||
if (watcherState.vpnState.isDown()) {
|
||||
defaultTunnel?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isMobileDataConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel on mobile data condition met")
|
||||
val mobileDataTunnel = getMobileDataTunnel()
|
||||
val tunnel =
|
||||
mobileDataTunnel ?: defaultTunnel
|
||||
if (watcherState.vpnState.isDown() || activeTunnel?.isMobileDataTunnel == false) {
|
||||
tunnel?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isTunnelOffOnMobileDataConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
|
||||
if (!watcherState.vpnState.isDown()) {
|
||||
activeTunnel?.let {
|
||||
tunnelService.get().stopTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isUntrustedWifiConditionMet() -> {
|
||||
Timber.i("Untrusted wifi condition met")
|
||||
if (activeTunnel == null || watcherState.isCurrentSSIDActiveTunnelNetwork() == false ||
|
||||
watcherState.vpnState.isDown()
|
||||
) {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met",
|
||||
)
|
||||
watcherState.getTunnelWithMatchingTunnelNetwork()?.let {
|
||||
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}")
|
||||
if (watcherState.vpnState.isDown() || activeTunnel?.id != it.id) {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isMobileDataConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel on mobile data condition met")
|
||||
val mobileDataTunnel = getMobileDataTunnel()
|
||||
val tunnel =
|
||||
mobileDataTunnel ?: defaultTunnel
|
||||
if (isTunnelDown() || activeTunnel?.isMobileDataTunnel == false) {
|
||||
tunnel?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isTunnelOffOnMobileDataConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
|
||||
if (!isTunnelDown()) {
|
||||
activeTunnel?.let {
|
||||
tunnelService.get().stopTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isUntrustedWifiConditionMet() -> {
|
||||
if (activeTunnel?.tunnelNetworks?.contains(watcherState.currentNetworkSSID) == false ||
|
||||
activeTunnel == null
|
||||
) {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met",
|
||||
)
|
||||
getSsidTunnel(watcherState.currentNetworkSSID)?.let {
|
||||
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}")
|
||||
if (isTunnelDown() || activeTunnel?.id != it.id) {
|
||||
} ?: suspend {
|
||||
Timber.i("No tunnel associated with this SSID, using defaults")
|
||||
val default = appDataRepository.getPrimaryOrFirstTunnel()
|
||||
if (default?.name != tunnelService.get().name || watcherState.vpnState.isDown()) {
|
||||
default?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
} ?: suspend {
|
||||
Timber.i("No tunnel associated with this SSID, using defaults")
|
||||
val default = appDataRepository.getPrimaryOrFirstTunnel()
|
||||
if (default?.name != tunnelService.get().name || isTunnelDown()) {
|
||||
default?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}.invoke()
|
||||
}
|
||||
}
|
||||
}.invoke()
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isTrustedWifiConditionMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off",
|
||||
)
|
||||
if (!isTunnelDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
watcherState.isTrustedWifiConditionMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off",
|
||||
)
|
||||
if (!watcherState.vpnState.isDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
|
||||
watcherState.isTunnelOffOnWifiConditionMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on wifi condition met, turning vpn off",
|
||||
)
|
||||
if (!isTunnelDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
watcherState.isTunnelOffOnWifiConditionMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on wifi condition met, turning vpn off",
|
||||
)
|
||||
if (!watcherState.vpnState.isDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
|
||||
watcherState.isTunnelOffOnNoConnectivityMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on no connectivity met, turning vpn off",
|
||||
)
|
||||
if (!isTunnelDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
watcherState.isTunnelOffOnNoConnectivityMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on no connectivity met, turning vpn off",
|
||||
)
|
||||
if (!watcherState.vpnState.isDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
|
||||
else -> {
|
||||
Timber.i("$autoTunnel - no condition met")
|
||||
}
|
||||
else -> {
|
||||
Timber.i("$autoTunnel - no condition met")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+36
-2
@@ -1,13 +1,19 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList
|
||||
|
||||
data class AutoTunnelState(
|
||||
val vpnState: VpnState = VpnState(),
|
||||
val isWifiConnected: Boolean = false,
|
||||
val isEthernetConnected: Boolean = false,
|
||||
val isMobileDataConnected: Boolean = false,
|
||||
val currentNetworkSSID: String = "",
|
||||
val settings: Settings = Settings(),
|
||||
val tunnels: TunnelConfigs = emptyList(),
|
||||
) {
|
||||
fun isEthernetConditionMet(): Boolean {
|
||||
return (
|
||||
@@ -38,7 +44,7 @@ data class AutoTunnelState(
|
||||
return (
|
||||
!isEthernetConnected &&
|
||||
isWifiConnected &&
|
||||
!settings.trustedNetworkSSIDs.contains(currentNetworkSSID) &&
|
||||
!isCurrentSSIDTrusted() &&
|
||||
settings.isTunnelOnWifiEnabled
|
||||
)
|
||||
}
|
||||
@@ -48,7 +54,7 @@ data class AutoTunnelState(
|
||||
!isEthernetConnected &&
|
||||
(
|
||||
isWifiConnected &&
|
||||
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)
|
||||
isCurrentSSIDTrusted()
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -70,4 +76,32 @@ data class AutoTunnelState(
|
||||
!isMobileDataConnected
|
||||
)
|
||||
}
|
||||
|
||||
fun isCurrentSSIDTrusted(): Boolean {
|
||||
return if (settings.isWildcardsEnabled) {
|
||||
settings.trustedNetworkSSIDs.isMatchingToWildcardList(currentNetworkSSID)
|
||||
} else {
|
||||
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)
|
||||
}
|
||||
}
|
||||
fun isCurrentSSIDActiveTunnelNetwork(): Boolean {
|
||||
val currentTunnelNetworks = vpnState.tunnelConfig?.tunnelNetworks
|
||||
return (
|
||||
if (settings.isWildcardsEnabled) {
|
||||
currentTunnelNetworks?.isMatchingToWildcardList(currentNetworkSSID)
|
||||
} else {
|
||||
currentTunnelNetworks?.contains(currentNetworkSSID)
|
||||
}
|
||||
) == true
|
||||
}
|
||||
|
||||
fun getTunnelWithMatchingTunnelNetwork(): TunnelConfig? {
|
||||
return tunnels.firstOrNull {
|
||||
if (settings.isWildcardsEnabled) {
|
||||
it.tunnelNetworks.isMatchingToWildcardList(currentNetworkSSID)
|
||||
} else {
|
||||
it.tunnelNetworks.contains(currentNetworkSSID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.IBinder
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import timber.log.Timber
|
||||
|
||||
open class ForegroundService : LifecycleService() {
|
||||
private var isServiceStarted = false
|
||||
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
super.onBind(intent)
|
||||
// We don't provide binding, so return null
|
||||
return null
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
super.onStartCommand(intent, flags, startId)
|
||||
Timber.d("onStartCommand executed with startId: $startId")
|
||||
if (intent != null) {
|
||||
val action = intent.action
|
||||
when (action) {
|
||||
Action.START.name,
|
||||
Action.START_FOREGROUND.name,
|
||||
-> startService(intent.extras)
|
||||
|
||||
Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService()
|
||||
Constants.ALWAYS_ON_VPN_ACTION -> {
|
||||
Timber.i("Always-on VPN starting service")
|
||||
startService(intent.extras)
|
||||
}
|
||||
|
||||
else -> Timber.d("This should never happen. No action in the received intent")
|
||||
}
|
||||
} else {
|
||||
Timber.d(
|
||||
"with a null intent. It has been probably restarted by the system.",
|
||||
)
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
protected open fun startService(extras: Bundle?) {
|
||||
if (isServiceStarted) return
|
||||
Timber.d("Starting ${this.javaClass.simpleName}")
|
||||
isServiceStarted = true
|
||||
}
|
||||
|
||||
protected open fun stopService() {
|
||||
Timber.d("Stopping ${this.javaClass.simpleName}")
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
isServiceStarted = false
|
||||
}
|
||||
}
|
||||
+62
-48
@@ -3,67 +3,81 @@ package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.zaneschepke.wireguardautotunnel.util.SingletonHolder
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||
import jakarta.inject.Inject
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import timber.log.Timber
|
||||
|
||||
class ServiceManager {
|
||||
private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) {
|
||||
val intent =
|
||||
Intent(context, cls).also {
|
||||
it.action = action.name
|
||||
extras?.forEach { (k, v) -> it.putExtra(k, v) }
|
||||
}
|
||||
intent.component?.javaClass
|
||||
try {
|
||||
when (action) {
|
||||
Action.START_FOREGROUND, Action.STOP_FOREGROUND ->
|
||||
context.startForegroundService(
|
||||
intent,
|
||||
)
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class ServiceManager
|
||||
@Inject constructor(private val context: Context) {
|
||||
|
||||
Action.START, Action.STOP -> context.startService(intent)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e.message)
|
||||
private val _autoTunnelActive = MutableStateFlow(false)
|
||||
|
||||
val autoTunnelActive = _autoTunnelActive.asStateFlow()
|
||||
|
||||
var autoTunnelService = CompletableDeferred<AutoTunnelService>()
|
||||
var backgroundService = CompletableDeferred<TunnelBackgroundService>()
|
||||
|
||||
companion object : SingletonHolder<ServiceManager, Context>(::ServiceManager)
|
||||
|
||||
private fun <T : Service> startService(cls: Class<T>, background: Boolean) {
|
||||
val intent = Intent(context, cls)
|
||||
if (background) {
|
||||
context.startForegroundService(intent)
|
||||
} else {
|
||||
context.startService(intent)
|
||||
}
|
||||
}
|
||||
|
||||
fun startWatcherServiceForeground(context: Context) {
|
||||
actionOnService(
|
||||
Action.START_FOREGROUND,
|
||||
context,
|
||||
AutoTunnelService::class.java,
|
||||
)
|
||||
suspend fun startAutoTunnel(background: Boolean) {
|
||||
if (autoTunnelService.isCompleted) return _autoTunnelActive.update { true }
|
||||
kotlin.runCatching {
|
||||
startService(AutoTunnelService::class.java, background)
|
||||
autoTunnelService.await()
|
||||
autoTunnelService.getCompleted().start()
|
||||
_autoTunnelActive.update { true }
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun startWatcherService(context: Context) {
|
||||
actionOnService(
|
||||
Action.START,
|
||||
context,
|
||||
AutoTunnelService::class.java,
|
||||
)
|
||||
suspend fun startBackgroundService() {
|
||||
if (backgroundService.isCompleted) return
|
||||
kotlin.runCatching {
|
||||
startService(TunnelBackgroundService::class.java, true)
|
||||
backgroundService.await()
|
||||
backgroundService.getCompleted().start()
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun stopWatcherService(context: Context) {
|
||||
actionOnService(
|
||||
Action.STOP,
|
||||
context,
|
||||
AutoTunnelService::class.java,
|
||||
)
|
||||
fun stopBackgroundService() {
|
||||
if (!backgroundService.isCompleted) return
|
||||
runCatching {
|
||||
backgroundService.getCompleted().stop()
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun startTunnelBackgroundService(context: Context) {
|
||||
actionOnService(
|
||||
Action.START_FOREGROUND,
|
||||
context,
|
||||
TunnelBackgroundService::class.java,
|
||||
)
|
||||
fun stopAutoTunnel() {
|
||||
if (!autoTunnelService.isCompleted) return
|
||||
runCatching {
|
||||
autoTunnelService.getCompleted().stop()
|
||||
_autoTunnelActive.update { false }
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun stopTunnelBackgroundService(context: Context) {
|
||||
actionOnService(
|
||||
Action.STOP,
|
||||
context,
|
||||
TunnelBackgroundService::class.java,
|
||||
)
|
||||
fun requestTunnelTileUpdate() {
|
||||
context.requestTunnelTileServiceStateUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
+36
-8
@@ -1,33 +1,61 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||
|
||||
import android.app.Notification
|
||||
import android.os.Bundle
|
||||
import android.content.Intent
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import javax.inject.Inject
|
||||
|
||||
@AndroidEntryPoint
|
||||
class TunnelBackgroundService : ForegroundService() {
|
||||
class TunnelBackgroundService : LifecycleService() {
|
||||
|
||||
@Inject
|
||||
lateinit var notificationService: NotificationService
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
private val foregroundId = 123
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
startForeground(foregroundId, createNotification())
|
||||
start()
|
||||
}
|
||||
|
||||
override fun startService(extras: Bundle?) {
|
||||
super.startService(extras)
|
||||
startForeground(foregroundId, createNotification())
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
super.onBind(intent)
|
||||
// We don't provide binding, so return null
|
||||
return null
|
||||
}
|
||||
|
||||
override fun stopService() {
|
||||
super.stopService()
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
serviceManager.backgroundService.complete(this)
|
||||
return super.onStartCommand(intent, flags, startId)
|
||||
}
|
||||
|
||||
fun start() {
|
||||
ServiceCompat.startForeground(
|
||||
this,
|
||||
foregroundId,
|
||||
createNotification(),
|
||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
||||
)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
serviceManager.backgroundService = CompletableDeferred()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun createNotification(): Notification {
|
||||
|
||||
+1
-27
@@ -5,8 +5,6 @@ import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.NetworkRequest
|
||||
import android.net.wifi.SupplicantState
|
||||
import android.net.wifi.WifiInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
@@ -21,7 +19,7 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
|
||||
private val connectivityManager =
|
||||
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
|
||||
private val wifiManager =
|
||||
val wifiManager =
|
||||
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
|
||||
override val networkStatus =
|
||||
@@ -83,30 +81,6 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
|
||||
|
||||
awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) }
|
||||
}
|
||||
|
||||
override fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
||||
var ssid: String? = getWifiNameFromCapabilities(networkCapabilities)
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
|
||||
val info = wifiManager.connectionInfo
|
||||
if (info.supplicantState === SupplicantState.COMPLETED) {
|
||||
ssid = info.ssid
|
||||
}
|
||||
}
|
||||
return ssid?.trim('"')
|
||||
}
|
||||
|
||||
companion object {
|
||||
private fun getWifiNameFromCapabilities(networkCapabilities: NetworkCapabilities): String? {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val info: WifiInfo
|
||||
if (networkCapabilities.transportInfo is WifiInfo) {
|
||||
info = networkCapabilities.transportInfo as WifiInfo
|
||||
return info.ssid
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <Result> Flow<NetworkStatus>.map(
|
||||
|
||||
+6
-1
@@ -10,4 +10,9 @@ class EthernetService
|
||||
constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) :
|
||||
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET)
|
||||
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET) {
|
||||
|
||||
override fun isNetworkSecure(): Boolean {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
+5
-1
@@ -10,4 +10,8 @@ class MobileDataService
|
||||
constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) :
|
||||
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR)
|
||||
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR) {
|
||||
override fun isNetworkSecure(): Boolean {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.network
|
||||
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.wifi.WifiInfo
|
||||
import android.os.Build
|
||||
|
||||
fun NetworkCapabilities.getWifiName(): String? {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val info: WifiInfo
|
||||
if (transportInfo is WifiInfo) {
|
||||
info = transportInfo as WifiInfo
|
||||
return info.ssid
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
+5
-1
@@ -4,7 +4,11 @@ import android.net.NetworkCapabilities
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface NetworkService<T> {
|
||||
fun getNetworkName(networkCapabilities: NetworkCapabilities): String?
|
||||
fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
||||
return null
|
||||
}
|
||||
|
||||
fun isNetworkSecure(): Boolean
|
||||
|
||||
val networkStatus: Flow<NetworkStatus>
|
||||
}
|
||||
|
||||
+20
-1
@@ -2,6 +2,8 @@ package com.zaneschepke.wireguardautotunnel.service.network
|
||||
|
||||
import android.content.Context
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.wifi.SupplicantState
|
||||
import android.os.Build
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
|
||||
@@ -10,4 +12,21 @@ class WifiService
|
||||
constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) :
|
||||
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI)
|
||||
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI) {
|
||||
|
||||
override fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
||||
var ssid = networkCapabilities.getWifiName()
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
|
||||
val info = wifiManager.connectionInfo
|
||||
if (info.supplicantState === SupplicantState.COMPLETED) {
|
||||
ssid = info.ssid
|
||||
}
|
||||
}
|
||||
return ssid?.trim('"')
|
||||
}
|
||||
|
||||
override fun isNetworkSecure(): Boolean {
|
||||
// TODO
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@ import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.SplashActivity
|
||||
import com.zaneschepke.wireguardautotunnel.ui.MainActivity
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
|
||||
@@ -63,7 +63,7 @@ constructor(
|
||||
}
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
val pendingIntent: PendingIntent =
|
||||
Intent(context, SplashActivity::class.java).let { notificationIntent ->
|
||||
Intent(context, MainActivity::class.java).let { notificationIntent ->
|
||||
PendingIntent.getActivity(
|
||||
context,
|
||||
0,
|
||||
|
||||
+8
-16
@@ -6,9 +6,8 @@ import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.Action
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.AutoTunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.stopTunnelBackground
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -24,6 +23,9 @@ class ShortcutsActivity : ComponentActivity() {
|
||||
@Inject
|
||||
lateinit var tunnelService: Provider<TunnelService>
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
@Inject
|
||||
@ApplicationScope
|
||||
lateinit var applicationScope: CoroutineScope
|
||||
@@ -44,26 +46,16 @@ class ShortcutsActivity : ComponentActivity() {
|
||||
Timber.d("Shortcut action on name: ${tunnelConfig?.name}")
|
||||
tunnelConfig?.let {
|
||||
when (intent.action) {
|
||||
Action.START.name -> this@ShortcutsActivity.startTunnelBackground(it.id)
|
||||
Action.STOP.name -> this@ShortcutsActivity.stopTunnelBackground(it.id)
|
||||
Action.START.name -> tunnelService.get().startTunnel(it, true)
|
||||
Action.STOP.name -> tunnelService.get().stopTunnel(it)
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
AutoTunnelService::class.java.simpleName, LEGACY_AUTO_TUNNEL_SERVICE_NAME -> {
|
||||
when (intent.action) {
|
||||
Action.START.name ->
|
||||
appDataRepository.settings.save(
|
||||
settings.copy(
|
||||
isAutoTunnelPaused = false,
|
||||
),
|
||||
)
|
||||
Action.STOP.name ->
|
||||
appDataRepository.settings.save(
|
||||
settings.copy(
|
||||
isAutoTunnelPaused = true,
|
||||
),
|
||||
)
|
||||
Action.START.name -> serviceManager.startAutoTunnel(true)
|
||||
Action.STOP.name -> serviceManager.stopAutoTunnel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+24
-61
@@ -1,7 +1,6 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.tile
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
@@ -9,7 +8,6 @@ import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
@@ -33,45 +31,9 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
||||
|
||||
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
|
||||
|
||||
/* This works around an annoying unsolved frameworks bug some people are hitting. */
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
var ret: IBinder? = null
|
||||
try {
|
||||
ret = super.onBind(intent)
|
||||
} catch (e: Throwable) {
|
||||
Timber.e("Failed to bind to AutoTunnelTile")
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||
|
||||
applicationScope.launch {
|
||||
appDataRepository.settings.getSettingsFlow().collect {
|
||||
kotlin.runCatching {
|
||||
when (it.isAutoTunnelEnabled) {
|
||||
true -> {
|
||||
if (it.isAutoTunnelPaused) {
|
||||
setInactive()
|
||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.paused))
|
||||
} else {
|
||||
setActive()
|
||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.active))
|
||||
}
|
||||
}
|
||||
|
||||
false -> {
|
||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.disabled))
|
||||
setUnavailable()
|
||||
}
|
||||
}
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStopListening() {
|
||||
@@ -86,26 +48,28 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
||||
override fun onStartListening() {
|
||||
super.onStartListening()
|
||||
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||
lifecycleScope.launch {
|
||||
if (appDataRepository.tunnels.getAll().isEmpty()) return@launch setUnavailable()
|
||||
updateTileState()
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateTileState() {
|
||||
serviceManager.autoTunnelActive.value.let {
|
||||
if (it) setActive() else setInactive()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
unlockAndRun {
|
||||
lifecycleScope.launch {
|
||||
kotlin.runCatching {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isAutoTunnelPaused) {
|
||||
return@launch appDataRepository.settings.save(
|
||||
settings.copy(
|
||||
isAutoTunnelPaused = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
appDataRepository.settings.save(
|
||||
settings.copy(
|
||||
isAutoTunnelPaused = true,
|
||||
),
|
||||
)
|
||||
if (serviceManager.autoTunnelActive.value) {
|
||||
serviceManager.stopAutoTunnel()
|
||||
setInactive()
|
||||
} else {
|
||||
serviceManager.startAutoTunnel(true)
|
||||
setActive()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,16 +96,15 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
||||
}
|
||||
}
|
||||
|
||||
private fun setTileDescription(description: String) {
|
||||
kotlin.runCatching {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
qsTile.subtitle = description
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
qsTile.stateDescription = description
|
||||
}
|
||||
qsTile.updateTile()
|
||||
/* This works around an annoying unsolved frameworks bug some people are hitting. */
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
var ret: IBinder? = null
|
||||
try {
|
||||
ret = super.onBind(intent)
|
||||
} catch (_: Throwable) {
|
||||
Timber.e("Failed to bind to TunnelControlTile")
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
override val lifecycle: Lifecycle
|
||||
|
||||
+20
-7
@@ -1,6 +1,8 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.tile
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
import androidx.lifecycle.Lifecycle
|
||||
@@ -11,8 +13,6 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.stopTunnelBackground
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -36,7 +36,6 @@ class TunnelControlTile : TileService(), LifecycleOwner {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
Timber.d("onCreate for tile service")
|
||||
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||
}
|
||||
|
||||
@@ -52,6 +51,7 @@ class TunnelControlTile : TileService(), LifecycleOwner {
|
||||
override fun onStartListening() {
|
||||
super.onStartListening()
|
||||
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||
Timber.d("Updating tile!")
|
||||
lifecycleScope.launch {
|
||||
if (appDataRepository.tunnels.getAll().isEmpty()) return@launch setUnavailable()
|
||||
updateTileState()
|
||||
@@ -68,13 +68,15 @@ class TunnelControlTile : TileService(), LifecycleOwner {
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
unlockAndRun {
|
||||
Timber.d("Click")
|
||||
lifecycleScope.launch {
|
||||
val context = this@TunnelControlTile
|
||||
val lastActive = appDataRepository.getStartTunnelConfig()
|
||||
lastActive?.let { tunnel ->
|
||||
if (tunnel.isActive) return@launch context.stopTunnelBackground(tunnel.id)
|
||||
context.startTunnelBackground(tunnel.id)
|
||||
if (tunnel.isActive) {
|
||||
tunnelService.get().stopTunnel(tunnel)
|
||||
} else {
|
||||
tunnelService.get().startTunnel(tunnel, true)
|
||||
}
|
||||
updateTileState()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -124,6 +126,17 @@ class TunnelControlTile : TileService(), LifecycleOwner {
|
||||
}
|
||||
}
|
||||
|
||||
/* This works around an annoying unsolved frameworks bug some people are hitting. */
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
var ret: IBinder? = null
|
||||
try {
|
||||
ret = super.onBind(intent)
|
||||
} catch (_: Throwable) {
|
||||
Timber.e("Failed to bind to TunnelControlTile")
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
override val lifecycle: Lifecycle
|
||||
get() = lifecycleRegistry
|
||||
}
|
||||
|
||||
+4
-1
@@ -5,10 +5,12 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
interface TunnelService : Tunnel, org.amnezia.awg.backend.Tunnel {
|
||||
suspend fun startTunnel(tunnelConfig: TunnelConfig): Result<TunnelState>
|
||||
suspend fun startTunnel(tunnelConfig: TunnelConfig, background: Boolean = false): Result<TunnelState>
|
||||
|
||||
suspend fun stopTunnel(tunnelConfig: TunnelConfig): Result<TunnelState>
|
||||
|
||||
suspend fun bounceTunnel(tunnelConfig: TunnelConfig): Result<TunnelState>
|
||||
|
||||
val vpnState: StateFlow<VpnState>
|
||||
|
||||
suspend fun runningTunnelNames(): Set<String>
|
||||
@@ -16,5 +18,6 @@ interface TunnelService : Tunnel, org.amnezia.awg.backend.Tunnel {
|
||||
suspend fun getState(): TunnelState
|
||||
|
||||
fun cancelStatsJob()
|
||||
|
||||
fun startStatsJob()
|
||||
}
|
||||
|
||||
+100
-45
@@ -2,25 +2,25 @@ package com.zaneschepke.wireguardautotunnel.service.tunnel
|
||||
|
||||
import com.wireguard.android.backend.Backend
|
||||
import com.wireguard.android.backend.Tunnel.State
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.TunnelConfigRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.module.Kernel
|
||||
import com.zaneschepke.wireguardautotunnel.module.Userspace
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.AmneziaStatistics
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.WireGuardStatistics
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.amnezia.awg.backend.Tunnel
|
||||
@@ -32,14 +32,31 @@ class WireGuardTunnel
|
||||
@Inject
|
||||
constructor(
|
||||
private val amneziaBackend: Provider<org.amnezia.awg.backend.Backend>,
|
||||
@Userspace private val userspaceBackend: Provider<Backend>,
|
||||
tunnelConfigRepository: TunnelConfigRepository,
|
||||
@Kernel private val kernelBackend: Provider<Backend>,
|
||||
private val appDataRepository: AppDataRepository,
|
||||
@ApplicationScope private val applicationScope: CoroutineScope,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
private val serviceManager: ServiceManager,
|
||||
) : TunnelService {
|
||||
|
||||
private val _vpnState = MutableStateFlow(VpnState())
|
||||
override val vpnState: StateFlow<VpnState> = _vpnState.asStateFlow()
|
||||
override val vpnState: StateFlow<VpnState> = _vpnState.combine(
|
||||
tunnelConfigRepository.getTunnelConfigsFlow(),
|
||||
) {
|
||||
vpnState, tunnels ->
|
||||
vpnState.copy(
|
||||
tunnelConfig = tunnels.firstOrNull { it.id == vpnState.tunnelConfig?.id },
|
||||
)
|
||||
}.stateIn(applicationScope, SharingStarted.Lazily, VpnState())
|
||||
|
||||
private var statsJob: Job? = null
|
||||
|
||||
private suspend fun backend(): Any {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isKernelEnabled) return kernelBackend.get()
|
||||
return amneziaBackend.get()
|
||||
}
|
||||
|
||||
override suspend fun runningTunnelNames(): Set<String> {
|
||||
return when (val backend = backend()) {
|
||||
@@ -49,8 +66,6 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
private var statsJob: Job? = null
|
||||
|
||||
private suspend fun setState(tunnelConfig: TunnelConfig, tunnelState: TunnelState): Result<TunnelState> {
|
||||
return runCatching {
|
||||
when (val backend = backend()) {
|
||||
@@ -74,44 +89,86 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun backend(): Any {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isKernelEnabled) return kernelBackend.get()
|
||||
if (settings.isAmneziaEnabled) return amneziaBackend.get()
|
||||
return userspaceBackend.get()
|
||||
}
|
||||
|
||||
override suspend fun startTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||
override suspend fun startTunnel(tunnelConfig: TunnelConfig, background: Boolean): Result<TunnelState> {
|
||||
return withContext(ioDispatcher) {
|
||||
if (_vpnState.value.status == TunnelState.UP) vpnState.value.tunnelConfig?.let { stopTunnel(it) }
|
||||
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = true))
|
||||
appDataRepository.appState.setLastActiveTunnelId(tunnelConfig.id)
|
||||
emitTunnelConfig(tunnelConfig)
|
||||
onBeforeStart(tunnelConfig, background)
|
||||
setState(tunnelConfig, TunnelState.UP).onSuccess {
|
||||
emitTunnelState(it)
|
||||
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||
}.onFailure {
|
||||
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = false))
|
||||
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||
Timber.e(it)
|
||||
onStartFailed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun stopTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||
return withContext(ioDispatcher) {
|
||||
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = false))
|
||||
onBeforeStop(tunnelConfig)
|
||||
setState(tunnelConfig, TunnelState.DOWN).onSuccess {
|
||||
emitTunnelState(it)
|
||||
resetBackendStatistics()
|
||||
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = true))
|
||||
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||
onStopFailed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// use this when we just want to bounce tunnel and not change tunnelConfig active state
|
||||
override suspend fun bounceTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||
toggleTunnel(tunnelConfig)
|
||||
delay(VPN_RESTART_DELAY)
|
||||
return toggleTunnel(tunnelConfig)
|
||||
}
|
||||
|
||||
private suspend fun toggleTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||
return withContext(ioDispatcher) {
|
||||
setState(tunnelConfig, TunnelState.TOGGLE).onSuccess {
|
||||
emitTunnelState(it)
|
||||
resetBackendStatistics()
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun onStopFailed() {
|
||||
_vpnState.value.tunnelConfig?.let {
|
||||
appDataRepository.tunnels.save(it.copy(isActive = true))
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun onStartFailed() {
|
||||
_vpnState.value.tunnelConfig?.let {
|
||||
appDataRepository.tunnels.save(it.copy(isActive = false))
|
||||
}
|
||||
cancelStatsJob()
|
||||
resetBackendStatistics()
|
||||
}
|
||||
|
||||
private suspend fun onBeforeStart(tunnelConfig: TunnelConfig, background: Boolean) {
|
||||
if (_vpnState.value.status == TunnelState.UP &&
|
||||
tunnelConfig != _vpnState.value.tunnelConfig
|
||||
) {
|
||||
vpnState.value.tunnelConfig?.let { stopTunnel(it) }
|
||||
}
|
||||
if (background) serviceManager.startBackgroundService()
|
||||
resetBackendStatistics()
|
||||
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = true))
|
||||
emitVpnStateConfig(tunnelConfig)
|
||||
startStatsJob()
|
||||
Timber.d("Updating start")
|
||||
serviceManager.requestTunnelTileUpdate()
|
||||
}
|
||||
|
||||
private suspend fun onBeforeStop(tunnelConfig: TunnelConfig) {
|
||||
cancelStatsJob()
|
||||
resetBackendStatistics()
|
||||
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = false))
|
||||
serviceManager.stopBackgroundService()
|
||||
Timber.d("UPdating stop")
|
||||
serviceManager.requestTunnelTileUpdate()
|
||||
}
|
||||
|
||||
private fun emitTunnelState(state: TunnelState) {
|
||||
_vpnState.tryEmit(
|
||||
_vpnState.value.copy(
|
||||
@@ -128,7 +185,7 @@ constructor(
|
||||
)
|
||||
}
|
||||
|
||||
private fun emitTunnelConfig(tunnelConfig: TunnelConfig?) {
|
||||
private fun emitVpnStateConfig(tunnelConfig: TunnelConfig) {
|
||||
_vpnState.tryEmit(
|
||||
_vpnState.value.copy(
|
||||
tunnelConfig = tunnelConfig,
|
||||
@@ -164,21 +221,9 @@ constructor(
|
||||
return _vpnState.value.tunnelConfig?.name ?: ""
|
||||
}
|
||||
|
||||
override fun onStateChange(newState: Tunnel.State) {
|
||||
handleStateChange(TunnelState.from(newState))
|
||||
}
|
||||
|
||||
private fun handleStateChange(state: TunnelState) {
|
||||
emitTunnelState(state)
|
||||
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||
when (state) {
|
||||
TunnelState.UP -> startStatsJob()
|
||||
else -> cancelStatsJob()
|
||||
}
|
||||
}
|
||||
|
||||
private fun startTunnelStatisticsJob() = applicationScope.launch(ioDispatcher) {
|
||||
val backend = backend()
|
||||
delay(STATS_START_DELAY)
|
||||
while (true) {
|
||||
when (backend) {
|
||||
is Backend -> emitBackendStatistics(
|
||||
@@ -192,11 +237,21 @@ constructor(
|
||||
)
|
||||
}
|
||||
}
|
||||
delay(Constants.VPN_STATISTIC_CHECK_INTERVAL)
|
||||
delay(VPN_STATISTIC_CHECK_INTERVAL)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStateChange(newState: Tunnel.State) {
|
||||
emitTunnelState(TunnelState.from(newState))
|
||||
}
|
||||
|
||||
override fun onStateChange(state: State) {
|
||||
handleStateChange(TunnelState.from(state))
|
||||
emitTunnelState(TunnelState.from(state))
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val STATS_START_DELAY = 5_000L
|
||||
const val VPN_STATISTIC_CHECK_INTERVAL = 1_000L
|
||||
const val VPN_RESTART_DELAY = 1_000L
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||
|
||||
data class AppUiState(
|
||||
val snackbarMessage: String = "",
|
||||
val snackbarMessageConsumed: Boolean = true,
|
||||
val notificationPermissionAccepted: Boolean = false,
|
||||
val requestPermissions: Boolean = false,
|
||||
val settings: Settings = Settings(),
|
||||
val tunnels: List<TunnelConfig> = emptyList(),
|
||||
val vpnState: VpnState = VpnState(),
|
||||
val generalState: GeneralState = GeneralState(),
|
||||
val autoTunnelActive: Boolean = false,
|
||||
)
|
||||
|
||||
@@ -2,47 +2,100 @@ package com.zaneschepke.wireguardautotunnel.ui
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.onCompletion
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.takeWhile
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.plus
|
||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@HiltViewModel
|
||||
class AppViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
private val tunnelService: Provider<TunnelService>,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
private val serviceManager: ServiceManager,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _appUiState =
|
||||
MutableStateFlow(
|
||||
val uiState =
|
||||
combine(
|
||||
appDataRepository.settings.getSettingsFlow(),
|
||||
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
||||
tunnelService.get().vpnState,
|
||||
appDataRepository.appState.generalStateFlow,
|
||||
serviceManager.autoTunnelActive,
|
||||
) { settings, tunnels, tunnelState, generalState, autoTunnel ->
|
||||
AppUiState(
|
||||
settings,
|
||||
tunnels,
|
||||
tunnelState,
|
||||
generalState,
|
||||
autoTunnel,
|
||||
)
|
||||
}.stateIn(
|
||||
viewModelScope + ioDispatcher,
|
||||
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||
AppUiState(),
|
||||
)
|
||||
val appUiState = _appUiState.asStateFlow()
|
||||
|
||||
fun showSnackbarMessage(message: String) {
|
||||
_appUiState.update {
|
||||
it.copy(
|
||||
snackbarMessage = message,
|
||||
snackbarMessageConsumed = false,
|
||||
)
|
||||
private val _isAppReady = MutableStateFlow<Boolean>(false)
|
||||
val isAppReady = _isAppReady.asStateFlow()
|
||||
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
initPin()
|
||||
initAutoTunnel()
|
||||
initTunnel()
|
||||
appReadyCheck()
|
||||
}
|
||||
}
|
||||
|
||||
fun snackbarMessageConsumed() {
|
||||
_appUiState.update {
|
||||
it.copy(
|
||||
snackbarMessage = "",
|
||||
snackbarMessageConsumed = true,
|
||||
)
|
||||
private suspend fun appReadyCheck() {
|
||||
val tunnelCount = appDataRepository.tunnels.count()
|
||||
uiState.takeWhile { it.tunnels.size != tunnelCount }.onCompletion {
|
||||
_isAppReady.emit(true)
|
||||
}.collect()
|
||||
}
|
||||
|
||||
private suspend fun initTunnel() {
|
||||
if (tunnelService.get().getState() == TunnelState.UP) tunnelService.get().startStatsJob()
|
||||
val activeTunnels = appDataRepository.tunnels.getActive()
|
||||
if (activeTunnels.isNotEmpty() &&
|
||||
tunnelService.get().getState() == TunnelState.DOWN
|
||||
) {
|
||||
tunnelService.get().startTunnel(activeTunnels.first())
|
||||
}
|
||||
}
|
||||
|
||||
fun onPinLockDisabled() = viewModelScope.launch {
|
||||
private suspend fun initPin() {
|
||||
val isPinEnabled = appDataRepository.appState.isPinLockEnabled()
|
||||
if (isPinEnabled) PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||
}
|
||||
|
||||
private suspend fun initAutoTunnel() {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isAutoTunnelEnabled) serviceManager.startAutoTunnel(false)
|
||||
}
|
||||
|
||||
fun onPinLockDisabled() = viewModelScope.launch(ioDispatcher) {
|
||||
PinManager.clearPin()
|
||||
appDataRepository.appState.setPinLockEnabled(false)
|
||||
}
|
||||
@@ -50,4 +103,8 @@ constructor(
|
||||
fun onPinLockEnabled() = viewModelScope.launch {
|
||||
appDataRepository.appState.setPinLockEnabled(true)
|
||||
}
|
||||
|
||||
fun setLocationDisclosureShown() = viewModelScope.launch {
|
||||
appDataRepository.appState.setLocationDisclosureShown(true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,229 +1,225 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import androidx.activity.SystemBarStyle
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.viewModels
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Home
|
||||
import androidx.compose.material.icons.rounded.QuestionMark
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarData
|
||||
import androidx.compose.material3.SnackbarDuration
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.SnackbarResult
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.navigation.NavType
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import androidx.navigation.navArgument
|
||||
import androidx.navigation.toRoute
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.datastore.LocaleStorage
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalFocusRequester
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.CustomSnackBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarControllerProvider
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.options.OptionsScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.pinlock.PinLockScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.scanner.ScannerScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.SettingsScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.AppearanceScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.display.DisplayScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.language.LanguageScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.AutoTunnelScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.disclosure.LocationDisclosureScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.support.SupportScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.support.logs.LogsScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.WireguardAutoTunnelTheme
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
|
||||
@AndroidEntryPoint
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
private val localeStorage: LocaleStorage by lazy {
|
||||
(application as WireGuardAutoTunnel).localeStorage
|
||||
}
|
||||
|
||||
private lateinit var oldPrefLocaleCode: String
|
||||
|
||||
@Inject
|
||||
lateinit var appStateRepository: AppStateRepository
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelService: TunnelService
|
||||
|
||||
private val viewModel by viewModels<AppViewModel>()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
val isPinLockEnabled = intent.extras?.getBoolean(SplashActivity.IS_PIN_LOCK_ENABLED_KEY)
|
||||
|
||||
enableEdgeToEdge(navigationBarStyle = SystemBarStyle.dark(Color.Transparent.toArgb()))
|
||||
installSplashScreen().apply {
|
||||
setKeepOnScreenCondition {
|
||||
!viewModel.isAppReady.value
|
||||
}
|
||||
}
|
||||
|
||||
setContent {
|
||||
val appViewModel = hiltViewModel<AppViewModel>()
|
||||
val appUiState by appViewModel.appUiState.collectAsStateWithLifecycle()
|
||||
val appUiState by viewModel.uiState.collectAsStateWithLifecycle(lifecycle = this.lifecycle)
|
||||
val navController = rememberNavController()
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val rootItemFocusRequester = remember { FocusRequester() }
|
||||
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
LaunchedEffect(appUiState.tunnels) {
|
||||
Timber.d("Updating launched")
|
||||
requestTunnelTileServiceStateUpdate()
|
||||
}
|
||||
|
||||
fun showSnackBarMessage(message: StringValue) {
|
||||
lifecycleScope.launch(Dispatchers.Main) {
|
||||
val result =
|
||||
snackbarHostState.showSnackbar(
|
||||
message = message.asString(this@MainActivity),
|
||||
duration = SnackbarDuration.Short,
|
||||
)
|
||||
when (result) {
|
||||
SnackbarResult.ActionPerformed,
|
||||
SnackbarResult.Dismissed,
|
||||
-> {
|
||||
snackbarHostState.currentSnackbarData?.dismiss()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(appUiState.autoTunnelActive) {
|
||||
requestAutoTunnelTileServiceUpdate()
|
||||
}
|
||||
|
||||
with(appUiState.settings) {
|
||||
LaunchedEffect(isAutoTunnelEnabled) {
|
||||
this@MainActivity.requestAutoTunnelTileServiceUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
WireguardAutoTunnelTheme {
|
||||
LaunchedEffect(appUiState.snackbarMessageConsumed) {
|
||||
if (!appUiState.snackbarMessageConsumed) {
|
||||
showSnackBarMessage(StringValue.DynamicString(appUiState.snackbarMessage))
|
||||
appViewModel.snackbarMessageConsumed()
|
||||
}
|
||||
}
|
||||
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
|
||||
Scaffold(
|
||||
snackbarHost = {
|
||||
SnackbarHost(snackbarHostState) { snackbarData: SnackbarData ->
|
||||
CustomSnackBar(
|
||||
snackbarData.visuals.message,
|
||||
isRtl = false,
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceColorAtElevation(
|
||||
2.dp,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
containerColor = MaterialTheme.colorScheme.background,
|
||||
modifier =
|
||||
Modifier
|
||||
.focusable()
|
||||
.focusProperties {
|
||||
when (navBackStackEntry?.destination?.route) {
|
||||
Screen.Lock.route -> Unit
|
||||
else -> up = focusRequester
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
BottomNavBar(
|
||||
navController,
|
||||
listOf(
|
||||
Screen.Main.navItem,
|
||||
Screen.Settings.navItem,
|
||||
Screen.Support.navItem,
|
||||
),
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Surface(modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||
NavHost(
|
||||
navController,
|
||||
enterTransition = { fadeIn(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||
exitTransition = { fadeOut(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||
startDestination = (if (isPinLockEnabled == true) Screen.Lock.route else Screen.Main.route),
|
||||
) {
|
||||
composable(
|
||||
Screen.Main.route,
|
||||
) {
|
||||
MainScreen(
|
||||
focusRequester = focusRequester,
|
||||
appViewModel = appViewModel,
|
||||
navController = navController,
|
||||
)
|
||||
}
|
||||
composable(
|
||||
Screen.Settings.route,
|
||||
) {
|
||||
SettingsScreen(
|
||||
appViewModel = appViewModel,
|
||||
navController = navController,
|
||||
focusRequester = focusRequester,
|
||||
)
|
||||
}
|
||||
composable(
|
||||
Screen.Support.route,
|
||||
) {
|
||||
SupportScreen(
|
||||
focusRequester = focusRequester,
|
||||
navController = navController,
|
||||
)
|
||||
}
|
||||
composable(Screen.Support.Logs.route) {
|
||||
LogsScreen()
|
||||
}
|
||||
composable(
|
||||
"${Screen.Config.route}/{id}?configType={configType}",
|
||||
arguments =
|
||||
listOf(
|
||||
navArgument("id") {
|
||||
type = NavType.StringType
|
||||
defaultValue = "0"
|
||||
},
|
||||
navArgument("configType") {
|
||||
type = NavType.StringType
|
||||
defaultValue = ConfigType.WIREGUARD.name
|
||||
},
|
||||
),
|
||||
) {
|
||||
val id = it.arguments?.getString("id")
|
||||
val configType =
|
||||
ConfigType.valueOf(
|
||||
it.arguments?.getString("configType") ?: ConfigType.WIREGUARD.name,
|
||||
)
|
||||
if (!id.isNullOrBlank()) {
|
||||
ConfigScreen(
|
||||
navController = navController,
|
||||
tunnelId = id,
|
||||
appViewModel = appViewModel,
|
||||
focusRequester = focusRequester,
|
||||
configType = configType,
|
||||
CompositionLocalProvider(LocalFocusRequester provides rootItemFocusRequester) {
|
||||
CompositionLocalProvider(LocalNavController provides navController) {
|
||||
SnackbarControllerProvider { host ->
|
||||
WireguardAutoTunnelTheme(theme = appUiState.generalState.theme) {
|
||||
Scaffold(
|
||||
contentWindowInsets = WindowInsets(0.dp),
|
||||
snackbarHost = {
|
||||
SnackbarHost(host) { snackbarData: SnackbarData ->
|
||||
CustomSnackBar(
|
||||
snackbarData.visuals.message,
|
||||
isRtl = false,
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceColorAtElevation(
|
||||
2.dp,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
BottomNavBar(
|
||||
navController,
|
||||
listOf(
|
||||
BottomNavItem(
|
||||
name = stringResource(R.string.tunnels),
|
||||
route = Route.Main,
|
||||
icon = Icons.Rounded.Home,
|
||||
),
|
||||
BottomNavItem(
|
||||
name = stringResource(R.string.settings),
|
||||
route = Route.Settings,
|
||||
icon = Icons.Rounded.Settings,
|
||||
),
|
||||
BottomNavItem(
|
||||
name = stringResource(R.string.support),
|
||||
route = Route.Support,
|
||||
icon = Icons.Rounded.QuestionMark,
|
||||
),
|
||||
),
|
||||
)
|
||||
},
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize().padding(it)) {
|
||||
NavHost(
|
||||
navController,
|
||||
enterTransition = { fadeIn(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||
exitTransition = { fadeOut(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||
startDestination = (if (appUiState.generalState.isPinLockEnabled == true) Route.Lock else Route.Main),
|
||||
) {
|
||||
composable<Route.Main> {
|
||||
MainScreen(
|
||||
uiState = appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.Settings> {
|
||||
SettingsScreen(
|
||||
appViewModel = viewModel,
|
||||
uiState = appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.LocationDisclosure> {
|
||||
LocationDisclosureScreen(viewModel, appUiState)
|
||||
}
|
||||
composable<Route.AutoTunnel> {
|
||||
AutoTunnelScreen(
|
||||
appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.Appearance> {
|
||||
AppearanceScreen()
|
||||
}
|
||||
composable<Route.Language> {
|
||||
LanguageScreen(localeStorage)
|
||||
}
|
||||
composable<Route.Display> {
|
||||
DisplayScreen(appUiState)
|
||||
}
|
||||
composable<Route.Support> {
|
||||
SupportScreen()
|
||||
}
|
||||
composable<Route.Logs> {
|
||||
LogsScreen()
|
||||
}
|
||||
composable<Route.Config> {
|
||||
val args = it.toRoute<Route.Config>()
|
||||
ConfigScreen(
|
||||
tunnelId = args.id,
|
||||
)
|
||||
}
|
||||
composable<Route.Option> {
|
||||
val args = it.toRoute<Route.Option>()
|
||||
OptionsScreen(
|
||||
tunnelId = args.id,
|
||||
appUiState = appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.Lock> {
|
||||
PinLockScreen(
|
||||
appViewModel = viewModel,
|
||||
)
|
||||
}
|
||||
composable<Route.Scanner> {
|
||||
ScannerScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
composable("${Screen.Option.route}/{id}") {
|
||||
val id = it.arguments?.getString("id")
|
||||
if (!id.isNullOrBlank()) {
|
||||
OptionsScreen(
|
||||
navController = navController,
|
||||
tunnelId = id,
|
||||
appViewModel = appViewModel,
|
||||
focusRequester = focusRequester,
|
||||
)
|
||||
}
|
||||
}
|
||||
composable(Screen.Lock.route) {
|
||||
PinLockScreen(
|
||||
navController = navController,
|
||||
appViewModel = appViewModel,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,6 +227,21 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun attachBaseContext(newBase: Context) {
|
||||
oldPrefLocaleCode = LocaleStorage(newBase).getPreferredLocale()
|
||||
applyOverrideConfiguration(LocaleUtil.getLocalizedConfiguration(oldPrefLocaleCode))
|
||||
super.attachBaseContext(newBase)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
val currentLocaleCode = LocaleStorage(this).getPreferredLocale()
|
||||
if (oldPrefLocaleCode != currentLocaleCode) {
|
||||
recreate() // locale is changed, restart the activity to update
|
||||
oldPrefLocaleCode = currentLocaleCode
|
||||
}
|
||||
super.onResume()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
tunnelService.cancelStatsJob()
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
sealed class Route {
|
||||
@Serializable
|
||||
data object Support : Route()
|
||||
|
||||
@Serializable
|
||||
data object Settings : Route()
|
||||
|
||||
@Serializable
|
||||
data object AutoTunnel : Route()
|
||||
|
||||
@Serializable
|
||||
data object LocationDisclosure : Route()
|
||||
|
||||
@Serializable
|
||||
data object Appearance : Route()
|
||||
|
||||
@Serializable
|
||||
data object Display : Route()
|
||||
|
||||
@Serializable
|
||||
data object Language : Route()
|
||||
|
||||
@Serializable
|
||||
data object Main : Route()
|
||||
|
||||
@Serializable
|
||||
data class Option(
|
||||
val id: Int,
|
||||
) : Route()
|
||||
|
||||
@Serializable
|
||||
data object Lock : Route()
|
||||
|
||||
@Serializable
|
||||
data object Scanner : Route()
|
||||
|
||||
@Serializable
|
||||
data class Config(
|
||||
val id: Int,
|
||||
) : Route()
|
||||
|
||||
@Serializable
|
||||
data object Logs : Route()
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Home
|
||||
import androidx.compose.material.icons.rounded.QuestionMark
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem
|
||||
|
||||
sealed class Screen(val route: String) {
|
||||
data object Main : Screen("main") {
|
||||
val navItem =
|
||||
BottomNavItem(
|
||||
name = WireGuardAutoTunnel.instance.getString(R.string.tunnels),
|
||||
route = route,
|
||||
icon = Icons.Rounded.Home,
|
||||
)
|
||||
}
|
||||
|
||||
data object Settings : Screen("settings") {
|
||||
val navItem =
|
||||
BottomNavItem(
|
||||
name = WireGuardAutoTunnel.instance.getString(R.string.settings),
|
||||
route = route,
|
||||
icon = Icons.Rounded.Settings,
|
||||
)
|
||||
}
|
||||
|
||||
data object Support : Screen("support") {
|
||||
val navItem =
|
||||
BottomNavItem(
|
||||
name = WireGuardAutoTunnel.instance.getString(R.string.support),
|
||||
route = route,
|
||||
icon = Icons.Rounded.QuestionMark,
|
||||
)
|
||||
|
||||
data object Logs : Screen("support/logs")
|
||||
}
|
||||
|
||||
data object Config : Screen("config")
|
||||
|
||||
data object Lock : Screen("lock")
|
||||
|
||||
data object Option : Screen("option")
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.launch
|
||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@SuppressLint("CustomSplashScreen")
|
||||
@AndroidEntryPoint
|
||||
class SplashActivity : ComponentActivity() {
|
||||
@Inject
|
||||
lateinit var appStateRepository: AppStateRepository
|
||||
|
||||
@Inject
|
||||
lateinit var appDataRepository: AppDataRepository
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelService: Provider<TunnelService>
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val splashScreen = installSplashScreen()
|
||||
splashScreen.setKeepOnScreenCondition { true }
|
||||
}
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.CREATED) {
|
||||
val pinLockEnabled = appStateRepository.isPinLockEnabled()
|
||||
if (pinLockEnabled) {
|
||||
PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||
}
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isAutoTunnelEnabled) serviceManager.startWatcherService(application.applicationContext)
|
||||
if (tunnelService.get().getState() == TunnelState.UP) tunnelService.get().startStatsJob()
|
||||
val tunnels = appDataRepository.tunnels.getActive()
|
||||
if (tunnels.isNotEmpty() && tunnelService.get().getState() == TunnelState.DOWN) tunnelService.get().startTunnel(tunnels.first())
|
||||
requestTunnelTileServiceStateUpdate()
|
||||
requestAutoTunnelTileServiceUpdate()
|
||||
|
||||
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"
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -12,12 +13,12 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
|
||||
@Composable
|
||||
fun ClickableIconButton(onClick: () -> Unit, onIconClick: () -> Unit, text: String, icon: ImageVector, enabled: Boolean) {
|
||||
fun ClickableIconButton(onClick: () -> Unit, onIconClick: () -> Unit, text: String, icon: ImageVector, enabled: Boolean = true) {
|
||||
TextButton(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
) {
|
||||
Text(text, Modifier.weight(1f, false))
|
||||
Text(text, Modifier.weight(1f, false), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary)
|
||||
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun ExpandingRowListItem(
|
||||
leading: @Composable () -> Unit,
|
||||
text: String,
|
||||
onHold: () -> Unit = {},
|
||||
onClick: () -> Unit,
|
||||
trailing: @Composable () -> Unit,
|
||||
isExpanded: Boolean,
|
||||
expanded: @Composable () -> Unit = {},
|
||||
) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.animateContentSize()
|
||||
.clip(RoundedCornerShape(30.dp))
|
||||
.combinedClickable(
|
||||
onClick = { onClick() },
|
||||
onLongClick = { onHold() },
|
||||
),
|
||||
) {
|
||||
Column {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 15.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(15.dp),
|
||||
modifier = Modifier.fillMaxWidth(13 / 20f),
|
||||
) {
|
||||
leading()
|
||||
Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
trailing()
|
||||
}
|
||||
if (isExpanded) expanded()
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
|
||||
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
|
||||
|
||||
class NestedScrollListener(val onUp: () -> Unit, val onDown: () -> Unit) : NestedScrollConnection {
|
||||
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
|
||||
if (available.y < -1) onDown()
|
||||
if (available.y > 1) onUp()
|
||||
return Offset.Zero
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.toThreeDecimalPlaceString
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun RowListItem(
|
||||
icon: @Composable () -> Unit,
|
||||
text: String,
|
||||
onHold: () -> Unit,
|
||||
onClick: () -> Unit,
|
||||
rowButton: @Composable () -> Unit,
|
||||
expanded: Boolean,
|
||||
statistics: TunnelStatistics?,
|
||||
focusRequester: FocusRequester,
|
||||
) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.focusRequester(focusRequester)
|
||||
.animateContentSize()
|
||||
.clip(RoundedCornerShape(30.dp))
|
||||
.combinedClickable(
|
||||
onClick = { onClick() },
|
||||
onLongClick = { onHold() },
|
||||
),
|
||||
) {
|
||||
Column {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 15.dp, vertical = 5.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(13 / 20f),
|
||||
) {
|
||||
icon()
|
||||
Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
rowButton()
|
||||
}
|
||||
if (expanded) {
|
||||
statistics?.getPeers()?.forEach {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(end = 10.dp, bottom = 10.dp, start = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||
) {
|
||||
// TODO change these to string resources
|
||||
val handshakeEpoch = statistics.peerStats(it)!!.latestHandshakeEpochMillis
|
||||
val peerTx = statistics.peerStats(it)!!.txBytes
|
||||
val peerRx = statistics.peerStats(it)!!.rxBytes
|
||||
val peerId = it.toBase64().subSequence(0, 3).toString() + "***"
|
||||
val handshakeSec =
|
||||
NumberUtils.getSecondsBetweenTimestampAndNow(handshakeEpoch)
|
||||
val handshake =
|
||||
if (handshakeSec == null) "never" else "$handshakeSec secs ago"
|
||||
val peerTxMB = NumberUtils.bytesToMB(peerTx).toThreeDecimalPlaceString()
|
||||
val peerRxMB = NumberUtils.bytesToMB(peerRx).toThreeDecimalPlaceString()
|
||||
val fontSize = 9.sp
|
||||
Text("peer: $peerId", fontSize = fontSize)
|
||||
Text("handshake: $handshake", fontSize = fontSize)
|
||||
Text("tx: $peerTxMB MB", fontSize = fontSize)
|
||||
Text("rx: $peerRxMB MB", fontSize = fontSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun SelectedLabel() {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
stringResource(id = R.string.selected),
|
||||
modifier =
|
||||
Modifier.padding(
|
||||
horizontal = 24.dp.scaledWidth(),
|
||||
vertical = 16.dp.scaledHeight(),
|
||||
),
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
import kotlin.let
|
||||
|
||||
@androidx.compose.runtime.Composable
|
||||
fun IconSurfaceButton(title: String, onClick: () -> Unit, selected: Boolean, leadingIcon: ImageVector? = null, description: String? = null) {
|
||||
val border: BorderStroke? =
|
||||
if (selected) {
|
||||
BorderStroke(
|
||||
1.dp,
|
||||
MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
Card(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(IntrinsicSize.Min),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
border = border,
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.clickable { onClick() }
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(horizontal = 8.dp.scaledWidth(), vertical = 10.dp.scaledHeight())
|
||||
.padding(end = 16.dp.scaledWidth()).padding(start = 8.dp.scaledWidth())
|
||||
.fillMaxSize(),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.Start,
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.Companion.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp.scaledWidth()),
|
||||
) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(
|
||||
16.dp.scaledWidth(),
|
||||
),
|
||||
verticalAlignment = Alignment.Companion.CenterVertically,
|
||||
modifier = Modifier.padding(vertical = if (description == null) 10.dp.scaledHeight() else 0.dp),
|
||||
) {
|
||||
leadingIcon?.let {
|
||||
Icon(
|
||||
leadingIcon,
|
||||
leadingIcon.name,
|
||||
Modifier.size(iconSize),
|
||||
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
Column {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
description?.let {
|
||||
Text(
|
||||
description,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button
|
||||
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
|
||||
@Composable
|
||||
fun ScaledSwitch(checked: Boolean, onClick: (checked: Boolean) -> Unit, enabled: Boolean = true, modifier: Modifier = Modifier) {
|
||||
Switch(
|
||||
checked,
|
||||
{ onClick(it) },
|
||||
modifier.scale((52.dp.scaledHeight() / 52.dp)),
|
||||
enabled = enabled,
|
||||
)
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.ripple
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
|
||||
@Composable
|
||||
fun SelectionItemButton(
|
||||
leading: (@Composable () -> Unit)? = null,
|
||||
buttonText: String,
|
||||
trailing: (@Composable () -> Unit)? = null,
|
||||
onClick: () -> Unit,
|
||||
ripple: Boolean = true,
|
||||
) {
|
||||
Card(
|
||||
modifier =
|
||||
Modifier.clip(RoundedCornerShape(8.dp))
|
||||
.clickable(
|
||||
indication = if (ripple) ripple() else null,
|
||||
interactionSource = remember { MutableInteractionSource() },
|
||||
onClick = { onClick() },
|
||||
)
|
||||
.height(56.dp.scaledHeight()),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.background,
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
leading?.let {
|
||||
it()
|
||||
}
|
||||
Text(
|
||||
buttonText,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
trailing?.let {
|
||||
it()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button.surface
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
|
||||
data class SelectionItem(
|
||||
val leadingIcon: ImageVector? = null,
|
||||
val trailing: (@Composable () -> Unit)? = null,
|
||||
val title: (@Composable () -> Unit),
|
||||
val description: (@Composable () -> Unit)? = null,
|
||||
val onClick: (() -> Unit)? = null,
|
||||
val height: Int = 64,
|
||||
)
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button.surface
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun SurfaceSelectionGroupButton(items: List<SelectionItem>) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
) {
|
||||
items.mapIndexed { index, item ->
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier
|
||||
.then(item.onClick?.let { Modifier.clickable { it() } } ?: Modifier)
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp.scaledHeight()),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.padding(start = 16.dp.scaledWidth())
|
||||
.weight(4f, false)
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
item.leadingIcon?.let { icon ->
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier = Modifier.size(iconSize),
|
||||
)
|
||||
}
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterVertically),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = if (item.leadingIcon != null) 16.dp.scaledWidth() else 0.dp)
|
||||
.padding(vertical = if (item.description == null) 16.dp.scaledHeight() else 6.dp.scaledHeight()),
|
||||
) {
|
||||
item.title()
|
||||
item.description?.let {
|
||||
it()
|
||||
}
|
||||
}
|
||||
}
|
||||
item.trailing?.let {
|
||||
Box(
|
||||
contentAlignment = Alignment.CenterEnd,
|
||||
modifier = Modifier
|
||||
.padding(end = 24.dp.scaledWidth(), start = 16.dp.scaledWidth())
|
||||
.weight(1f),
|
||||
) {
|
||||
it()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (index + 1 != items.size) HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
-6
@@ -1,5 +1,6 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.config
|
||||
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
@@ -14,23 +15,29 @@ fun ConfigurationTextBox(
|
||||
value: String,
|
||||
hint: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
keyboardActions: KeyboardActions,
|
||||
keyboardActions: KeyboardActions = KeyboardActions(),
|
||||
label: String,
|
||||
modifier: Modifier,
|
||||
isError: Boolean = false,
|
||||
keyboardOptions: KeyboardOptions = KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
trailing: @Composable () -> Unit = {},
|
||||
interactionSource: MutableInteractionSource? = null,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
isError = isError,
|
||||
modifier = modifier,
|
||||
value = value,
|
||||
singleLine = true,
|
||||
interactionSource = interactionSource,
|
||||
onValueChange = { onValueChange(it) },
|
||||
label = { Text(label) },
|
||||
maxLines = 1,
|
||||
placeholder = { Text(hint) },
|
||||
keyboardOptions =
|
||||
KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardOptions = keyboardOptions,
|
||||
keyboardActions = keyboardActions,
|
||||
trailingIcon = trailing,
|
||||
)
|
||||
}
|
||||
|
||||
+11
-6
@@ -3,28 +3,33 @@ package com.zaneschepke.wireguardautotunnel.ui.common.config
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.Dp
|
||||
|
||||
@Composable
|
||||
fun ConfigurationToggle(label: String, enabled: Boolean, checked: Boolean, padding: Dp, onCheckChanged: () -> Unit, modifier: Modifier = Modifier) {
|
||||
fun ConfigurationToggle(
|
||||
label: String,
|
||||
enabled: Boolean = true,
|
||||
checked: Boolean,
|
||||
onCheckChanged: (checked: Boolean) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(padding),
|
||||
.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(
|
||||
label,
|
||||
textAlign = TextAlign.Start,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier =
|
||||
Modifier
|
||||
.weight(
|
||||
@@ -37,7 +42,7 @@ fun ConfigurationToggle(label: String, enabled: Boolean, checked: Boolean, paddi
|
||||
modifier = modifier,
|
||||
enabled = enabled,
|
||||
checked = checked,
|
||||
onCheckedChange = { onCheckChanged() },
|
||||
onCheckedChange = { onCheckChanged(it) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.config
|
||||
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Save
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
|
||||
@Composable
|
||||
fun SubmitConfigurationTextBox(
|
||||
value: String?,
|
||||
label: String,
|
||||
hint: String,
|
||||
isErrorValue: (value: String?) -> Boolean,
|
||||
onSubmit: (value: String) -> Unit,
|
||||
keyboardOptions: KeyboardOptions = KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
) {
|
||||
val focusManager = LocalFocusManager.current
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val isFocused by interactionSource.collectIsFocusedAsState()
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
|
||||
var stateValue by remember { mutableStateOf(value ?: "") }
|
||||
|
||||
OutlinedTextField(
|
||||
isError = isErrorValue(stateValue),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(),
|
||||
value = stateValue,
|
||||
singleLine = true,
|
||||
interactionSource = interactionSource,
|
||||
onValueChange = { stateValue = it },
|
||||
label = { Text(label) },
|
||||
maxLines = 1,
|
||||
placeholder = { Text(hint) },
|
||||
keyboardOptions = keyboardOptions,
|
||||
keyboardActions = KeyboardActions(
|
||||
onDone = {
|
||||
onSubmit(stateValue)
|
||||
keyboardController?.hide()
|
||||
},
|
||||
),
|
||||
trailingIcon = {
|
||||
if (!isErrorValue(stateValue) && isFocused) {
|
||||
IconButton(onClick = {
|
||||
onSubmit(stateValue)
|
||||
keyboardController?.hide()
|
||||
focusManager.clearFocus()
|
||||
}) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Save,
|
||||
contentDescription = stringResource(R.string.save_changes),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
+8
-1
@@ -10,13 +10,20 @@ import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.Composable
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
|
||||
@Composable
|
||||
fun rememberFileImportLauncherForResult(onNoFileExplorer: () -> Unit, onData: (data: Uri) -> Unit): ManagedActivityResultLauncher<String, Uri?> {
|
||||
return rememberLauncherForActivityResult(
|
||||
object : ActivityResultContracts.GetContent() {
|
||||
override fun createIntent(context: Context, input: String): Intent {
|
||||
val intent = super.createIntent(context, input)
|
||||
val intent = super.createIntent(context, input).apply {
|
||||
type = if (context.isRunningOnTv()) {
|
||||
Constants.ALLOWED_TV_FILE_TYPES
|
||||
} else {
|
||||
Constants.ALL_FILE_TYPES
|
||||
}
|
||||
}
|
||||
|
||||
/* AndroidTV now comes with stubs that do nothing but display a Toast less helpful than
|
||||
* what we can do, so detect this and throw an exception that we can catch later. */
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.label
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
|
||||
@Composable
|
||||
fun GroupLabel(title: String) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.label
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import com.zaneschepke.wireguardautotunnel.BuildConfig
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
|
||||
@Composable
|
||||
fun VersionLabel() {
|
||||
val clipboardManager = LocalClipboardManager.current
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
) {
|
||||
Text(
|
||||
"${stringResource(R.string.version)}: ${BuildConfig.VERSION_NAME}",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.outline,
|
||||
modifier = Modifier.clickable {
|
||||
clipboardManager.setText(AnnotatedString(BuildConfig.VERSION_NAME))
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -10,7 +10,6 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.navigation.NavController
|
||||
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
@@ -20,19 +19,20 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
|
||||
var showBottomBar by rememberSaveable { mutableStateOf(true) }
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
|
||||
showBottomBar = bottomNavItems.firstOrNull { navBackStackEntry?.destination?.route?.contains(it.route) == true } != null
|
||||
showBottomBar = bottomNavItems.any {
|
||||
navBackStackEntry?.isCurrentRoute(it.route::class) == true
|
||||
}
|
||||
|
||||
if (showBottomBar) {
|
||||
NavigationBar(
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
) {
|
||||
bottomNavItems.forEach { item ->
|
||||
val selected = navBackStackEntry?.destination?.route?.contains(item.route) == true
|
||||
|
||||
bottomNavItems.forEachIndexed { index, item ->
|
||||
val selected = navBackStackEntry.isCurrentRoute(item.route::class)
|
||||
NavigationBarItem(
|
||||
selected = selected,
|
||||
onClick = {
|
||||
if (navBackStackEntry?.destination?.route == item.route) return@NavigationBarItem
|
||||
if (selected) return@NavigationBarItem
|
||||
navController.navigate(item.route) {
|
||||
// Pop up to the start destination of the graph to
|
||||
// avoid building up a large stack of destinations
|
||||
@@ -48,7 +48,7 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
|
||||
label = {
|
||||
Text(
|
||||
text = item.name,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
)
|
||||
},
|
||||
icon = {
|
||||
|
||||
+2
-1
@@ -1,9 +1,10 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
|
||||
data class BottomNavItem(
|
||||
val name: String,
|
||||
val route: String,
|
||||
val route: Route,
|
||||
val icon: ImageVector,
|
||||
)
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.navigation.NavBackStackEntry
|
||||
import androidx.navigation.NavDestination.Companion.hasRoute
|
||||
import androidx.navigation.NavDestination.Companion.hierarchy
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
@SuppressLint("RestrictedApi")
|
||||
fun <T : Route> NavBackStackEntry?.isCurrentRoute(cls: KClass<T>): Boolean {
|
||||
return this?.destination?.hierarchy?.any {
|
||||
it.hasRoute(route = cls)
|
||||
} == true
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.navigation.NavHostController
|
||||
|
||||
val LocalNavController = compositionLocalOf<NavHostController> {
|
||||
error("NavController was not provided")
|
||||
}
|
||||
|
||||
val LocalFocusRequester = compositionLocalOf<FocusRequester> { error("FocusRequester is not provided") }
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.material3.CenterAlignedTopAppBar
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun TopNavBar(title: String, trailing: @Composable () -> Unit = {}, showBack: Boolean = true) {
|
||||
val navController = LocalNavController.current
|
||||
CenterAlignedTopAppBar(
|
||||
title = {
|
||||
Text(title)
|
||||
},
|
||||
navigationIcon = {
|
||||
if (showBack) {
|
||||
IconButton(onClick = { navController.popBackStack() }) {
|
||||
val icon = Icons.AutoMirrored.Outlined.ArrowBack
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
trailing()
|
||||
},
|
||||
)
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.screen
|
||||
|
||||
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.padding
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun LoadingScreen() {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.focusable()
|
||||
.padding(),
|
||||
) {
|
||||
Column(modifier = Modifier.padding(120.dp)) { CircularProgressIndicator() }
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.prompt
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.snackbar
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.snackbar
|
||||
|
||||
import androidx.compose.material3.SnackbarDuration
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.SnackbarResult
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.runtime.ReadOnlyComposable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.coroutines.EmptyCoroutineContext
|
||||
|
||||
private val LocalSnackbarController = staticCompositionLocalOf {
|
||||
SnackbarController(
|
||||
host = SnackbarHostState(),
|
||||
scope = CoroutineScope(EmptyCoroutineContext),
|
||||
)
|
||||
}
|
||||
private val channel = Channel<SnackbarChannelMessage>(capacity = 1)
|
||||
|
||||
@Composable
|
||||
fun SnackbarControllerProvider(content: @Composable (snackbarHost: SnackbarHostState) -> Unit) {
|
||||
val snackHostState = remember { SnackbarHostState() }
|
||||
val scope = rememberCoroutineScope()
|
||||
val snackController = remember(scope) { SnackbarController(snackHostState, scope) }
|
||||
val context = LocalContext.current
|
||||
|
||||
DisposableEffect(snackController, scope) {
|
||||
val job = scope.launch {
|
||||
for (payload in channel) {
|
||||
snackController.showMessage(
|
||||
message = payload.message.asString(context),
|
||||
duration = payload.duration,
|
||||
action = payload.action,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
onDispose {
|
||||
job.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalSnackbarController provides snackController) {
|
||||
content(
|
||||
snackHostState,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Immutable
|
||||
class SnackbarController(
|
||||
private val host: SnackbarHostState,
|
||||
private val scope: CoroutineScope,
|
||||
) {
|
||||
companion object {
|
||||
val current
|
||||
@Composable
|
||||
@ReadOnlyComposable
|
||||
get() = LocalSnackbarController.current
|
||||
|
||||
fun showMessage(message: StringValue, action: SnackbarAction? = null, duration: SnackbarDuration = SnackbarDuration.Short) {
|
||||
channel.trySend(
|
||||
SnackbarChannelMessage(
|
||||
message = message,
|
||||
duration = duration,
|
||||
action = action,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun showMessage(message: String, action: SnackbarAction? = null, duration: SnackbarDuration = SnackbarDuration.Short) {
|
||||
scope.launch {
|
||||
/**
|
||||
* note: uncomment this line if you want snackbar to be displayed immediately,
|
||||
* rather than being enqueued and waiting [duration] * current_queue_size
|
||||
*/
|
||||
host.currentSnackbarData?.dismiss()
|
||||
val result =
|
||||
host.showSnackbar(
|
||||
message = message,
|
||||
actionLabel = action?.title,
|
||||
duration = duration,
|
||||
)
|
||||
|
||||
if (result == SnackbarResult.ActionPerformed) {
|
||||
action?.onActionPress?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class SnackbarChannelMessage(
|
||||
val message: StringValue,
|
||||
val action: SnackbarAction?,
|
||||
val duration: SnackbarDuration = SnackbarDuration.Short,
|
||||
)
|
||||
|
||||
data class SnackbarAction(val title: String, val onActionPress: () -> Unit)
|
||||
+2
-4
@@ -1,22 +1,20 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.text
|
||||
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
@Composable
|
||||
fun SectionTitle(title: String, padding: Dp) {
|
||||
Text(
|
||||
title,
|
||||
textAlign = TextAlign.Start,
|
||||
style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.ExtraBold),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(padding, bottom = 5.dp, top = 5.dp),
|
||||
)
|
||||
}
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.textbox
|
||||
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextFieldDefaults
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun CustomTextField(
|
||||
value: String,
|
||||
modifier: Modifier = Modifier,
|
||||
textStyle: TextStyle = MaterialTheme.typography.bodyLarge.copy(color = MaterialTheme.colorScheme.onSurface),
|
||||
label: @Composable () -> Unit,
|
||||
containerColor: Color,
|
||||
onValueChange: (value: String) -> Unit = {},
|
||||
singleLine: Boolean = false,
|
||||
placeholder: @Composable (() -> Unit)? = null,
|
||||
keyboardOptions: KeyboardOptions,
|
||||
keyboardActions: KeyboardActions,
|
||||
supportingText: @Composable (() -> Unit)? = null,
|
||||
leading: @Composable (() -> Unit)? = null,
|
||||
trailing: @Composable (() -> Unit)? = null,
|
||||
isError: Boolean = false,
|
||||
readOnly: Boolean = false,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val space = " "
|
||||
BasicTextField(
|
||||
value = value,
|
||||
textStyle = textStyle,
|
||||
onValueChange = {
|
||||
onValueChange(it)
|
||||
},
|
||||
keyboardActions = keyboardActions,
|
||||
keyboardOptions = keyboardOptions,
|
||||
readOnly = readOnly,
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.onSurface),
|
||||
modifier = modifier,
|
||||
interactionSource = interactionSource,
|
||||
enabled = enabled,
|
||||
singleLine = singleLine,
|
||||
) {
|
||||
OutlinedTextFieldDefaults.DecorationBox(
|
||||
value = space + value,
|
||||
innerTextField = {
|
||||
if (value.isEmpty()) {
|
||||
if (placeholder != null) {
|
||||
placeholder()
|
||||
}
|
||||
}
|
||||
it.invoke()
|
||||
},
|
||||
contentPadding = OutlinedTextFieldDefaults.contentPadding(top = 0.dp, bottom = 0.dp),
|
||||
leadingIcon = leading,
|
||||
trailingIcon = trailing,
|
||||
singleLine = singleLine,
|
||||
supportingText = supportingText,
|
||||
colors = TextFieldDefaults.colors().copy(
|
||||
disabledLabelColor = MaterialTheme.colorScheme.onSurface,
|
||||
disabledContainerColor = containerColor,
|
||||
focusedLabelColor = MaterialTheme.colorScheme.onSurface,
|
||||
focusedContainerColor = containerColor,
|
||||
unfocusedContainerColor = containerColor,
|
||||
focusedTextColor = MaterialTheme.colorScheme.onSurface,
|
||||
cursorColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
enabled = enabled,
|
||||
label = label,
|
||||
visualTransformation = VisualTransformation.None,
|
||||
interactionSource = interactionSource,
|
||||
placeholder = placeholder,
|
||||
container = {
|
||||
OutlinedTextFieldDefaults.ContainerBox(
|
||||
enabled,
|
||||
isError = isError,
|
||||
interactionSource,
|
||||
colors = TextFieldDefaults.colors().copy(
|
||||
errorContainerColor = containerColor,
|
||||
disabledLabelColor = MaterialTheme.colorScheme.onSurface,
|
||||
disabledContainerColor = containerColor,
|
||||
focusedIndicatorColor = MaterialTheme.colorScheme.onSurface,
|
||||
focusedLabelColor = MaterialTheme.colorScheme.onSurface,
|
||||
focusedContainerColor = containerColor,
|
||||
unfocusedContainerColor = containerColor,
|
||||
focusedTextColor = MaterialTheme.colorScheme.onSurface,
|
||||
cursorColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
focusedBorderThickness = 0.5.dp,
|
||||
unfocusedBorderThickness = 0.5.dp,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
+89
-310
@@ -1,36 +1,26 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.config
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Android
|
||||
import androidx.compose.material.icons.rounded.ContentCopy
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.Refresh
|
||||
import androidx.compose.material.icons.rounded.Save
|
||||
import androidx.compose.material3.BasicAlertDialog
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FabPosition
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -39,12 +29,11 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -53,7 +42,6 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.platform.ClipboardManager
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -67,65 +55,59 @@ import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavController
|
||||
import com.google.accompanist.drawablepainter.DrawablePainter
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.SearchBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationTextBox
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.AuthorizationPrompt
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.screen.LoadingScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.components.ApplicationSelectionDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.getMessage
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||
@OptIn(
|
||||
ExperimentalMaterial3Api::class,
|
||||
)
|
||||
@Composable
|
||||
fun ConfigScreen(
|
||||
viewModel: ConfigViewModel = hiltViewModel(),
|
||||
focusRequester: FocusRequester,
|
||||
navController: NavController,
|
||||
appViewModel: AppViewModel,
|
||||
tunnelId: String,
|
||||
configType: ConfigType,
|
||||
) {
|
||||
fun ConfigScreen(tunnelId: Int) {
|
||||
val viewModel = hiltViewModel<ConfigViewModel, ConfigViewModel.ConfigViewModelFactory> { factory ->
|
||||
factory.create(tunnelId)
|
||||
}
|
||||
|
||||
val context = LocalContext.current
|
||||
val snackbar = SnackbarController.current
|
||||
val clipboardManager: ClipboardManager = LocalClipboardManager.current
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
val navController = LocalNavController.current
|
||||
|
||||
var showApplicationsDialog by remember { mutableStateOf(false) }
|
||||
var showAuthPrompt by remember { mutableStateOf(false) }
|
||||
var isAuthenticated by remember { mutableStateOf(false) }
|
||||
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
var configType by remember { mutableStateOf<ConfigType?>(null) }
|
||||
val derivedConfigType = remember {
|
||||
derivedStateOf<ConfigType> {
|
||||
configType ?: if (!uiState.hasAmneziaProperties()) ConfigType.WIREGUARD else ConfigType.AMNEZIA
|
||||
}
|
||||
}
|
||||
val saved by viewModel.saved.collectAsStateWithLifecycle(null)
|
||||
|
||||
LaunchedEffect(Unit) { viewModel.init(tunnelId) }
|
||||
|
||||
LaunchedEffect(uiState.loading) {
|
||||
if (!uiState.loading && context.isRunningOnTv()) {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
kotlin.runCatching {
|
||||
focusRequester.requestFocus()
|
||||
}.onFailure {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
LaunchedEffect(saved) {
|
||||
if (saved == true) {
|
||||
navController.navigate(Route.Main)
|
||||
}
|
||||
}
|
||||
|
||||
if (uiState.loading) {
|
||||
LoadingScreen()
|
||||
return
|
||||
LaunchedEffect(Unit) {
|
||||
delay(2_000L)
|
||||
viewModel.cleanUpUninstalledApps()
|
||||
}
|
||||
|
||||
val keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() })
|
||||
|
||||
val keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done)
|
||||
|
||||
val fillMaxHeight = .85f
|
||||
@@ -160,13 +142,13 @@ fun ConfigScreen(
|
||||
},
|
||||
onError = {
|
||||
showAuthPrompt = false
|
||||
appViewModel.showSnackbarMessage(
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.error_authentication_failed),
|
||||
)
|
||||
},
|
||||
onFailure = {
|
||||
showAuthPrompt = false
|
||||
appViewModel.showSnackbarMessage(
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.error_authorization_failed),
|
||||
)
|
||||
},
|
||||
@@ -174,182 +156,22 @@ fun ConfigScreen(
|
||||
}
|
||||
|
||||
if (showApplicationsDialog) {
|
||||
val sortedPackages =
|
||||
remember(uiState.packages) {
|
||||
uiState.packages.sortedBy { viewModel.getPackageLabel(it) }
|
||||
}
|
||||
BasicAlertDialog(onDismissRequest = { showApplicationsDialog = false }) {
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.fillMaxHeight(if (uiState.isAllApplicationsEnabled) 1 / 5f else 4 / 5f),
|
||||
) {
|
||||
Column(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(stringResource(id = R.string.tunnel_all))
|
||||
Switch(
|
||||
checked = uiState.isAllApplicationsEnabled,
|
||||
onCheckedChange = { viewModel.onAllApplicationsChange(it) },
|
||||
)
|
||||
}
|
||||
if (!uiState.isAllApplicationsEnabled) {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(stringResource(id = R.string.include))
|
||||
Checkbox(
|
||||
checked = uiState.include,
|
||||
onCheckedChange = {
|
||||
viewModel.onIncludeChange(!uiState.include)
|
||||
},
|
||||
)
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(stringResource(id = R.string.exclude))
|
||||
Checkbox(
|
||||
checked = !uiState.include,
|
||||
onCheckedChange = {
|
||||
viewModel.onIncludeChange(!uiState.include)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
SearchBar(viewModel::emitQueriedPackages)
|
||||
}
|
||||
Spacer(Modifier.padding(5.dp))
|
||||
LazyColumn(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.fillMaxHeight(4 / 5f),
|
||||
) {
|
||||
items(sortedPackages, key = { it.packageName }) { pack ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(5.dp),
|
||||
) {
|
||||
Row(modifier = Modifier.fillMaxWidth(fillMaxWidth)) {
|
||||
val drawable =
|
||||
pack.applicationInfo?.loadIcon(context.packageManager)
|
||||
if (drawable != null) {
|
||||
Image(
|
||||
painter = DrawablePainter(drawable),
|
||||
stringResource(id = R.string.icon),
|
||||
modifier = Modifier.size(50.dp, 50.dp),
|
||||
)
|
||||
} else {
|
||||
val icon = Icons.Rounded.Android
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier = Modifier.size(50.dp, 50.dp),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
viewModel.getPackageLabel(pack),
|
||||
modifier = Modifier.padding(5.dp),
|
||||
)
|
||||
}
|
||||
Checkbox(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
checked =
|
||||
(
|
||||
uiState.checkedPackageNames.contains(
|
||||
pack.packageName,
|
||||
)
|
||||
),
|
||||
onCheckedChange = {
|
||||
if (it) {
|
||||
viewModel.onAddCheckedPackage(pack.packageName)
|
||||
} else {
|
||||
viewModel.onRemoveCheckedPackage(pack.packageName)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = 5.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
TextButton(onClick = { showApplicationsDialog = false }) {
|
||||
Text(stringResource(R.string.done))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ApplicationSelectionDialog(viewModel, uiState) {
|
||||
showApplicationsDialog = false
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.edit_tunnel))
|
||||
},
|
||||
floatingActionButtonPosition = FabPosition.End,
|
||||
floatingActionButton = {
|
||||
val secondaryColor = MaterialTheme.colorScheme.secondary
|
||||
val hoverColor = MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp)
|
||||
var fobColor by remember { mutableStateOf(secondaryColor) }
|
||||
FloatingActionButton(
|
||||
modifier =
|
||||
Modifier.onFocusChanged {
|
||||
if (context.isRunningOnTv()) {
|
||||
fobColor = if (it.isFocused) hoverColor else secondaryColor
|
||||
}
|
||||
},
|
||||
onClick = {
|
||||
viewModel.onSaveAllChanges(configType).onSuccess {
|
||||
appViewModel.showSnackbarMessage(
|
||||
context.getString(R.string.config_changes_saved),
|
||||
)
|
||||
navController.navigate(Screen.Main.route)
|
||||
}.onFailure {
|
||||
appViewModel.showSnackbarMessage(it.getMessage(context))
|
||||
}
|
||||
viewModel.onSaveAllChanges()
|
||||
},
|
||||
containerColor = fobColor,
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
) {
|
||||
Icon(
|
||||
@@ -360,7 +182,7 @@ fun ConfigScreen(
|
||||
}
|
||||
},
|
||||
) {
|
||||
Column {
|
||||
Column(Modifier.padding(it)) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
@@ -385,7 +207,7 @@ fun ConfigScreen(
|
||||
Modifier.fillMaxWidth(fillMaxWidth)
|
||||
}
|
||||
)
|
||||
.padding(bottom = 10.dp),
|
||||
.padding(bottom = 10.dp.scaledHeight()).padding(top = 24.dp.scaledHeight()),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
@@ -399,16 +221,20 @@ fun ConfigScreen(
|
||||
stringResource(R.string.interface_),
|
||||
padding = screenPadding,
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(id = R.string.show_amnezia_properties),
|
||||
checked = derivedConfigType.value == ConfigType.AMNEZIA,
|
||||
onCheckChanged = { configType = if (it) ConfigType.AMNEZIA else ConfigType.WIREGUARD },
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.tunnelName,
|
||||
onValueChange = { value -> viewModel.onTunnelNameChange(value) },
|
||||
onValueChange = viewModel::onTunnelNameChange,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.name),
|
||||
hint = stringResource(R.string.tunnel_name).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
modifier =
|
||||
@@ -417,12 +243,12 @@ fun ConfigScreen(
|
||||
.clickable { showAuthPrompt = true },
|
||||
value = uiState.interfaceProxy.privateKey,
|
||||
visualTransformation =
|
||||
if ((tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated) {
|
||||
if ((tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID.toInt()) || isAuthenticated) {
|
||||
VisualTransformation.None
|
||||
} else {
|
||||
PasswordVisualTransformation()
|
||||
},
|
||||
enabled = (tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID) || isAuthenticated,
|
||||
enabled = (tunnelId == Constants.MANUAL_TUNNEL_CONFIG_ID.toInt()) || isAuthenticated,
|
||||
onValueChange = { value -> viewModel.onPrivateKeyChange(value) },
|
||||
trailingIcon = {
|
||||
IconButton(
|
||||
@@ -472,31 +298,29 @@ fun ConfigScreen(
|
||||
keyboardOptions = keyboardOptions,
|
||||
keyboardActions = keyboardActions,
|
||||
)
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.addresses,
|
||||
onValueChange = { value -> viewModel.onAddressesChanged(value) },
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.addresses),
|
||||
hint = stringResource(R.string.comma_separated_list),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth(3 / 5f)
|
||||
.padding(end = 5.dp),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.listenPort,
|
||||
onValueChange = { value -> viewModel.onListenPortChanged(value) },
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.listen_port),
|
||||
hint = stringResource(R.string.random),
|
||||
modifier = Modifier.width(IntrinsicSize.Min),
|
||||
)
|
||||
}
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.addresses,
|
||||
onValueChange = viewModel::onAddressesChanged,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.addresses),
|
||||
hint = stringResource(R.string.comma_separated_list),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(end = 5.dp),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.listenPort,
|
||||
onValueChange = viewModel::onListenPortChanged,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.listen_port),
|
||||
hint = stringResource(R.string.random),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.dnsServers,
|
||||
onValueChange = { value -> viewModel.onDnsServersChanged(value) },
|
||||
onValueChange = viewModel::onDnsServersChanged,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.dns_servers),
|
||||
hint = stringResource(R.string.comma_separated_list),
|
||||
@@ -507,35 +331,27 @@ fun ConfigScreen(
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.mtu,
|
||||
onValueChange = { value -> viewModel.onMtuChanged(value) },
|
||||
onValueChange = viewModel::onMtuChanged,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.mtu),
|
||||
hint = stringResource(R.string.auto),
|
||||
modifier = Modifier.width(IntrinsicSize.Min),
|
||||
)
|
||||
}
|
||||
if (configType == ConfigType.AMNEZIA) {
|
||||
if (derivedConfigType.value == ConfigType.AMNEZIA) {
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.junkPacketCount,
|
||||
onValueChange = {
|
||||
value ->
|
||||
viewModel.onJunkPacketCountChanged(value)
|
||||
},
|
||||
onValueChange = viewModel::onJunkPacketCountChanged,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.junk_packet_count),
|
||||
hint = stringResource(R.string.junk_packet_count).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.junkPacketMinSize,
|
||||
onValueChange = { value ->
|
||||
viewModel.onJunkPacketMinSizeChanged(
|
||||
value,
|
||||
)
|
||||
},
|
||||
onValueChange = viewModel::onJunkPacketMinSizeChanged,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.junk_packet_minimum_size),
|
||||
hint =
|
||||
@@ -544,16 +360,11 @@ fun ConfigScreen(
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.junkPacketMaxSize,
|
||||
onValueChange = { value ->
|
||||
viewModel.onJunkPacketMaxSizeChanged(
|
||||
value,
|
||||
)
|
||||
},
|
||||
onValueChange = viewModel::onJunkPacketMaxSizeChanged,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.junk_packet_maximum_size),
|
||||
hint =
|
||||
@@ -562,30 +373,21 @@ fun ConfigScreen(
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.initPacketJunkSize,
|
||||
onValueChange = { value ->
|
||||
viewModel.onInitPacketJunkSizeChanged(
|
||||
value,
|
||||
)
|
||||
},
|
||||
onValueChange = viewModel::onInitPacketJunkSizeChanged,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.init_packet_junk_size),
|
||||
hint = stringResource(R.string.init_packet_junk_size).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.responsePacketJunkSize,
|
||||
onValueChange = {
|
||||
value ->
|
||||
viewModel.onResponsePacketJunkSize(value)
|
||||
},
|
||||
onValueChange = viewModel::onResponsePacketJunkSize,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.response_packet_junk_size),
|
||||
hint =
|
||||
@@ -594,15 +396,11 @@ fun ConfigScreen(
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.initPacketMagicHeader,
|
||||
onValueChange = {
|
||||
value ->
|
||||
viewModel.onInitPacketMagicHeader(value)
|
||||
},
|
||||
onValueChange = viewModel::onInitPacketMagicHeader,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.init_packet_magic_header),
|
||||
hint =
|
||||
@@ -611,16 +409,11 @@ fun ConfigScreen(
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.responsePacketMagicHeader,
|
||||
onValueChange = { value ->
|
||||
viewModel.onResponsePacketMagicHeader(
|
||||
value,
|
||||
)
|
||||
},
|
||||
onValueChange = viewModel::onResponsePacketMagicHeader,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.response_packet_magic_header),
|
||||
hint =
|
||||
@@ -629,16 +422,11 @@ fun ConfigScreen(
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.underloadPacketMagicHeader,
|
||||
onValueChange = { value ->
|
||||
viewModel.onUnderloadPacketMagicHeader(
|
||||
value,
|
||||
)
|
||||
},
|
||||
onValueChange = viewModel::onUnderloadPacketMagicHeader,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.underload_packet_magic_header),
|
||||
hint =
|
||||
@@ -647,16 +435,11 @@ fun ConfigScreen(
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.transportPacketMagicHeader,
|
||||
onValueChange = { value ->
|
||||
viewModel.onTransportPacketMagicHeader(
|
||||
value,
|
||||
)
|
||||
},
|
||||
onValueChange = viewModel::onTransportPacketMagicHeader,
|
||||
keyboardActions = keyboardActions,
|
||||
label = stringResource(R.string.transport_packet_magic_header),
|
||||
hint =
|
||||
@@ -665,8 +448,7 @@ fun ConfigScreen(
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
Row(
|
||||
@@ -814,9 +596,6 @@ fun ConfigScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (context.isRunningOnTv()) {
|
||||
Spacer(modifier = Modifier.weight(.17f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+12
-2
@@ -15,9 +15,12 @@ data class ConfigUiState(
|
||||
val isAllApplicationsEnabled: Boolean = false,
|
||||
val loading: Boolean = true,
|
||||
val tunnel: TunnelConfig? = null,
|
||||
val tunnelName: String = "",
|
||||
var tunnelName: String = "",
|
||||
val isAmneziaEnabled: Boolean = false,
|
||||
) {
|
||||
fun hasAmneziaProperties(): Boolean {
|
||||
return this.interfaceProxy.junkPacketCount != ""
|
||||
}
|
||||
companion object {
|
||||
fun from(config: Config): ConfigUiState {
|
||||
val proxyPeers = config.peers.map { PeerProxy.from(it) }
|
||||
@@ -45,7 +48,6 @@ data class ConfigUiState(
|
||||
}
|
||||
|
||||
fun from(config: org.amnezia.awg.config.Config): ConfigUiState {
|
||||
// TODO update with new values
|
||||
val proxyPeers = config.peers.map { PeerProxy.from(it) }
|
||||
val proxyInterface = InterfaceProxy.from(config.`interface`)
|
||||
var include = true
|
||||
@@ -69,5 +71,13 @@ data class ConfigUiState(
|
||||
isAllApplicationsEnabled,
|
||||
)
|
||||
}
|
||||
|
||||
fun from(tunnel: TunnelConfig): ConfigUiState {
|
||||
val config = tunnel.toAmConfig()
|
||||
return from(config).copy(
|
||||
tunnelName = tunnel.name,
|
||||
tunnel = tunnel,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+218
-192
@@ -15,100 +15,119 @@ import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.SettingsRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.PeerProxy
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.removeAt
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.update
|
||||
import dagger.assisted.Assisted
|
||||
import dagger.assisted.AssistedFactory
|
||||
import dagger.assisted.AssistedInject
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.plus
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
@HiltViewModel(assistedFactory = ConfigViewModel.ConfigViewModelFactory::class)
|
||||
class ConfigViewModel
|
||||
@Inject
|
||||
@AssistedInject
|
||||
constructor(
|
||||
private val settingsRepository: SettingsRepository,
|
||||
private val appDataRepository: AppDataRepository,
|
||||
@Assisted val id: Int,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
) : ViewModel() {
|
||||
private val packageManager = WireGuardAutoTunnel.instance.packageManager
|
||||
|
||||
private val _uiState = MutableStateFlow(ConfigUiState())
|
||||
val uiState = _uiState.asStateFlow()
|
||||
private val _saved = MutableSharedFlow<Boolean>()
|
||||
val saved = _saved.asSharedFlow()
|
||||
|
||||
fun init(tunnelId: String) = viewModelScope.launch(ioDispatcher) {
|
||||
val packages = getQueriedPackages("")
|
||||
val state =
|
||||
if (tunnelId != Constants.MANUAL_TUNNEL_CONFIG_ID) {
|
||||
val tunnelConfig =
|
||||
appDataRepository.tunnels.getAll()
|
||||
.firstOrNull { it.id.toString() == tunnelId }
|
||||
val isAmneziaEnabled = settingsRepository.getSettings().isAmneziaEnabled
|
||||
if (tunnelConfig != null) {
|
||||
(
|
||||
if (isAmneziaEnabled) {
|
||||
val amConfig =
|
||||
if (tunnelConfig.amQuick == "") tunnelConfig.wgQuick else tunnelConfig.amQuick
|
||||
ConfigUiState.from(TunnelConfig.configFromAmQuick(amConfig))
|
||||
} else {
|
||||
ConfigUiState.from(
|
||||
TunnelConfig.configFromWgQuick(tunnelConfig.wgQuick),
|
||||
)
|
||||
}
|
||||
).copy(
|
||||
packages = packages,
|
||||
loading = false,
|
||||
tunnel = tunnelConfig,
|
||||
tunnelName = tunnelConfig.name,
|
||||
isAmneziaEnabled = isAmneziaEnabled,
|
||||
)
|
||||
} else {
|
||||
ConfigUiState(loading = false, packages = packages)
|
||||
}
|
||||
} else {
|
||||
ConfigUiState(loading = false, packages = packages)
|
||||
}
|
||||
_uiState.value = state
|
||||
}
|
||||
private val _uiState = MutableStateFlow(ConfigUiState())
|
||||
val uiState = _uiState.onStart {
|
||||
appDataRepository.tunnels.getById(id)?.let {
|
||||
val packages = getQueriedPackages()
|
||||
_uiState.value = ConfigUiState.from(it).copy(
|
||||
packages = packages,
|
||||
)
|
||||
}
|
||||
}.stateIn(
|
||||
viewModelScope + ioDispatcher,
|
||||
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||
ConfigUiState(),
|
||||
)
|
||||
|
||||
fun onTunnelNameChange(name: String) {
|
||||
_uiState.value = _uiState.value.copy(tunnelName = name)
|
||||
_uiState.update {
|
||||
it.copy(tunnelName = name)
|
||||
}
|
||||
}
|
||||
|
||||
fun onIncludeChange(include: Boolean) {
|
||||
_uiState.value = _uiState.value.copy(include = include)
|
||||
_uiState.update {
|
||||
it.copy(include = include)
|
||||
}
|
||||
}
|
||||
|
||||
fun cleanUpUninstalledApps() = viewModelScope.launch(ioDispatcher) {
|
||||
uiState.value.tunnel?.let {
|
||||
val config = it.toAmConfig()
|
||||
val packages = getQueriedPackages()
|
||||
val packageSet = packages.map { pack -> pack.packageName }.toSet()
|
||||
val includedApps = config.`interface`.includedApplications.toMutableList()
|
||||
val excludedApps = config.`interface`.excludedApplications.toMutableList()
|
||||
if (includedApps.isEmpty() && excludedApps.isEmpty()) return@launch
|
||||
if (includedApps.retainAll(packageSet) || excludedApps.retainAll(packageSet)) {
|
||||
Timber.i("Removing split tunnel package name that no longer exists on the device")
|
||||
_uiState.update { state ->
|
||||
state.copy(
|
||||
checkedPackageNames = if (_uiState.value.include) includedApps else excludedApps,
|
||||
)
|
||||
}
|
||||
val wgQuick = buildConfig().toWgQuickString(true)
|
||||
val amQuick = buildAmConfig().toAwgQuickString(true)
|
||||
saveConfig(
|
||||
it.copy(
|
||||
amQuick = amQuick,
|
||||
wgQuick = wgQuick,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onAddCheckedPackage(packageName: String) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
checkedPackageNames = _uiState.value.checkedPackageNames + packageName,
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
checkedPackageNames = it.checkedPackageNames + packageName,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onAllApplicationsChange(isAllApplicationsEnabled: Boolean) {
|
||||
_uiState.value = _uiState.value.copy(isAllApplicationsEnabled = isAllApplicationsEnabled)
|
||||
_uiState.update {
|
||||
it.copy(isAllApplicationsEnabled = isAllApplicationsEnabled)
|
||||
}
|
||||
}
|
||||
|
||||
fun onRemoveCheckedPackage(packageName: String) {
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
checkedPackageNames = _uiState.value.checkedPackageNames - packageName,
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
checkedPackageNames = it.checkedPackageNames - packageName,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getQueriedPackages(query: String): List<PackageInfo> {
|
||||
private fun getQueriedPackages(query: String = ""): List<PackageInfo> {
|
||||
return getAllInternetCapablePackages().filter {
|
||||
getPackageLabel(it).lowercase().contains(query.lowercase())
|
||||
}
|
||||
@@ -137,7 +156,9 @@ constructor(
|
||||
return _uiState.value.isAllApplicationsEnabled
|
||||
}
|
||||
|
||||
private fun saveConfig(tunnelConfig: TunnelConfig) = viewModelScope.launch { appDataRepository.tunnels.save(tunnelConfig) }
|
||||
private fun saveConfig(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
appDataRepository.tunnels.save(tunnelConfig)
|
||||
}
|
||||
|
||||
private fun updateTunnelConfig(tunnelConfig: TunnelConfig?) = viewModelScope.launch {
|
||||
if (tunnelConfig != null) {
|
||||
@@ -174,105 +195,113 @@ constructor(
|
||||
}
|
||||
|
||||
private fun emptyCheckedPackagesList() {
|
||||
_uiState.value = _uiState.value.copy(checkedPackageNames = emptyList())
|
||||
_uiState.update {
|
||||
it.copy(checkedPackageNames = emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildInterfaceListFromProxyInterface(): Interface {
|
||||
val builder = Interface.Builder()
|
||||
builder.parsePrivateKey(_uiState.value.interfaceProxy.privateKey.trim())
|
||||
builder.parseAddresses(_uiState.value.interfaceProxy.addresses.trim())
|
||||
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) {
|
||||
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim())
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.mtu.isNotEmpty()) {
|
||||
builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim())
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
|
||||
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
|
||||
}
|
||||
if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
|
||||
if (_uiState.value.include) {
|
||||
builder.includeApplications(
|
||||
_uiState.value.checkedPackageNames,
|
||||
)
|
||||
}
|
||||
if (!_uiState.value.include) {
|
||||
builder.excludeApplications(
|
||||
_uiState.value.checkedPackageNames,
|
||||
)
|
||||
with(_uiState.value.interfaceProxy) {
|
||||
builder.parsePrivateKey(this.privateKey.trim())
|
||||
builder.parseAddresses(this.addresses.trim())
|
||||
if (this.dnsServers.isNotEmpty()) {
|
||||
builder.parseDnsServers(this.dnsServers.trim())
|
||||
}
|
||||
if (this.mtu.isNotEmpty()) {
|
||||
builder.parseMtu(this.mtu.trim())
|
||||
}
|
||||
if (this.listenPort.isNotEmpty()) {
|
||||
builder.parseListenPort(this.listenPort.trim())
|
||||
}
|
||||
if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
|
||||
if (_uiState.value.include) {
|
||||
builder.includeApplications(
|
||||
_uiState.value.checkedPackageNames,
|
||||
)
|
||||
}
|
||||
if (!_uiState.value.include) {
|
||||
builder.excludeApplications(
|
||||
_uiState.value.checkedPackageNames,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
private fun buildAmInterfaceListFromProxyInterface(): org.amnezia.awg.config.Interface {
|
||||
val builder = org.amnezia.awg.config.Interface.Builder()
|
||||
builder.parsePrivateKey(_uiState.value.interfaceProxy.privateKey.trim())
|
||||
builder.parseAddresses(_uiState.value.interfaceProxy.addresses.trim())
|
||||
if (_uiState.value.interfaceProxy.dnsServers.isNotEmpty()) {
|
||||
builder.parseDnsServers(_uiState.value.interfaceProxy.dnsServers.trim())
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.mtu.isNotEmpty()) {
|
||||
builder.parseMtu(_uiState.value.interfaceProxy.mtu.trim())
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.listenPort.isNotEmpty()) {
|
||||
builder.parseListenPort(_uiState.value.interfaceProxy.listenPort.trim())
|
||||
}
|
||||
if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
|
||||
if (_uiState.value.include) {
|
||||
builder.includeApplications(
|
||||
_uiState.value.checkedPackageNames,
|
||||
)
|
||||
}
|
||||
if (!_uiState.value.include) {
|
||||
builder.excludeApplications(
|
||||
_uiState.value.checkedPackageNames,
|
||||
)
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.junkPacketCount.isNotEmpty()) {
|
||||
builder.setJunkPacketCount(
|
||||
_uiState.value.interfaceProxy.junkPacketCount.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.junkPacketMinSize.isNotEmpty()) {
|
||||
builder.setJunkPacketMinSize(
|
||||
_uiState.value.interfaceProxy.junkPacketMinSize.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.junkPacketMaxSize.isNotEmpty()) {
|
||||
builder.setJunkPacketMaxSize(
|
||||
_uiState.value.interfaceProxy.junkPacketMaxSize.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.initPacketJunkSize.isNotEmpty()) {
|
||||
builder.setInitPacketJunkSize(
|
||||
_uiState.value.interfaceProxy.initPacketJunkSize.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.responsePacketJunkSize.isNotEmpty()) {
|
||||
builder.setResponsePacketJunkSize(
|
||||
_uiState.value.interfaceProxy.responsePacketJunkSize.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.initPacketMagicHeader.isNotEmpty()) {
|
||||
builder.setInitPacketMagicHeader(
|
||||
_uiState.value.interfaceProxy.initPacketMagicHeader.trim().toLong(),
|
||||
)
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.responsePacketMagicHeader.isNotEmpty()) {
|
||||
builder.setResponsePacketMagicHeader(
|
||||
_uiState.value.interfaceProxy.responsePacketMagicHeader.trim().toLong(),
|
||||
)
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.transportPacketMagicHeader.isNotEmpty()) {
|
||||
builder.setTransportPacketMagicHeader(
|
||||
_uiState.value.interfaceProxy.transportPacketMagicHeader.trim().toLong(),
|
||||
)
|
||||
}
|
||||
if (_uiState.value.interfaceProxy.underloadPacketMagicHeader.isNotEmpty()) {
|
||||
builder.setUnderloadPacketMagicHeader(
|
||||
_uiState.value.interfaceProxy.underloadPacketMagicHeader.trim().toLong(),
|
||||
)
|
||||
with(_uiState.value.interfaceProxy) {
|
||||
builder.parsePrivateKey(this.privateKey.trim())
|
||||
builder.parseAddresses(this.addresses.trim())
|
||||
if (this.dnsServers.isNotEmpty()) {
|
||||
builder.parseDnsServers(this.dnsServers.trim())
|
||||
}
|
||||
if (this.mtu.isNotEmpty()) {
|
||||
builder.parseMtu(this.mtu.trim())
|
||||
}
|
||||
if (this.listenPort.isNotEmpty()) {
|
||||
builder.parseListenPort(this.listenPort.trim())
|
||||
}
|
||||
if (isAllApplicationsEnabled()) emptyCheckedPackagesList()
|
||||
if (_uiState.value.include) {
|
||||
builder.includeApplications(
|
||||
_uiState.value.checkedPackageNames,
|
||||
)
|
||||
}
|
||||
if (!_uiState.value.include) {
|
||||
builder.excludeApplications(
|
||||
_uiState.value.checkedPackageNames,
|
||||
)
|
||||
}
|
||||
if (this.junkPacketCount.isNotEmpty()) {
|
||||
builder.setJunkPacketCount(
|
||||
this.junkPacketCount.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (this.junkPacketMinSize.isNotEmpty()) {
|
||||
builder.setJunkPacketMinSize(
|
||||
this.junkPacketMinSize.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (this.junkPacketMaxSize.isNotEmpty()) {
|
||||
builder.setJunkPacketMaxSize(
|
||||
this.junkPacketMaxSize.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (this.initPacketJunkSize.isNotEmpty()) {
|
||||
builder.setInitPacketJunkSize(
|
||||
this.initPacketJunkSize.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (this.responsePacketJunkSize.isNotEmpty()) {
|
||||
builder.setResponsePacketJunkSize(
|
||||
this.responsePacketJunkSize.trim().toInt(),
|
||||
)
|
||||
}
|
||||
if (this.initPacketMagicHeader.isNotEmpty()) {
|
||||
builder.setInitPacketMagicHeader(
|
||||
this.initPacketMagicHeader.trim().toLong(),
|
||||
)
|
||||
}
|
||||
if (this.responsePacketMagicHeader.isNotEmpty()) {
|
||||
builder.setResponsePacketMagicHeader(
|
||||
this.responsePacketMagicHeader.trim().toLong(),
|
||||
)
|
||||
}
|
||||
if (this.transportPacketMagicHeader.isNotEmpty()) {
|
||||
builder.setTransportPacketMagicHeader(
|
||||
this.transportPacketMagicHeader.trim().toLong(),
|
||||
)
|
||||
}
|
||||
if (this.underloadPacketMagicHeader.isNotEmpty()) {
|
||||
builder.setUnderloadPacketMagicHeader(
|
||||
this.underloadPacketMagicHeader.trim().toLong(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
@@ -291,41 +320,33 @@ constructor(
|
||||
.build()
|
||||
}
|
||||
|
||||
fun onSaveAllChanges(configType: ConfigType): Result<Unit> {
|
||||
return try {
|
||||
fun onSaveAllChanges() = viewModelScope.launch {
|
||||
kotlin.runCatching {
|
||||
val wgQuick = buildConfig().toWgQuickString(true)
|
||||
val amQuick =
|
||||
if (configType == ConfigType.AMNEZIA) {
|
||||
buildAmConfig().toAwgQuickString(true)
|
||||
} else {
|
||||
TunnelConfig.AM_QUICK_DEFAULT
|
||||
}
|
||||
val tunnelConfig =
|
||||
when (uiState.value.tunnel) {
|
||||
null ->
|
||||
TunnelConfig(
|
||||
name = _uiState.value.tunnelName,
|
||||
wgQuick = wgQuick,
|
||||
amQuick = amQuick,
|
||||
)
|
||||
|
||||
else ->
|
||||
uiState.value.tunnel!!.copy(
|
||||
name = _uiState.value.tunnelName,
|
||||
wgQuick = wgQuick,
|
||||
amQuick = amQuick,
|
||||
)
|
||||
}
|
||||
val amQuick = buildAmConfig().toAwgQuickString(true)
|
||||
val tunnelConfig = uiState.value.tunnel?.copy(
|
||||
name = _uiState.value.tunnelName,
|
||||
amQuick = amQuick,
|
||||
wgQuick = wgQuick,
|
||||
) ?: TunnelConfig(
|
||||
name = _uiState.value.tunnelName,
|
||||
wgQuick = wgQuick,
|
||||
amQuick = amQuick,
|
||||
)
|
||||
updateTunnelConfig(tunnelConfig)
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e)
|
||||
val message = e.message?.substringAfter(":", missingDelimiterValue = "")
|
||||
val stringValue =
|
||||
message?.let {
|
||||
StringValue.DynamicString(message)
|
||||
} ?: StringValue.StringResource(R.string.unknown_error)
|
||||
Result.failure(WgTunnelExceptions.ConfigParseError(stringValue))
|
||||
SnackbarController.showMessage(
|
||||
StringValue.StringResource(R.string.config_changes_saved),
|
||||
)
|
||||
_saved.emit(true)
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
val message = it.message?.substringAfter(":", missingDelimiterValue = "")
|
||||
val stringValue = if (message.isNullOrBlank()) {
|
||||
StringValue.StringResource(R.string.unknown_error)
|
||||
} else {
|
||||
StringValue.DynamicString(message)
|
||||
}
|
||||
SnackbarController.showMessage(stringValue)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,7 +429,7 @@ constructor(
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy =
|
||||
_uiState.value.interfaceProxy.copy(
|
||||
it.interfaceProxy.copy(
|
||||
privateKey = keyPair.privateKey.toBase64(),
|
||||
publicKey = keyPair.publicKey.toBase64(),
|
||||
),
|
||||
@@ -419,7 +440,7 @@ constructor(
|
||||
fun onAddressesChanged(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy = _uiState.value.interfaceProxy.copy(addresses = value),
|
||||
interfaceProxy = it.interfaceProxy.copy(addresses = value),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -427,7 +448,7 @@ constructor(
|
||||
fun onListenPortChanged(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy = _uiState.value.interfaceProxy.copy(listenPort = value),
|
||||
interfaceProxy = it.interfaceProxy.copy(listenPort = value),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -435,21 +456,21 @@ constructor(
|
||||
fun onDnsServersChanged(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy = _uiState.value.interfaceProxy.copy(dnsServers = value),
|
||||
interfaceProxy = it.interfaceProxy.copy(dnsServers = value),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onMtuChanged(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(interfaceProxy = _uiState.value.interfaceProxy.copy(mtu = value))
|
||||
it.copy(interfaceProxy = it.interfaceProxy.copy(mtu = value))
|
||||
}
|
||||
}
|
||||
|
||||
private fun onInterfacePublicKeyChange(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy = _uiState.value.interfaceProxy.copy(publicKey = value),
|
||||
interfaceProxy = it.interfaceProxy.copy(publicKey = value),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -457,7 +478,7 @@ constructor(
|
||||
fun onPrivateKeyChange(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy = _uiState.value.interfaceProxy.copy(privateKey = value),
|
||||
interfaceProxy = it.interfaceProxy.copy(privateKey = value),
|
||||
)
|
||||
}
|
||||
if (NumberUtils.isValidKey(value)) {
|
||||
@@ -479,7 +500,7 @@ constructor(
|
||||
fun onJunkPacketCountChanged(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy = _uiState.value.interfaceProxy.copy(junkPacketCount = value),
|
||||
interfaceProxy = it.interfaceProxy.copy(junkPacketCount = value),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -487,7 +508,7 @@ constructor(
|
||||
fun onJunkPacketMinSizeChanged(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy = _uiState.value.interfaceProxy.copy(junkPacketMinSize = value),
|
||||
interfaceProxy = it.interfaceProxy.copy(junkPacketMinSize = value),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -495,7 +516,7 @@ constructor(
|
||||
fun onJunkPacketMaxSizeChanged(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy = _uiState.value.interfaceProxy.copy(junkPacketMaxSize = value),
|
||||
interfaceProxy = it.interfaceProxy.copy(junkPacketMaxSize = value),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -503,7 +524,7 @@ constructor(
|
||||
fun onInitPacketJunkSizeChanged(value: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy = _uiState.value.interfaceProxy.copy(initPacketJunkSize = value),
|
||||
interfaceProxy = it.interfaceProxy.copy(initPacketJunkSize = value),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -512,7 +533,7 @@ constructor(
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy =
|
||||
_uiState.value.interfaceProxy.copy(
|
||||
it.interfaceProxy.copy(
|
||||
responsePacketJunkSize = value,
|
||||
),
|
||||
)
|
||||
@@ -523,7 +544,7 @@ constructor(
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy =
|
||||
_uiState.value.interfaceProxy.copy(
|
||||
it.interfaceProxy.copy(
|
||||
initPacketMagicHeader = value,
|
||||
),
|
||||
)
|
||||
@@ -534,7 +555,7 @@ constructor(
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy =
|
||||
_uiState.value.interfaceProxy.copy(
|
||||
it.interfaceProxy.copy(
|
||||
responsePacketMagicHeader = value,
|
||||
),
|
||||
)
|
||||
@@ -545,7 +566,7 @@ constructor(
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy =
|
||||
_uiState.value.interfaceProxy.copy(
|
||||
it.interfaceProxy.copy(
|
||||
transportPacketMagicHeader = value,
|
||||
),
|
||||
)
|
||||
@@ -556,10 +577,15 @@ constructor(
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
interfaceProxy =
|
||||
_uiState.value.interfaceProxy.copy(
|
||||
it.interfaceProxy.copy(
|
||||
underloadPacketMagicHeader = value,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@AssistedFactory
|
||||
interface ConfigViewModelFactory {
|
||||
fun create(id: Int): ConfigViewModel
|
||||
}
|
||||
}
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.config.components
|
||||
|
||||
import android.content.pm.PackageInfo
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Android
|
||||
import androidx.compose.material3.BasicAlertDialog
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.google.accompanist.drawablepainter.DrawablePainter
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.SearchBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ApplicationSelectionDialog(viewModel: ConfigViewModel, uiState: ConfigUiState, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val licenseComparator = compareBy<PackageInfo> { viewModel.getPackageLabel(it) }
|
||||
|
||||
val sortedPackages = remember(uiState.packages, licenseComparator) {
|
||||
uiState.packages.sortedWith(licenseComparator)
|
||||
}
|
||||
BasicAlertDialog(
|
||||
onDismissRequest = { onDismiss() },
|
||||
) {
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.fillMaxHeight(if (uiState.isAllApplicationsEnabled) 1 / 5f else 4 / 5f),
|
||||
) {
|
||||
Column(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(stringResource(id = R.string.tunnel_all))
|
||||
Switch(
|
||||
checked = uiState.isAllApplicationsEnabled,
|
||||
onCheckedChange = viewModel::onAllApplicationsChange,
|
||||
)
|
||||
}
|
||||
if (!uiState.isAllApplicationsEnabled) {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(stringResource(id = R.string.include))
|
||||
Checkbox(
|
||||
checked = uiState.include,
|
||||
onCheckedChange = {
|
||||
viewModel.onIncludeChange(!uiState.include)
|
||||
},
|
||||
)
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(stringResource(id = R.string.exclude))
|
||||
Checkbox(
|
||||
checked = !uiState.include,
|
||||
onCheckedChange = {
|
||||
viewModel.onIncludeChange(!uiState.include)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
SearchBar(viewModel::emitQueriedPackages)
|
||||
}
|
||||
Spacer(Modifier.padding(5.dp))
|
||||
LazyColumn(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.fillMaxHeight(19 / 22f),
|
||||
) {
|
||||
items(sortedPackages, key = { it.packageName }) { pack ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(5.dp).padding(end = 25.dp),
|
||||
) {
|
||||
Row(modifier = Modifier.fillMaxWidth().padding(start = 5.dp)) {
|
||||
val drawable =
|
||||
pack.applicationInfo?.loadIcon(context.packageManager)
|
||||
val iconSize = 35.dp
|
||||
if (drawable != null) {
|
||||
Image(
|
||||
painter = DrawablePainter(drawable),
|
||||
stringResource(id = R.string.icon),
|
||||
modifier = Modifier.size(iconSize),
|
||||
)
|
||||
} else {
|
||||
val icon = Icons.Rounded.Android
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier = Modifier.size(iconSize),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
viewModel.getPackageLabel(pack),
|
||||
modifier = Modifier.padding(5.dp),
|
||||
)
|
||||
}
|
||||
Checkbox(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
checked =
|
||||
(
|
||||
uiState.checkedPackageNames.contains(
|
||||
pack.packageName,
|
||||
)
|
||||
),
|
||||
onCheckedChange = {
|
||||
if (it) {
|
||||
viewModel.onAddCheckedPackage(pack.packageName)
|
||||
} else {
|
||||
viewModel.onRemoveCheckedPackage(pack.packageName)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = 5.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
TextButton(onClick = { onDismiss() }) {
|
||||
Text(stringResource(R.string.done))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -25,7 +25,10 @@ data class InterfaceProxy(
|
||||
publicKey = i.keyPair.publicKey.toBase64().trim(),
|
||||
privateKey = i.keyPair.privateKey.toBase64().trim(),
|
||||
addresses = i.addresses.joinToString(", ").trim(),
|
||||
dnsServers = i.dnsServers.joinToString(", ").replace("/", "").trim(),
|
||||
dnsServers = listOf(
|
||||
i.dnsServers.joinToString(", ").replace("/", "").trim(),
|
||||
i.dnsSearchDomains.joinToString(", ").trim(),
|
||||
).filter { it.length > 0 }.joinToString(", "),
|
||||
listenPort =
|
||||
if (i.listenPort.isPresent) {
|
||||
i.listenPort.get().toString().trim()
|
||||
@@ -41,7 +44,7 @@ data class InterfaceProxy(
|
||||
publicKey = i.keyPair.publicKey.toBase64().trim(),
|
||||
privateKey = i.keyPair.privateKey.toBase64().trim(),
|
||||
addresses = i.addresses.joinToString(", ").trim(),
|
||||
dnsServers = i.dnsServers.joinToString(", ").replace("/", "").trim(),
|
||||
dnsServers = (i.dnsServers + i.dnsSearchDomains).joinToString(", ").replace("/", "").trim(),
|
||||
listenPort =
|
||||
if (i.listenPort.isPresent) {
|
||||
i.listenPort.get().toString().trim()
|
||||
|
||||
+129
-425
@@ -1,183 +1,112 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.net.VpnService
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.ScrollableDefaults
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.overscroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Bolt
|
||||
import androidx.compose.material.icons.rounded.Circle
|
||||
import androidx.compose.material.icons.rounded.CopyAll
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.Info
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import androidx.compose.material.icons.rounded.Smartphone
|
||||
import androidx.compose.material.icons.rounded.Star
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material3.FabPosition
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
|
||||
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
|
||||
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavController
|
||||
import com.journeyapps.barcodescanner.ScanContract
|
||||
import com.journeyapps.barcodescanner.ScanOptions
|
||||
import com.wireguard.android.backend.GoBackend
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.RowListItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.NestedScrollListener
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.InfoDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.functions.rememberFileImportLauncherForResult
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.screen.LoadingScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.AutoTunnelRowItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.GettingStartedLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.ScrollDismissMultiFab
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.ScrollDismissFab
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.TunnelImportSheet
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.TunnelRowItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.VpnDeniedDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.corn
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.mint
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.getMessage
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.handshakeStatus
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isBatteryOptimizationsDisabled
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.mapPeerStats
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.openWebUrl
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
|
||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun MainScreen(
|
||||
viewModel: MainViewModel = hiltViewModel(),
|
||||
appViewModel: AppViewModel,
|
||||
focusRequester: FocusRequester,
|
||||
navController: NavController,
|
||||
) {
|
||||
val haptic = LocalHapticFeedback.current
|
||||
fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val navController = LocalNavController.current
|
||||
val snackbar = SnackbarController.current
|
||||
|
||||
var showBottomSheet by remember { mutableStateOf(false) }
|
||||
var configType by remember { mutableStateOf(ConfigType.WIREGUARD) }
|
||||
var showVpnPermissionDialog by remember { mutableStateOf(false) }
|
||||
val isVisible = rememberSaveable { mutableStateOf(true) }
|
||||
var isFabVisible by rememberSaveable { mutableStateOf(true) }
|
||||
var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) }
|
||||
var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) }
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
val isRunningOnTv = remember { context.isRunningOnTv() }
|
||||
|
||||
val nestedScrollConnection =
|
||||
remember {
|
||||
object : NestedScrollConnection {
|
||||
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
|
||||
// Hide FAB
|
||||
if (available.y < -1) {
|
||||
isVisible.value = false
|
||||
}
|
||||
// Show FAB
|
||||
if (available.y > 1) {
|
||||
isVisible.value = true
|
||||
}
|
||||
return Offset.Zero
|
||||
}
|
||||
}
|
||||
}
|
||||
val nestedScrollConnection = remember {
|
||||
NestedScrollListener({ isFabVisible = false }, { isFabVisible = true })
|
||||
}
|
||||
|
||||
val vpnActivityResultState =
|
||||
val vpnActivity =
|
||||
rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
onResult = {
|
||||
val accepted = (it.resultCode == RESULT_OK)
|
||||
if (accepted) {
|
||||
Timber.d("VPN permission granted")
|
||||
} else {
|
||||
showVpnPermissionDialog = true
|
||||
}
|
||||
if (it.resultCode != RESULT_OK) showVpnPermissionDialog = true
|
||||
},
|
||||
)
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
if (context.isRunningOnTv()) {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
kotlin.runCatching {
|
||||
focusRequester.requestFocus()
|
||||
}.onFailure {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
val batteryActivity =
|
||||
rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result: ActivityResult ->
|
||||
viewModel.setBatteryOptimizeDisableShown()
|
||||
}
|
||||
}
|
||||
|
||||
val tunnelFileImportResultLauncher = rememberFileImportLauncherForResult(onNoFileExplorer = {
|
||||
appViewModel.showSnackbarMessage(
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.error_no_file_explorer),
|
||||
)
|
||||
}, onData = { data ->
|
||||
scope.launch {
|
||||
viewModel.onTunnelFileSelected(data, configType, context).onFailure {
|
||||
appViewModel.showSnackbarMessage(it.getMessage(context))
|
||||
}
|
||||
}
|
||||
viewModel.onTunnelFileSelected(data, context)
|
||||
})
|
||||
|
||||
val scanLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ScanContract(),
|
||||
onResult = {
|
||||
if (it.contents != null) {
|
||||
scope.launch {
|
||||
viewModel.onTunnelQrResult(it.contents, configType).onFailure { error ->
|
||||
appViewModel.showSnackbarMessage(error.getMessage(context))
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
val requestPermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestPermission(),
|
||||
) { isGranted ->
|
||||
if (!isGranted) return@rememberLauncherForActivityResult snackbar.showMessage("Camera permission required")
|
||||
navController.navigate(Route.Scanner)
|
||||
}
|
||||
|
||||
VpnDeniedDialog(showVpnPermissionDialog, onDismiss = { showVpnPermissionDialog = false })
|
||||
|
||||
@@ -185,7 +114,7 @@ fun MainScreen(
|
||||
InfoDialog(
|
||||
onDismiss = { showDeleteTunnelAlertDialog = false },
|
||||
onAttest = {
|
||||
selectedTunnel?.let { viewModel.onDelete(it, context) }
|
||||
selectedTunnel?.let { viewModel::onDelete }
|
||||
showDeleteTunnelAlertDialog = false
|
||||
selectedTunnel = null
|
||||
},
|
||||
@@ -195,62 +124,90 @@ fun MainScreen(
|
||||
)
|
||||
}
|
||||
|
||||
fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) {
|
||||
if (checked) {
|
||||
if (uiState.settings.isKernelEnabled) {
|
||||
context.startTunnelBackground(tunnel.id)
|
||||
} else {
|
||||
viewModel.onTunnelStart(tunnel)
|
||||
fun requestBatteryOptimizationsDisabled() {
|
||||
val intent =
|
||||
Intent().apply {
|
||||
action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
|
||||
data = Uri.parse("package:${context.packageName}")
|
||||
}
|
||||
} else {
|
||||
viewModel.onTunnelStop(
|
||||
tunnel,
|
||||
)
|
||||
batteryActivity.launch(intent)
|
||||
}
|
||||
|
||||
fun onAutoTunnelToggle() {
|
||||
if (!uiState.generalState.isBatteryOptimizationDisableShown &&
|
||||
!context.isBatteryOptimizationsDisabled() && !isRunningOnTv
|
||||
) {
|
||||
return requestBatteryOptimizationsDisabled()
|
||||
}
|
||||
val intent = if (!uiState.settings.isKernelEnabled) {
|
||||
VpnService.prepare(context)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (intent != null) return vpnActivity.launch(intent)
|
||||
viewModel.onToggleAutoTunnel()
|
||||
}
|
||||
|
||||
if (uiState.loading) {
|
||||
return LoadingScreen()
|
||||
}
|
||||
|
||||
fun launchQrScanner() {
|
||||
val scanOptions = ScanOptions()
|
||||
scanOptions.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
||||
scanOptions.setOrientationLocked(true)
|
||||
scanOptions.setPrompt(
|
||||
context.getString(R.string.scanning_qr),
|
||||
)
|
||||
scanOptions.setBeepEnabled(false)
|
||||
scanLauncher.launch(scanOptions)
|
||||
fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) {
|
||||
val intent = if (uiState.settings.isKernelEnabled) null else VpnService.prepare(context)
|
||||
if (intent != null) return vpnActivity.launch(intent)
|
||||
if (!checked) viewModel.onTunnelStop(tunnel).also { return }
|
||||
viewModel.onTunnelStart(tunnel, uiState.settings.isKernelEnabled)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
modifier =
|
||||
Modifier.pointerInput(Unit) {
|
||||
if (uiState.tunnels.isNotEmpty()) {
|
||||
detectTapGestures(
|
||||
onTap = {
|
||||
selectedTunnel = null
|
||||
},
|
||||
)
|
||||
}
|
||||
if (uiState.tunnels.isEmpty()) return@pointerInput
|
||||
detectTapGestures(
|
||||
onTap = {
|
||||
selectedTunnel = null
|
||||
},
|
||||
)
|
||||
},
|
||||
floatingActionButtonPosition = FabPosition.End,
|
||||
floatingActionButton = {
|
||||
ScrollDismissMultiFab(R.drawable.add, focusRequester, isVisible = isVisible.value, onFabItemClicked = {
|
||||
showBottomSheet = true
|
||||
configType = ConfigType.valueOf(it.value)
|
||||
})
|
||||
if (!isRunningOnTv) {
|
||||
ScrollDismissFab({
|
||||
val icon = Icons.Filled.Add
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
tint = MaterialTheme.colorScheme.onPrimary,
|
||||
)
|
||||
}, isVisible = isFabVisible, onClick = {
|
||||
showBottomSheet = true
|
||||
})
|
||||
}
|
||||
},
|
||||
topBar = {
|
||||
if (isRunningOnTv) {
|
||||
TopNavBar(
|
||||
showBack = false,
|
||||
title = stringResource(R.string.app_name),
|
||||
trailing = {
|
||||
IconButton(onClick = {
|
||||
showBottomSheet = true
|
||||
}) {
|
||||
val icon = Icons.Outlined.Add
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
TunnelImportSheet(
|
||||
showBottomSheet,
|
||||
onDismiss = { showBottomSheet = false },
|
||||
onFileClick = { tunnelFileImportResultLauncher.launch(Constants.ALLOWED_FILE_TYPES) },
|
||||
onQrClick = { launchQrScanner() },
|
||||
onFileClick = { tunnelFileImportResultLauncher.launch(Constants.ALLOWED_TV_FILE_TYPES) },
|
||||
onQrClick = { requestPermissionLauncher.launch(android.Manifest.permission.CAMERA) },
|
||||
onManualImportClick = {
|
||||
navController.navigate(
|
||||
"${Screen.Config.route}/${Constants.MANUAL_TUNNEL_CONFIG_ID}?configType=$configType",
|
||||
Route.Config(Constants.MANUAL_TUNNEL_CONFIG_ID),
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -259,7 +216,7 @@ fun MainScreen(
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.fillMaxSize().padding(it)
|
||||
.overscroll(ScrollableDefaults.overscrollEffect())
|
||||
.nestedScroll(nestedScrollConnection),
|
||||
state = rememberLazyListState(0, uiState.tunnels.count()),
|
||||
@@ -271,286 +228,33 @@ fun MainScreen(
|
||||
item {
|
||||
GettingStartedLabel(onClick = { context.openWebUrl(it) })
|
||||
}
|
||||
}
|
||||
item {
|
||||
if (uiState.settings.isAutoTunnelEnabled) {
|
||||
val itemFocusRequester = remember { FocusRequester() }
|
||||
val autoTunnelingLabel =
|
||||
buildAnnotatedString {
|
||||
append(stringResource(id = R.string.auto_tunneling))
|
||||
append(": ")
|
||||
if (uiState.settings.isAutoTunnelPaused) {
|
||||
append(
|
||||
stringResource(id = R.string.paused),
|
||||
)
|
||||
} else {
|
||||
append(
|
||||
stringResource(id = R.string.active),
|
||||
)
|
||||
}
|
||||
}
|
||||
RowListItem(
|
||||
icon = {
|
||||
val icon = Icons.Rounded.Bolt
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(end = 8.5.dp)
|
||||
.size(25.dp),
|
||||
tint =
|
||||
if (uiState.settings.isAutoTunnelPaused) {
|
||||
Color.Gray
|
||||
} else {
|
||||
mint
|
||||
},
|
||||
)
|
||||
},
|
||||
text = autoTunnelingLabel.text,
|
||||
rowButton = {
|
||||
if (uiState.settings.isAutoTunnelPaused) {
|
||||
TextButton(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
onClick = { viewModel.resumeAutoTunneling() },
|
||||
) {
|
||||
Text(stringResource(id = R.string.resume))
|
||||
}
|
||||
} else {
|
||||
TextButton(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
onClick = { viewModel.pauseAutoTunneling() },
|
||||
) {
|
||||
Text(stringResource(id = R.string.pause))
|
||||
}
|
||||
}
|
||||
},
|
||||
onClick = {
|
||||
if (context.isRunningOnTv()) {
|
||||
itemFocusRequester.requestFocus()
|
||||
}
|
||||
},
|
||||
onHold = {},
|
||||
expanded = false,
|
||||
statistics = null,
|
||||
focusRequester = focusRequester,
|
||||
)
|
||||
} else {
|
||||
item {
|
||||
AutoTunnelRowItem(uiState, {
|
||||
onAutoTunnelToggle()
|
||||
})
|
||||
}
|
||||
}
|
||||
items(
|
||||
uiState.tunnels,
|
||||
key = { tunnel -> tunnel.id },
|
||||
) { tunnel ->
|
||||
val isActive = uiState.tunnels.any { it.id == tunnel.id && it.isActive }
|
||||
val leadingIconColor =
|
||||
(
|
||||
if (
|
||||
isActive
|
||||
) {
|
||||
uiState.vpnState.statistics
|
||||
?.mapPeerStats()
|
||||
?.map { it.value?.handshakeStatus() }
|
||||
.let { statuses ->
|
||||
when {
|
||||
statuses?.all { it == HandshakeStatus.HEALTHY } == true -> mint
|
||||
statuses?.any { it == HandshakeStatus.STALE } == true -> corn
|
||||
statuses?.all { it == HandshakeStatus.NOT_STARTED } == true ->
|
||||
Color.Gray
|
||||
|
||||
else -> {
|
||||
Color.Gray
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Color.Gray
|
||||
}
|
||||
)
|
||||
val itemFocusRequester = remember { FocusRequester() }
|
||||
val expanded = remember { mutableStateOf(false) }
|
||||
RowListItem(
|
||||
icon = {
|
||||
val circleIcon = Icons.Rounded.Circle
|
||||
val icon =
|
||||
if (tunnel.isPrimaryTunnel) {
|
||||
Icons.Rounded.Star
|
||||
} else if (tunnel.isMobileDataTunnel) {
|
||||
Icons.Rounded.Smartphone
|
||||
} else {
|
||||
circleIcon
|
||||
}
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
tint = leadingIconColor,
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(
|
||||
end = if (icon == circleIcon) 12.5.dp else 10.dp,
|
||||
start = if (icon == circleIcon) 2.5.dp else 0.dp,
|
||||
)
|
||||
.size(if (icon == circleIcon) 15.dp else 20.dp),
|
||||
)
|
||||
},
|
||||
text = tunnel.name,
|
||||
onHold = {
|
||||
if (
|
||||
(uiState.vpnState.status == TunnelState.UP) &&
|
||||
(tunnel.name == uiState.vpnState.tunnelConfig?.name)
|
||||
) {
|
||||
appViewModel.showSnackbarMessage(
|
||||
context.getString(R.string.turn_off_tunnel),
|
||||
)
|
||||
return@RowListItem
|
||||
}
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
selectedTunnel = tunnel
|
||||
},
|
||||
onClick = {
|
||||
if (!context.isRunningOnTv()) {
|
||||
if (
|
||||
isActive
|
||||
) {
|
||||
expanded.value = !expanded.value
|
||||
}
|
||||
} else {
|
||||
selectedTunnel = tunnel
|
||||
itemFocusRequester.requestFocus()
|
||||
}
|
||||
},
|
||||
statistics = uiState.vpnState.statistics,
|
||||
expanded = expanded.value,
|
||||
focusRequester = focusRequester,
|
||||
rowButton = {
|
||||
if (
|
||||
tunnel.id == selectedTunnel?.id &&
|
||||
!context.isRunningOnTv()
|
||||
) {
|
||||
Row {
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (
|
||||
uiState.settings.isAutoTunnelEnabled &&
|
||||
!uiState.settings.isAutoTunnelPaused
|
||||
) {
|
||||
appViewModel.showSnackbarMessage(
|
||||
context.getString(R.string.turn_off_tunnel),
|
||||
)
|
||||
} else {
|
||||
navController.navigate(
|
||||
"${Screen.Option.route}/${selectedTunnel?.id}",
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Settings
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
modifier = Modifier.focusable(),
|
||||
onClick = { viewModel.onCopyTunnel(selectedTunnel) },
|
||||
) {
|
||||
val icon = Icons.Rounded.CopyAll
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
modifier = Modifier.focusable(),
|
||||
onClick = { showDeleteTunnelAlertDialog = true },
|
||||
) {
|
||||
val icon = Icons.Rounded.Delete
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!isActive) expanded.value = false
|
||||
@Composable
|
||||
fun TunnelSwitch() = Switch(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
checked = isActive,
|
||||
onCheckedChange = { checked ->
|
||||
if (!checked) expanded.value = false
|
||||
val intent = if (uiState.settings.isKernelEnabled) null else GoBackend.VpnService.prepare(context)
|
||||
if (intent != null) return@Switch vpnActivityResultState.launch(intent)
|
||||
onTunnelToggle(checked, tunnel)
|
||||
},
|
||||
)
|
||||
if (context.isRunningOnTv()) {
|
||||
Row {
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (uiState.settings.isAutoTunnelEnabled && !uiState.settings.isAutoTunnelPaused) {
|
||||
appViewModel.showSnackbarMessage(
|
||||
context.getString(R.string.turn_off_auto),
|
||||
)
|
||||
} else {
|
||||
selectedTunnel = tunnel
|
||||
navController.navigate(
|
||||
"${Screen.Option.route}/${selectedTunnel?.id}",
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Settings
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
modifier = Modifier.focusRequester(focusRequester),
|
||||
onClick = {
|
||||
if (
|
||||
uiState.vpnState.status == TunnelState.UP &&
|
||||
(uiState.vpnState.tunnelConfig?.name == tunnel.name)
|
||||
) {
|
||||
expanded.value = !expanded.value
|
||||
} else {
|
||||
appViewModel.showSnackbarMessage(
|
||||
context.getString(R.string.turn_on_tunnel),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Info
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { viewModel.onCopyTunnel(tunnel) },
|
||||
) {
|
||||
val icon = Icons.Rounded.CopyAll
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (
|
||||
uiState.vpnState.status == TunnelState.UP &&
|
||||
tunnel.name == uiState.vpnState.tunnelConfig?.name
|
||||
) {
|
||||
appViewModel.showSnackbarMessage(
|
||||
context.getString(R.string.turn_off_tunnel),
|
||||
)
|
||||
} else {
|
||||
selectedTunnel = tunnel
|
||||
showDeleteTunnelAlertDialog = true
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Delete
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
TunnelSwitch()
|
||||
}
|
||||
} else {
|
||||
TunnelSwitch()
|
||||
}
|
||||
}
|
||||
},
|
||||
val isActive = uiState.tunnels.any {
|
||||
it.id == tunnel.id &&
|
||||
it.isActive
|
||||
}
|
||||
val expanded = uiState.generalState.isTunnelStatsExpanded
|
||||
TunnelRowItem(
|
||||
isActive,
|
||||
expanded,
|
||||
selectedTunnel?.id == tunnel.id,
|
||||
tunnel,
|
||||
vpnState = uiState.vpnState,
|
||||
{ selectedTunnel = tunnel },
|
||||
{ viewModel.onExpandedChanged(!expanded) },
|
||||
onDelete = { showDeleteTunnelAlertDialog = true },
|
||||
onCopy = { viewModel.onCopyTunnel(tunnel) },
|
||||
onSwitchClick = { onTunnelToggle(it, tunnel) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||
|
||||
data class MainUiState(
|
||||
val settings: Settings = Settings(),
|
||||
val tunnels: TunnelConfigs = emptyList(),
|
||||
val vpnState: VpnState = VpnState(),
|
||||
val loading: Boolean = true,
|
||||
)
|
||||
+115
-230
@@ -6,62 +6,48 @@ import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.wireguard.config.Config
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.FileReadException
|
||||
import com.zaneschepke.wireguardautotunnel.util.InvalidFileExtensionException
|
||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.extractNameAndNumber
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.hasNumberInParentheses
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.toWgQuickString
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import timber.log.Timber
|
||||
import java.io.InputStream
|
||||
import java.util.zip.ZipInputStream
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@HiltViewModel
|
||||
class MainViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
private val serviceManager: ServiceManager,
|
||||
val tunnelService: TunnelService,
|
||||
private val tunnelService: Provider<TunnelService>,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
private val serviceManager: ServiceManager,
|
||||
) : ViewModel() {
|
||||
val uiState =
|
||||
combine(
|
||||
appDataRepository.settings.getSettingsFlow(),
|
||||
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
||||
tunnelService.vpnState,
|
||||
) { settings, tunnels, vpnState ->
|
||||
MainUiState(settings, tunnels, vpnState, false)
|
||||
}
|
||||
.stateIn(
|
||||
viewModelScope,
|
||||
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||
MainUiState(),
|
||||
)
|
||||
|
||||
private fun stopWatcherService(context: Context) {
|
||||
serviceManager.stopWatcherService(context)
|
||||
}
|
||||
|
||||
fun onDelete(tunnel: TunnelConfig, context: Context) {
|
||||
fun onDelete(tunnel: TunnelConfig) {
|
||||
viewModelScope.launch {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
val isPrimary = tunnel.isPrimaryTunnel
|
||||
if (appDataRepository.tunnels.count() == 1 || isPrimary) {
|
||||
stopWatcherService(context)
|
||||
serviceManager.stopAutoTunnel()
|
||||
resetTunnelSetting(settings)
|
||||
}
|
||||
appDataRepository.tunnels.delete(tunnel)
|
||||
@@ -77,42 +63,31 @@ constructor(
|
||||
)
|
||||
}
|
||||
|
||||
fun onTunnelStart(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
fun onExpandedChanged(expanded: Boolean) = viewModelScope.launch {
|
||||
appDataRepository.appState.setTunnelStatsExpanded(expanded)
|
||||
}
|
||||
|
||||
fun onTunnelStart(tunnelConfig: TunnelConfig, background: Boolean) = viewModelScope.launch {
|
||||
Timber.i("Starting tunnel ${tunnelConfig.name}")
|
||||
tunnelService.startTunnel(tunnelConfig)
|
||||
tunnelService.get().startTunnel(tunnelConfig, background)
|
||||
}
|
||||
|
||||
fun onTunnelStop(tunnel: TunnelConfig) = viewModelScope.launch {
|
||||
Timber.i("Stopping active tunnel")
|
||||
tunnelService.stopTunnel(tunnel)
|
||||
tunnelService.get().stopTunnel(tunnel)
|
||||
}
|
||||
|
||||
private fun validateConfigString(config: String, configType: ConfigType) {
|
||||
when (configType) {
|
||||
ConfigType.AMNEZIA -> TunnelConfig.configFromAmQuick(config)
|
||||
ConfigType.WIREGUARD -> TunnelConfig.configFromWgQuick(config)
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateQrCodeDefaultName(config: String, configType: ConfigType): String {
|
||||
private fun generateQrCodeDefaultName(config: String): String {
|
||||
return try {
|
||||
when (configType) {
|
||||
ConfigType.AMNEZIA -> {
|
||||
TunnelConfig.configFromAmQuick(config).peers[0].endpoint.get().host
|
||||
}
|
||||
|
||||
ConfigType.WIREGUARD -> {
|
||||
TunnelConfig.configFromWgQuick(config).peers[0].endpoint.get().host
|
||||
}
|
||||
}
|
||||
TunnelConfig.configFromAmQuick(config).peers[0].endpoint.get().host
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e)
|
||||
NumberUtils.generateRandomTunnelName()
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateQrCodeTunnelName(config: String, configType: ConfigType): String {
|
||||
var defaultName = generateQrCodeDefaultName(config, configType)
|
||||
private fun generateQrCodeTunnelName(config: String): String {
|
||||
var defaultName = generateQrCodeDefaultName(config)
|
||||
val lines = config.lines().toMutableList()
|
||||
val linesIterator = lines.iterator()
|
||||
while (linesIterator.hasNext()) {
|
||||
@@ -125,189 +100,107 @@ constructor(
|
||||
return defaultName
|
||||
}
|
||||
|
||||
suspend fun onTunnelQrResult(result: String, configType: ConfigType): Result<Unit> {
|
||||
return withContext(ioDispatcher) {
|
||||
try {
|
||||
validateConfigString(result, configType)
|
||||
val tunnelName =
|
||||
makeTunnelNameUnique(generateQrCodeTunnelName(result, configType))
|
||||
val tunnelConfig =
|
||||
when (configType) {
|
||||
ConfigType.AMNEZIA -> {
|
||||
TunnelConfig(
|
||||
name = tunnelName,
|
||||
amQuick = result,
|
||||
wgQuick =
|
||||
TunnelConfig.configFromAmQuick(
|
||||
result,
|
||||
).toWgQuickString(),
|
||||
)
|
||||
}
|
||||
|
||||
ConfigType.WIREGUARD ->
|
||||
TunnelConfig(
|
||||
name = tunnelName,
|
||||
wgQuick = result,
|
||||
)
|
||||
}
|
||||
addTunnel(tunnelConfig)
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e)
|
||||
Result.failure(WgTunnelExceptions.InvalidQrCode())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun makeTunnelNameUnique(name: String): String {
|
||||
return withContext(ioDispatcher) {
|
||||
val tunnels = appDataRepository.tunnels.getAll()
|
||||
var tunnelName = name
|
||||
var num = 1
|
||||
while (tunnels.any { it.name == tunnelName }) {
|
||||
tunnelName = "$name($num)"
|
||||
tunnelName = if (!tunnelName.hasNumberInParentheses()) {
|
||||
"$name($num)"
|
||||
} else {
|
||||
val pair = tunnelName.extractNameAndNumber()
|
||||
"${pair?.first}($num)"
|
||||
}
|
||||
num++
|
||||
}
|
||||
tunnelName
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveTunnelConfigFromStream(stream: InputStream, fileName: String, type: ConfigType) {
|
||||
var amQuick: String? = null
|
||||
val wgQuick =
|
||||
stream.use {
|
||||
when (type) {
|
||||
ConfigType.AMNEZIA -> {
|
||||
val config = org.amnezia.awg.config.Config.parse(it)
|
||||
amQuick = config.toAwgQuickString(true)
|
||||
config.toWgQuickString()
|
||||
}
|
||||
|
||||
ConfigType.WIREGUARD -> {
|
||||
Config.parse(it).toWgQuickString(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val tunnelName = makeTunnelNameUnique(getNameFromFileName(fileName))
|
||||
addTunnel(
|
||||
TunnelConfig(
|
||||
name = tunnelName,
|
||||
wgQuick = wgQuick,
|
||||
amQuick = amQuick ?: TunnelConfig.AM_QUICK_DEFAULT,
|
||||
),
|
||||
)
|
||||
}
|
||||
private suspend fun saveTunnelConfigFromStream(stream: InputStream, fileName: String) {
|
||||
val amConfig = stream.use { org.amnezia.awg.config.Config.parse(it) }
|
||||
val tunnelName = makeTunnelNameUnique(getNameFromFileName(fileName))
|
||||
saveTunnel(
|
||||
TunnelConfig(
|
||||
name = tunnelName,
|
||||
wgQuick = amConfig.toWgQuickString(),
|
||||
amQuick = amConfig.toAwgQuickString(true),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun getInputStreamFromUri(uri: Uri, context: Context): InputStream? {
|
||||
return context.applicationContext.contentResolver.openInputStream(uri)
|
||||
}
|
||||
|
||||
suspend fun onTunnelFileSelected(uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
|
||||
return withContext(ioDispatcher) {
|
||||
try {
|
||||
if (isValidUriContentScheme(uri)) {
|
||||
val fileName = getFileName(context, uri)
|
||||
return@withContext when (getFileExtensionFromFileName(fileName)) {
|
||||
Constants.CONF_FILE_EXTENSION ->
|
||||
saveTunnelFromConfUri(fileName, uri, configType, context)
|
||||
|
||||
Constants.ZIP_FILE_EXTENSION ->
|
||||
saveTunnelsFromZipUri(
|
||||
uri,
|
||||
configType,
|
||||
context,
|
||||
)
|
||||
|
||||
else -> Result.failure(WgTunnelExceptions.InvalidFileExtension())
|
||||
}
|
||||
} else {
|
||||
Result.failure(WgTunnelExceptions.InvalidFileExtension())
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e)
|
||||
Result.failure(WgTunnelExceptions.FileReadFailed())
|
||||
fun onTunnelFileSelected(uri: Uri, context: Context) = viewModelScope.launch(ioDispatcher) {
|
||||
kotlin.runCatching {
|
||||
if (!isValidUriContentScheme(uri)) throw InvalidFileExtensionException
|
||||
val fileName = getFileName(context, uri)
|
||||
when (getFileExtensionFromFileName(fileName)) {
|
||||
Constants.CONF_FILE_EXTENSION ->
|
||||
saveTunnelFromConfUri(fileName, uri, context)
|
||||
Constants.ZIP_FILE_EXTENSION ->
|
||||
saveTunnelsFromZipUri(
|
||||
uri,
|
||||
context,
|
||||
)
|
||||
else -> throw InvalidFileExtensionException
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun saveTunnelsFromZipUri(uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
|
||||
return withContext(ioDispatcher) {
|
||||
ZipInputStream(getInputStreamFromUri(uri, context)).use { zip ->
|
||||
generateSequence { zip.nextEntry }
|
||||
.filterNot {
|
||||
it.isDirectory ||
|
||||
getFileExtensionFromFileName(it.name) != Constants.CONF_FILE_EXTENSION
|
||||
}
|
||||
.forEach {
|
||||
val name = getNameFromFileName(it.name)
|
||||
withContext(viewModelScope.coroutineContext) {
|
||||
try {
|
||||
var amQuick: String? = null
|
||||
val wgQuick =
|
||||
when (configType) {
|
||||
ConfigType.AMNEZIA -> {
|
||||
val config =
|
||||
org.amnezia.awg.config.Config.parse(
|
||||
zip,
|
||||
)
|
||||
amQuick = config.toAwgQuickString(true)
|
||||
config.toWgQuickString()
|
||||
}
|
||||
|
||||
ConfigType.WIREGUARD -> {
|
||||
Config.parse(zip).toWgQuickString(true)
|
||||
}
|
||||
}
|
||||
addTunnel(
|
||||
TunnelConfig(
|
||||
name = makeTunnelNameUnique(name),
|
||||
wgQuick = wgQuick,
|
||||
amQuick = amQuick ?: TunnelConfig.AM_QUICK_DEFAULT,
|
||||
),
|
||||
)
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(WgTunnelExceptions.FileReadFailed())
|
||||
}
|
||||
}
|
||||
}
|
||||
Result.success(Unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun saveTunnelFromConfUri(name: String, uri: Uri, configType: ConfigType, context: Context): Result<Unit> {
|
||||
return withContext(ioDispatcher) {
|
||||
val stream = getInputStreamFromUri(uri, context)
|
||||
return@withContext if (stream != null) {
|
||||
try {
|
||||
saveTunnelConfigFromStream(stream, name, configType)
|
||||
} catch (e: Exception) {
|
||||
return@withContext Result.failure(WgTunnelExceptions.ConfigParseError())
|
||||
}
|
||||
Result.success(Unit)
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
if (it is InvalidFileExtensionException) {
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.error_file_extension))
|
||||
} else {
|
||||
Result.failure(WgTunnelExceptions.FileReadFailed())
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.error_file_format))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
saveTunnel(tunnelConfig)
|
||||
}
|
||||
|
||||
fun pauseAutoTunneling() = viewModelScope.launch {
|
||||
fun onToggleAutoTunnel() = viewModelScope.launch {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
val toggled = !settings.isAutoTunnelEnabled
|
||||
if (toggled) {
|
||||
serviceManager.startAutoTunnel(false)
|
||||
} else {
|
||||
serviceManager.stopAutoTunnel()
|
||||
}
|
||||
appDataRepository.settings.save(
|
||||
uiState.value.settings.copy(isAutoTunnelPaused = true),
|
||||
settings.copy(
|
||||
isAutoTunnelEnabled = toggled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun resumeAutoTunneling() = viewModelScope.launch {
|
||||
appDataRepository.settings.save(
|
||||
uiState.value.settings.copy(isAutoTunnelPaused = false),
|
||||
)
|
||||
private suspend fun saveTunnelsFromZipUri(uri: Uri, context: Context) {
|
||||
ZipInputStream(getInputStreamFromUri(uri, context)).use { zip ->
|
||||
generateSequence { zip.nextEntry }
|
||||
.filterNot {
|
||||
it.isDirectory ||
|
||||
getFileExtensionFromFileName(it.name) != Constants.CONF_FILE_EXTENSION
|
||||
}
|
||||
.forEach { entry ->
|
||||
val name = getNameFromFileName(entry.name)
|
||||
val amConf = org.amnezia.awg.config.Config.parse(zip.bufferedReader())
|
||||
saveTunnel(
|
||||
TunnelConfig(
|
||||
name = makeTunnelNameUnique(name),
|
||||
wgQuick = amConf.toWgQuickString(),
|
||||
amQuick = amConf.toAwgQuickString(true),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setBatteryOptimizeDisableShown() = viewModelScope.launch {
|
||||
appDataRepository.appState.setBatteryOptimizationDisableShown(true)
|
||||
}
|
||||
|
||||
private suspend fun saveTunnelFromConfUri(name: String, uri: Uri, context: Context) {
|
||||
val stream = getInputStreamFromUri(uri, context) ?: throw FileReadException
|
||||
saveTunnelConfigFromStream(stream, name)
|
||||
}
|
||||
|
||||
private fun saveTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
@@ -315,32 +208,23 @@ constructor(
|
||||
}
|
||||
|
||||
private fun getFileNameByCursor(context: Context, uri: Uri): String? {
|
||||
context.contentResolver.query(uri, null, null, null, null)?.use {
|
||||
return getDisplayNameByCursor(it)
|
||||
return context.contentResolver.query(uri, null, null, null, null)?.use {
|
||||
getDisplayNameByCursor(it)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun getDisplayNameColumnIndex(cursor: Cursor): Int? {
|
||||
val columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
return if (columnIndex != -1) {
|
||||
return columnIndex
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (columnIndex == -1) return null
|
||||
return columnIndex
|
||||
}
|
||||
|
||||
private fun getDisplayNameByCursor(cursor: Cursor): String? {
|
||||
return if (cursor.moveToFirst()) {
|
||||
val index = getDisplayNameColumnIndex(cursor)
|
||||
if (index != null) {
|
||||
cursor.getString(index)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val move = cursor.moveToFirst()
|
||||
if (!move) return null
|
||||
val index = getDisplayNameColumnIndex(cursor)
|
||||
if (index == null) return index
|
||||
return cursor.getString(index)
|
||||
}
|
||||
|
||||
private fun isValidUriContentScheme(uri: Uri): Boolean {
|
||||
@@ -366,14 +250,15 @@ constructor(
|
||||
|
||||
private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
|
||||
|
||||
fun onCopyTunnel(tunnel: TunnelConfig?) = viewModelScope.launch {
|
||||
tunnel?.let {
|
||||
saveTunnel(
|
||||
TunnelConfig(
|
||||
name = it.name.plus(NumberUtils.randomThree()),
|
||||
wgQuick = it.wgQuick,
|
||||
),
|
||||
)
|
||||
}
|
||||
fun onCopyTunnel(tunnel: TunnelConfig) = viewModelScope.launch {
|
||||
saveTunnel(
|
||||
tunnel.copy(
|
||||
id = 0,
|
||||
isPrimaryTunnel = false,
|
||||
isMobileDataTunnel = false,
|
||||
isActive = false,
|
||||
name = makeTunnelNameUnique(tunnel.name),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Bolt
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.ExpandingRowListItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.ScaledSwitch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.SilverTree
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
|
||||
@Composable
|
||||
fun AutoTunnelRowItem(appUiState: AppUiState, onToggle: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val itemFocusRequester = remember { FocusRequester() }
|
||||
ExpandingRowListItem(
|
||||
leading = {
|
||||
val icon = Icons.Rounded.Bolt
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier =
|
||||
Modifier
|
||||
.size(16.dp.scaledHeight()).scale(1.5f),
|
||||
tint =
|
||||
if (!appUiState.autoTunnelActive) {
|
||||
Color.Gray
|
||||
} else {
|
||||
SilverTree
|
||||
},
|
||||
)
|
||||
},
|
||||
text = stringResource(R.string.auto_tunneling),
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
appUiState.settings.isAutoTunnelEnabled,
|
||||
onClick = {
|
||||
onToggle()
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
if (context.isRunningOnTv()) {
|
||||
itemFocusRequester.requestFocus()
|
||||
}
|
||||
},
|
||||
isExpanded = false,
|
||||
)
|
||||
}
|
||||
+9
-83
@@ -1,108 +1,34 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||
|
||||
import androidx.annotation.DrawableRes
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.iamageo.multifablibrary.FabIcon
|
||||
import com.iamageo.multifablibrary.FabOption
|
||||
import com.iamageo.multifablibrary.MultiFabItem
|
||||
import com.iamageo.multifablibrary.MultiFloatingActionButton
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
||||
|
||||
@Composable
|
||||
fun ScrollDismissMultiFab(
|
||||
@DrawableRes res: Int,
|
||||
focusRequester: FocusRequester,
|
||||
isVisible: Boolean,
|
||||
onFabItemClicked: (fabItem: MultiFabItem) -> Unit,
|
||||
) {
|
||||
// Nested scroll for control FAB
|
||||
|
||||
val context = LocalContext.current
|
||||
|
||||
fun ScrollDismissFab(icon: @Composable () -> Unit, isVisible: Boolean, onClick: () -> Unit) {
|
||||
AnimatedVisibility(
|
||||
visible = isVisible,
|
||||
enter = slideInVertically(initialOffsetY = { it * 2 }),
|
||||
exit = slideOutVertically(targetOffsetY = { it * 2 }),
|
||||
modifier =
|
||||
Modifier
|
||||
.focusRequester(focusRequester)
|
||||
.focusGroup(),
|
||||
) {
|
||||
val fobColor = MaterialTheme.colorScheme.secondary
|
||||
val fobIconColor = MaterialTheme.colorScheme.background
|
||||
MultiFloatingActionButton(
|
||||
fabIcon =
|
||||
FabIcon(
|
||||
iconRes = res,
|
||||
iconResAfterRotate = R.drawable.close,
|
||||
iconRotate = 180f,
|
||||
),
|
||||
fabOption =
|
||||
FabOption(
|
||||
iconTint = fobIconColor,
|
||||
backgroundTint = fobColor,
|
||||
),
|
||||
itemsMultiFab =
|
||||
listOf(
|
||||
MultiFabItem(
|
||||
label = {
|
||||
Text(
|
||||
stringResource(id = R.string.amnezia),
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(end = 10.dp),
|
||||
)
|
||||
},
|
||||
modifier =
|
||||
Modifier
|
||||
.size(40.dp),
|
||||
icon = res,
|
||||
value = ConfigType.AMNEZIA.name,
|
||||
miniFabOption =
|
||||
FabOption(
|
||||
backgroundTint = fobColor,
|
||||
fobIconColor,
|
||||
),
|
||||
),
|
||||
MultiFabItem(
|
||||
label = {
|
||||
Text(
|
||||
stringResource(id = R.string.wireguard),
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(end = 10.dp),
|
||||
)
|
||||
},
|
||||
icon = res,
|
||||
value = ConfigType.WIREGUARD.name,
|
||||
miniFabOption =
|
||||
FabOption(
|
||||
backgroundTint = fobColor,
|
||||
fobIconColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
onFabItemClicked = {
|
||||
onFabItemClicked(it)
|
||||
FloatingActionButton(
|
||||
onClick = {
|
||||
onClick()
|
||||
},
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
)
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
) {
|
||||
icon()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Circle
|
||||
import androidx.compose.material.icons.rounded.CopyAll
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.Info
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import androidx.compose.material.icons.rounded.Smartphone
|
||||
import androidx.compose.material.icons.rounded.Star
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.ExpandingRowListItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.ScaledSwitch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.asColor
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
|
||||
@Composable
|
||||
fun TunnelRowItem(
|
||||
isActive: Boolean,
|
||||
expanded: Boolean,
|
||||
isSelected: Boolean,
|
||||
tunnel: TunnelConfig,
|
||||
vpnState: VpnState,
|
||||
onHold: () -> Unit,
|
||||
onClick: () -> Unit,
|
||||
onCopy: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onSwitchClick: (checked: Boolean) -> Unit,
|
||||
) {
|
||||
val leadingIconColor = if (!isActive) Color.Gray else vpnState.statistics.asColor()
|
||||
val context = LocalContext.current
|
||||
val snackbar = SnackbarController.current
|
||||
val navController = LocalNavController.current
|
||||
val haptic = LocalHapticFeedback.current
|
||||
val itemFocusRequester = remember { FocusRequester() }
|
||||
ExpandingRowListItem(
|
||||
leading = {
|
||||
val circleIcon = Icons.Rounded.Circle
|
||||
val icon =
|
||||
if (tunnel.isPrimaryTunnel) {
|
||||
Icons.Rounded.Star
|
||||
} else if (tunnel.isMobileDataTunnel) {
|
||||
Icons.Rounded.Smartphone
|
||||
} else {
|
||||
circleIcon
|
||||
}
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
tint = leadingIconColor,
|
||||
modifier = Modifier.size(16.dp.scaledHeight()),
|
||||
)
|
||||
},
|
||||
text = tunnel.name,
|
||||
onHold = {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
onHold()
|
||||
},
|
||||
onClick = {
|
||||
if (!context.isRunningOnTv()) {
|
||||
if (isActive) {
|
||||
onClick()
|
||||
}
|
||||
} else {
|
||||
onHold()
|
||||
itemFocusRequester.requestFocus()
|
||||
}
|
||||
},
|
||||
isExpanded = expanded && isActive,
|
||||
expanded = { if (isActive && expanded) TunnelStatisticsRow(vpnState.statistics, tunnel) },
|
||||
trailing = {
|
||||
if (
|
||||
isSelected &&
|
||||
!context.isRunningOnTv()
|
||||
) {
|
||||
Row {
|
||||
IconButton(
|
||||
onClick = {
|
||||
navController.navigate(
|
||||
Route.Option(tunnel.id),
|
||||
)
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Settings
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
modifier = Modifier.focusable(),
|
||||
onClick = { onCopy() },
|
||||
) {
|
||||
val icon = Icons.Rounded.CopyAll
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
enabled = !isActive,
|
||||
modifier = Modifier.focusable(),
|
||||
onClick = { onDelete() },
|
||||
) {
|
||||
val icon = Icons.Rounded.Delete
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (context.isRunningOnTv()) {
|
||||
Row {
|
||||
IconButton(
|
||||
onClick = {
|
||||
onHold()
|
||||
navController.navigate(
|
||||
Route.Option(tunnel.id),
|
||||
)
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Settings
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (isActive) {
|
||||
onClick()
|
||||
} else {
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.turn_on_tunnel),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Info
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { onCopy() },
|
||||
) {
|
||||
val icon = Icons.Rounded.CopyAll
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (isActive) {
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.turn_off_tunnel),
|
||||
)
|
||||
} else {
|
||||
onHold()
|
||||
onDelete()
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Delete
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
ScaledSwitch(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
checked = isActive,
|
||||
onClick = onSwitchClick,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
ScaledSwitch(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
checked = isActive,
|
||||
onClick = onSwitchClick,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.toThreeDecimalPlaceString
|
||||
|
||||
@Composable
|
||||
fun TunnelStatisticsRow(statistics: TunnelStatistics?, tunnelConfig: TunnelConfig) {
|
||||
val config = TunnelConfig.configFromAmQuick(tunnelConfig.wgQuick)
|
||||
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(end = 10.dp, bottom = 10.dp, start = 45.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(30.dp, Alignment.Start),
|
||||
) {
|
||||
config.peers.forEach {
|
||||
val peerId = it.publicKey.toBase64().subSequence(0, 3).toString() + "***"
|
||||
val peerRx = statistics?.peerStats(it.publicKey)?.rxBytes ?: 0
|
||||
val peerTx = statistics?.peerStats(it.publicKey)?.txBytes ?: 0
|
||||
val peerTxMB = NumberUtils.bytesToMB(peerTx).toThreeDecimalPlaceString()
|
||||
val peerRxMB = NumberUtils.bytesToMB(peerRx).toThreeDecimalPlaceString()
|
||||
val handshake = statistics?.peerStats(it.publicKey)?.latestHandshakeEpochMillis?.let {
|
||||
if (it == 0L) {
|
||||
stringResource(R.string.never)
|
||||
} else {
|
||||
"${NumberUtils.getSecondsBetweenTimestampAndNow(it)} ${stringResource(R.string.sec)}"
|
||||
}
|
||||
} ?: stringResource(R.string.never)
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.peer).lowercase() + ": $peerId",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.outline,
|
||||
)
|
||||
Text("tx: $peerTxMB MB", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)
|
||||
}
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.handshake) + ": $handshake", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)
|
||||
Text("rx: $peerRxMB MB", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+149
-247
@@ -1,295 +1,197 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.options
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material.icons.outlined.Edit
|
||||
import androidx.compose.material.icons.outlined.NetworkPing
|
||||
import androidx.compose.material.icons.outlined.PhoneAndroid
|
||||
import androidx.compose.material.icons.outlined.Security
|
||||
import androidx.compose.material.icons.outlined.Star
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavController
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.ClickableIconButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.ScrollDismissMultiFab
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.getMessage
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.ScaledSwitch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SelectionItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SurfaceSelectionGroupButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.label.GroupLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.components.TrustedNetworkTextBox
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.components.WildcardsLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun OptionsScreen(
|
||||
optionsViewModel: OptionsViewModel = hiltViewModel(),
|
||||
navController: NavController,
|
||||
appViewModel: AppViewModel,
|
||||
focusRequester: FocusRequester,
|
||||
tunnelId: String,
|
||||
) {
|
||||
val scrollState = rememberScrollState()
|
||||
val uiState by optionsViewModel.uiState.collectAsStateWithLifecycle()
|
||||
val context = LocalContext.current
|
||||
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val scope = rememberCoroutineScope()
|
||||
val focusManager = LocalFocusManager.current
|
||||
val screenPadding = 5.dp
|
||||
val fillMaxWidth = .85f
|
||||
fun OptionsScreen(optionsViewModel: OptionsViewModel = hiltViewModel(), appUiState: AppUiState, tunnelId: Int) {
|
||||
val navController = LocalNavController.current
|
||||
val config = appUiState.tunnels.first { it.id == tunnelId }
|
||||
|
||||
var currentText by remember { mutableStateOf("") }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
optionsViewModel.init(tunnelId)
|
||||
if (context.isRunningOnTv()) {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
kotlin.runCatching {
|
||||
focusRequester.requestFocus()
|
||||
}.onFailure {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(config.tunnelNetworks) {
|
||||
currentText = ""
|
||||
}
|
||||
|
||||
fun saveTrustedSSID() {
|
||||
if (currentText.isNotEmpty()) {
|
||||
scope.launch {
|
||||
optionsViewModel.onSaveRunSSID(currentText).onSuccess {
|
||||
currentText = ""
|
||||
}.onFailure {
|
||||
appViewModel.showSnackbarMessage(it.getMessage(context))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
floatingActionButton = {
|
||||
ScrollDismissMultiFab(R.drawable.edit, focusRequester, isVisible = true, onFabItemClicked = {
|
||||
val configType = ConfigType.valueOf(it.value)
|
||||
navController.navigate(
|
||||
"${Screen.Config.route}/$tunnelId?configType=${configType.name}",
|
||||
)
|
||||
topBar = {
|
||||
TopNavBar(config.name, trailing = {
|
||||
IconButton(onClick = {
|
||||
navController.navigate(
|
||||
Route.Config(config.id),
|
||||
)
|
||||
}) {
|
||||
val icon = Icons.Outlined.Edit
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
)
|
||||
}
|
||||
})
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(scrollState)
|
||||
.clickable(
|
||||
indication = null,
|
||||
interactionSource = interactionSource,
|
||||
) {
|
||||
focusManager.clearFocus()
|
||||
},
|
||||
.padding(it)
|
||||
.padding(top = 24.dp.scaledHeight())
|
||||
.padding(horizontal = 24.dp.scaledWidth()),
|
||||
) {
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
(
|
||||
if (context.isRunningOnTv()) {
|
||||
Modifier
|
||||
.height(IntrinsicSize.Min)
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 10.dp)
|
||||
} else {
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 20.dp)
|
||||
}
|
||||
)
|
||||
.padding(bottom = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.general),
|
||||
padding = screenPadding,
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.set_primary_tunnel),
|
||||
enabled = true,
|
||||
checked = uiState.isDefaultTunnel,
|
||||
modifier =
|
||||
Modifier
|
||||
.focusRequester(focusRequester),
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { optionsViewModel.onTogglePrimaryTunnel() },
|
||||
)
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
(
|
||||
if (context.isRunningOnTv()) {
|
||||
Modifier
|
||||
.height(IntrinsicSize.Min)
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 10.dp)
|
||||
} else {
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 20.dp)
|
||||
}
|
||||
)
|
||||
.padding(bottom = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.auto_tunneling),
|
||||
padding = screenPadding,
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.mobile_data_tunnel),
|
||||
enabled = true,
|
||||
checked = uiState.tunnel?.isMobileDataTunnel == true,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { optionsViewModel.onToggleIsMobileDataTunnel() },
|
||||
)
|
||||
Column {
|
||||
FlowRow(
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(screenPadding)
|
||||
.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
) {
|
||||
uiState.tunnel?.tunnelNetworks?.forEach { ssid ->
|
||||
ClickableIconButton(
|
||||
onClick = {
|
||||
if (context.isRunningOnTv()) {
|
||||
focusRequester.requestFocus()
|
||||
optionsViewModel.onDeleteRunSSID(ssid)
|
||||
}
|
||||
},
|
||||
onIconClick = {
|
||||
if (context.isRunningOnTv()) focusRequester.requestFocus()
|
||||
optionsViewModel.onDeleteRunSSID(ssid)
|
||||
},
|
||||
text = ssid,
|
||||
icon = Icons.Filled.Close,
|
||||
enabled = true,
|
||||
)
|
||||
}
|
||||
if (uiState.tunnel == null || uiState.tunnel?.tunnelNetworks?.isEmpty() == true) {
|
||||
Text(
|
||||
stringResource(R.string.no_wifi_names_configured),
|
||||
fontStyle = FontStyle.Italic,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
OutlinedTextField(
|
||||
enabled = true,
|
||||
value = currentText,
|
||||
onValueChange = { currentText = it },
|
||||
label = { Text(stringResource(id = R.string.use_tunnel_on_wifi_name)) },
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(
|
||||
start = screenPadding,
|
||||
top = 5.dp,
|
||||
bottom = 10.dp,
|
||||
),
|
||||
maxLines = 1,
|
||||
keyboardOptions =
|
||||
KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardActions = KeyboardActions(onDone = { saveTrustedSSID() }),
|
||||
trailingIcon = {
|
||||
if (currentText != "") {
|
||||
IconButton(onClick = { saveTrustedSSID() }) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Add,
|
||||
contentDescription =
|
||||
if (currentText == "") {
|
||||
stringResource(
|
||||
id =
|
||||
R.string
|
||||
.trusted_ssid_empty_description,
|
||||
)
|
||||
} else {
|
||||
stringResource(
|
||||
id =
|
||||
R.string
|
||||
.trusted_ssid_value_description,
|
||||
)
|
||||
},
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
GroupLabel(stringResource(R.string.auto_tunneling))
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Star,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.primary_tunnel),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
description = {
|
||||
Text(
|
||||
stringResource(R.string.set_primary_tunnel),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.outline),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
config.isPrimaryTunnel,
|
||||
onClick = { optionsViewModel.onTogglePrimaryTunnel(config) },
|
||||
)
|
||||
},
|
||||
onClick = { optionsViewModel.onTogglePrimaryTunnel(config) },
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.PhoneAndroid,
|
||||
title = { Text(stringResource(R.string.mobile_tunnel), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
description = {
|
||||
Text(
|
||||
stringResource(R.string.mobile_data_tunnel),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.outline),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
config.isMobileDataTunnel,
|
||||
onClick = { optionsViewModel.onToggleIsMobileDataTunnel(config) },
|
||||
)
|
||||
},
|
||||
onClick = { optionsViewModel.onToggleIsMobileDataTunnel(config) },
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.NetworkPing,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.restart_on_ping),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
checked = config.isPingEnabled,
|
||||
onClick = { optionsViewModel.onToggleRestartOnPing(config) },
|
||||
)
|
||||
},
|
||||
onClick = { optionsViewModel.onToggleRestartOnPing(config) },
|
||||
),
|
||||
SelectionItem(
|
||||
title = {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp.scaledHeight()),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.weight(4f, false)
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
val icon = Icons.Outlined.Security
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier = Modifier.size(iconSize),
|
||||
)
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterVertically),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 16.dp.scaledWidth())
|
||||
.padding(vertical = 6.dp.scaledHeight()),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.use_tunnel_on_wifi_name),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
description = {
|
||||
TrustedNetworkTextBox(
|
||||
config.tunnelNetworks,
|
||||
onDelete = { optionsViewModel.onDeleteRunSSID(it, config) },
|
||||
currentText = currentText,
|
||||
onSave = { optionsViewModel.onSaveRunSSID(it, config) },
|
||||
onValueChange = { currentText = it },
|
||||
supporting = {
|
||||
if (appUiState.settings.isWildcardsEnabled) {
|
||||
WildcardsLabel()
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.options
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
|
||||
data class OptionsUiState(
|
||||
val id: String? = null,
|
||||
val tunnel: TunnelConfig? = null,
|
||||
val isDefaultTunnel: Boolean = false,
|
||||
)
|
||||
+47
-75
@@ -1,20 +1,14 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.options
|
||||
|
||||
import androidx.compose.ui.util.fastFirstOrNull
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
@@ -23,86 +17,64 @@ class OptionsViewModel
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
) : ViewModel() {
|
||||
private val _optionState = MutableStateFlow(OptionsUiState())
|
||||
|
||||
val uiState =
|
||||
combine(
|
||||
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
||||
_optionState,
|
||||
) { tunnels, optionState ->
|
||||
if (optionState.id != null) {
|
||||
val tunnelConfig = tunnels.fastFirstOrNull { it.id.toString() == optionState.id }
|
||||
val isPrimaryTunnel = tunnelConfig?.isPrimaryTunnel == true
|
||||
OptionsUiState(optionState.id, tunnelConfig, isPrimaryTunnel)
|
||||
} else {
|
||||
OptionsUiState()
|
||||
}
|
||||
}.stateIn(
|
||||
viewModelScope,
|
||||
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||
OptionsUiState(),
|
||||
fun onDeleteRunSSID(ssid: String, tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
appDataRepository.tunnels.save(
|
||||
tunnelConfig =
|
||||
tunnelConfig.copy(
|
||||
tunnelNetworks = (tunnelConfig.tunnelNetworks - ssid).toMutableList(),
|
||||
),
|
||||
)
|
||||
|
||||
fun init(tunnelId: String) {
|
||||
_optionState.update {
|
||||
it.copy(
|
||||
id = tunnelId,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onDeleteRunSSID(ssid: String) = viewModelScope.launch {
|
||||
uiState.value.tunnel?.let {
|
||||
appDataRepository.tunnels.save(
|
||||
tunnelConfig =
|
||||
it.copy(
|
||||
tunnelNetworks = (uiState.value.tunnel!!.tunnelNetworks - ssid).toMutableList(),
|
||||
fun saveTunnelChanges(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
appDataRepository.tunnels.save(tunnelConfig)
|
||||
}
|
||||
|
||||
fun onSaveRunSSID(ssid: String, tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
if (ssid.isBlank()) return@launch
|
||||
val trimmed = ssid.trim()
|
||||
val tunnelsWithName = appDataRepository.tunnels.findByTunnelNetworksName(trimmed)
|
||||
|
||||
if (!tunnelConfig.tunnelNetworks.contains(trimmed) &&
|
||||
tunnelsWithName.isEmpty()
|
||||
) {
|
||||
saveTunnelChanges(
|
||||
tunnelConfig.copy(
|
||||
tunnelNetworks = (tunnelConfig.tunnelNetworks + ssid).toMutableList(),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
SnackbarController.showMessage(
|
||||
StringValue.StringResource(
|
||||
R.string.error_ssid_exists,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveTunnel(tunnelConfig: TunnelConfig?) = viewModelScope.launch {
|
||||
tunnelConfig?.let {
|
||||
appDataRepository.tunnels.save(it)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun onSaveRunSSID(ssid: String): Result<Unit> {
|
||||
val trimmed = ssid.trim()
|
||||
val tunnelsWithName =
|
||||
withContext(viewModelScope.coroutineContext) {
|
||||
appDataRepository.tunnels.findByTunnelNetworksName(trimmed)
|
||||
}
|
||||
return if (uiState.value.tunnel?.tunnelNetworks?.contains(trimmed) != true &&
|
||||
tunnelsWithName.isEmpty()
|
||||
) {
|
||||
uiState.value.tunnel?.tunnelNetworks?.add(trimmed)
|
||||
saveTunnel(uiState.value.tunnel)
|
||||
Result.success(Unit)
|
||||
fun onToggleIsMobileDataTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
if (tunnelConfig.isMobileDataTunnel) {
|
||||
appDataRepository.tunnels.updateMobileDataTunnel(null)
|
||||
} else {
|
||||
Result.failure(WgTunnelExceptions.SsidConflict())
|
||||
appDataRepository.tunnels.updateMobileDataTunnel(tunnelConfig)
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleIsMobileDataTunnel() = viewModelScope.launch {
|
||||
uiState.value.tunnel?.let {
|
||||
if (it.isMobileDataTunnel) {
|
||||
appDataRepository.tunnels.updateMobileDataTunnel(null)
|
||||
} else {
|
||||
appDataRepository.tunnels.updateMobileDataTunnel(it)
|
||||
}
|
||||
}
|
||||
fun onTogglePrimaryTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
appDataRepository.tunnels.updatePrimaryTunnel(
|
||||
when (tunnelConfig.isPrimaryTunnel) {
|
||||
true -> null
|
||||
false -> tunnelConfig
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fun onTogglePrimaryTunnel() = viewModelScope.launch {
|
||||
if (uiState.value.tunnel != null) {
|
||||
appDataRepository.tunnels.updatePrimaryTunnel(
|
||||
when (uiState.value.isDefaultTunnel) {
|
||||
true -> null
|
||||
false -> uiState.value.tunnel
|
||||
},
|
||||
)
|
||||
}
|
||||
fun onToggleRestartOnPing(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
appDataRepository.tunnels.save(
|
||||
tunnelConfig.copy(
|
||||
isPingEnabled = !tunnelConfig.isPingEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+13
-8
@@ -5,20 +5,24 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.navigation.NavController
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import xyz.teamgravity.pin_lock_compose.PinLock
|
||||
|
||||
@Composable
|
||||
fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
|
||||
fun PinLockScreen(appViewModel: AppViewModel) {
|
||||
val context = LocalContext.current
|
||||
val navController = LocalNavController.current
|
||||
val snackbar = SnackbarController.current
|
||||
PinLock(
|
||||
title = { pinExists ->
|
||||
Text(
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
text =
|
||||
if (pinExists) {
|
||||
stringResource(id = R.string.enter_pin)
|
||||
@@ -29,27 +33,28 @@ fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
|
||||
},
|
||||
)
|
||||
},
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
backgroundColor = MaterialTheme.colorScheme.surface,
|
||||
textColor = MaterialTheme.colorScheme.onSurface,
|
||||
onPinCorrect = {
|
||||
// pin is correct, navigate or hide pin lock
|
||||
if (context.isRunningOnTv()) {
|
||||
navController.navigate(Screen.Main.route)
|
||||
navController.navigate(Route.Main)
|
||||
} else {
|
||||
val isPopped = navController.popBackStack()
|
||||
if (!isPopped) {
|
||||
navController.navigate(Screen.Main.route)
|
||||
navController.navigate(Route.Main)
|
||||
}
|
||||
}
|
||||
},
|
||||
onPinIncorrect = {
|
||||
// pin is incorrect, show error
|
||||
appViewModel.showSnackbarMessage(
|
||||
snackbar.showMessage(
|
||||
StringValue.StringResource(R.string.incorrect_pin).asString(context),
|
||||
)
|
||||
},
|
||||
onPinCreated = {
|
||||
// pin created for the first time, navigate or hide pin lock
|
||||
appViewModel.showSnackbarMessage(
|
||||
snackbar.showMessage(
|
||||
StringValue.StringResource(R.string.pin_created).asString(context),
|
||||
)
|
||||
appViewModel.onPinLockEnabled()
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.scanner
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||
import com.journeyapps.barcodescanner.CompoundBarcodeView
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
|
||||
@OptIn(ExperimentalPermissionsApi::class)
|
||||
@Composable
|
||||
fun ScannerScreen(viewModel: ScannerViewModel = hiltViewModel()) {
|
||||
val context = LocalContext.current
|
||||
val navController = LocalNavController.current
|
||||
|
||||
val success = viewModel.success.collectAsStateWithLifecycle(null)
|
||||
|
||||
LaunchedEffect(success.value) {
|
||||
if (success.value != null) navController.popBackStack()
|
||||
}
|
||||
|
||||
val barcodeView = remember {
|
||||
CompoundBarcodeView(context).apply {
|
||||
this.initializeFromIntent((context as Activity).intent)
|
||||
this.setStatusText("")
|
||||
this.decodeSingle { result ->
|
||||
result.text?.let { barCodeOrQr ->
|
||||
viewModel.onTunnelQrResult(barCodeOrQr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
AndroidView(factory = { barcodeView })
|
||||
DisposableEffect(Unit) {
|
||||
barcodeView.resume()
|
||||
onDispose {
|
||||
barcodeView.pause()
|
||||
}
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.scanner
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.toWgQuickString
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class ScannerViewModel @Inject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _success = MutableSharedFlow<Boolean>()
|
||||
val success = _success.asSharedFlow()
|
||||
|
||||
private suspend fun makeTunnelNameUnique(name: String): String {
|
||||
return withContext(ioDispatcher) {
|
||||
val tunnels = appDataRepository.tunnels.getAll()
|
||||
var tunnelName = name
|
||||
var num = 1
|
||||
while (tunnels.any { it.name == tunnelName }) {
|
||||
tunnelName = "$name($num)"
|
||||
num++
|
||||
}
|
||||
tunnelName
|
||||
}
|
||||
}
|
||||
|
||||
fun onTunnelQrResult(result: String) = viewModelScope.launch(ioDispatcher) {
|
||||
kotlin.runCatching {
|
||||
val amConfig = TunnelConfig.configFromAmQuick(result)
|
||||
val amQuick = amConfig.toAwgQuickString(true)
|
||||
val wgQuick = amConfig.toWgQuickString()
|
||||
val tunnelName = makeTunnelNameUnique(generateQrCodeDefaultName(result))
|
||||
val tunnelConfig = TunnelConfig(name = tunnelName, wgQuick = wgQuick, amQuick = amQuick)
|
||||
appDataRepository.tunnels.save(tunnelConfig)
|
||||
_success.emit(true)
|
||||
}.onFailure {
|
||||
_success.emit(false)
|
||||
Timber.e(it)
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.error_invalid_code))
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateQrCodeDefaultName(config: String): String {
|
||||
return try {
|
||||
TunnelConfig.configFromAmQuick(config).peers[0].endpoint.get().host
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e)
|
||||
NumberUtils.generateRandomTunnelName()
|
||||
}
|
||||
}
|
||||
}
|
||||
+256
-595
@@ -1,87 +1,62 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Context.POWER_SERVICE
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material.icons.automirrored.outlined.ViewQuilt
|
||||
import androidx.compose.material.icons.filled.AppShortcut
|
||||
import androidx.compose.material.icons.outlined.AdminPanelSettings
|
||||
import androidx.compose.material.icons.outlined.Bolt
|
||||
import androidx.compose.material.icons.outlined.Code
|
||||
import androidx.compose.material.icons.outlined.FolderZip
|
||||
import androidx.compose.material.icons.outlined.Notifications
|
||||
import androidx.compose.material.icons.outlined.Pin
|
||||
import androidx.compose.material.icons.outlined.Restore
|
||||
import androidx.compose.material.icons.outlined.VpnLock
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavController
|
||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||
import com.google.accompanist.permissions.isGranted
|
||||
import com.google.accompanist.permissions.rememberPermissionState
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Screen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.ClickableIconButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.ScaledSwitch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SelectionItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SurfaceSelectionGroupButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalFocusRequester
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.AuthorizationPrompt
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.VpnDeniedDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.BackgroundLocationDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.BackgroundLocationDisclosure
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.LocationServicesDialog
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.getMessage
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.ForwardButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.topPadding
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchAppSettings
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchNotificationSettings
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchVpnSettings
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.showToast
|
||||
import kotlinx.coroutines.launch
|
||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||
|
||||
@OptIn(
|
||||
@@ -89,584 +64,270 @@ import xyz.teamgravity.pin_lock_compose.PinManager
|
||||
ExperimentalLayoutApi::class,
|
||||
)
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
viewModel: SettingsViewModel = hiltViewModel(),
|
||||
appViewModel: AppViewModel,
|
||||
navController: NavController,
|
||||
focusRequester: FocusRequester,
|
||||
) {
|
||||
fun SettingsScreen(viewModel: SettingsViewModel = hiltViewModel(), appViewModel: AppViewModel, uiState: AppUiState) {
|
||||
val context = LocalContext.current
|
||||
val navController = LocalNavController.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val scrollState = rememberScrollState()
|
||||
val snackbar = SnackbarController.current
|
||||
val rootFocusRequester = LocalFocusRequester.current
|
||||
val isRunningOnTv = remember { context.isRunningOnTv() }
|
||||
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
val kernelSupport by viewModel.kernelSupport.collectAsStateWithLifecycle()
|
||||
|
||||
val fineLocationState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
var currentText by remember { mutableStateOf("") }
|
||||
var isBackgroundLocationGranted by remember { mutableStateOf(true) }
|
||||
var showVpnPermissionDialog by remember { mutableStateOf(false) }
|
||||
var showLocationServicesAlertDialog by remember { mutableStateOf(false) }
|
||||
var didExportFiles by remember { mutableStateOf(false) }
|
||||
var showAuthPrompt by remember { mutableStateOf(false) }
|
||||
var showLocationDialog by remember { mutableStateOf(false) }
|
||||
|
||||
val screenPadding = 5.dp
|
||||
val fillMaxWidth = .85f
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
viewModel.checkKernelSupport()
|
||||
}
|
||||
|
||||
val notificationPermissionState =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
val startForResult =
|
||||
rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result: ActivityResult ->
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
result.data
|
||||
// Handle the Intent
|
||||
}
|
||||
viewModel.setBatteryOptimizeDisableShown()
|
||||
}
|
||||
|
||||
val vpnActivityResultState =
|
||||
rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
onResult = {
|
||||
val accepted = (it.resultCode == RESULT_OK)
|
||||
if (accepted) {
|
||||
viewModel.onToggleAutoTunnel(context)
|
||||
} else {
|
||||
showVpnPermissionDialog = true
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
fun isBatteryOptimizationsDisabled(): Boolean {
|
||||
val pm = context.getSystemService(POWER_SERVICE) as PowerManager
|
||||
return pm.isIgnoringBatteryOptimizations(context.packageName)
|
||||
}
|
||||
|
||||
fun requestBatteryOptimizationsDisabled() {
|
||||
val intent =
|
||||
Intent().apply {
|
||||
this.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
|
||||
data = Uri.fromParts("package", context.packageName, null)
|
||||
}
|
||||
startForResult.launch(intent)
|
||||
}
|
||||
|
||||
fun handleAutoTunnelToggle() {
|
||||
if (!uiState.isBatteryOptimizeDisableShown || !isBatteryOptimizationsDisabled()) return requestBatteryOptimizationsDisabled()
|
||||
if (notificationPermissionState != null && !notificationPermissionState.status.isGranted) {
|
||||
appViewModel.showSnackbarMessage(
|
||||
context.getString(R.string.notification_permission_required),
|
||||
)
|
||||
return notificationPermissionState.launchPermissionRequest()
|
||||
}
|
||||
val intent = if (!uiState.settings.isKernelEnabled) {
|
||||
com.wireguard.android.backend.GoBackend.VpnService.prepare(context)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (intent != null) return vpnActivityResultState.launch(intent)
|
||||
viewModel.onToggleAutoTunnel(context)
|
||||
}
|
||||
|
||||
fun saveTrustedSSID() {
|
||||
if (currentText.isNotEmpty()) {
|
||||
viewModel.onSaveTrustedSSID(currentText).onSuccess {
|
||||
currentText = ""
|
||||
}.onFailure {
|
||||
appViewModel.showSnackbarMessage(it.getMessage(context))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun checkFineLocationGranted() {
|
||||
isBackgroundLocationGranted =
|
||||
if (!fineLocationState.status.isGranted) {
|
||||
false
|
||||
} else {
|
||||
viewModel.setLocationDisclosureShown()
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fun onRootDenied() = appViewModel.showSnackbarMessage(context.getString(R.string.error_root_denied))
|
||||
|
||||
fun onRootAccepted() = appViewModel.showSnackbarMessage(context.getString(R.string.root_accepted))
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
if (
|
||||
context.isRunningOnTv() &&
|
||||
Build.VERSION.SDK_INT == Build.VERSION_CODES.Q
|
||||
) {
|
||||
checkFineLocationGranted()
|
||||
} else {
|
||||
val backgroundLocationState =
|
||||
rememberPermissionState(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
|
||||
isBackgroundLocationGranted =
|
||||
if (!backgroundLocationState.status.isGranted) {
|
||||
false
|
||||
} else {
|
||||
SideEffect { viewModel.setLocationDisclosureShown() }
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
|
||||
checkFineLocationGranted()
|
||||
}
|
||||
if (!uiState.isLocationDisclosureShown) {
|
||||
BackgroundLocationDisclosure(
|
||||
onDismiss = { viewModel.setLocationDisclosureShown() },
|
||||
onAttest = {
|
||||
context.launchAppSettings()
|
||||
viewModel.setLocationDisclosureShown()
|
||||
},
|
||||
scrollState,
|
||||
focusRequester,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
BackgroundLocationDialog(
|
||||
showLocationDialog,
|
||||
onDismiss = { showLocationDialog = false },
|
||||
onAttest = { showLocationDialog = false },
|
||||
)
|
||||
|
||||
LocationServicesDialog(
|
||||
showLocationServicesAlertDialog,
|
||||
onDismiss = { showVpnPermissionDialog = false },
|
||||
onAttest = { handleAutoTunnelToggle() },
|
||||
)
|
||||
|
||||
VpnDeniedDialog(showVpnPermissionDialog, onDismiss = { showVpnPermissionDialog = false })
|
||||
|
||||
if (showAuthPrompt) {
|
||||
AuthorizationPrompt(
|
||||
onSuccess = {
|
||||
showAuthPrompt = false
|
||||
scope.launch {
|
||||
viewModel.exportAllConfigs().onSuccess {
|
||||
appViewModel.showSnackbarMessage(context.getString(R.string.exported_configs_message))
|
||||
}.onFailure {
|
||||
appViewModel.showSnackbarMessage(context.getString(R.string.export_configs_failed))
|
||||
}
|
||||
}
|
||||
viewModel.exportAllConfigs(context)
|
||||
},
|
||||
onError = { _ ->
|
||||
showAuthPrompt = false
|
||||
appViewModel.showSnackbarMessage(
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.error_authentication_failed),
|
||||
)
|
||||
},
|
||||
onFailure = {
|
||||
showAuthPrompt = false
|
||||
appViewModel.showSnackbarMessage(
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.error_authorization_failed),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (uiState.isLocationDisclosureShown) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(scrollState)
|
||||
.clickable(
|
||||
indication = null,
|
||||
interactionSource = interactionSource,
|
||||
) {
|
||||
focusManager.clearFocus()
|
||||
},
|
||||
) {
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
(
|
||||
if (context.isRunningOnTv()) {
|
||||
Modifier
|
||||
.height(IntrinsicSize.Min)
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 10.dp)
|
||||
} else {
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 20.dp)
|
||||
}
|
||||
)
|
||||
.padding(bottom = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.auto_tunneling),
|
||||
padding = screenPadding,
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(id = R.string.tunnel_on_wifi),
|
||||
enabled =
|
||||
!(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled
|
||||
),
|
||||
checked = uiState.settings.isTunnelOnWifiEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleTunnelOnWifi() },
|
||||
modifier =
|
||||
if (uiState.settings.isAutoTunnelEnabled) {
|
||||
Modifier
|
||||
} else {
|
||||
Modifier
|
||||
.focusRequester(focusRequester)
|
||||
},
|
||||
)
|
||||
if (uiState.settings.isTunnelOnWifiEnabled) {
|
||||
Column {
|
||||
FlowRow(
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(screenPadding)
|
||||
.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
) {
|
||||
uiState.settings.trustedNetworkSSIDs.forEach { ssid ->
|
||||
ClickableIconButton(
|
||||
onClick = {
|
||||
if (context.isRunningOnTv()) {
|
||||
focusRequester.requestFocus()
|
||||
viewModel.onDeleteTrustedSSID(ssid)
|
||||
}
|
||||
},
|
||||
onIconClick = {
|
||||
if (context.isRunningOnTv()) focusRequester.requestFocus()
|
||||
viewModel.onDeleteTrustedSSID(ssid)
|
||||
},
|
||||
text = ssid,
|
||||
icon = Icons.Filled.Close,
|
||||
enabled =
|
||||
!(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled
|
||||
),
|
||||
)
|
||||
}
|
||||
if (uiState.settings.trustedNetworkSSIDs.isEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.none),
|
||||
fontStyle = FontStyle.Italic,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
OutlinedTextField(
|
||||
enabled =
|
||||
!(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled
|
||||
),
|
||||
value = currentText,
|
||||
onValueChange = { currentText = it },
|
||||
label = { Text(stringResource(R.string.add_trusted_ssid)) },
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(
|
||||
start = screenPadding,
|
||||
top = 5.dp,
|
||||
bottom = 10.dp,
|
||||
),
|
||||
maxLines = 1,
|
||||
keyboardOptions =
|
||||
KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardActions = KeyboardActions(onDone = { saveTrustedSSID() }),
|
||||
trailingIcon = {
|
||||
if (currentText != "") {
|
||||
IconButton(onClick = { saveTrustedSSID() }) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Add,
|
||||
contentDescription =
|
||||
if (currentText == "") {
|
||||
stringResource(
|
||||
id =
|
||||
R.string
|
||||
.trusted_ssid_empty_description,
|
||||
)
|
||||
} else {
|
||||
stringResource(
|
||||
id =
|
||||
R.string
|
||||
.trusted_ssid_value_description,
|
||||
)
|
||||
},
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.tunnel_mobile_data),
|
||||
enabled =
|
||||
!(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled
|
||||
),
|
||||
checked = uiState.settings.isTunnelOnMobileDataEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleTunnelOnMobileData() },
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(id = R.string.tunnel_on_ethernet),
|
||||
enabled =
|
||||
!(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled
|
||||
),
|
||||
checked = uiState.settings.isTunnelOnEthernetEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleTunnelOnEthernet() },
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.restart_on_ping),
|
||||
enabled =
|
||||
!(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled
|
||||
),
|
||||
checked = uiState.settings.isPingEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleRestartOnPing() },
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
(
|
||||
if (!uiState.settings.isAutoTunnelEnabled) {
|
||||
Modifier
|
||||
} else {
|
||||
Modifier.focusRequester(
|
||||
focusRequester,
|
||||
)
|
||||
}
|
||||
)
|
||||
.fillMaxSize()
|
||||
.padding(top = 5.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp, Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.verticalScroll(rememberScrollState())
|
||||
.fillMaxSize()
|
||||
.padding(top = topPadding)
|
||||
.padding(bottom = 40.dp.scaledHeight())
|
||||
.padding(horizontal = 24.dp.scaledWidth())
|
||||
.then(
|
||||
if (!isRunningOnTv) {
|
||||
Modifier.clickable(
|
||||
indication = null,
|
||||
interactionSource = interactionSource,
|
||||
) {
|
||||
TextButton(
|
||||
enabled = !uiState.settings.isAlwaysOnVpnEnabled,
|
||||
onClick = {
|
||||
if (uiState.tunnels.isEmpty()) return@TextButton context.showToast(R.string.tunnel_required)
|
||||
if (
|
||||
uiState.settings.isTunnelOnWifiEnabled &&
|
||||
!uiState.settings.isAutoTunnelEnabled
|
||||
) {
|
||||
when (false) {
|
||||
isBackgroundLocationGranted -> showLocationDialog = true
|
||||
fineLocationState.status.isGranted -> showLocationDialog = true
|
||||
viewModel.isLocationEnabled(context) ->
|
||||
showLocationServicesAlertDialog = true
|
||||
|
||||
else -> {
|
||||
handleAutoTunnelToggle()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
handleAutoTunnelToggle()
|
||||
}
|
||||
},
|
||||
) {
|
||||
val autoTunnelButtonText =
|
||||
if (uiState.settings.isAutoTunnelEnabled) {
|
||||
stringResource(R.string.disable_auto_tunnel)
|
||||
} else {
|
||||
stringResource(id = R.string.enable_auto_tunnel)
|
||||
}
|
||||
Text(autoTunnelButtonText)
|
||||
}
|
||||
focusManager.clearFocus()
|
||||
}
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(vertical = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.backend),
|
||||
padding = screenPadding,
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.use_amnezia),
|
||||
enabled =
|
||||
!(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled ||
|
||||
(uiState.vpnState.status == TunnelState.UP) || uiState.settings.isKernelEnabled
|
||||
} else {
|
||||
Modifier
|
||||
},
|
||||
),
|
||||
) {
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Bolt,
|
||||
title = { Text(stringResource(R.string.auto_tunneling), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
description = {
|
||||
Text(
|
||||
stringResource(R.string.on_demand_rules),
|
||||
style = MaterialTheme.typography.bodySmall.copy(MaterialTheme.colorScheme.outline),
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
if (!uiState.generalState.isLocationDisclosureShown) return@SelectionItem navController.navigate(Route.LocationDisclosure)
|
||||
navController.navigate(Route.AutoTunnel)
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton(Modifier.focusable().focusRequester(rootFocusRequester)) { navController.navigate(Route.AutoTunnel) }
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
SurfaceSelectionGroupButton(
|
||||
buildList {
|
||||
if (!isRunningOnTv) {
|
||||
addAll(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Filled.AppShortcut,
|
||||
{
|
||||
ScaledSwitch(
|
||||
uiState.settings.isShortcutsEnabled,
|
||||
onClick = { viewModel.onToggleShortcutsEnabled() },
|
||||
)
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.enabled_app_shortcuts),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = { viewModel.onToggleShortcutsEnabled() },
|
||||
),
|
||||
checked = uiState.settings.isAmneziaEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = {
|
||||
viewModel.onToggleAmnezia()
|
||||
},
|
||||
SelectionItem(
|
||||
Icons.Outlined.VpnLock,
|
||||
{
|
||||
ScaledSwitch(
|
||||
enabled = !(
|
||||
(
|
||||
uiState.settings.isTunnelOnWifiEnabled ||
|
||||
uiState.settings.isTunnelOnEthernetEnabled ||
|
||||
uiState.settings.isTunnelOnMobileDataEnabled
|
||||
) &&
|
||||
uiState.settings.isAutoTunnelEnabled
|
||||
),
|
||||
onClick = { viewModel.onToggleAlwaysOnVPN() },
|
||||
checked = uiState.settings.isAlwaysOnVpnEnabled,
|
||||
)
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.always_on_vpn_support),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = { viewModel.onToggleAlwaysOnVPN() },
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.AdminPanelSettings,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.kill_switch),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
context.launchVpnSettings()
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton { context.launchVpnSettings() }
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
if (kernelSupport) {
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.use_kernel),
|
||||
enabled =
|
||||
!(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled ||
|
||||
(uiState.vpnState.status == TunnelState.UP)
|
||||
),
|
||||
checked = uiState.settings.isKernelEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = {
|
||||
scope.launch {
|
||||
viewModel.onToggleKernelMode({ onRootAccepted() }, { onRootDenied() })
|
||||
}
|
||||
add(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Restore,
|
||||
{
|
||||
ScaledSwitch(
|
||||
uiState.settings.isRestoreOnBootEnabled,
|
||||
onClick = { viewModel.onToggleRestartAtBoot() },
|
||||
)
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.restart_at_boot),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = { viewModel.onToggleRestartAtBoot() },
|
||||
),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.AutoMirrored.Outlined.ViewQuilt,
|
||||
title = { Text(stringResource(R.string.appearance), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
onClick = {
|
||||
navController.navigate(Route.Appearance)
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton { navController.navigate(Route.Appearance) }
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.Notifications,
|
||||
title = { Text(stringResource(R.string.notifications), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
onClick = {
|
||||
context.launchNotificationSettings()
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton { context.launchNotificationSettings() }
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.Pin,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.enable_app_lock),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
uiState.generalState.isPinLockEnabled,
|
||||
onClick = {
|
||||
if (uiState.generalState.isPinLockEnabled) {
|
||||
appViewModel.onPinLockDisabled()
|
||||
} else {
|
||||
PinManager.initialize(context)
|
||||
navController.navigate(Route.Lock)
|
||||
}
|
||||
},
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = 5.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
viewModel.requestRoot({ onRootAccepted() }, { onRootDenied() })
|
||||
},
|
||||
) {
|
||||
Text(stringResource(R.string.request_root))
|
||||
}
|
||||
},
|
||||
onClick = {
|
||||
if (uiState.generalState.isPinLockEnabled) {
|
||||
appViewModel.onPinLockDisabled()
|
||||
} else {
|
||||
PinManager.initialize(context)
|
||||
navController.navigate(Route.Lock)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(vertical = 10.dp)
|
||||
.padding(bottom = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.other),
|
||||
padding = screenPadding,
|
||||
)
|
||||
if (!context.isRunningOnTv()) {
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.always_on_vpn_support),
|
||||
enabled = !uiState.settings.isAutoTunnelEnabled,
|
||||
checked = uiState.settings.isAlwaysOnVpnEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleAlwaysOnVPN() },
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.enabled_app_shortcuts),
|
||||
enabled = true,
|
||||
checked = uiState.settings.isShortcutsEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleShortcutsEnabled() },
|
||||
)
|
||||
}
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.restart_at_boot),
|
||||
enabled = true,
|
||||
checked = uiState.settings.isRestoreOnBootEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = {
|
||||
viewModel.onToggleRestartAtBoot()
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
if (!isRunningOnTv) {
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Code,
|
||||
title = { Text(stringResource(R.string.kernel), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
description = {
|
||||
Text(
|
||||
stringResource(R.string.use_kernel),
|
||||
style = MaterialTheme.typography.bodySmall.copy(MaterialTheme.colorScheme.outline),
|
||||
)
|
||||
},
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.enable_app_lock),
|
||||
enabled = true,
|
||||
checked = uiState.isPinLockEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = {
|
||||
if (uiState.isPinLockEnabled) {
|
||||
appViewModel.onPinLockDisabled()
|
||||
} else {
|
||||
// TODO may want to show a dialog before proceeding in the future
|
||||
PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||
navController.navigate(Screen.Lock.route)
|
||||
}
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
uiState.settings.isKernelEnabled,
|
||||
onClick = { viewModel.onToggleKernelMode() },
|
||||
enabled = !(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled ||
|
||||
(uiState.vpnState.status == TunnelState.UP)
|
||||
),
|
||||
)
|
||||
},
|
||||
)
|
||||
if (!context.isRunningOnTv()) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = 5.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
TextButton(
|
||||
enabled = !didExportFiles,
|
||||
onClick = {
|
||||
if (uiState.tunnels.isEmpty()) return@TextButton context.showToast(R.string.tunnel_required)
|
||||
showAuthPrompt = true
|
||||
},
|
||||
) {
|
||||
Text(stringResource(R.string.export_configs))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
onClick = {
|
||||
viewModel.onToggleKernelMode()
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
if (!isRunningOnTv) {
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.FolderZip,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.export_configs),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
if (uiState.tunnels.isEmpty()) return@SelectionItem context.showToast(R.string.tunnel_required)
|
||||
showAuthPrompt = true
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||
|
||||
data class SettingsUiState(
|
||||
val settings: Settings = Settings(),
|
||||
val tunnels: List<TunnelConfig> = emptyList(),
|
||||
val vpnState: VpnState = VpnState(),
|
||||
val isLocationDisclosureShown: Boolean = true,
|
||||
val isBatteryOptimizeDisableShown: Boolean = false,
|
||||
val isPinLockEnabled: Boolean = false,
|
||||
)
|
||||
+70
-199
@@ -1,32 +1,26 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings
|
||||
|
||||
import android.content.Context
|
||||
import android.location.LocationManager
|
||||
import androidx.core.location.LocationManagerCompat
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.wireguard.android.backend.WgQuickBackend
|
||||
import com.wireguard.android.util.RootShell
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.FileUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.WgTunnelExceptions
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchShareFile
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import timber.log.Timber
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@@ -35,226 +29,103 @@ class SettingsViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
private val serviceManager: ServiceManager,
|
||||
private val rootShell: Provider<RootShell>,
|
||||
private val fileUtils: FileUtils,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
tunnelService: TunnelService,
|
||||
) : ViewModel() {
|
||||
private val _kernelSupport = MutableStateFlow(false)
|
||||
val kernelSupport = _kernelSupport.asStateFlow()
|
||||
|
||||
val uiState =
|
||||
combine(
|
||||
appDataRepository.settings.getSettingsFlow(),
|
||||
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
||||
tunnelService.vpnState,
|
||||
appDataRepository.appState.generalStateFlow,
|
||||
) { settings, tunnels, tunnelState, generalState ->
|
||||
SettingsUiState(
|
||||
settings,
|
||||
tunnels,
|
||||
tunnelState,
|
||||
generalState.isLocationDisclosureShown,
|
||||
generalState.isBatteryOptimizationDisableShown,
|
||||
generalState.isPinLockEnabled,
|
||||
)
|
||||
}
|
||||
.stateIn(
|
||||
viewModelScope,
|
||||
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||
SettingsUiState(),
|
||||
)
|
||||
|
||||
fun onSaveTrustedSSID(ssid: String): Result<Unit> {
|
||||
val trimmed = ssid.trim()
|
||||
return if (!uiState.value.settings.trustedNetworkSSIDs.contains(trimmed)) {
|
||||
uiState.value.settings.trustedNetworkSSIDs.add(trimmed)
|
||||
saveSettings(uiState.value.settings)
|
||||
Result.success(Unit)
|
||||
} else {
|
||||
Result.failure(WgTunnelExceptions.SsidConflict())
|
||||
}
|
||||
}
|
||||
private val settings = appDataRepository.settings.getSettingsFlow()
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, Settings())
|
||||
|
||||
fun setLocationDisclosureShown() = viewModelScope.launch {
|
||||
appDataRepository.appState.setLocationDisclosureShown(true)
|
||||
}
|
||||
|
||||
fun setBatteryOptimizeDisableShown() = viewModelScope.launch {
|
||||
appDataRepository.appState.setBatteryOptimizationDisableShown(true)
|
||||
}
|
||||
|
||||
fun onToggleTunnelOnMobileData() {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isTunnelOnMobileDataEnabled = !uiState.value.settings.isTunnelOnMobileDataEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun onDeleteTrustedSSID(ssid: String) {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
trustedNetworkSSIDs =
|
||||
(uiState.value.settings.trustedNetworkSSIDs - ssid).toMutableList(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun onExportTunnels(files: List<File>): Result<Unit> {
|
||||
return fileUtils.saveFilesToZip(files)
|
||||
}
|
||||
|
||||
fun onToggleAutoTunnel(context: Context) = viewModelScope.launch {
|
||||
val isAutoTunnelEnabled = uiState.value.settings.isAutoTunnelEnabled
|
||||
var isAutoTunnelPaused = uiState.value.settings.isAutoTunnelPaused
|
||||
|
||||
if (isAutoTunnelEnabled) {
|
||||
serviceManager.stopWatcherService(context)
|
||||
} else {
|
||||
serviceManager.startWatcherService(context)
|
||||
isAutoTunnelPaused = false
|
||||
}
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isAutoTunnelEnabled = !isAutoTunnelEnabled,
|
||||
isAutoTunnelPaused = isAutoTunnelPaused,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun onToggleAlwaysOnVPN() = viewModelScope.launch {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isAlwaysOnVpnEnabled = !uiState.value.settings.isAlwaysOnVpnEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
|
||||
|
||||
fun onToggleTunnelOnEthernet() {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isTunnelOnEthernetEnabled = !uiState.value.settings.isTunnelOnEthernetEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun isLocationEnabled(context: Context): Boolean {
|
||||
val locationManager =
|
||||
context.getSystemService(
|
||||
Context.LOCATION_SERVICE,
|
||||
) as LocationManager
|
||||
return LocationManagerCompat.isLocationEnabled(locationManager)
|
||||
}
|
||||
|
||||
fun onToggleShortcutsEnabled() {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isShortcutsEnabled = !uiState.value.settings.isShortcutsEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun saveKernelMode(enabled: Boolean) {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isKernelEnabled = enabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun onToggleTunnelOnWifi() {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isTunnelOnWifiEnabled = !uiState.value.settings.isTunnelOnWifiEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun onToggleAmnezia() = viewModelScope.launch {
|
||||
if (uiState.value.settings.isKernelEnabled) {
|
||||
saveKernelMode(false)
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isAlwaysOnVpnEnabled = !isAlwaysOnVpnEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
saveAmneziaMode(!uiState.value.settings.isAmneziaEnabled)
|
||||
}
|
||||
|
||||
private fun saveAmneziaMode(on: Boolean) {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isAmneziaEnabled = on,
|
||||
),
|
||||
)
|
||||
fun onToggleShortcutsEnabled() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
this.copy(
|
||||
isShortcutsEnabled = !isShortcutsEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleKernelMode(onSuccess: () -> Unit, onFailure: () -> Unit) = viewModelScope.launch {
|
||||
if (!uiState.value.settings.isKernelEnabled) {
|
||||
requestRoot(
|
||||
{
|
||||
onSuccess()
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
private fun saveKernelMode(enabled: Boolean) = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
this.copy(
|
||||
isKernelEnabled = enabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleKernelMode() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
if (!isKernelEnabled) {
|
||||
requestRoot().onSuccess {
|
||||
if (!isKernelSupported()) return@onSuccess SnackbarController.showMessage(StringValue.StringResource(R.string.kernel_not_supported))
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isKernelEnabled = true,
|
||||
isAmneziaEnabled = false,
|
||||
),
|
||||
)
|
||||
},
|
||||
{
|
||||
onFailure()
|
||||
saveKernelMode(enabled = false)
|
||||
},
|
||||
)
|
||||
} else {
|
||||
saveKernelMode(enabled = false)
|
||||
}
|
||||
} else {
|
||||
saveKernelMode(enabled = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleRestartOnPing() = viewModelScope.launch {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isPingEnabled = !uiState.value.settings.isPingEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun checkKernelSupport() = viewModelScope.launch {
|
||||
val kernelSupport =
|
||||
withContext(ioDispatcher) {
|
||||
WgQuickBackend.hasKernelSupport()
|
||||
}
|
||||
_kernelSupport.update {
|
||||
kernelSupport
|
||||
private suspend fun isKernelSupported(): Boolean {
|
||||
return withContext(ioDispatcher) {
|
||||
WgQuickBackend.hasKernelSupport()
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleRestartAtBoot() = viewModelScope.launch {
|
||||
saveSettings(
|
||||
uiState.value.settings.copy(
|
||||
isRestoreOnBootEnabled = !uiState.value.settings.isRestoreOnBootEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun requestRoot(onSuccess: () -> Unit, onFailure: () -> Unit) = viewModelScope.launch(ioDispatcher) {
|
||||
kotlin.runCatching {
|
||||
rootShell.get().start()
|
||||
Timber.i("Root shell accepted!")
|
||||
onSuccess()
|
||||
}.onFailure {
|
||||
onFailure()
|
||||
}.onSuccess {
|
||||
onSuccess()
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isRestoreOnBootEnabled = !isRestoreOnBootEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun exportAllConfigs(): Result<Unit> {
|
||||
return kotlin.runCatching {
|
||||
private suspend fun requestRoot(): Result<Unit> {
|
||||
return withContext(ioDispatcher) {
|
||||
kotlin.runCatching {
|
||||
rootShell.get().start()
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.root_accepted))
|
||||
}.onFailure {
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.error_root_denied))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun exportAllConfigs(context: Context) = viewModelScope.launch {
|
||||
kotlin.runCatching {
|
||||
val shareFile = fileUtils.createNewShareFile("wg-export_${Instant.now().epochSecond}.zip")
|
||||
val tunnels = appDataRepository.tunnels.getAll()
|
||||
val wgFiles = fileUtils.createWgFiles(tunnels)
|
||||
val amFiles = fileUtils.createAmFiles(tunnels)
|
||||
onExportTunnels(wgFiles + amFiles)
|
||||
val allFiles = wgFiles + amFiles
|
||||
fileUtils.zipAll(shareFile, allFiles)
|
||||
val uri = FileProvider.getUriForFile(context, context.getString(R.string.provider), shareFile)
|
||||
context.launchShareFile(uri)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Contrast
|
||||
import androidx.compose.material.icons.outlined.Translate
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SelectionItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SurfaceSelectionGroupButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.ForwardButton
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun AppearanceScreen() {
|
||||
val navController = LocalNavController.current
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.appearance))
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize().padding(it)
|
||||
.padding(top = 24.dp.scaledHeight())
|
||||
.padding(horizontal = 24.dp.scaledWidth()),
|
||||
) {
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Translate,
|
||||
title = { Text(stringResource(R.string.language), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
onClick = { navController.navigate(Route.Language) },
|
||||
trailing = {
|
||||
ForwardButton { navController.navigate(Route.Language) }
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Contrast,
|
||||
title = { Text(stringResource(R.string.display_theme), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
onClick = { navController.navigate(Route.Display) },
|
||||
trailing = {
|
||||
ForwardButton { navController.navigate(Route.Display) }
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.display
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.IconSurfaceButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun DisplayScreen(appUiState: AppUiState, viewModel: DisplayViewModel = hiltViewModel()) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.display_theme))
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(it)
|
||||
.padding(top = 24.dp.scaledHeight())
|
||||
.padding(horizontal = 24.dp.scaledWidth()),
|
||||
) {
|
||||
IconSurfaceButton(
|
||||
title = stringResource(R.string.automatic),
|
||||
onClick = {
|
||||
viewModel.onThemeChange(Theme.AUTOMATIC)
|
||||
},
|
||||
selected = appUiState.generalState.theme == Theme.AUTOMATIC,
|
||||
)
|
||||
IconSurfaceButton(
|
||||
title = stringResource(R.string.light),
|
||||
onClick = { viewModel.onThemeChange(Theme.LIGHT) },
|
||||
selected = appUiState.generalState.theme == Theme.LIGHT,
|
||||
)
|
||||
IconSurfaceButton(
|
||||
title = stringResource(R.string.dark),
|
||||
onClick = { viewModel.onThemeChange(Theme.DARK) },
|
||||
selected = appUiState.generalState.theme == Theme.DARK,
|
||||
)
|
||||
IconSurfaceButton(
|
||||
title = stringResource(R.string.dynamic),
|
||||
onClick = { viewModel.onThemeChange(Theme.DYNAMIC) },
|
||||
selected = appUiState.generalState.theme == Theme.DYNAMIC,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.display
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class DisplayViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val appStateRepository: AppStateRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
fun onThemeChange(theme: Theme) = viewModelScope.launch {
|
||||
appStateRepository.setTheme(theme)
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.language
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.datastore.LocaleStorage
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.SelectedLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.SelectionItemButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.navigateAndForget
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
import timber.log.Timber
|
||||
import java.text.Collator
|
||||
import java.util.Locale
|
||||
|
||||
@Composable
|
||||
fun LanguageScreen(localeStorage: LocaleStorage) {
|
||||
val navController = LocalNavController.current
|
||||
|
||||
val context = LocalContext.current
|
||||
|
||||
val collator = Collator.getInstance(Locale.getDefault())
|
||||
|
||||
val currentLocale = remember { mutableStateOf(LocaleUtil.OPTION_PHONE_LANGUAGE) }
|
||||
|
||||
val locales = LocaleUtil.supportedLocales.map {
|
||||
val tag = it.replace("_", "-")
|
||||
Locale.forLanguageTag(tag)
|
||||
}
|
||||
|
||||
val sortedLocales =
|
||||
remember(locales) {
|
||||
locales.sortedWith(compareBy(collator) { it.getDisplayName(it) }).toList()
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
currentLocale.value = localeStorage.getPreferredLocale()
|
||||
}
|
||||
|
||||
fun onChangeLocale(locale: String) {
|
||||
Timber.d("Setting preferred locale: $locale")
|
||||
localeStorage.setPreferredLocale(locale)
|
||||
LocaleUtil.applyLocalizedContext(context, locale)
|
||||
navController.navigateAndForget(Route.Main)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.language))
|
||||
},
|
||||
) {
|
||||
LazyColumn(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize().padding(it)
|
||||
.padding(horizontal = 24.dp.scaledWidth()).windowInsetsPadding(WindowInsets.navigationBars),
|
||||
) {
|
||||
item {
|
||||
Box(modifier = Modifier.padding(top = 24.dp.scaledHeight())) {
|
||||
SelectionItemButton(
|
||||
buttonText = stringResource(R.string.automatic),
|
||||
onClick = {
|
||||
onChangeLocale(LocaleUtil.OPTION_PHONE_LANGUAGE)
|
||||
},
|
||||
trailing = {
|
||||
if (currentLocale.value == LocaleUtil.OPTION_PHONE_LANGUAGE) {
|
||||
SelectedLabel()
|
||||
}
|
||||
},
|
||||
ripple = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
items(sortedLocales, key = { it }) { locale ->
|
||||
SelectionItemButton(
|
||||
buttonText = locale.getDisplayLanguage(locale).capitalize(locale) +
|
||||
if (locale.toLanguageTag().contains("-")) " (${locale.getDisplayCountry(locale).capitalize(locale)})" else "",
|
||||
onClick = {
|
||||
onChangeLocale(locale.toLanguageTag())
|
||||
},
|
||||
trailing = {
|
||||
if (locale.toLanguageTag() == currentLocale.value) {
|
||||
SelectedLabel()
|
||||
}
|
||||
},
|
||||
ripple = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user