Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
482d3b22a1 | ||
|
|
107f07cf55 | ||
|
|
1db29ee44a | ||
|
|
43f0d42d65 | ||
|
|
2b0f842579 | ||
|
|
17ede339fa | ||
|
|
ac643caf03 | ||
|
|
0ceae2f557 | ||
|
|
df41b44302 | ||
|
|
4619292174 | ||
|
|
cff974851a | ||
|
|
d9080195ab | ||
|
|
026c2c9493 | ||
|
|
8907f4cf96 | ||
|
|
9aceaaa200 | ||
|
|
9e744b309e | ||
|
|
603e90dcca | ||
|
|
e7105b0245 | ||
|
|
25e359595b | ||
|
|
9f9c79cf2b | ||
|
|
447a309f69 | ||
|
|
8b975c77ce | ||
|
|
04ef7adb44 | ||
|
|
f236136919 | ||
|
|
a33a945477 | ||
|
|
8502860512 | ||
|
|
50f069731c | ||
|
|
37653792fd | ||
|
|
2cb3439efd | ||
|
|
8ac908e684 | ||
|
|
5a1bf79e4b | ||
|
|
5f56c471ce | ||
|
|
87feb7f483 | ||
|
|
a63184830d | ||
|
|
4e99ef1211 | ||
|
|
fa6398c40e | ||
|
|
778ce20f6e | ||
|
|
7da1a34495 | ||
|
|
bac4ccf26e | ||
|
|
e601b2dbaa | ||
|
|
8c6bb33527 | ||
|
|
43e57c9357 | ||
|
|
87d9afd55b | ||
|
|
7a2c7eccb3 | ||
|
|
dbc3454742 | ||
|
|
ad798f0a79 | ||
|
|
9604d07cea | ||
|
|
b13adc5340 | ||
|
|
5f2dbccebf | ||
|
|
bab6c754dc | ||
|
|
ddc219d01f | ||
|
|
275eb3ab0b | ||
|
|
62c941a07b |
@@ -9,6 +9,7 @@ title: "[Preset] "
|
|||||||
- URL:
|
- URL:
|
||||||
- Homepage or documentation:
|
- Homepage or documentation:
|
||||||
- Privacy policy (DoH servers) or license (blocklists):
|
- Privacy policy (DoH servers) or license (blocklists):
|
||||||
|
- Donation page (DoH servers, optional):
|
||||||
|
|
||||||
- [ ] DoH server: public and supports RFC 8484
|
- [ ] DoH server: public and supports RFC 8484
|
||||||
- [ ] Blocklist: public and actively maintained
|
- [ ] Blocklist: public and actively maintained
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ Issues and pull requests go to the repository on [Gitea](https://git.skysparkle.
|
|||||||
## Ways to help
|
## Ways to help
|
||||||
|
|
||||||
- **Report a bug** — use the *Bug report* template.
|
- **Report a bug** — use the *Bug report* template.
|
||||||
- **Add a DoH server** — add one line to [`servers/servers.txt`](servers/servers.txt), see [Adding a DoH server](#adding-a-doh-server).
|
- **Add a DoH server** — open an issue with the *DoH server or blocklist* template, see [Adding a DoH server](#adding-a-doh-server).
|
||||||
- **Suggest a blocklist** — use the *DoH server or blocklist* template.
|
- **Suggest a blocklist** — use the *DoH server or blocklist* template.
|
||||||
- **Suggest a feature** — use the *Feature request* template; check [Out of scope](#out-of-scope) first.
|
- **Suggest a feature** — use the *Feature request* template; check [Out of scope](#out-of-scope) first.
|
||||||
- **Fix a translation** — use the *Translation fix* template or send a pull request.
|
- **Fix a translation** — use the *Translation fix* template or send a pull request.
|
||||||
@@ -38,24 +38,9 @@ These will not be accepted:
|
|||||||
|
|
||||||
## Adding a DoH server
|
## Adding a DoH server
|
||||||
|
|
||||||
The server list lives in [`servers/servers.txt`](servers/servers.txt). The app downloads it when the user taps **Update server list**, so a new server reaches users without a new release.
|
Servers ship with the app in [`Providers.kt`](app/src/main/java/cc/skysparkle/sparkledns/Providers.kt), so a new server reaches users with the next release. The app never downloads a server list.
|
||||||
|
|
||||||
To add a server, open the file on Gitea, click **Edit**, add one line at the end and send it as a pull request:
|
To suggest a server, open an issue with the *DoH server or blocklist* template, or send a pull request that adds one entry to `Providers.builtIn` with the server's name, DoH URL, privacy policy link, bootstrap IPs, whether it supports HTTP/3 and, optionally, the operator's own donation page.
|
||||||
|
|
||||||
```
|
|
||||||
Name | DoH URL | Privacy policy | h3
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Name** — how the server appears in the app, up to 40 characters.
|
|
||||||
- **DoH URL** — the full `https://` address of the DoH endpoint.
|
|
||||||
- **Privacy policy** — an `https://` link to the operator's privacy policy. Lines without one are ignored.
|
|
||||||
- **h3** — optional. Add it only if the server supports HTTP/3.
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
```
|
|
||||||
Example DNS | https://dns.example.org/dns-query | https://example.org/privacy | h3
|
|
||||||
```
|
|
||||||
|
|
||||||
The server must:
|
The server must:
|
||||||
|
|
||||||
@@ -66,7 +51,7 @@ The server must:
|
|||||||
|
|
||||||
Before sending, check that it works: in the app choose **Custom server**, enter the URL and tap **Test server**.
|
Before sending, check that it works: in the app choose **Custom server**, enter the URL and tap **Test server**.
|
||||||
|
|
||||||
Please don't change the lines of the servers that ship with the app (SkySparkle, Quad9, Digitale Gesellschaft, UncensoredDNS, Freifunk München): the app always keeps their built-in addresses. If you are unsure whether a server fits, open an issue with the *DoH server or blocklist* template instead.
|
If you are unsure whether a server fits, open an issue with the *DoH server or blocklist* template first.
|
||||||
|
|
||||||
## Blocklists
|
## Blocklists
|
||||||
|
|
||||||
@@ -86,7 +71,7 @@ If your code adds new strings, add them to `values/strings.xml`. Translations fo
|
|||||||
1. Fork the repository and create a branch from `main`.
|
1. Fork the repository and create a branch from `main`.
|
||||||
2. Keep one topic per pull request.
|
2. Keep one topic per pull request.
|
||||||
3. Follow the existing Kotlin and Jetpack Compose style; keep comments short and in English; don't reformat unrelated code.
|
3. Follow the existing Kotlin and Jetpack Compose style; keep comments short and in English; don't reformat unrelated code.
|
||||||
4. Make sure `./gradlew assembleDebug` builds, and test on a device or emulator.
|
4. Make sure `./gradlew assembleDebug testDebugUnitTest` passes, and test on a device or emulator. For changes that may affect speed or memory, `scripts/bench.sh` compares two APKs on a rooted device or emulator (`scripts/bench-build.sh` builds them from two revisions).
|
||||||
5. Write short, plain commit messages in English (for example `Fix tunnel restart after server switch`).
|
5. Write short, plain commit messages in English (for example `Fix tunnel restart after server switch`).
|
||||||
6. Add screenshots for UI changes.
|
6. Add screenshots for UI changes.
|
||||||
|
|
||||||
|
|||||||
@@ -636,8 +636,7 @@ the "copyright" line and a pointer to where the full notice is found.
|
|||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
This program is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
the Free Software Foundation, either version 3 of the License, or
|
the Free Software Foundation, version 3 of the License.
|
||||||
(at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
This program is distributed in the hope that it will be useful,
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
|||||||
@@ -1,53 +1,52 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="assets/icon-rounded.png" width="128" alt="SparkleDNS icon">
|
<img src="assets/icon-rounded.png" width="112" alt="SparkleDNS icon">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<h1 align="center">SparkleDNS</h1>
|
<h1 align="center">SparkleDNS</h1>
|
||||||
|
|
||||||
<p align="center"><b>A lightweight DNS-over-HTTPS client for Android.</b></p>
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://git.skysparkle.cc/kalarina/Sparkledns/releases"><img src="assets/get-it-on-gitea.png" height="60" alt="Get it on Gitea"></a>
|
<b>A lightweight DNS-over-HTTPS client for Android.</b><br>
|
||||||
|
A local VPN that captures only DNS traffic and sends every query to the DoH server you choose (RFC 8484). Everything else goes through your normal connection.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="https://img.shields.io/badge/Android-8.0%2B-2e7d32?logo=android&logoColor=white&labelColor=1b1b1b" alt="Android 8.0+">
|
<a href="https://github.com/kalarina-bit/Sparkledns/releases/latest"><img src="https://img.shields.io/github/v/release/kalarina-bit/Sparkledns?style=for-the-badge&label=release&labelColor=1b1b1b&color=2e7d32" alt="Latest release"></a>
|
||||||
<img src="https://img.shields.io/badge/License-GPL--3.0--or--later-2e7d32?labelColor=1b1b1b" alt="GPL-3.0-or-later">
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
SparkleDNS starts a local VPN that captures only DNS traffic and sends every query to the DoH server you choose (RFC 8484). Everything else goes through your normal connection.
|
<p align="center">
|
||||||
|
<a href="https://f-droid.org/packages/cc.skysparkle.sparkledns/"><img src="assets/get-it-on%20(1).png" height="56" alt="Get it on F-Droid"></a>
|
||||||
|
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.skysparkle.cc/kalarina/Sparkledns"><img src="assets/badge_obtainium.png" height="56" alt="Get it on Obtainium"></a>
|
||||||
|
<a href="https://github.com/kalarina-bit/Sparkledns/releases/latest"><img src="assets/get-it-on-github.png" height="56" alt="Get it on GitHub"></a>
|
||||||
|
<a href="https://git.skysparkle.cc/kalarina/Sparkledns/releases"><img src="assets/get-it-on-gitea.png" height="56" alt="Get it on Gitea"></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
## Features
|
<p align="center">
|
||||||
|
<img src="assets/screenshots/1-private-dns-control.png" width="160" alt="Private DNS control">
|
||||||
|
<img src="assets/screenshots/2-protected.png" width="160" alt="You're protected">
|
||||||
|
<img src="assets/screenshots/3-see-every-request.png" width="160" alt="See every request">
|
||||||
|
<img src="assets/screenshots/4-block-more-noise.png" width="160" alt="Block more noise">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> If you find SparkleDNS useful, please consider giving it a ⭐ — it helps others discover the project.
|
||||||
|
|
||||||
|
## ✨ Features
|
||||||
|
|
||||||
- 🔌 **One-tap connect/disconnect**, with a Quick Settings tile
|
- 🔌 **One-tap connect/disconnect**, with a Quick Settings tile
|
||||||
- 🔄 **Switch servers on the fly** — the tunnel restarts automatically
|
- 🔄 **Switch servers on the fly** — the tunnel restarts automatically
|
||||||
- 🚀 **Built-in server test** showing protocol and latency
|
- 🚀 **Built-in server test** showing protocol and latency
|
||||||
- 📊 **Live query monitor** with stats, filters and one-tap blocking
|
- 📊 **Activity** — 24-hour and 7-day charts, share of the biggest companies, and a live log with filters and one-tap blocking. Numbers stay on the device
|
||||||
- 📱 **Per-app DNS** — chosen apps bypass the tunnel
|
- 📱 **Per-app DNS** — chosen apps bypass the tunnel
|
||||||
- 🚫 **Custom blocklists** — your own domains plus hosts/domain/AdBlock lists by URL (HaGeZi Pro++ and TIF presets)
|
- 🚫 **Custom blocklists** — your own domains plus hosts/domain/AdBlock lists by URL (HaGeZi Pro, Pro++ and TIF presets), updated automatically every day or week, on Wi-Fi only if you like
|
||||||
- 🔓 **No analytics, no Google Play Services**
|
- 🔓 **No analytics, no Google Play Services**
|
||||||
|
|
||||||
## Screenshots
|
## <img src="assets/icon-install.png" width="32" alt=""> Installation
|
||||||
|
|
||||||
<p align="center">
|
- **[F-Droid](https://f-droid.org/packages/cc.skysparkle.sparkledns/)** — install and update through the F-Droid client.
|
||||||
<img src="assets/screenshots/1-your-dns-your-choice.png" width="200" alt="Your DNS, your choice">
|
- **[Obtainium](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.skysparkle.cc/kalarina/Sparkledns)** — installs the APK straight from Gitea releases and keeps it up to date.
|
||||||
<img src="assets/screenshots/2-protected.png" width="200" alt="Protected via SkySparkle">
|
- **Manually** — download the latest APK from [GitHub](https://github.com/kalarina-bit/Sparkledns/releases/latest) or [Gitea](https://git.skysparkle.cc/kalarina/Sparkledns/releases), allow installs from unknown sources for the app you open it with (Settings → Apps → Special access → Install unknown apps), then open the `.apk` and confirm.
|
||||||
<img src="assets/screenshots/3-stay-informed.png" width="200" alt="Stay informed">
|
|
||||||
<img src="assets/screenshots/4-block-your-way.png" width="200" alt="Block your way">
|
|
||||||
<img src="assets/screenshots/5-choose-your-own-route.png" width="200" alt="Choose your own route">
|
|
||||||
</p>
|
|
||||||
|
|
||||||
## Installation
|
## <img src="assets/icon-verify.png" width="32" alt=""> Verifying a download
|
||||||
|
|
||||||
<img src="assets/icon-install.png" width="36" align="left">
|
|
||||||
|
|
||||||
1. Download the latest APK from the [Releases page](https://git.skysparkle.cc/kalarina/Sparkledns/releases).
|
|
||||||
2. Allow installs from unknown sources for the app you open it with (Settings → Apps → Special access → Install unknown apps).
|
|
||||||
3. Open the `.apk` file and confirm the install.
|
|
||||||
|
|
||||||
## Verifying a download
|
|
||||||
|
|
||||||
<img src="assets/icon-verify.png" width="36" align="left">
|
|
||||||
|
|
||||||
Every official APK is signed with the same key. Check it before installing:
|
Every official APK is signed with the same key. Check it before installing:
|
||||||
|
|
||||||
@@ -63,7 +62,7 @@ The SHA-256 fingerprint of the signing certificate must be:
|
|||||||
|
|
||||||
`apksigner` prints the same value in lowercase without colons. On Android you can check it with [AppVerifier](https://github.com/soupslurpr/AppVerifier) (app ID `cc.skysparkle.sparkledns`).
|
`apksigner` prints the same value in lowercase without colons. On Android you can check it with [AppVerifier](https://github.com/soupslurpr/AppVerifier) (app ID `cc.skysparkle.sparkledns`).
|
||||||
|
|
||||||
## Building from source
|
## <img src="assets/icon-structure.png" width="32" alt=""> Building from source
|
||||||
|
|
||||||
Requires JDK 17+ and Android SDK 36.
|
Requires JDK 17+ and Android SDK 36.
|
||||||
|
|
||||||
@@ -75,12 +74,12 @@ Requires JDK 17+ and Android SDK 36.
|
|||||||
|
|
||||||
1. Bump `versionName` and `versionCode` in `app/build.gradle.kts` (`versionCode = major * 10000 + minor * 100 + patch`).
|
1. Bump `versionName` and `versionCode` in `app/build.gradle.kts` (`versionCode = major * 10000 + minor * 100 + patch`).
|
||||||
2. Add `fastlane/metadata/android/<locale>/changelogs/<versionCode>.txt`.
|
2. Add `fastlane/metadata/android/<locale>/changelogs/<versionCode>.txt`.
|
||||||
3. Tag the commit as `v<versionName>` (for example `v1.0.6`) — F-Droid detects new releases from these tags.
|
3. Tag the commit as `v<versionName>` (for example `v1.0.9`) — F-Droid detects new releases from these tags, so upload the signed APK to the release right away.
|
||||||
|
|
||||||
## Contributing
|
## 🤝 Contributing
|
||||||
|
|
||||||
Bug reports, DoH server and blocklist suggestions, translation fixes and pull requests are welcome in the [issue tracker](https://git.skysparkle.cc/kalarina/Sparkledns/issues). Please read [CONTRIBUTING.md](CONTRIBUTING.md) first — it explains what fits the project and how to send changes. To open an issue or a pull request, [create an account](https://git.skysparkle.cc/user/sign_up) on this Gitea.
|
Bug reports, DoH server and blocklist suggestions, translation fixes and pull requests are welcome in the [issue tracker](https://git.skysparkle.cc/kalarina/Sparkledns/issues). Please read [CONTRIBUTING.md](CONTRIBUTING.md) first — it explains what fits the project and how to send changes. To open an issue or a pull request, [create an account](https://git.skysparkle.cc/user/sign_up) on this Gitea.
|
||||||
|
|
||||||
## License
|
## 📄 License
|
||||||
|
|
||||||
[GNU General Public License v3.0 or later](LICENSE).
|
[GNU General Public License v3.0 only](LICENSE).
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ android {
|
|||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
// Single source of truth: the About screen reads these through BuildConfig.
|
// Single source of truth: the About screen reads these through BuildConfig.
|
||||||
// Kept as plain literals so F-Droid can detect new versions. Code = major * 10000 + minor * 100 + patch.
|
// Kept as plain literals so F-Droid can detect new versions. Code = major * 10000 + minor * 100 + patch.
|
||||||
versionCode = 10007
|
versionCode = 10100
|
||||||
versionName = "1.0.7"
|
versionName = "1.1.0"
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
@@ -27,6 +27,12 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
androidResources {
|
||||||
|
// Only the languages the app itself is translated to; library strings for other
|
||||||
|
// languages were unused weight, as the app falls back to English there anyway
|
||||||
|
localeFilters += listOf("en", "de", "ja", "lt", "ru", "zh")
|
||||||
|
}
|
||||||
|
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility = JavaVersion.VERSION_17
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
targetCompatibility = JavaVersion.VERSION_17
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
@@ -42,6 +48,11 @@ android {
|
|||||||
includeInApk = false
|
includeInApk = false
|
||||||
includeInBundle = false
|
includeInBundle = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
testOptions {
|
||||||
|
// android.util.Log and friends are no-ops in JVM unit tests
|
||||||
|
unitTests.isReturnDefaultValues = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
@@ -49,6 +60,13 @@ dependencies {
|
|||||||
implementation("androidx.activity:activity-compose:1.10.1")
|
implementation("androidx.activity:activity-compose:1.10.1")
|
||||||
implementation("androidx.compose.ui:ui")
|
implementation("androidx.compose.ui:ui")
|
||||||
implementation("androidx.compose.material3:material3")
|
implementation("androidx.compose.material3:material3")
|
||||||
|
// Already pulled in by Compose at this version; declared because the app uses it directly
|
||||||
|
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.0")
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||||
|
|
||||||
|
// Debug builds only, never part of a release
|
||||||
|
debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14")
|
||||||
|
|
||||||
|
testImplementation("junit:junit:4.13.2")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
# Readable stack traces in crash reports
|
# File names and line numbers stay in stack traces, names are obfuscated. To read a crash
|
||||||
|
# report, build the same release (builds are reproducible) and run
|
||||||
|
# retrace app/build/outputs/mapping/release/mapping.txt crash.txt
|
||||||
-keepattributes SourceFile,LineNumberTable
|
-keepattributes SourceFile,LineNumberTable
|
||||||
-dontobfuscate
|
|
||||||
|
|||||||
@@ -7,6 +7,8 @@
|
|||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||||
|
<!-- Keeps the scheduled blocklist update after a reboot -->
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
|
||||||
<!-- Lists launcher apps for per-app DNS settings without QUERY_ALL_PACKAGES -->
|
<!-- Lists launcher apps for per-app DNS settings without QUERY_ALL_PACKAGES -->
|
||||||
<queries>
|
<queries>
|
||||||
@@ -51,6 +53,11 @@
|
|||||||
android:value="Local DNS-over-HTTPS VPN that keeps encrypted DNS active while the user has it enabled" />
|
android:value="Local DNS-over-HTTPS VPN that keeps encrypted DNS active while the user has it enabled" />
|
||||||
</service>
|
</service>
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".BlocklistUpdateJob"
|
||||||
|
android:exported="false"
|
||||||
|
android:permission="android.permission.BIND_JOB_SERVICE" />
|
||||||
|
|
||||||
<service
|
<service
|
||||||
android:name=".DnsTileService"
|
android:name=".DnsTileService"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import android.content.ActivityNotFoundException
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.util.Log
|
||||||
|
import android.widget.Toast
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.animation.AnimatedContent
|
import androidx.compose.animation.AnimatedContent
|
||||||
import androidx.compose.animation.fadeIn
|
import androidx.compose.animation.fadeIn
|
||||||
@@ -264,7 +267,12 @@ private fun InfoRow(label: String, value: String) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
internal fun openUrl(context: Context, url: String) {
|
internal fun openUrl(context: Context, url: String) {
|
||||||
runCatching {
|
try {
|
||||||
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
|
} catch (_: ActivityNotFoundException) {
|
||||||
|
// Without a browser the tap used to do nothing at all
|
||||||
|
Toast.makeText(context, R.string.no_browser, Toast.LENGTH_SHORT).show()
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
Log.w("SparkleDNS", "Cannot open $url", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,490 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
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.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
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.itemsIndexed
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
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.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.geometry.Size
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
private enum class ActivityFilter(@StringRes val label: Int) {
|
||||||
|
ALL(R.string.mon_all),
|
||||||
|
BLOCKED(R.string.status_blocked),
|
||||||
|
CACHED(R.string.status_cached),
|
||||||
|
ERRORS(R.string.mon_errors),
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum class Period(val hours: Int, @StringRes val label: Int) {
|
||||||
|
DAY(24, R.string.period_24h),
|
||||||
|
WEEK(24 * 7, R.string.period_7d),
|
||||||
|
}
|
||||||
|
|
||||||
|
private val TimeFormat = SimpleDateFormat("HH:mm:ss", Locale.ROOT)
|
||||||
|
|
||||||
|
// Colors of the company slices, then the rest
|
||||||
|
private val SliceColors = listOf(Palette.Accent, Color(0xFFE6E8EE), Color(0xFF7C69E8), Color(0xFFC9A36A))
|
||||||
|
private val OtherColor = Palette.Track
|
||||||
|
|
||||||
|
private class Slice(val label: String, val share: Float, val color: Color)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val custom by Blocklist.custom.collectAsStateWithLifecycle()
|
||||||
|
val customSet = remember(custom) { custom.toHashSet() }
|
||||||
|
|
||||||
|
var period by rememberSaveable { mutableStateOf(Period.DAY) }
|
||||||
|
var entries by remember { mutableStateOf(QueryLog.snapshot()) }
|
||||||
|
var summary by remember { mutableStateOf(StatsStore.summary(period.hours)) }
|
||||||
|
var filter by rememberSaveable { mutableStateOf(ActivityFilter.ALL) }
|
||||||
|
var search by rememberSaveable { mutableStateOf("") }
|
||||||
|
var filterMenu by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
OnQueryLogChange {
|
||||||
|
entries = QueryLog.snapshot()
|
||||||
|
summary = StatsStore.summary(period.hours)
|
||||||
|
}
|
||||||
|
val statsVersion by StatsStore.version.collectAsStateWithLifecycle()
|
||||||
|
LaunchedEffect(period, statsVersion) { summary = StatsStore.summary(period.hours) }
|
||||||
|
|
||||||
|
val visible = remember(entries, filter, search) {
|
||||||
|
val term = search.trim()
|
||||||
|
entries.filter { e ->
|
||||||
|
val matchesFilter = when (filter) {
|
||||||
|
ActivityFilter.ALL -> true
|
||||||
|
ActivityFilter.BLOCKED -> e.status == QueryStatus.BLOCKED
|
||||||
|
ActivityFilter.CACHED -> e.status == QueryStatus.CACHED
|
||||||
|
ActivityFilter.ERRORS -> e.status == QueryStatus.FAILED
|
||||||
|
}
|
||||||
|
matchesFilter && (term.isEmpty() || e.domain.contains(term, ignoreCase = true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toggleBlock(domain: String, unblock: Boolean) {
|
||||||
|
scope.launch {
|
||||||
|
val result = withContext(Dispatchers.IO) {
|
||||||
|
tryEdit {
|
||||||
|
if (unblock) {
|
||||||
|
Blocklist.removeCustom(context, domain)
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
Blocklist.addCustom(context, domain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val ok = result.getOrElse {
|
||||||
|
showEditError(context, it)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
val message = when {
|
||||||
|
!ok -> context.getString(R.string.bl_invalid)
|
||||||
|
unblock -> context.getString(R.string.mon_unblocked, domain)
|
||||||
|
else -> context.getString(R.string.mon_blocked_added, domain)
|
||||||
|
}
|
||||||
|
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun copy(domain: String) {
|
||||||
|
context.getSystemService(ClipboardManager::class.java)
|
||||||
|
.setPrimaryClip(ClipData.newPlainText("domain", domain))
|
||||||
|
}
|
||||||
|
|
||||||
|
LazyColumn(
|
||||||
|
modifier = modifier,
|
||||||
|
contentPadding = PaddingValues(start = 20.dp, end = 20.dp, top = 16.dp, bottom = bottomPadding),
|
||||||
|
) {
|
||||||
|
item(key = "header") {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.heightIn(min = 44.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
ScreenTitle(stringResource(R.string.tab_activity), Modifier.weight(1f))
|
||||||
|
PeriodChip(stringResource(period.label)) {
|
||||||
|
period = if (period == Period.DAY) Period.WEEK else Period.DAY
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item(key = "stats") {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(top = 20.dp, start = 4.dp, end = 4.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
|
) {
|
||||||
|
StatBlock(formatCompact(summary.total), stringResource(R.string.stat_requests), Modifier.weight(1f))
|
||||||
|
StatBlock(formatCompact(summary.blocked), stringResource(R.string.mon_blocked), Modifier.weight(1f))
|
||||||
|
StatBlock(stringResource(R.string.mon_ms, summary.avgLatencyMs), stringResource(R.string.stat_avg), Modifier.weight(1f))
|
||||||
|
val cache = if (summary.total == 0L) 0 else summary.cached * 100 / summary.total
|
||||||
|
StatBlock("$cache%", stringResource(R.string.mon_cached), Modifier.weight(1f))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item(key = "companies") {
|
||||||
|
CompanyCard(summary, Modifier.padding(top = 20.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
item(key = "recent") {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(top = 24.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.recent_title),
|
||||||
|
color = Palette.Fg,
|
||||||
|
fontSize = 17.sp,
|
||||||
|
fontWeight = FontWeight.ExtraBold,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
IconButton(
|
||||||
|
onClick = {
|
||||||
|
QueryLog.clear()
|
||||||
|
entries = emptyList()
|
||||||
|
},
|
||||||
|
enabled = entries.isNotEmpty(),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_delete),
|
||||||
|
contentDescription = stringResource(R.string.mon_clear),
|
||||||
|
tint = Palette.Fg2,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item(key = "search") {
|
||||||
|
SearchField(
|
||||||
|
value = search,
|
||||||
|
onValueChange = { search = it },
|
||||||
|
placeholder = stringResource(R.string.mon_search),
|
||||||
|
modifier = Modifier.padding(top = 6.dp, bottom = 4.dp),
|
||||||
|
trailing = {
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { filterMenu = true }) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_tab_settings),
|
||||||
|
contentDescription = stringResource(R.string.filter),
|
||||||
|
tint = if (filter == ActivityFilter.ALL) Palette.Fg2 else Palette.Accent,
|
||||||
|
modifier = Modifier.size(18.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
DropdownMenu(expanded = filterMenu, onDismissRequest = { filterMenu = false }) {
|
||||||
|
ActivityFilter.entries.forEach { option ->
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = {
|
||||||
|
Text(
|
||||||
|
stringResource(option.label),
|
||||||
|
color = if (option == filter) Palette.Accent else Palette.Fg,
|
||||||
|
fontWeight = if (option == filter) FontWeight.Bold else FontWeight.Normal,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
onClick = {
|
||||||
|
filter = option
|
||||||
|
filterMenu = false
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (visible.isEmpty()) {
|
||||||
|
item(key = "empty") {
|
||||||
|
EmptyState(
|
||||||
|
R.drawable.ic_tab_monitor,
|
||||||
|
stringResource(if (entries.isEmpty()) R.string.mon_empty else R.string.mon_no_match),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
itemsIndexed(visible, key = { _, entry -> entry.id }, contentType = { _, _ -> "query" }) { index, entry ->
|
||||||
|
val blockedByMe = entry.domain in customSet
|
||||||
|
QueryRow(
|
||||||
|
modifier = Modifier.animateItem(),
|
||||||
|
entry = entry,
|
||||||
|
first = index == 0,
|
||||||
|
blockedByMe = blockedByMe,
|
||||||
|
onBlock = { toggleBlock(entry.domain, unblock = false) },
|
||||||
|
onUnblock = { toggleBlock(entry.domain, unblock = true) },
|
||||||
|
onCopy = { copy(entry.domain) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PeriodChip(text: String, onClick: () -> Unit) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.clip(RoundedCornerShape(18.dp))
|
||||||
|
.border(1.dp, Palette.Track, RoundedCornerShape(18.dp))
|
||||||
|
.clickable(onClick = onClick)
|
||||||
|
.padding(start = 14.dp, end = 10.dp, top = 8.dp, bottom = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text(text, color = Palette.Fg, fontSize = 12.sp, fontWeight = FontWeight.Bold)
|
||||||
|
Spacer(Modifier.width(4.dp))
|
||||||
|
Icon(painterResource(R.drawable.ic_expand), contentDescription = null, tint = Palette.Fg2, modifier = Modifier.size(14.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun CompanyCard(summary: StatsSummary, modifier: Modifier = Modifier) {
|
||||||
|
val other = stringResource(R.string.companies_other)
|
||||||
|
val slices = remember(summary, other) { companySlices(summary, other) }
|
||||||
|
Column(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.appCard()
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.companies_title), color = Palette.Fg, fontSize = 15.sp, fontWeight = FontWeight.Bold)
|
||||||
|
Text(stringResource(R.string.companies_desc), color = Palette.Fg2, fontSize = 12.sp, lineHeight = 17.sp)
|
||||||
|
Spacer(Modifier.size(10.dp))
|
||||||
|
if (summary.total == 0L) {
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.no_data),
|
||||||
|
color = Palette.Fg3,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
modifier = Modifier.padding(vertical = 12.dp),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Donut(slices, Modifier.size(104.dp))
|
||||||
|
Spacer(Modifier.width(20.dp))
|
||||||
|
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
slices.forEach { slice ->
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.size(8.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(slice.color)
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text(
|
||||||
|
slice.label,
|
||||||
|
color = Palette.Fg,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
String.format(Locale.getDefault(), "%.1f%%", slice.share * 100f),
|
||||||
|
color = Palette.Fg,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The four companies with most requests, then everything else
|
||||||
|
private fun companySlices(summary: StatsSummary, otherLabel: String): List<Slice> {
|
||||||
|
if (summary.total == 0L) return emptyList()
|
||||||
|
val top = Company.entries
|
||||||
|
.map { it to summary.companies[it.ordinal] }
|
||||||
|
.filter { it.second > 0 }
|
||||||
|
.sortedByDescending { it.second }
|
||||||
|
.take(SliceColors.size)
|
||||||
|
val slices = top.mapIndexed { index, (company, count) ->
|
||||||
|
Slice(company.label, count.toFloat() / summary.total, SliceColors[index])
|
||||||
|
}
|
||||||
|
val rest = (1f - slices.sumOf { it.share.toDouble() }.toFloat()).coerceAtLeast(0f)
|
||||||
|
return slices + Slice(otherLabel, rest, OtherColor)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Donut(slices: List<Slice>, modifier: Modifier = Modifier) {
|
||||||
|
Canvas(modifier) {
|
||||||
|
val stroke = 14.dp.toPx()
|
||||||
|
val diameter = size.minDimension - stroke
|
||||||
|
val topLeft = Offset((size.width - diameter) / 2f, (size.height - diameter) / 2f)
|
||||||
|
val arcSize = Size(diameter, diameter)
|
||||||
|
drawArc(OtherColor, 0f, 360f, useCenter = false, topLeft = topLeft, size = arcSize, style = Stroke(width = stroke))
|
||||||
|
var start = -90f
|
||||||
|
slices.forEach { slice ->
|
||||||
|
val sweep = slice.share * 360f
|
||||||
|
if (sweep > 0f) {
|
||||||
|
drawArc(slice.color, start, sweep, useCenter = false, topLeft = topLeft, size = arcSize, style = Stroke(width = stroke))
|
||||||
|
}
|
||||||
|
start += sweep
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun QueryRow(
|
||||||
|
modifier: Modifier,
|
||||||
|
entry: QueryEntry,
|
||||||
|
first: Boolean,
|
||||||
|
blockedByMe: Boolean,
|
||||||
|
onBlock: () -> Unit,
|
||||||
|
onUnblock: () -> Unit,
|
||||||
|
onCopy: () -> Unit,
|
||||||
|
) {
|
||||||
|
var menu by remember { mutableStateOf(false) }
|
||||||
|
val (avatarBackground, avatarColor) = when (entry.status) {
|
||||||
|
QueryStatus.BLOCKED -> Palette.Blocked.copy(alpha = 0.14f) to Palette.Blocked
|
||||||
|
QueryStatus.CACHED -> CachedColor.copy(alpha = 0.14f) to CachedColor
|
||||||
|
QueryStatus.FAILED -> WarningColor.copy(alpha = 0.14f) to WarningColor
|
||||||
|
QueryStatus.OK -> Color(0xFF2A2C33) to Palette.Fg
|
||||||
|
}
|
||||||
|
val detail = when (entry.status) {
|
||||||
|
QueryStatus.OK -> stringResource(R.string.mon_ms, entry.latencyMs)
|
||||||
|
QueryStatus.CACHED -> stringResource(R.string.status_cached)
|
||||||
|
QueryStatus.BLOCKED -> stringResource(if (blockedByMe) R.string.bl_my else R.string.tab_blocklist)
|
||||||
|
QueryStatus.FAILED -> stringResource(R.string.status_failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
Box(modifier.fillMaxWidth()) {
|
||||||
|
Column {
|
||||||
|
if (!first) HorizontalDivider(color = Palette.Line)
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { menu = true }
|
||||||
|
.padding(vertical = 10.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(34.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(avatarBackground),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Text(initialOf(entry.domain), color = avatarColor, fontSize = 13.sp, fontWeight = FontWeight.ExtraBold)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
entry.domain,
|
||||||
|
color = Palette.Fg,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
"${DnsMessage.typeName(entry.type)} · $detail",
|
||||||
|
color = Palette.Fg3,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Column(horizontalAlignment = Alignment.End) {
|
||||||
|
if (entry.status == QueryStatus.BLOCKED) {
|
||||||
|
Text(stringResource(R.string.status_blocked), color = Palette.Blocked, fontSize = 12.sp, fontWeight = FontWeight.Bold)
|
||||||
|
} else if (entry.status == QueryStatus.FAILED) {
|
||||||
|
Text(stringResource(R.string.status_failed), color = WarningColor, fontSize = 12.sp, fontWeight = FontWeight.Bold)
|
||||||
|
}
|
||||||
|
Text(TimeFormat.format(Date(entry.time)), color = Palette.Fg3, fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||||
|
if (blockedByMe) {
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(stringResource(R.string.mon_unblock)) },
|
||||||
|
onClick = {
|
||||||
|
menu = false
|
||||||
|
onUnblock()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
} else if (entry.status != QueryStatus.BLOCKED) {
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(stringResource(R.string.mon_block)) },
|
||||||
|
onClick = {
|
||||||
|
menu = false
|
||||||
|
onBlock()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(stringResource(R.string.copy)) },
|
||||||
|
onClick = {
|
||||||
|
menu = false
|
||||||
|
onCopy()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// First letter of the main part of a domain: "a" for app-measurement.com, "g" for www.google.com
|
||||||
|
private fun initialOf(domain: String): String {
|
||||||
|
val parts = domain.split('.').filter { it.isNotEmpty() }
|
||||||
|
val main = if (parts.size >= 2) parts[parts.size - 2] else parts.firstOrNull().orEmpty()
|
||||||
|
return main.firstOrNull { it.isLetterOrDigit() }?.toString() ?: "·"
|
||||||
|
}
|
||||||
@@ -4,84 +4,185 @@ import androidx.activity.compose.BackHandler
|
|||||||
import androidx.annotation.DrawableRes
|
import androidx.annotation.DrawableRes
|
||||||
import androidx.annotation.StringRes
|
import androidx.annotation.StringRes
|
||||||
import androidx.compose.animation.AnimatedContent
|
import androidx.compose.animation.AnimatedContent
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.animateColorAsState
|
||||||
import androidx.compose.animation.fadeIn
|
import androidx.compose.animation.fadeIn
|
||||||
import androidx.compose.animation.fadeOut
|
import androidx.compose.animation.fadeOut
|
||||||
import androidx.compose.animation.slideInHorizontally
|
import androidx.compose.animation.slideInHorizontally
|
||||||
import androidx.compose.animation.slideOutHorizontally
|
import androidx.compose.animation.slideOutHorizontally
|
||||||
import androidx.compose.animation.togetherWith
|
import androidx.compose.animation.togetherWith
|
||||||
import androidx.compose.foundation.layout.consumeWindowInsets
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.WindowInsets
|
||||||
|
import androidx.compose.foundation.layout.asPaddingValues
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.imePadding
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.navigationBars
|
||||||
|
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.statusBarsPadding
|
||||||
|
import androidx.compose.foundation.selection.selectable
|
||||||
|
import androidx.compose.foundation.selection.selectableGroup
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.NavigationBar
|
|
||||||
import androidx.compose.material3.NavigationBarItem
|
|
||||||
import androidx.compose.material3.Scaffold
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.draw.shadow
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
|
||||||
private enum class Tab(@StringRes val label: Int, @DrawableRes val icon: Int) {
|
// The three tabs of the bottom panel, then the pages opened from them
|
||||||
HOME(R.string.tab_home, R.drawable.ic_tab_home),
|
private enum class Screen(@StringRes val label: Int, @DrawableRes val icon: Int, val isTab: Boolean) {
|
||||||
MONITOR(R.string.tab_monitor, R.drawable.ic_tab_monitor),
|
HOME(R.string.tab_home, R.drawable.ic_tab_home, true),
|
||||||
APPS(R.string.tab_apps, R.drawable.ic_tab_apps),
|
ACTIVITY(R.string.tab_activity, R.drawable.ic_tab_monitor, true),
|
||||||
BLOCKLIST(R.string.tab_blocklist, R.drawable.ic_tab_block),
|
SETTINGS(R.string.tab_settings, R.drawable.ic_tab_settings, true),
|
||||||
ABOUT(R.string.tab_about, R.drawable.ic_tab_info),
|
BLOCKLIST(R.string.blocklist_title, R.drawable.ic_tab_block, false),
|
||||||
|
APPS(R.string.settings_apps, R.drawable.ic_tab_apps, false),
|
||||||
|
ABOUT(R.string.tab_about, R.drawable.ic_tab_info, false),
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun AppShell() {
|
fun AppShell() {
|
||||||
var tab by rememberSaveable { mutableStateOf(Tab.HOME) }
|
var tab by rememberSaveable { mutableStateOf(Screen.HOME) }
|
||||||
|
var page by rememberSaveable { mutableStateOf<Screen?>(null) }
|
||||||
|
val current = page ?: tab
|
||||||
|
|
||||||
// Back leads to Home first; only Home closes the app
|
// Back closes an open page first, then leads to Home; only Home closes the app
|
||||||
BackHandler(enabled = tab != Tab.HOME) { tab = Tab.HOME }
|
BackHandler(enabled = page == null && tab != Screen.HOME) { tab = Screen.HOME }
|
||||||
|
BackHandler(enabled = page != null) { page = null }
|
||||||
|
|
||||||
Scaffold(
|
val navInset = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
|
||||||
bottomBar = {
|
// Room under the last item of a tab, so it can scroll clear of the floating panel
|
||||||
NavigationBar {
|
val tabBottom = navInset + 112.dp
|
||||||
Tab.entries.forEach { item ->
|
val pageBottom = navInset + 24.dp
|
||||||
NavigationBarItem(
|
|
||||||
selected = tab == item,
|
Box(
|
||||||
onClick = { tab = item },
|
Modifier
|
||||||
icon = { Icon(painterResource(item.icon), contentDescription = null) },
|
.fillMaxSize()
|
||||||
label = {
|
.background(Palette.Bg)
|
||||||
Text(stringResource(item.label), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
) {
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) { padding ->
|
|
||||||
// Screens drift a little in the direction of the tab that was picked and cross-fade
|
|
||||||
AnimatedContent(
|
AnimatedContent(
|
||||||
targetState = tab,
|
targetState = current,
|
||||||
transitionSpec = {
|
transitionSpec = {
|
||||||
val forward = targetState.ordinal > initialState.ordinal
|
// Pages slide in from the side; tabs drift a little towards the tab that was picked
|
||||||
val shift = { width: Int -> if (forward) width / 8 else -width / 8 }
|
val pageMove = targetState.isTab != initialState.isTab
|
||||||
|
val forward = if (pageMove) !targetState.isTab else targetState.ordinal > initialState.ordinal
|
||||||
|
val divisor = if (pageMove) 3 else 8
|
||||||
|
val shift = { width: Int -> if (forward) width / divisor else -width / divisor }
|
||||||
(fadeIn(Motion.enterFade) + slideInHorizontally(Motion.slide) { shift(it) }) togetherWith
|
(fadeIn(Motion.enterFade) + slideInHorizontally(Motion.slide) { shift(it) }) togetherWith
|
||||||
(fadeOut(Motion.exitFade) + slideOutHorizontally(Motion.slide) { -shift(it) })
|
(fadeOut(Motion.exitFade) + slideOutHorizontally(Motion.slide) { -shift(it) })
|
||||||
},
|
},
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(padding)
|
.statusBarsPadding()
|
||||||
.consumeWindowInsets(padding)
|
|
||||||
.imePadding(),
|
.imePadding(),
|
||||||
label = "tabs",
|
label = "screens",
|
||||||
) { current ->
|
) { screen ->
|
||||||
val modifier = Modifier.fillMaxSize()
|
val modifier = Modifier.fillMaxSize()
|
||||||
when (current) {
|
when (screen) {
|
||||||
Tab.HOME -> HomeScreen(modifier)
|
Screen.HOME -> HomeScreen(
|
||||||
Tab.MONITOR -> MonitorScreen(modifier)
|
bottomPadding = tabBottom,
|
||||||
Tab.APPS -> AppsScreen(modifier)
|
onOpenBlocklist = { page = Screen.BLOCKLIST },
|
||||||
Tab.BLOCKLIST -> BlocklistScreen(modifier)
|
modifier = modifier,
|
||||||
Tab.ABOUT -> AboutScreen(modifier)
|
)
|
||||||
|
Screen.ACTIVITY -> ActivityScreen(bottomPadding = tabBottom, modifier = modifier)
|
||||||
|
Screen.SETTINGS -> SettingsScreen(
|
||||||
|
bottomPadding = tabBottom,
|
||||||
|
onOpenApps = { page = Screen.APPS },
|
||||||
|
onOpenAbout = { page = Screen.ABOUT },
|
||||||
|
modifier = modifier,
|
||||||
|
)
|
||||||
|
Screen.BLOCKLIST -> BlocklistScreen(bottomPadding = pageBottom, onBack = { page = null }, modifier = modifier)
|
||||||
|
Screen.APPS -> SubPage(stringResource(R.string.settings_apps), onBack = { page = null }, modifier = modifier) {
|
||||||
|
AppsScreen(Modifier.fillMaxSize())
|
||||||
|
}
|
||||||
|
Screen.ABOUT -> SubPage(stringResource(R.string.tab_about), onBack = { page = null }, modifier = modifier) {
|
||||||
|
AboutScreen(Modifier.fillMaxSize())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = page == null,
|
||||||
|
enter = fadeIn(Motion.enterFade),
|
||||||
|
exit = fadeOut(Motion.exitFade),
|
||||||
|
modifier = Modifier.align(Alignment.BottomCenter),
|
||||||
|
) {
|
||||||
|
Box(contentAlignment = Alignment.BottomCenter) {
|
||||||
|
// Content scrolling under the panel fades out instead of being cut off
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(120.dp + navInset)
|
||||||
|
.background(Brush.verticalGradient(0f to Color.Transparent, 0.7f to Palette.Bg))
|
||||||
|
)
|
||||||
|
NavPill(
|
||||||
|
current = tab,
|
||||||
|
onSelect = { tab = it },
|
||||||
|
modifier = Modifier
|
||||||
|
.navigationBarsPadding()
|
||||||
|
.padding(bottom = 20.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Floating bottom panel: dark, with the picked tab lit in the accent color
|
||||||
|
@Composable
|
||||||
|
private fun NavPill(current: Screen, onSelect: (Screen) -> Unit, modifier: Modifier = Modifier) {
|
||||||
|
val shape = RoundedCornerShape(30.dp)
|
||||||
|
Row(
|
||||||
|
modifier = modifier
|
||||||
|
.shadow(18.dp, shape)
|
||||||
|
.clip(shape)
|
||||||
|
.background(Palette.Nav)
|
||||||
|
.border(1.dp, Color.White.copy(alpha = 0.07f), shape)
|
||||||
|
.padding(6.dp)
|
||||||
|
.selectableGroup(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
|
Screen.entries.filter { it.isTab }.forEach { item ->
|
||||||
|
val selected = item == current
|
||||||
|
val background by animateColorAsState(
|
||||||
|
if (selected) Palette.AccentSoft else Color.Transparent,
|
||||||
|
animationSpec = Motion.color,
|
||||||
|
label = "navBackground",
|
||||||
|
)
|
||||||
|
val tint by animateColorAsState(
|
||||||
|
if (selected) Palette.Accent else Palette.NavIcon,
|
||||||
|
animationSpec = Motion.color,
|
||||||
|
label = "navTint",
|
||||||
|
)
|
||||||
|
val label = stringResource(item.label)
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(width = 58.dp, height = 44.dp)
|
||||||
|
.clip(RoundedCornerShape(22.dp))
|
||||||
|
.background(background)
|
||||||
|
.selectable(selected = selected, onClick = { onSelect(item) }, role = Role.Tab)
|
||||||
|
.semantics { contentDescription = label },
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(painterResource(item.icon), contentDescription = null, tint = tint, modifier = Modifier.size(22.dp))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,26 +39,28 @@ import androidx.compose.material3.TextButton
|
|||||||
import androidx.compose.material3.TriStateCheckbox
|
import androidx.compose.material3.TriStateCheckbox
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.produceState
|
import androidx.compose.runtime.produceState
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.Saver
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.draw.rotate
|
|
||||||
import androidx.compose.ui.graphics.ImageBitmap
|
import androidx.compose.ui.graphics.ImageBitmap
|
||||||
import androidx.compose.ui.graphics.asImageBitmap
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.semantics.Role
|
import androidx.compose.ui.semantics.Role
|
||||||
import androidx.compose.ui.state.ToggleableState
|
import androidx.compose.ui.state.ToggleableState
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
@@ -77,20 +79,29 @@ private enum class AppGroup(@StringRes val label: Int, @DrawableRes val icon: In
|
|||||||
|
|
||||||
private class AppItem(val label: String, val packageName: String, val group: AppGroup)
|
private class AppItem(val label: String, val packageName: String, val group: AppGroup)
|
||||||
|
|
||||||
// Decoded icons survive scrolling and tab switches instead of being rendered again every time
|
// Decoded icons survive scrolling and tab switches instead of being rendered again every time.
|
||||||
private val IconCache = LruCache<String, ImageBitmap>(256)
|
// Limited by memory rather than count, since icon size now follows the screen density.
|
||||||
|
private val IconCache = object : LruCache<String, ImageBitmap>(10 * 1024 * 1024) {
|
||||||
|
override fun sizeOf(key: String, value: ImageBitmap) = value.width * value.height * 4
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun clearAppIconCache() = IconCache.evictAll()
|
||||||
|
|
||||||
|
// Shown right away when the tab opens again, while the list is read anew in the background.
|
||||||
|
// Only touched on the main thread.
|
||||||
|
private var lastAppList: List<AppItem>? = null
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun AppsScreen(modifier: Modifier = Modifier) {
|
fun AppsScreen(modifier: Modifier = Modifier) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val prefs = remember { Prefs(context) }
|
val prefs = remember { Prefs(context) }
|
||||||
val active by DohVpnService.active.collectAsState()
|
val active by DohVpnService.active.collectAsStateWithLifecycle()
|
||||||
val activeExcluded by DohVpnService.activeExcluded.collectAsState()
|
val activeExcluded by DohVpnService.activeExcluded.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
var apps by remember { mutableStateOf<List<AppItem>?>(null) }
|
var apps by remember { mutableStateOf(lastAppList) }
|
||||||
var excluded by remember { mutableStateOf(prefs.excludedApps) }
|
var excluded by remember { mutableStateOf(prefs.excludedApps) }
|
||||||
var search by rememberSaveable { mutableStateOf("") }
|
var search by rememberSaveable { mutableStateOf("") }
|
||||||
var collapsed by remember { mutableStateOf(setOf(AppGroup.SYSTEM)) }
|
var collapsed by rememberSaveable(stateSaver = CollapsedSaver) { mutableStateOf(setOf(AppGroup.SYSTEM)) }
|
||||||
val pending = active != null && excluded != activeExcluded
|
val pending = active != null && excluded != activeExcluded
|
||||||
var showAppsHint by remember { mutableStateOf(!prefs.isHintDismissed(HINT_APPS)) }
|
var showAppsHint by remember { mutableStateOf(!prefs.isHintDismissed(HINT_APPS)) }
|
||||||
// Closing the "reconnect" card hides it until the selection changes again
|
// Closing the "reconnect" card hides it until the selection changes again
|
||||||
@@ -100,7 +111,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
|
|||||||
val searching = search.isNotBlank()
|
val searching = search.isNotBlank()
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
apps = withContext(Dispatchers.IO) { loadApps(context) }
|
apps = withContext(Dispatchers.IO) { loadApps(context) }.also { lastAppList = it }
|
||||||
}
|
}
|
||||||
|
|
||||||
val groups = remember(apps, search) {
|
val groups = remember(apps, search) {
|
||||||
@@ -188,7 +199,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
|
|||||||
|
|
||||||
groups.forEach { (group, items) ->
|
groups.forEach { (group, items) ->
|
||||||
val expanded = searching || group !in collapsed
|
val expanded = searching || group !in collapsed
|
||||||
item(key = "group:${group.name}") {
|
item(key = "group:${group.name}", contentType = "group") {
|
||||||
GroupHeader(
|
GroupHeader(
|
||||||
modifier = Modifier.animateItem(),
|
modifier = Modifier.animateItem(),
|
||||||
group = group,
|
group = group,
|
||||||
@@ -205,7 +216,7 @@ fun AppsScreen(modifier: Modifier = Modifier) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (expanded) {
|
if (expanded) {
|
||||||
itemsIndexed(items, key = { _, app -> app.packageName }) { index, app ->
|
itemsIndexed(items, key = { _, app -> app.packageName }, contentType = { _, _ -> "app" }) { index, app ->
|
||||||
AppRow(
|
AppRow(
|
||||||
modifier = Modifier.animateItem(),
|
modifier = Modifier.animateItem(),
|
||||||
app = app,
|
app = app,
|
||||||
@@ -237,7 +248,8 @@ private fun GroupHeader(
|
|||||||
else -> ToggleableState.Indeterminate
|
else -> ToggleableState.Indeterminate
|
||||||
}
|
}
|
||||||
|
|
||||||
val chevron by animateFloatAsState(if (expanded) 180f else 0f, Motion.rotation, label = "chevron")
|
// Read only in the draw phase, so the animation does not recompose the header every frame
|
||||||
|
val chevron = animateFloatAsState(if (expanded) 180f else 0f, Motion.rotation, label = "chevron")
|
||||||
|
|
||||||
Row(
|
Row(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
@@ -267,7 +279,7 @@ private fun GroupHeader(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.padding(end = 8.dp)
|
.padding(end = 8.dp)
|
||||||
.size(22.dp)
|
.size(22.dp)
|
||||||
.rotate(chevron),
|
.graphicsLayer { rotationZ = chevron.value },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -275,12 +287,15 @@ private fun GroupHeader(
|
|||||||
@Composable
|
@Composable
|
||||||
private fun AppRow(modifier: Modifier, app: AppItem, enabled: Boolean, last: Boolean, onToggle: (Boolean) -> Unit) {
|
private fun AppRow(modifier: Modifier, app: AppItem, enabled: Boolean, last: Boolean, onToggle: (Boolean) -> Unit) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val icon by produceState<ImageBitmap?>(IconCache.get(app.packageName), app.packageName) {
|
// Rendered at the size it is shown (40 dp), so icons stay sharp on dense screens
|
||||||
|
val iconPx = with(LocalDensity.current) { 40.dp.roundToPx() }
|
||||||
|
val cacheKey = "${app.packageName}@$iconPx"
|
||||||
|
val icon by produceState<ImageBitmap?>(IconCache.get(cacheKey), cacheKey) {
|
||||||
if (value != null) return@produceState
|
if (value != null) return@produceState
|
||||||
value = withContext(Dispatchers.IO) {
|
value = withContext(Dispatchers.IO) {
|
||||||
runCatching { context.packageManager.getApplicationIcon(app.packageName).toImageBitmap(96) }
|
runCatching { context.packageManager.getApplicationIcon(app.packageName).toImageBitmap(iconPx) }
|
||||||
.getOrNull()
|
.getOrNull()
|
||||||
?.also { IconCache.put(app.packageName, it) }
|
?.also { IconCache.put(cacheKey, it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,7 +338,7 @@ private fun AppRow(modifier: Modifier, app: AppItem, enabled: Boolean, last: Boo
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
Spacer(Modifier.width(12.dp))
|
Spacer(Modifier.width(12.dp))
|
||||||
Switch(checked = enabled, onCheckedChange = null)
|
Switch(checked = enabled, onCheckedChange = null, colors = appSwitchColors())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -363,4 +378,10 @@ private fun Drawable.toImageBitmap(size: Int): ImageBitmap {
|
|||||||
return bitmap.asImageBitmap()
|
return bitmap.asImageBitmap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Collapsed groups survive rotation and process death
|
||||||
|
private val CollapsedSaver = Saver<Set<AppGroup>, String>(
|
||||||
|
save = { groups -> groups.joinToString(",") { it.name } },
|
||||||
|
restore = { saved -> saved.split(',').mapNotNull { name -> AppGroup.entries.firstOrNull { it.name == name } }.toSet() },
|
||||||
|
)
|
||||||
|
|
||||||
private const val HINT_APPS = "apps"
|
private const val HINT_APPS = "apps"
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import android.app.job.JobInfo
|
||||||
|
import android.app.job.JobParameters
|
||||||
|
import android.app.job.JobScheduler
|
||||||
|
import android.app.job.JobService
|
||||||
|
import android.content.ComponentName
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
enum class UpdateInterval(val days: Long) { OFF(0), DAILY(1), WEEKLY(7) }
|
||||||
|
|
||||||
|
// Downloads newer versions of the user's blocklists in the background. Uses the system
|
||||||
|
// JobScheduler, so the app needs no extra library and nothing runs while the conditions are not met.
|
||||||
|
object AutoUpdate {
|
||||||
|
private const val JOB_ID = 4201
|
||||||
|
|
||||||
|
// JobInfo.networkType is deprecated in favour of NetworkRequest, which needs API 28
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
fun apply(context: Context) {
|
||||||
|
val prefs = Prefs(context)
|
||||||
|
val scheduler = context.getSystemService(JobScheduler::class.java) ?: return
|
||||||
|
val interval = prefs.updateInterval
|
||||||
|
if (interval == UpdateInterval.OFF) {
|
||||||
|
scheduler.cancel(JOB_ID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val period = TimeUnit.DAYS.toMillis(interval.days)
|
||||||
|
val network = if (prefs.updateWifiOnly) JobInfo.NETWORK_TYPE_UNMETERED else JobInfo.NETWORK_TYPE_ANY
|
||||||
|
// Scheduling the same job again would start its period over, so an unchanged one is kept
|
||||||
|
val existing = scheduler.getPendingJob(JOB_ID)
|
||||||
|
if (existing != null && existing.intervalMillis == period && existing.networkType == network) return
|
||||||
|
|
||||||
|
val job = JobInfo.Builder(JOB_ID, ComponentName(context, BlocklistUpdateJob::class.java))
|
||||||
|
.setPeriodic(period)
|
||||||
|
.setRequiredNetworkType(network)
|
||||||
|
.setRequiresBatteryNotLow(true)
|
||||||
|
.setPersisted(true)
|
||||||
|
.build()
|
||||||
|
try {
|
||||||
|
scheduler.schedule(job)
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
Log.w("SparkleDNS", "Cannot schedule blocklist updates", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BlocklistUpdateJob : JobService() {
|
||||||
|
override fun onStartJob(params: JobParameters): Boolean {
|
||||||
|
Thread({
|
||||||
|
val ok = try {
|
||||||
|
Blocklist.updateAllNow(applicationContext)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w("SparkleDNS", "Blocklist update failed", e)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
// A failed run is retried later with the system's back-off
|
||||||
|
jobFinished(params, !ok)
|
||||||
|
}, "blocklist-update").start()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Downloads cannot be cut short halfway; the next run picks up where this one stopped
|
||||||
|
override fun onStopJob(params: JobParameters): Boolean = true
|
||||||
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import android.util.Log
|
||||||
|
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
@@ -21,14 +24,17 @@ import java.nio.channels.FileChannel
|
|||||||
import java.security.MessageDigest
|
import java.security.MessageDigest
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
data class RemoteList(val url: String, val count: Int, val updated: Long)
|
// A switched-off list keeps its file, so switching it on again needs no download
|
||||||
|
data class RemoteList(val url: String, val count: Int, val updated: Long, val enabled: Boolean = true)
|
||||||
|
|
||||||
// Blocks a domain together with all its subdomains. Changes apply instantly, no reconnect needed.
|
// Blocks a domain together with all its subdomains. Changes apply instantly, no reconnect needed.
|
||||||
// Domains are kept as sorted 64-bit hashes: about 8 bytes per entry, so million-entry lists fit easily.
|
// Domains are kept as sorted 64-bit hashes: about 8 bytes per entry, so million-entry lists fit easily.
|
||||||
object Blocklist {
|
object Blocklist {
|
||||||
const val ALL_LISTS = "*"
|
const val ALL_LISTS = "*"
|
||||||
|
|
||||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
private val scope = CoroutineScope(
|
||||||
|
SupervisorJob() + Dispatchers.IO + CoroutineExceptionHandler { _, e -> Log.e("SparkleDNS", "Blocklist task failed", e) }
|
||||||
|
)
|
||||||
private val lock = Any()
|
private val lock = Any()
|
||||||
|
|
||||||
private val _enabled = MutableStateFlow(true)
|
private val _enabled = MutableStateFlow(true)
|
||||||
@@ -51,24 +57,16 @@ object Blocklist {
|
|||||||
private val _error = MutableStateFlow<String?>(null)
|
private val _error = MutableStateFlow<String?>(null)
|
||||||
val error: StateFlow<String?> = _error
|
val error: StateFlow<String?> = _error
|
||||||
|
|
||||||
|
// Downloaded lists and own domains are kept apart, so editing a few own domains
|
||||||
|
// does not rebuild a set that can hold millions of entries
|
||||||
@Volatile
|
@Volatile
|
||||||
private var hashes = LongArray(0)
|
|
||||||
private var listHashes = LongArray(0)
|
private var listHashes = LongArray(0)
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var customHashes = LongArray(0)
|
||||||
private var loaded = false
|
private var loaded = false
|
||||||
|
|
||||||
fun isBlocked(name: String): Boolean {
|
fun isBlocked(name: String): Boolean = _enabled.value && isBlockedIn(name, listHashes, customHashes)
|
||||||
if (!_enabled.value) return false
|
|
||||||
val set = hashes
|
|
||||||
if (set.isEmpty()) return false
|
|
||||||
val domain = name.trimEnd('.')
|
|
||||||
var start = 0
|
|
||||||
while (true) {
|
|
||||||
if (set.binarySearch(DomainHash.of(domain, start)) >= 0) return true
|
|
||||||
val dot = domain.indexOf('.', start)
|
|
||||||
if (dot < 0) return false
|
|
||||||
start = dot + 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun reload(context: Context) = synchronized(lock) { load(BlocklistStore(context)) }
|
fun reload(context: Context) = synchronized(lock) { load(BlocklistStore(context)) }
|
||||||
|
|
||||||
@@ -84,7 +82,7 @@ object Blocklist {
|
|||||||
val updated = (_custom.value + domain).distinct().sorted()
|
val updated = (_custom.value + domain).distinct().sorted()
|
||||||
store.saveCustom(updated)
|
store.saveCustom(updated)
|
||||||
_custom.value = updated
|
_custom.value = updated
|
||||||
combine()
|
updateCustomHashes()
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,7 +92,7 @@ object Blocklist {
|
|||||||
val updated = _custom.value - domain
|
val updated = _custom.value - domain
|
||||||
store.saveCustom(updated)
|
store.saveCustom(updated)
|
||||||
_custom.value = updated
|
_custom.value = updated
|
||||||
combine()
|
updateCustomHashes()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun removeList(context: Context, url: String) = synchronized(lock) {
|
fun removeList(context: Context, url: String) = synchronized(lock) {
|
||||||
@@ -107,6 +105,15 @@ object Blocklist {
|
|||||||
reloadListHashes(store)
|
reloadListHashes(store)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun setListEnabled(context: Context, url: String, value: Boolean) = synchronized(lock) {
|
||||||
|
val store = BlocklistStore(context)
|
||||||
|
ensureLoaded(store)
|
||||||
|
val updated = _lists.value.map { if (it.url == url) it.copy(enabled = value) else it }
|
||||||
|
store.saveLists(updated)
|
||||||
|
_lists.value = updated
|
||||||
|
reloadListHashes(store)
|
||||||
|
}
|
||||||
|
|
||||||
// Downloads run in the background, outside the lock, so editing own domains never waits for them.
|
// Downloads run in the background, outside the lock, so editing own domains never waits for them.
|
||||||
// Returns false when another download is already running.
|
// Returns false when another download is already running.
|
||||||
fun download(context: Context, url: String): Boolean {
|
fun download(context: Context, url: String): Boolean {
|
||||||
@@ -114,9 +121,10 @@ object Blocklist {
|
|||||||
if (target.isEmpty() || !_busy.compareAndSet(null, target)) return false
|
if (target.isEmpty() || !_busy.compareAndSet(null, target)) return false
|
||||||
_error.value = null
|
_error.value = null
|
||||||
val store = BlocklistStore(context.applicationContext)
|
val store = BlocklistStore(context.applicationContext)
|
||||||
|
val previous = _lists.value.firstOrNull { it.url == target }
|
||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
val list = store.download(target)
|
val list = store.download(target, previous)
|
||||||
commit(store, listOf(list))
|
commit(store, listOf(list))
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_error.value = e.message ?: e.javaClass.simpleName
|
_error.value = e.message ?: e.javaClass.simpleName
|
||||||
@@ -127,22 +135,25 @@ object Blocklist {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Switched-off lists are skipped: nobody uses them until they are switched on again
|
||||||
fun updateAll(context: Context): Boolean {
|
fun updateAll(context: Context): Boolean {
|
||||||
if (_lists.value.isEmpty() || !_busy.compareAndSet(null, ALL_LISTS)) return false
|
val current = _lists.value.filter { it.enabled }
|
||||||
|
if (current.isEmpty() || !_busy.compareAndSet(null, ALL_LISTS)) return false
|
||||||
_error.value = null
|
_error.value = null
|
||||||
val store = BlocklistStore(context.applicationContext)
|
val store = BlocklistStore(context.applicationContext)
|
||||||
val urls = _lists.value.map { it.url }
|
|
||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
val fresh = urls.mapNotNull { url ->
|
val fresh = current.mapNotNull { list ->
|
||||||
try {
|
try {
|
||||||
store.download(url)
|
store.download(list.url, list)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
if (_error.value == null) _error.value = e.message ?: e.javaClass.simpleName
|
if (_error.value == null) _error.value = e.message ?: e.javaClass.simpleName
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
commit(store, fresh)
|
commit(store, fresh)
|
||||||
|
} catch (e: IOException) {
|
||||||
|
_error.value = e.message ?: e.javaClass.simpleName
|
||||||
} finally {
|
} finally {
|
||||||
_busy.value = null
|
_busy.value = null
|
||||||
}
|
}
|
||||||
@@ -150,10 +161,38 @@ object Blocklist {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Blocking, for the background update job. Returns false when a list could not be downloaded.
|
||||||
|
fun updateAllNow(context: Context): Boolean {
|
||||||
|
val store = BlocklistStore(context.applicationContext)
|
||||||
|
synchronized(lock) { ensureLoaded(store) }
|
||||||
|
val current = _lists.value.filter { it.enabled }
|
||||||
|
// Nothing to do, or the user is updating right now
|
||||||
|
if (current.isEmpty() || !_busy.compareAndSet(null, ALL_LISTS)) return true
|
||||||
|
var ok = true
|
||||||
|
try {
|
||||||
|
val fresh = current.mapNotNull { list ->
|
||||||
|
try {
|
||||||
|
store.download(list.url, list)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w("SparkleDNS", "Cannot update ${list.url}", e)
|
||||||
|
ok = false
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
commit(store, fresh)
|
||||||
|
} catch (e: IOException) {
|
||||||
|
Log.w("SparkleDNS", "Cannot save updated lists", e)
|
||||||
|
ok = false
|
||||||
|
} finally {
|
||||||
|
_busy.value = null
|
||||||
|
}
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
private fun commit(store: BlocklistStore, fresh: List<RemoteList>) = synchronized(lock) {
|
private fun commit(store: BlocklistStore, fresh: List<RemoteList>) = synchronized(lock) {
|
||||||
ensureLoaded(store)
|
ensureLoaded(store)
|
||||||
val byUrl = fresh.associateBy { it.url }
|
val byUrl = fresh.associateBy { it.url }
|
||||||
val kept = _lists.value.map { byUrl[it.url] ?: it }
|
val kept = _lists.value.map { old -> byUrl[old.url]?.copy(enabled = old.enabled) ?: old }
|
||||||
val added = fresh.filter { new -> kept.none { it.url == new.url } }
|
val added = fresh.filter { new -> kept.none { it.url == new.url } }
|
||||||
val updated = kept + added
|
val updated = kept + added
|
||||||
store.saveLists(updated)
|
store.saveLists(updated)
|
||||||
@@ -169,35 +208,76 @@ object Blocklist {
|
|||||||
_enabled.value = store.enabled
|
_enabled.value = store.enabled
|
||||||
_custom.value = store.loadCustom()
|
_custom.value = store.loadCustom()
|
||||||
_lists.value = store.loadLists()
|
_lists.value = store.loadLists()
|
||||||
|
val custom = _custom.value
|
||||||
|
customHashes = LongArray(custom.size) { DomainHash.of(custom[it]) }.sortUnique()
|
||||||
reloadListHashes(store)
|
reloadListHashes(store)
|
||||||
loaded = true
|
loaded = true
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun reloadListHashes(store: BlocklistStore) {
|
private fun reloadListHashes(store: BlocklistStore) {
|
||||||
listHashes = merge(_lists.value.map { store.loadListHashes(it.url) })
|
listHashes = mergeSorted(_lists.value.filter { it.enabled }.map { store.loadListHashes(it.url) })
|
||||||
combine()
|
_total.value = unionSize(listHashes, customHashes)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun combine() {
|
private fun updateCustomHashes() {
|
||||||
val custom = _custom.value
|
val custom = _custom.value
|
||||||
hashes = if (custom.isEmpty()) {
|
customHashes = LongArray(custom.size) { DomainHash.of(custom[it]) }.sortUnique()
|
||||||
listHashes
|
_total.value = unionSize(listHashes, customHashes)
|
||||||
} else {
|
|
||||||
merge(listOf(listHashes, LongArray(custom.size) { DomainHash.of(custom[it]) }))
|
|
||||||
}
|
|
||||||
_total.value = hashes.size
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun merge(parts: List<LongArray>): LongArray {
|
// True when the name or one of its parent domains is in either sorted hash set
|
||||||
val nonEmpty = parts.filter { it.isNotEmpty() }
|
internal fun isBlockedIn(name: String, lists: LongArray, custom: LongArray): Boolean {
|
||||||
if (nonEmpty.size <= 1) return nonEmpty.firstOrNull() ?: LongArray(0) // stored lists are already sorted
|
if (lists.isEmpty() && custom.isEmpty()) return false
|
||||||
val all = LongArray(nonEmpty.sumOf { it.size })
|
val domain = name.trimEnd('.')
|
||||||
var pos = 0
|
var start = 0
|
||||||
nonEmpty.forEach { it.copyInto(all, pos); pos += it.size }
|
while (true) {
|
||||||
return all.sortUnique()
|
val hash = DomainHash.of(domain, start)
|
||||||
|
if (lists.binarySearch(hash) >= 0 || custom.binarySearch(hash) >= 0) return true
|
||||||
|
val dot = domain.indexOf('.', start)
|
||||||
|
if (dot < 0) return false
|
||||||
|
start = dot + 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Number of distinct entries in both sorted sets; the custom set is small
|
||||||
|
internal fun unionSize(lists: LongArray, custom: LongArray): Int =
|
||||||
|
lists.size + custom.count { lists.binarySearch(it) < 0 }
|
||||||
|
|
||||||
|
// Merges sorted, duplicate-free arrays in linear time instead of sorting their concatenation
|
||||||
|
internal fun mergeSorted(parts: List<LongArray>): LongArray {
|
||||||
|
var arrays = parts.filter { it.isNotEmpty() }.map { if (it.isSortedUnique()) it else it.copyOf().sortUnique() }
|
||||||
|
if (arrays.isEmpty()) return LongArray(0)
|
||||||
|
while (arrays.size > 1) {
|
||||||
|
arrays = arrays.chunked(2).map { if (it.size == 2) mergeTwo(it[0], it[1]) else it[0] }
|
||||||
|
}
|
||||||
|
return arrays[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mergeTwo(a: LongArray, b: LongArray): LongArray {
|
||||||
|
val out = LongArray(a.size + b.size)
|
||||||
|
var i = 0
|
||||||
|
var j = 0
|
||||||
|
var n = 0
|
||||||
|
while (i < a.size && j < b.size) {
|
||||||
|
val x = a[i]
|
||||||
|
val y = b[j]
|
||||||
|
when {
|
||||||
|
x < y -> { out[n++] = x; i++ }
|
||||||
|
x > y -> { out[n++] = y; j++ }
|
||||||
|
else -> { out[n++] = x; i++; j++ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (i < a.size) out[n++] = a[i++]
|
||||||
|
while (j < b.size) out[n++] = b[j++]
|
||||||
|
return if (n == out.size) out else out.copyOf(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun LongArray.isSortedUnique(): Boolean {
|
||||||
|
for (i in 1 until size) if (this[i - 1] >= this[i]) return false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
internal object DomainHash {
|
internal object DomainHash {
|
||||||
private const val FNV_OFFSET = -3750763034362895579L // 0xcbf29ce484222325
|
private const val FNV_OFFSET = -3750763034362895579L // 0xcbf29ce484222325
|
||||||
private const val FNV_PRIME = 1099511628211L
|
private const val FNV_PRIME = 1099511628211L
|
||||||
@@ -260,7 +340,7 @@ private class BlocklistStore(context: Context) {
|
|||||||
val array = JSONArray(raw)
|
val array = JSONArray(raw)
|
||||||
(0 until array.length()).map {
|
(0 until array.length()).map {
|
||||||
val o = array.getJSONObject(it)
|
val o = array.getJSONObject(it)
|
||||||
RemoteList(o.getString("url"), o.getInt("count"), o.getLong("updated"))
|
RemoteList(o.getString("url"), o.getInt("count"), o.getLong("updated"), o.optBoolean("enabled", true))
|
||||||
}
|
}
|
||||||
}.getOrDefault(emptyList())
|
}.getOrDefault(emptyList())
|
||||||
}
|
}
|
||||||
@@ -268,7 +348,9 @@ private class BlocklistStore(context: Context) {
|
|||||||
fun saveLists(lists: List<RemoteList>) {
|
fun saveLists(lists: List<RemoteList>) {
|
||||||
val array = JSONArray()
|
val array = JSONArray()
|
||||||
lists.forEach {
|
lists.forEach {
|
||||||
array.put(JSONObject().put("url", it.url).put("count", it.count).put("updated", it.updated))
|
array.put(
|
||||||
|
JSONObject().put("url", it.url).put("count", it.count).put("updated", it.updated).put("enabled", it.enabled)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
sp.edit().putString("lists", array.toString()).commit()
|
sp.edit().putString("lists", array.toString()).commit()
|
||||||
}
|
}
|
||||||
@@ -290,22 +372,38 @@ private class BlocklistStore(context: Context) {
|
|||||||
fun deleteListFile(url: String) {
|
fun deleteListFile(url: String) {
|
||||||
binFile(url).delete()
|
binFile(url).delete()
|
||||||
textFile(url).delete()
|
textFile(url).delete()
|
||||||
|
sp.edit().remove(etagKey(url)).remove(modifiedKey(url)).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun download(url: String): RemoteList {
|
// With the list already on disk the server is asked for a changed one only, so updating
|
||||||
val request = runCatching { Request.Builder().url(url).build() }
|
// a list that did not change costs a few hundred bytes instead of megabytes
|
||||||
.getOrElse { throw IOException("Invalid URL") }
|
fun download(url: String, previous: RemoteList? = null): RemoteList {
|
||||||
|
val builder = runCatching { Request.Builder().url(url) }.getOrElse { throw IOException("Invalid URL") }
|
||||||
|
if (previous != null && binFile(url).exists()) {
|
||||||
|
sp.getString(etagKey(url), null)?.let { builder.header("If-None-Match", it) }
|
||||||
|
sp.getString(modifiedKey(url), null)?.let { builder.header("If-Modified-Since", it) }
|
||||||
|
}
|
||||||
|
|
||||||
client.newCall(request).execute().use { response ->
|
client.newCall(builder.build()).execute().use { response ->
|
||||||
|
if (response.code == 304 && previous != null) return previous.copy(updated = System.currentTimeMillis())
|
||||||
if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
|
if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
|
||||||
val body = response.body ?: throw IOException("Empty response")
|
val body = response.body ?: throw IOException("Empty response")
|
||||||
val parsed = LongList()
|
val parsed = LongList()
|
||||||
body.charStream().buffered().useLines { lines ->
|
body.charStream().buffered().useLines { lines ->
|
||||||
lines.forEach { line -> BlocklistParser.parseLine(line)?.let { parsed.add(DomainHash.of(it)) } }
|
lines.forEach { line ->
|
||||||
|
val domain = BlocklistParser.parseLine(line) ?: return@forEach
|
||||||
|
// Far above the largest common lists; keeps a wrong URL from exhausting memory
|
||||||
|
if (parsed.size >= MAX_LIST_DOMAINS) throw IOException("List too large")
|
||||||
|
parsed.add(DomainHash.of(domain))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
val result = parsed.toArray().sortUnique()
|
val result = parsed.toArray().sortUnique()
|
||||||
if (result.isEmpty()) throw IOException("No domains found")
|
if (result.isEmpty()) throw IOException("No domains found")
|
||||||
write(url, result)
|
write(url, result)
|
||||||
|
sp.edit()
|
||||||
|
.putOrRemove(etagKey(url), response.header("ETag"))
|
||||||
|
.putOrRemove(modifiedKey(url), response.header("Last-Modified"))
|
||||||
|
.apply()
|
||||||
return RemoteList(url, result.size, System.currentTimeMillis())
|
return RemoteList(url, result.size, System.currentTimeMillis())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -332,6 +430,12 @@ private class BlocklistStore(context: Context) {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun etagKey(url: String) = "etag_${hash(url)}"
|
||||||
|
private fun modifiedKey(url: String) = "modified_${hash(url)}"
|
||||||
|
|
||||||
|
private fun SharedPreferences.Editor.putOrRemove(key: String, value: String?) =
|
||||||
|
if (value == null) remove(key) else putString(key, value)
|
||||||
|
|
||||||
private fun binFile(url: String) = File(dir, "list_${hash(url)}.bin")
|
private fun binFile(url: String) = File(dir, "list_${hash(url)}.bin")
|
||||||
private fun textFile(url: String) = File(dir, "list_${hash(url)}.txt")
|
private fun textFile(url: String) = File(dir, "list_${hash(url)}.txt")
|
||||||
|
|
||||||
@@ -339,9 +443,10 @@ private class BlocklistStore(context: Context) {
|
|||||||
.take(8).joinToString("") { "%02x".format(it) }
|
.take(8).joinToString("") { "%02x".format(it) }
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
const val MAX_LIST_DOMAINS = 4_000_000
|
||||||
|
|
||||||
val client: OkHttpClient by lazy {
|
val client: OkHttpClient by lazy {
|
||||||
OkHttpClient.Builder()
|
Http.client.newBuilder()
|
||||||
.connectTimeout(15, TimeUnit.SECONDS)
|
|
||||||
.readTimeout(60, TimeUnit.SECONDS)
|
.readTimeout(60, TimeUnit.SECONDS)
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +1,46 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
|
import android.text.format.DateUtils
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.annotation.StringRes
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.animation.animateContentSize
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
import androidx.compose.foundation.horizontalScroll
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.itemsIndexed
|
||||||
|
import androidx.compose.foundation.selection.selectable
|
||||||
|
import androidx.compose.foundation.selection.toggleable
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.text.KeyboardActions
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.AssistChip
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.Card
|
|
||||||
import androidx.compose.material3.FilledTonalButton
|
|
||||||
import androidx.compose.material3.HorizontalDivider
|
import androidx.compose.material3.HorizontalDivider
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.LinearProgressIndicator
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Switch
|
import androidx.compose.material3.RadioButton
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
@@ -39,114 +49,189 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.RectangleShape
|
||||||
|
import androidx.compose.ui.graphics.Shape
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
import androidx.compose.ui.text.input.KeyboardType
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.text.DateFormat
|
import java.io.IOException
|
||||||
import java.util.Date
|
|
||||||
|
private class Preset(val name: String, val url: String, @StringRes val description: Int)
|
||||||
|
|
||||||
|
private const val HAGEZI_HOME = "https://github.com/hagezi/dns-blocklists"
|
||||||
|
|
||||||
private val Presets = listOf(
|
private val Presets = listOf(
|
||||||
"HaGeZi Pro++" to "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/pro.plus.txt",
|
Preset("HaGeZi Pro", "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/pro.txt", R.string.preset_pro_desc),
|
||||||
"HaGeZi TIF" to "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/tif.txt",
|
Preset("HaGeZi Pro++", "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/pro.plus.txt", R.string.preset_proplus_desc),
|
||||||
|
Preset("HaGeZi TIF", "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/tif.txt", R.string.preset_tif_desc),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
private val TopShape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp)
|
||||||
|
private val BottomShape = RoundedCornerShape(bottomStart = 20.dp, bottomEnd = 20.dp)
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun BlocklistScreen(modifier: Modifier = Modifier) {
|
fun BlocklistScreen(bottomPadding: Dp, onBack: () -> Unit, modifier: Modifier = Modifier) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val prefs = remember { Prefs(context) }
|
val prefs = remember { Prefs(context) }
|
||||||
var showNote by remember { mutableStateOf(!prefs.isHintDismissed(HINT_BLOCKLIST)) }
|
|
||||||
|
|
||||||
val enabled by Blocklist.enabled.collectAsState()
|
val enabled by Blocklist.enabled.collectAsStateWithLifecycle()
|
||||||
val total by Blocklist.total.collectAsState()
|
val custom by Blocklist.custom.collectAsStateWithLifecycle()
|
||||||
val custom by Blocklist.custom.collectAsState()
|
val lists by Blocklist.lists.collectAsStateWithLifecycle()
|
||||||
val lists by Blocklist.lists.collectAsState()
|
// Downloads live in Blocklist, so they keep running and stay visible when the page is closed
|
||||||
|
val busy by Blocklist.busy.collectAsStateWithLifecycle()
|
||||||
var domainInput by rememberSaveable { mutableStateOf("") }
|
val error by Blocklist.error.collectAsStateWithLifecycle()
|
||||||
var domainError by remember { mutableStateOf(false) }
|
|
||||||
var urlInput by rememberSaveable { mutableStateOf("") }
|
|
||||||
// Downloads live in Blocklist, so they keep running and stay visible across tab switches
|
|
||||||
val busy by Blocklist.busy.collectAsState()
|
|
||||||
val error by Blocklist.error.collectAsState()
|
|
||||||
val lastError = remember { arrayOf("") } // kept while the card animates out
|
val lastError = remember { arrayOf("") } // kept while the card animates out
|
||||||
error?.let { lastError[0] = it }
|
error?.let { lastError[0] = it }
|
||||||
|
|
||||||
|
var search by rememberSaveable { mutableStateOf("") }
|
||||||
|
var domainsOpen by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var domainInput by rememberSaveable { mutableStateOf("") }
|
||||||
|
var domainError by remember { mutableStateOf(false) }
|
||||||
|
var showAddList by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var showUpdates by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var interval by remember { mutableStateOf(prefs.updateInterval) }
|
||||||
|
var wifiOnly by remember { mutableStateOf(prefs.updateWifiOnly) }
|
||||||
|
|
||||||
|
val term = search.trim()
|
||||||
|
fun matches(vararg texts: String) = term.isEmpty() || texts.any { it.contains(term, ignoreCase = true) }
|
||||||
|
|
||||||
|
val presetUrls = remember { Presets.map { it.url }.toSet() }
|
||||||
|
val ownLists = lists.filter { it.url !in presetUrls }
|
||||||
|
val shownDomains = if (term.isEmpty()) custom else custom.filter { it.contains(term, ignoreCase = true) }
|
||||||
|
|
||||||
fun addDomain() {
|
fun addDomain() {
|
||||||
val input = domainInput
|
val input = domainInput
|
||||||
if (input.isBlank()) return
|
if (input.isBlank()) return
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val ok = withContext(Dispatchers.IO) { Blocklist.addCustom(context, input) }
|
val result = withContext(Dispatchers.IO) { tryEdit { Blocklist.addCustom(context, input) } }
|
||||||
|
result.onSuccess { ok ->
|
||||||
domainError = !ok
|
domainError = !ok
|
||||||
if (ok) domainInput = ""
|
if (ok) domainInput = ""
|
||||||
|
}.onFailure { showEditError(context, it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addList() {
|
LazyColumn(
|
||||||
val url = urlInput.trim()
|
modifier = modifier,
|
||||||
if (url.isNotEmpty() && Blocklist.download(context, url)) urlInput = ""
|
contentPadding = PaddingValues(start = 20.dp, end = 20.dp, bottom = bottomPadding),
|
||||||
}
|
|
||||||
|
|
||||||
Column(
|
|
||||||
modifier = modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.verticalScroll(rememberScrollState())
|
|
||||||
.padding(16.dp),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
|
||||||
) {
|
) {
|
||||||
Card(Modifier.fillMaxWidth()) {
|
item(key = "header") {
|
||||||
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
PageHeader(
|
||||||
IconBadge(
|
title = stringResource(R.string.blocklist_title),
|
||||||
R.drawable.ic_tab_block,
|
onBack = onBack,
|
||||||
tint = if (enabled) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.outline,
|
action = {
|
||||||
size = 52.dp,
|
AppSwitch(checked = enabled, onCheckedChange = { Blocklist.setEnabled(context, it) })
|
||||||
)
|
|
||||||
Spacer(Modifier.width(16.dp))
|
|
||||||
Column(Modifier.weight(1f)) {
|
|
||||||
Text(stringResource(R.string.bl_title), style = MaterialTheme.typography.titleMedium)
|
|
||||||
Text(
|
|
||||||
formatCount(total.toLong()),
|
|
||||||
style = MaterialTheme.typography.headlineSmall,
|
|
||||||
fontWeight = FontWeight.SemiBold,
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.bl_total_label),
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Switch(checked = enabled, onCheckedChange = { Blocklist.setEnabled(context, it) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AnimatedVisibility(visible = showNote, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
HintCard(
|
|
||||||
stringResource(R.string.bl_note),
|
|
||||||
icon = R.drawable.ic_tab_info,
|
|
||||||
onDismiss = {
|
|
||||||
showNote = false
|
|
||||||
prefs.dismissHint(HINT_BLOCKLIST)
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
SectionHeader(stringResource(R.string.bl_my), icon = R.drawable.ic_tab_block)
|
item(key = "search") {
|
||||||
|
SearchField(
|
||||||
|
value = search,
|
||||||
|
onValueChange = { search = it },
|
||||||
|
placeholder = stringResource(R.string.bl_search),
|
||||||
|
modifier = Modifier.padding(top = 4.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
Card(Modifier.fillMaxWidth()) {
|
item(key = "updates") {
|
||||||
Column(
|
UpdatesRow(
|
||||||
Modifier
|
interval = interval,
|
||||||
.animateContentSize(Motion.size)
|
wifiOnly = wifiOnly,
|
||||||
.padding(vertical = 8.dp)
|
onClick = { showUpdates = true },
|
||||||
|
modifier = Modifier.padding(top = 12.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
item(key = "error") {
|
||||||
|
AnimatedVisibility(visible = error != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
|
Box(Modifier.padding(top = 12.dp)) {
|
||||||
|
HintCard(
|
||||||
|
stringResource(R.string.bl_download_failed, lastError[0]),
|
||||||
|
icon = R.drawable.ic_alert,
|
||||||
|
tint = Palette.Blocked,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
items(Presets.filter { matches(it.name) }, key = { "preset:${it.url}" }) { preset ->
|
||||||
|
val list = lists.firstOrNull { it.url == preset.url }
|
||||||
|
val downloading = busy == preset.url || (busy == Blocklist.ALL_LISTS && list?.enabled == true)
|
||||||
|
BlocklistCard(
|
||||||
|
title = preset.name,
|
||||||
|
description = stringResource(preset.description),
|
||||||
|
source = "hagezi",
|
||||||
|
sourceUrl = HAGEZI_HOME,
|
||||||
|
info = listInfo(list, downloading),
|
||||||
|
checked = list?.enabled == true || busy == preset.url,
|
||||||
|
// A list that is not downloaded yet waits for a running download to finish
|
||||||
|
switchEnabled = list != null || busy == null,
|
||||||
|
progress = downloading,
|
||||||
|
onCheckedChange = { on ->
|
||||||
|
if (list == null) {
|
||||||
|
if (on) Blocklist.download(context, preset.url)
|
||||||
|
} else {
|
||||||
|
scope.editBlocklist(context) { Blocklist.setListEnabled(context, preset.url, on) }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier
|
||||||
|
.animateItem()
|
||||||
|
.padding(top = 12.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
items(ownLists.filter { matches(it.url) }, key = { "list:${it.url}" }) { list ->
|
||||||
|
val uri = remember(list.url) { Uri.parse(list.url) }
|
||||||
|
val downloading = busy == list.url || (busy == Blocklist.ALL_LISTS && list.enabled)
|
||||||
|
BlocklistCard(
|
||||||
|
title = uri.lastPathSegment ?: uri.host ?: list.url,
|
||||||
|
description = stringResource(R.string.list_added_by_you),
|
||||||
|
source = uri.host ?: "",
|
||||||
|
sourceUrl = null,
|
||||||
|
info = listInfo(list, downloading),
|
||||||
|
checked = list.enabled,
|
||||||
|
switchEnabled = true,
|
||||||
|
progress = downloading,
|
||||||
|
onCheckedChange = { on -> scope.editBlocklist(context) { Blocklist.setListEnabled(context, list.url, on) } },
|
||||||
|
onDelete = if (busy == null) {
|
||||||
|
{ scope.editBlocklist(context) { Blocklist.removeList(context, list.url) } }
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
},
|
||||||
|
modifier = Modifier
|
||||||
|
.animateItem()
|
||||||
|
.padding(top = 12.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
item(key = "domains") {
|
||||||
|
MyDomainsHeader(
|
||||||
|
count = custom.size,
|
||||||
|
open = domainsOpen,
|
||||||
|
onToggle = { domainsOpen = !domainsOpen },
|
||||||
|
shape = if (domainsOpen) TopShape else CardShape,
|
||||||
|
modifier = Modifier.padding(top = 12.dp),
|
||||||
) {
|
) {
|
||||||
|
// Input to add a domain; the accent button matches the rest of the app
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 12.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
@@ -155,207 +240,446 @@ fun BlocklistScreen(modifier: Modifier = Modifier) {
|
|||||||
placeholder = { Text(stringResource(R.string.bl_domain_hint), maxLines = 1) },
|
placeholder = { Text(stringResource(R.string.bl_domain_hint), maxLines = 1) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
isError = domainError,
|
isError = domainError,
|
||||||
|
shape = RoundedCornerShape(14.dp),
|
||||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
||||||
keyboardActions = KeyboardActions(onDone = { addDomain() }),
|
keyboardActions = KeyboardActions(onDone = { addDomain() }),
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
FilledTonalButton(onClick = ::addDomain, enabled = domainInput.isNotBlank()) {
|
Button(
|
||||||
Icon(painterResource(R.drawable.ic_add_domain), contentDescription = null, modifier = Modifier.size(18.dp))
|
onClick = ::addDomain,
|
||||||
|
enabled = domainInput.isNotBlank(),
|
||||||
|
shape = RoundedCornerShape(14.dp),
|
||||||
|
contentPadding = PaddingValues(horizontal = 18.dp),
|
||||||
|
modifier = Modifier.height(56.dp),
|
||||||
|
) {
|
||||||
|
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
||||||
Spacer(Modifier.width(6.dp))
|
Spacer(Modifier.width(6.dp))
|
||||||
Text(stringResource(R.string.add))
|
Text(stringResource(R.string.add), fontWeight = FontWeight.Bold)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
AnimatedVisibility(visible = domainError, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
AnimatedVisibility(visible = domainError, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.bl_invalid),
|
stringResource(R.string.bl_invalid),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
color = Palette.Blocked,
|
||||||
color = MaterialTheme.colorScheme.error,
|
fontSize = 12.sp,
|
||||||
modifier = Modifier.padding(horizontal = 16.dp),
|
modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (custom.isEmpty()) {
|
if (custom.isEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.bl_empty_custom),
|
stringResource(R.string.bl_empty_custom),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
color = Palette.Fg3,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
fontSize = 13.sp,
|
||||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
custom.forEach { domain ->
|
}
|
||||||
InsetDivider(16)
|
}
|
||||||
|
|
||||||
|
// Own domains are lazy rows, so hundreds of them are not all composed at once.
|
||||||
|
// Together with the header above they look like one card.
|
||||||
|
if (domainsOpen) {
|
||||||
|
itemsIndexed(shownDomains, key = { _, domain -> "domain:$domain" }, contentType = { _, _ -> "domain" }) { index, domain ->
|
||||||
|
val last = index == shownDomains.lastIndex
|
||||||
|
DomainRow(
|
||||||
|
domain = domain,
|
||||||
|
shape = if (last) BottomShape else RectangleShape,
|
||||||
|
onDelete = { scope.editBlocklist(context) { Blocklist.removeCustom(context, domain) } },
|
||||||
|
modifier = Modifier.animateItem(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (shownDomains.isEmpty()) {
|
||||||
|
item(key = "domains-end") {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(8.dp)
|
||||||
|
.clip(BottomShape)
|
||||||
|
.background(Palette.Card)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item(key = "add") {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(top = 24.dp),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Button(
|
||||||
|
onClick = { showAddList = true },
|
||||||
|
enabled = busy == null,
|
||||||
|
shape = RoundedCornerShape(24.dp),
|
||||||
|
contentPadding = PaddingValues(start = 16.dp, end = 22.dp),
|
||||||
|
modifier = Modifier.height(48.dp),
|
||||||
|
) {
|
||||||
|
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(20.dp))
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text(stringResource(R.string.bl_add_list), fontWeight = FontWeight.ExtraBold)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showAddList) {
|
||||||
|
AddListDialog(
|
||||||
|
busy = busy != null,
|
||||||
|
onAdd = { url -> Blocklist.download(context, url) },
|
||||||
|
onDismiss = { showAddList = false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showUpdates) {
|
||||||
|
UpdatesDialog(
|
||||||
|
interval = interval,
|
||||||
|
wifiOnly = wifiOnly,
|
||||||
|
canUpdateNow = busy == null && lists.any { it.enabled },
|
||||||
|
onInterval = {
|
||||||
|
interval = it
|
||||||
|
prefs.updateInterval = it
|
||||||
|
AutoUpdate.apply(context)
|
||||||
|
},
|
||||||
|
onWifiOnly = {
|
||||||
|
wifiOnly = it
|
||||||
|
prefs.updateWifiOnly = it
|
||||||
|
AutoUpdate.apply(context)
|
||||||
|
},
|
||||||
|
onUpdateNow = {
|
||||||
|
Blocklist.updateAll(context)
|
||||||
|
showUpdates = false
|
||||||
|
},
|
||||||
|
onDismiss = { showUpdates = false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun listInfo(list: RemoteList?, downloading: Boolean): String = when {
|
||||||
|
downloading -> stringResource(R.string.bl_updating)
|
||||||
|
list == null -> stringResource(R.string.list_not_downloaded)
|
||||||
|
else -> stringResource(
|
||||||
|
R.string.bl_list_info,
|
||||||
|
formatCount(list.count.toLong()),
|
||||||
|
DateUtils.getRelativeTimeSpanString(list.updated, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun UpdatesRow(interval: UpdateInterval, wifiOnly: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier) {
|
||||||
|
val shape = RoundedCornerShape(16.dp)
|
||||||
|
val label = stringResource(intervalLabel(interval))
|
||||||
|
val wifi = stringResource(R.string.auto_wifi)
|
||||||
|
val summary = if (interval != UpdateInterval.OFF && wifiOnly) "$label · $wifi" else label
|
||||||
|
Row(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clip(shape)
|
||||||
|
.border(1.dp, Palette.Line, shape)
|
||||||
|
.clickable(onClick = onClick)
|
||||||
|
.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Icon(painterResource(R.drawable.ic_refresh), contentDescription = null, tint = Palette.Accent, modifier = Modifier.size(20.dp))
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(stringResource(R.string.auto_update), color = Palette.Fg, fontSize = 14.sp, fontWeight = FontWeight.Bold)
|
||||||
|
Text(summary, color = Palette.Fg2, fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
Chevron()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@StringRes
|
||||||
|
private fun intervalLabel(interval: UpdateInterval): Int = when (interval) {
|
||||||
|
UpdateInterval.OFF -> R.string.auto_off
|
||||||
|
UpdateInterval.DAILY -> R.string.auto_daily
|
||||||
|
UpdateInterval.WEEKLY -> R.string.auto_weekly
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun BlocklistCard(
|
||||||
|
title: String,
|
||||||
|
description: String,
|
||||||
|
source: String,
|
||||||
|
sourceUrl: String?,
|
||||||
|
info: String,
|
||||||
|
checked: Boolean,
|
||||||
|
switchEnabled: Boolean,
|
||||||
|
progress: Boolean,
|
||||||
|
onCheckedChange: (Boolean) -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
onDelete: (() -> Unit)? = null,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
Column(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.appCard()
|
||||||
|
.padding(start = 16.dp, end = 10.dp, top = 6.dp, bottom = 14.dp),
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
color = Palette.Fg,
|
||||||
|
fontSize = 15.sp,
|
||||||
|
fontWeight = FontWeight.ExtraBold,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
if (onDelete != null) {
|
||||||
|
IconButton(onClick = onDelete) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_delete),
|
||||||
|
contentDescription = stringResource(R.string.delete),
|
||||||
|
tint = Palette.Fg3,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AppSwitch(checked = checked, onCheckedChange = onCheckedChange, enabled = switchEnabled)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
description,
|
||||||
|
color = Palette.Fg2,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
lineHeight = 17.sp,
|
||||||
|
maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.padding(end = 6.dp),
|
||||||
|
)
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(top = 6.dp, end = 6.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
if (source.isNotEmpty()) {
|
||||||
|
Text(
|
||||||
|
source,
|
||||||
|
color = Palette.Accent,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
maxLines = 1,
|
||||||
|
modifier = if (sourceUrl != null) Modifier.clickable { openUrl(context, sourceUrl) } else Modifier,
|
||||||
|
)
|
||||||
|
Text(" · ", color = Palette.Fg3, fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
Text(info, color = Palette.Fg3, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
AnimatedVisibility(visible = progress, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
|
LinearProgressIndicator(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(top = 10.dp, end = 6.dp),
|
||||||
|
color = Palette.Accent,
|
||||||
|
trackColor = Palette.Track,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun MyDomainsHeader(
|
||||||
|
count: Int,
|
||||||
|
open: Boolean,
|
||||||
|
onToggle: () -> Unit,
|
||||||
|
shape: Shape,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
content: @Composable () -> Unit,
|
||||||
|
) {
|
||||||
|
val chevron by animateFloatAsState(if (open) 180f else 0f, Motion.rotation, label = "chevron")
|
||||||
|
Column(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clip(shape)
|
||||||
|
.background(Palette.Card),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable(onClick = onToggle)
|
||||||
|
.padding(start = 16.dp, end = 14.dp, top = 14.dp, bottom = 14.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(stringResource(R.string.bl_my), color = Palette.Fg, fontSize = 15.sp, fontWeight = FontWeight.ExtraBold)
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.my_domains_desc),
|
||||||
|
color = Palette.Fg2,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
lineHeight = 17.sp,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
Text(
|
||||||
|
formatCount(count.toLong()),
|
||||||
|
color = Palette.Accent,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
modifier = Modifier
|
||||||
|
.clip(RoundedCornerShape(10.dp))
|
||||||
|
.background(Palette.AccentSoft)
|
||||||
|
.padding(horizontal = 8.dp, vertical = 3.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_expand),
|
||||||
|
contentDescription = null,
|
||||||
|
tint = Palette.Fg3,
|
||||||
|
modifier = Modifier
|
||||||
|
.size(20.dp)
|
||||||
|
.graphicsLayer { rotationZ = chevron },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
AnimatedVisibility(visible = open, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
|
Column { content() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun DomainRow(domain: String, shape: Shape, onDelete: () -> Unit, modifier: Modifier = Modifier) {
|
||||||
|
Column(
|
||||||
|
modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clip(shape)
|
||||||
|
.background(Palette.Card)
|
||||||
|
) {
|
||||||
|
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp), color = Palette.Line)
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.padding(start = 16.dp, end = 4.dp),
|
modifier = Modifier.padding(start = 16.dp, end = 4.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Text(domain, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
|
||||||
IconButton(onClick = { scope.launch(Dispatchers.IO) { Blocklist.removeCustom(context, domain) } }) {
|
|
||||||
Icon(painterResource(R.drawable.ic_delete), stringResource(R.string.delete), Modifier.size(20.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SectionHeader(
|
|
||||||
stringResource(R.string.bl_lists),
|
|
||||||
icon = R.drawable.ic_list,
|
|
||||||
action = {
|
|
||||||
TextButton(
|
|
||||||
onClick = { Blocklist.updateAll(context) },
|
|
||||||
enabled = lists.isNotEmpty() && busy == null,
|
|
||||||
) {
|
|
||||||
Icon(painterResource(R.drawable.ic_refresh), contentDescription = null, modifier = Modifier.size(18.dp))
|
|
||||||
Spacer(Modifier.width(6.dp))
|
|
||||||
Text(stringResource(if (busy == Blocklist.ALL_LISTS) R.string.bl_updating else R.string.bl_update_all))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
Card(Modifier.fillMaxWidth()) {
|
|
||||||
Column(
|
|
||||||
Modifier
|
|
||||||
.animateContentSize(Motion.size)
|
|
||||||
.padding(vertical = 8.dp)
|
|
||||||
) {
|
|
||||||
lists.forEachIndexed { index, list ->
|
|
||||||
if (index > 0) InsetDivider(68)
|
|
||||||
ListRow(
|
|
||||||
list = list,
|
|
||||||
updating = busy == list.url || busy == Blocklist.ALL_LISTS,
|
|
||||||
actionsEnabled = busy == null,
|
|
||||||
onRefresh = { Blocklist.download(context, list.url) },
|
|
||||||
onDelete = { scope.launch(Dispatchers.IO) { Blocklist.removeList(context, list.url) } },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (lists.isNotEmpty()) InsetDivider(16)
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
OutlinedTextField(
|
|
||||||
value = urlInput,
|
|
||||||
onValueChange = { urlInput = it },
|
|
||||||
placeholder = { Text(stringResource(R.string.bl_list_url), maxLines = 1) },
|
|
||||||
singleLine = true,
|
|
||||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
|
||||||
keyboardActions = KeyboardActions(onDone = { if (busy == null) addList() }),
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
)
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
FilledTonalButton(
|
|
||||||
onClick = ::addList,
|
|
||||||
enabled = urlInput.isNotBlank() && busy == null,
|
|
||||||
) {
|
|
||||||
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
|
||||||
Spacer(Modifier.width(6.dp))
|
|
||||||
Text(stringResource(R.string.add))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A new list being added has no row yet, so its progress shows under the input
|
|
||||||
val addingNew = busy != null && busy != Blocklist.ALL_LISTS && lists.none { it.url == busy }
|
|
||||||
AnimatedVisibility(visible = addingNew, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
LinearProgressIndicator(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val missingPresets = Presets.filter { (_, url) -> lists.none { it.url == url } }
|
|
||||||
AnimatedVisibility(visible = missingPresets.isNotEmpty(), enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
|
||||||
SectionHeader(stringResource(R.string.bl_presets))
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.horizontalScroll(rememberScrollState()),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
|
||||||
) {
|
|
||||||
missingPresets.forEach { (name, url) ->
|
|
||||||
AssistChip(
|
|
||||||
onClick = { Blocklist.download(context, url) },
|
|
||||||
enabled = busy == null,
|
|
||||||
leadingIcon = {
|
|
||||||
Icon(painterResource(R.drawable.ic_add), contentDescription = null, modifier = Modifier.size(18.dp))
|
|
||||||
},
|
|
||||||
label = { Text(if (busy == url) stringResource(R.string.bl_updating) else name) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AnimatedVisibility(visible = error != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
HintCard(
|
|
||||||
stringResource(R.string.bl_download_failed, lastError[0]),
|
|
||||||
icon = R.drawable.ic_alert,
|
|
||||||
tint = MaterialTheme.colorScheme.error,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun InsetDivider(start: Int) {
|
|
||||||
HorizontalDivider(
|
|
||||||
modifier = Modifier.padding(start = start.dp),
|
|
||||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun ListRow(
|
|
||||||
list: RemoteList,
|
|
||||||
updating: Boolean,
|
|
||||||
actionsEnabled: Boolean,
|
|
||||||
onRefresh: () -> Unit,
|
|
||||||
onDelete: () -> Unit,
|
|
||||||
) {
|
|
||||||
val uri = remember(list.url) { Uri.parse(list.url) }
|
|
||||||
val title = uri.lastPathSegment ?: list.url
|
|
||||||
val updated = remember(list.updated) {
|
|
||||||
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date(list.updated))
|
|
||||||
}
|
|
||||||
|
|
||||||
Column {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(start = 16.dp, end = 4.dp, top = 8.dp, bottom = 8.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
IconBadge(R.drawable.ic_list, size = 40.dp)
|
|
||||||
Spacer(Modifier.width(12.dp))
|
|
||||||
Column(Modifier.weight(1f)) {
|
|
||||||
Text(title, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
|
||||||
Text(
|
Text(
|
||||||
uri.host ?: "",
|
domain,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
color = Palette.Fg,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
fontSize = 14.sp,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
Text(
|
IconButton(onClick = onDelete) {
|
||||||
if (updating) stringResource(R.string.bl_updating)
|
Icon(
|
||||||
else stringResource(R.string.bl_list_info, formatCount(list.count.toLong()), updated),
|
painterResource(R.drawable.ic_delete),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
contentDescription = stringResource(R.string.delete),
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
tint = Palette.Fg3,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
IconButton(onClick = onRefresh, enabled = actionsEnabled) {
|
|
||||||
Icon(painterResource(R.drawable.ic_refresh), stringResource(R.string.bl_update_all), Modifier.size(20.dp))
|
|
||||||
}
|
|
||||||
IconButton(onClick = onDelete, enabled = actionsEnabled) {
|
|
||||||
Icon(painterResource(R.drawable.ic_delete), stringResource(R.string.delete), Modifier.size(20.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
AnimatedVisibility(visible = updating, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
LinearProgressIndicator(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(start = 68.dp, end = 16.dp, bottom = 8.dp),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private const val HINT_BLOCKLIST = "blocklist"
|
@Composable
|
||||||
|
private fun AddListDialog(busy: Boolean, onAdd: (String) -> Boolean, onDismiss: () -> Unit) {
|
||||||
|
var url by rememberSaveable { mutableStateOf("") }
|
||||||
|
fun submit() {
|
||||||
|
if (url.isNotBlank() && onAdd(url.trim())) onDismiss()
|
||||||
|
}
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(stringResource(R.string.bl_add_list)) },
|
||||||
|
text = {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
Text(stringResource(R.string.bl_note), color = Palette.Fg2, fontSize = 13.sp)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = url,
|
||||||
|
onValueChange = { url = it },
|
||||||
|
label = { Text(stringResource(R.string.bl_list_url)) },
|
||||||
|
placeholder = { Text("https://", maxLines = 1) },
|
||||||
|
singleLine = true,
|
||||||
|
shape = RoundedCornerShape(14.dp),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
||||||
|
keyboardActions = KeyboardActions(onDone = { submit() }),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
Button(onClick = ::submit, enabled = url.isNotBlank() && !busy, shape = RoundedCornerShape(14.dp)) {
|
||||||
|
Text(stringResource(R.string.add), fontWeight = FontWeight.Bold)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
|
||||||
|
},
|
||||||
|
containerColor = Palette.CardHigh,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun UpdatesDialog(
|
||||||
|
interval: UpdateInterval,
|
||||||
|
wifiOnly: Boolean,
|
||||||
|
canUpdateNow: Boolean,
|
||||||
|
onInterval: (UpdateInterval) -> Unit,
|
||||||
|
onWifiOnly: (Boolean) -> Unit,
|
||||||
|
onUpdateNow: () -> Unit,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(stringResource(R.string.auto_update)) },
|
||||||
|
text = {
|
||||||
|
Column {
|
||||||
|
UpdateInterval.entries.forEach { option ->
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clip(RoundedCornerShape(12.dp))
|
||||||
|
.selectable(selected = option == interval, onClick = { onInterval(option) }, role = Role.RadioButton)
|
||||||
|
.padding(vertical = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
RadioButton(selected = option == interval, onClick = null)
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
Text(stringResource(intervalLabel(option)), color = Palette.Fg, fontSize = 15.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp), color = Palette.Line)
|
||||||
|
val wifiEnabled = interval != UpdateInterval.OFF
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.toggleable(value = wifiOnly, enabled = wifiEnabled, role = Role.Switch, onValueChange = onWifiOnly)
|
||||||
|
.graphicsLayer { alpha = if (wifiEnabled) 1f else 0.45f }
|
||||||
|
.padding(vertical = 6.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(stringResource(R.string.auto_wifi), color = Palette.Fg, fontSize = 15.sp)
|
||||||
|
Text(stringResource(R.string.auto_wifi_desc), color = Palette.Fg3, fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
AppSwitch(checked = wifiOnly, onCheckedChange = null, enabled = wifiEnabled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = onDismiss) { Text(stringResource(R.string.done)) }
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = onUpdateNow, enabled = canUpdateNow) { Text(stringResource(R.string.auto_update_now)) }
|
||||||
|
},
|
||||||
|
containerColor = Palette.CardHigh,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Blocklist edits write to storage, which can fail (a full disk, for one)
|
||||||
|
internal inline fun <T> tryEdit(action: () -> T): Result<T> =
|
||||||
|
try {
|
||||||
|
Result.success(action())
|
||||||
|
} catch (e: IOException) {
|
||||||
|
Result.failure(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun CoroutineScope.editBlocklist(context: Context, action: () -> Unit) = launch {
|
||||||
|
withContext(Dispatchers.IO) { tryEdit(action) }.onFailure { showEditError(context, it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun showEditError(context: Context, error: Throwable) {
|
||||||
|
val reason = error.message ?: error.javaClass.simpleName
|
||||||
|
Toast.makeText(context, context.getString(R.string.test_fail, reason), Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
// The position of each company is saved in StatsStore: add new ones at the end only
|
||||||
|
enum class Company(val label: String) {
|
||||||
|
GOOGLE("Google"),
|
||||||
|
APPLE("Apple"),
|
||||||
|
META("Meta"),
|
||||||
|
AMAZON("Amazon"),
|
||||||
|
MICROSOFT("Microsoft"),
|
||||||
|
BYTEDANCE("ByteDance"),
|
||||||
|
X("X"),
|
||||||
|
YANDEX("Yandex"),
|
||||||
|
SAMSUNG("Samsung"),
|
||||||
|
XIAOMI("Xiaomi"),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tells which big company a domain belongs to, for the Company dominance card.
|
||||||
|
// Matches the domain and every parent of it against a small built-in table.
|
||||||
|
object Companies {
|
||||||
|
private val bySuffix = HashMap<String, Company>().apply {
|
||||||
|
fun add(company: Company, vararg domains: String) = domains.forEach { put(it, company) }
|
||||||
|
|
||||||
|
add(
|
||||||
|
Company.GOOGLE,
|
||||||
|
"google.com", "googleapis.com", "gstatic.com", "googleusercontent.com", "googlevideo.com",
|
||||||
|
"youtube.com", "youtu.be", "ytimg.com", "ggpht.com", "gvt1.com", "gvt2.com", "1e100.net",
|
||||||
|
"android.com", "googlesyndication.com", "googleadservices.com", "doubleclick.net",
|
||||||
|
"google-analytics.com", "googletagmanager.com", "googletagservices.com", "app-measurement.com",
|
||||||
|
"firebaseio.com", "firebase.com", "crashlytics.com", "withgoogle.com", "googlemail.com",
|
||||||
|
"gmail.com", "blogspot.com", "admob.com", "goo.gl",
|
||||||
|
)
|
||||||
|
add(
|
||||||
|
Company.APPLE,
|
||||||
|
"apple.com", "icloud.com", "icloud-content.com", "mzstatic.com", "apple-dns.net", "aaplimg.com",
|
||||||
|
"cdn-apple.com", "itunes.com", "me.com", "apple.news", "apple-cloudkit.com", "appleid.com",
|
||||||
|
)
|
||||||
|
add(
|
||||||
|
Company.META,
|
||||||
|
"facebook.com", "facebook.net", "fbcdn.net", "fbsbx.com", "fb.com", "instagram.com",
|
||||||
|
"cdninstagram.com", "whatsapp.com", "whatsapp.net", "messenger.com", "meta.com", "oculus.com",
|
||||||
|
"threads.net", "graph.facebook.com",
|
||||||
|
)
|
||||||
|
add(
|
||||||
|
Company.AMAZON,
|
||||||
|
"amazon.com", "amazonaws.com", "media-amazon.com", "ssl-images-amazon.com", "cloudfront.net",
|
||||||
|
"amazon-adsystem.com", "a2z.com", "primevideo.com", "aiv-cdn.net", "twitch.tv", "ttvnw.net",
|
||||||
|
"amazon.de", "amazon.co.uk", "amazontrust.com",
|
||||||
|
)
|
||||||
|
add(
|
||||||
|
Company.MICROSOFT,
|
||||||
|
"microsoft.com", "live.com", "outlook.com", "office.com", "office.net", "office365.com", "msn.com",
|
||||||
|
"bing.com", "windows.com", "windows.net", "windowsupdate.com", "azure.com", "azureedge.net",
|
||||||
|
"skype.com", "xbox.com", "xboxlive.com", "linkedin.com", "licdn.com", "github.com",
|
||||||
|
"githubusercontent.com", "msftncsi.com", "msedge.net", "microsoftonline.com", "sharepoint.com",
|
||||||
|
)
|
||||||
|
add(
|
||||||
|
Company.BYTEDANCE,
|
||||||
|
"tiktok.com", "tiktokv.com", "tiktokcdn.com", "tiktokcdn-us.com", "byteoversea.com",
|
||||||
|
"ibytedtos.com", "bytedance.com", "capcut.com", "byteimg.com",
|
||||||
|
)
|
||||||
|
add(Company.X, "twitter.com", "x.com", "twimg.com", "t.co")
|
||||||
|
add(Company.YANDEX, "yandex.ru", "yandex.net", "yandex.com", "ya.ru", "yastatic.net", "yandex.by", "yandex.kz")
|
||||||
|
add(Company.SAMSUNG, "samsung.com", "samsungapps.com", "samsungcloud.com", "samsungqbe.com", "samsungosp.com")
|
||||||
|
add(Company.XIAOMI, "xiaomi.com", "xiaomi.net", "mi.com", "miui.com", "mi-img.com")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun of(name: String): Company? {
|
||||||
|
var domain = name.lowercase().trimEnd('.')
|
||||||
|
while (domain.isNotEmpty()) {
|
||||||
|
bySuffix[domain]?.let { return it }
|
||||||
|
// Google's country sites: google.de, google.co.uk, google.com.br
|
||||||
|
if (domain.startsWith("google.") && domain.length - "google.".length <= 6) return Company.GOOGLE
|
||||||
|
val dot = domain.indexOf('.')
|
||||||
|
if (dot < 0) return null
|
||||||
|
domain = domain.substring(dot + 1)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,8 @@ package cc.skysparkle.sparkledns
|
|||||||
import android.app.Application
|
import android.app.Application
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.os.Process
|
||||||
|
import android.os.StrictMode
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.PrintWriter
|
import java.io.PrintWriter
|
||||||
import java.io.StringWriter
|
import java.io.StringWriter
|
||||||
@@ -10,8 +12,33 @@ import java.io.StringWriter
|
|||||||
class SparkleApp : Application() {
|
class SparkleApp : Application() {
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
|
if (BuildConfig.DEBUG) enableStrictMode()
|
||||||
CrashLog.install(this)
|
CrashLog.install(this)
|
||||||
Thread({ runCatching { Blocklist.reload(this) } }, "blocklist-load").start()
|
Thread({
|
||||||
|
// Reads what the first screen needs before it asks, so its first frame does not wait on storage
|
||||||
|
Prefs(this).providerId
|
||||||
|
CrashLog.preload(this)
|
||||||
|
StatsStore.init(this)
|
||||||
|
// Older versions cached a server list downloaded from the repository
|
||||||
|
File(filesDir, "servers.txt").delete()
|
||||||
|
AutoUpdate.apply(this)
|
||||||
|
// Lists can hold millions of entries; loading them should not take CPU from the first frames
|
||||||
|
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
|
||||||
|
runCatching { Blocklist.reload(this) }
|
||||||
|
}, "startup-load").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
// The VPN keeps the process running long after the screens are gone; decoded app icons
|
||||||
|
// (up to 10 MB) can be rendered again the next time the Apps tab opens
|
||||||
|
override fun onTrimMemory(level: Int) {
|
||||||
|
super.onTrimMemory(level)
|
||||||
|
if (level >= TRIM_MEMORY_UI_HIDDEN) clearAppIconCache()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug builds only: logs disk and network access on the main thread, leaked closeables and the like
|
||||||
|
private fun enableStrictMode() {
|
||||||
|
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build())
|
||||||
|
StrictMode.setVmPolicy(StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,10 +62,24 @@ object CrashLog {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun read(context: Context): String? =
|
@Volatile
|
||||||
File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText()
|
private var preloaded = false
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var report: String? = null
|
||||||
|
|
||||||
|
fun preload(context: Context) {
|
||||||
|
report = load(context)
|
||||||
|
preloaded = true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun read(context: Context): String? = if (preloaded) report else load(context)
|
||||||
|
|
||||||
fun clear(context: Context) {
|
fun clear(context: Context) {
|
||||||
|
report = null
|
||||||
File(context.filesDir, FILE_NAME).delete()
|
File(context.filesDir, FILE_NAME).delete()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun load(context: Context): String? =
|
||||||
|
runCatching { File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText() }.getOrNull()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ package cc.skysparkle.sparkledns
|
|||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
|
|
||||||
// TTL-aware LRU cache of DNS responses, keyed by the question section
|
// TTL-aware LRU cache of DNS responses, keyed by the question section
|
||||||
class DnsCache(private val maxEntries: Int = 2000) {
|
class DnsCache(
|
||||||
|
private val maxEntries: Int = 2000,
|
||||||
|
private val clock: () -> Long = SystemClock::elapsedRealtime,
|
||||||
|
) {
|
||||||
|
|
||||||
private class Entry(
|
private class Entry(
|
||||||
val response: ByteArray,
|
val response: ByteArray,
|
||||||
@@ -19,7 +22,7 @@ class DnsCache(private val maxEntries: Int = 2000) {
|
|||||||
|
|
||||||
fun get(query: ByteArray): ByteArray? {
|
fun get(query: ByteArray): ByteArray? {
|
||||||
val key = keyOf(query) ?: return null
|
val key = keyOf(query) ?: return null
|
||||||
val now = SystemClock.elapsedRealtime()
|
val now = clock()
|
||||||
val entry = synchronized(map) {
|
val entry = synchronized(map) {
|
||||||
val e = map[key] ?: return null
|
val e = map[key] ?: return null
|
||||||
if (now >= e.expiresAt) {
|
if (now >= e.expiresAt) {
|
||||||
@@ -47,7 +50,7 @@ class DnsCache(private val maxEntries: Int = 2000) {
|
|||||||
val ttl = minOf(minTtl, MAX_TTL)
|
val ttl = minOf(minTtl, MAX_TTL)
|
||||||
if (ttl <= 0) return
|
if (ttl <= 0) return
|
||||||
|
|
||||||
val now = SystemClock.elapsedRealtime()
|
val now = clock()
|
||||||
val entry = Entry(response.copyOf(), records.first, records.second, now, now + ttl * 1000L)
|
val entry = Entry(response.copyOf(), records.first, records.second, now, now + ttl * 1000L)
|
||||||
synchronized(map) { map[key] = entry }
|
synchronized(map) { map[key] = entry }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,9 +11,11 @@ import android.service.quicksettings.Tile
|
|||||||
import android.service.quicksettings.TileService
|
import android.service.quicksettings.TileService
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.MainScope
|
import kotlinx.coroutines.MainScope
|
||||||
import kotlinx.coroutines.cancel
|
import kotlinx.coroutines.cancel
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
|
|
||||||
class DnsTileService : TileService() {
|
class DnsTileService : TileService() {
|
||||||
@@ -32,7 +34,12 @@ class DnsTileService : TileService() {
|
|||||||
override fun onStartListening() {
|
override fun onStartListening() {
|
||||||
listening?.cancel()
|
listening?.cancel()
|
||||||
listening = MainScope().also { scope ->
|
listening = MainScope().also { scope ->
|
||||||
scope.launch { DohVpnService.active.collect { updateTile() } }
|
scope.launch {
|
||||||
|
// The tile can start a fresh process: read settings from storage off the main thread,
|
||||||
|
// which also leaves them in memory for onClick
|
||||||
|
val prefs = withContext(Dispatchers.IO) { Prefs(applicationContext).also { it.providerId } }
|
||||||
|
DohVpnService.active.collect { updateTile(prefs) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,13 +68,13 @@ class DnsTileService : TileService() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun updateTile() {
|
private fun updateTile(prefs: Prefs) {
|
||||||
val tile = qsTile ?: return
|
val tile = qsTile ?: return
|
||||||
val active = DohVpnService.active.value
|
val active = DohVpnService.active.value
|
||||||
tile.state = if (active != null) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
|
tile.state = if (active != null) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
|
||||||
tile.label = getString(R.string.app_name)
|
tile.label = getString(R.string.app_name)
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
tile.subtitle = (active ?: Prefs(this).resolve()).displayName(this)
|
tile.subtitle = (active ?: prefs.resolve()).displayName(this)
|
||||||
}
|
}
|
||||||
tile.updateTile()
|
tile.updateTile()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.Network
|
||||||
import android.net.http.HttpEngine
|
import android.net.http.HttpEngine
|
||||||
import android.net.http.HttpException
|
import android.net.http.HttpException
|
||||||
import android.net.http.UploadDataProvider
|
import android.net.http.UploadDataProvider
|
||||||
@@ -10,10 +12,10 @@ import android.net.http.UrlResponseInfo
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.annotation.RequiresApi
|
import androidx.annotation.RequiresApi
|
||||||
|
import okhttp3.ConnectionPool
|
||||||
import okhttp3.Dns
|
import okhttp3.Dns
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||||
import okhttp3.MediaType.Companion.toMediaType
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
import okhttp3.OkHttpClient
|
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import java.io.ByteArrayOutputStream
|
import java.io.ByteArrayOutputStream
|
||||||
@@ -27,6 +29,7 @@ import java.util.concurrent.ExecutionException
|
|||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
import java.util.concurrent.TimeoutException
|
import java.util.concurrent.TimeoutException
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
private const val DNS_MESSAGE = "application/dns-message"
|
private const val DNS_MESSAGE = "application/dns-message"
|
||||||
private const val MAX_DNS_SIZE = 65535
|
private const val MAX_DNS_SIZE = 65535
|
||||||
@@ -36,17 +39,37 @@ private const val TAG = "SparkleDNS"
|
|||||||
// everything else and older devices use OkHttp with HTTP/2.
|
// everything else and older devices use OkHttp with HTTP/2.
|
||||||
class DohClient(context: Context, provider: DohProvider) {
|
class DohClient(context: Context, provider: DohProvider) {
|
||||||
|
|
||||||
private val transport: Transport = createTransport(context.applicationContext, provider)
|
private val appContext = context.applicationContext
|
||||||
|
|
||||||
val lastProtocol: String? get() = transport.lastProtocol
|
// Built on the first query, i.e. on a worker thread: setting up HttpEngine takes long enough
|
||||||
|
// to stall the main thread, where the VPN service creates this client
|
||||||
|
private val transport = lazy { createTransport(appContext, provider) }
|
||||||
|
private val closed = AtomicBoolean(false)
|
||||||
|
private val released = AtomicBoolean(false)
|
||||||
|
|
||||||
|
val lastProtocol: String? get() = if (transport.isInitialized()) transport.value.lastProtocol else null
|
||||||
|
|
||||||
fun query(message: ByteArray): ByteArray {
|
fun query(message: ByteArray): ByteArray {
|
||||||
val body = transport.query(message)
|
if (closed.get()) throw IOException("Client closed")
|
||||||
|
val active = transport.value
|
||||||
|
// shutdown() may have run while the transport was being built
|
||||||
|
if (closed.get()) {
|
||||||
|
release()
|
||||||
|
throw IOException("Client closed")
|
||||||
|
}
|
||||||
|
val body = active.query(message)
|
||||||
if (!DnsMessage.isResponse(body)) throw IOException("Invalid DNS response")
|
if (!DnsMessage.isResponse(body)) throw IOException("Invalid DNS response")
|
||||||
return body
|
return body
|
||||||
}
|
}
|
||||||
|
|
||||||
fun shutdown() = transport.shutdown()
|
fun shutdown() {
|
||||||
|
closed.set(true)
|
||||||
|
if (transport.isInitialized()) release()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun release() {
|
||||||
|
if (released.compareAndSet(false, true)) transport.value.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
private fun createTransport(context: Context, provider: DohProvider): Transport {
|
private fun createTransport(context: Context, provider: DohProvider): Transport {
|
||||||
if (provider.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
if (provider.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||||
@@ -56,7 +79,7 @@ class DohClient(context: Context, provider: DohProvider) {
|
|||||||
Log.w(TAG, "HttpEngine unavailable, falling back to HTTP/2", e)
|
Log.w(TAG, "HttpEngine unavailable, falling back to HTTP/2", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return OkHttpTransport(provider)
|
return OkHttpTransport(context, provider)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,17 +89,42 @@ private interface Transport {
|
|||||||
fun shutdown()
|
fun shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
private class OkHttpTransport(private val provider: DohProvider) : Transport {
|
private class OkHttpTransport(context: Context, private val provider: DohProvider) : Transport {
|
||||||
|
|
||||||
private val url by lazy { provider.url.toHttpUrl() }
|
private val url by lazy { provider.url.toHttpUrl() }
|
||||||
|
|
||||||
private val client = OkHttpClient.Builder()
|
// Its own connection pool, so stopping a session drops only DoH connections
|
||||||
|
private val pool = ConnectionPool()
|
||||||
|
|
||||||
|
private val client = Http.client.newBuilder()
|
||||||
|
.connectionPool(pool)
|
||||||
.dns(BootstrapDns(provider.bootstrap))
|
.dns(BootstrapDns(provider.bootstrap))
|
||||||
.connectTimeout(5, TimeUnit.SECONDS)
|
.connectTimeout(5, TimeUnit.SECONDS)
|
||||||
.readTimeout(5, TimeUnit.SECONDS)
|
.readTimeout(5, TimeUnit.SECONDS)
|
||||||
.callTimeout(8, TimeUnit.SECONDS)
|
.callTimeout(8, TimeUnit.SECONDS)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
|
// Pooled connections still belong to the previous network after a switch between Wi-Fi and
|
||||||
|
// mobile data, and lookups over them can hang until the timeout. Drop them whenever the default
|
||||||
|
// network changes. (HttpEngine for HTTP/3 follows network changes on its own.)
|
||||||
|
private val connectivity = context.getSystemService(ConnectivityManager::class.java)
|
||||||
|
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
private var current: Network? = null
|
||||||
|
|
||||||
|
override fun onAvailable(network: Network) {
|
||||||
|
if (current != null && current != network) pool.evictAll()
|
||||||
|
current = network
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
if (network != current) return
|
||||||
|
current = null
|
||||||
|
pool.evictAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private val watchingNetwork =
|
||||||
|
connectivity != null && runCatching { connectivity.registerDefaultNetworkCallback(networkCallback) }.isSuccess
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
override var lastProtocol: String? = null
|
override var lastProtocol: String? = null
|
||||||
|
|
||||||
@@ -97,8 +145,8 @@ private class OkHttpTransport(private val provider: DohProvider) : Transport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun shutdown() {
|
override fun shutdown() {
|
||||||
client.dispatcher.executorService.shutdown()
|
if (watchingNetwork) runCatching { connectivity?.unregisterNetworkCallback(networkCallback) }
|
||||||
client.connectionPool.evictAll()
|
pool.evictAll()
|
||||||
}
|
}
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import android.content.pm.ServiceInfo
|
|||||||
import android.graphics.drawable.Icon
|
import android.graphics.drawable.Icon
|
||||||
import android.net.VpnService
|
import android.net.VpnService
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
import android.os.ParcelFileDescriptor
|
import android.os.ParcelFileDescriptor
|
||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
import android.system.ErrnoException
|
import android.system.ErrnoException
|
||||||
@@ -32,6 +34,14 @@ private const val WORKERS = 16
|
|||||||
private const val TAG = "SparkleDNS"
|
private const val TAG = "SparkleDNS"
|
||||||
private const val CHANNEL_ID = "vpn_status"
|
private const val CHANNEL_ID = "vpn_status"
|
||||||
private const val NOTIFICATION_ID = 1
|
private const val NOTIFICATION_ID = 1
|
||||||
|
private const val MAX_BAD_PACKETS = 100
|
||||||
|
|
||||||
|
// Android's resolver retries after 5 s, so an older lookup no longer has anyone waiting for it
|
||||||
|
private const val QUEUE_TIMEOUT_MS = 5000L
|
||||||
|
|
||||||
|
// Closing TLS connections writes to the network, so sessions release their DoH client here
|
||||||
|
// rather than on the main thread, where the service stops them
|
||||||
|
private val closer = Executors.newSingleThreadExecutor { r -> Thread(r, "doh-close").apply { isDaemon = true } }
|
||||||
|
|
||||||
// Local VPN that routes only the fake DNS address into the tunnel; all other traffic is untouched
|
// Local VPN that routes only the fake DNS address into the tunnel; all other traffic is untouched
|
||||||
class DohVpnService : VpnService() {
|
class DohVpnService : VpnService() {
|
||||||
@@ -50,6 +60,7 @@ class DohVpnService : VpnService() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private var session: Session? = null
|
private var session: Session? = null
|
||||||
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
if (intent?.action == ACTION_STOP) {
|
if (intent?.action == ACTION_STOP) {
|
||||||
@@ -76,6 +87,7 @@ class DohVpnService : VpnService() {
|
|||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
stopSession()
|
stopSession()
|
||||||
|
StatsStore.flush()
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,18 +109,22 @@ class DohVpnService : VpnService() {
|
|||||||
.allowFamily(OsConstants.AF_INET6)
|
.allowFamily(OsConstants.AF_INET6)
|
||||||
// The app itself bypasses the VPN so it can resolve and reach the DoH server
|
// The app itself bypasses the VPN so it can resolve and reach the DoH server
|
||||||
runCatching { builder.addDisallowedApplication(packageName) }
|
runCatching { builder.addDisallowedApplication(packageName) }
|
||||||
excluded.forEach { runCatching { builder.addDisallowedApplication(it) } }
|
.onFailure { Log.e(TAG, "Cannot exclude the app itself from the VPN", it) }
|
||||||
|
// Apps uninstalled since they were picked are simply skipped
|
||||||
|
excluded.forEach { app ->
|
||||||
|
runCatching { builder.addDisallowedApplication(app) }.onFailure { Log.i(TAG, "Not excluding $app: $it") }
|
||||||
|
}
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) builder.setMetered(false)
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) builder.setMetered(false)
|
||||||
|
|
||||||
// The new interface replaces the old one in place, so DNS never leaks during a server switch
|
// The new interface replaces the old one in place, so DNS never leaks during a server switch
|
||||||
val tun = runCatching { builder.establish() }.getOrNull()
|
val tun = runCatching { builder.establish() }.onFailure { Log.e(TAG, "Cannot establish the VPN", it) }.getOrNull()
|
||||||
val previous = session
|
val previous = session
|
||||||
if (tun == null) {
|
if (tun == null) {
|
||||||
stopSession()
|
stopSession()
|
||||||
stopSelf()
|
stopSelf()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
session = Session(tun, DohClient(this, provider)).also { it.start() }
|
session = Session(tun, DohClient(this, provider), ::onSessionFailed).also { it.start() }
|
||||||
runCatching { previous?.stop() }
|
runCatching { previous?.stop() }
|
||||||
|
|
||||||
_active.value = provider
|
_active.value = provider
|
||||||
@@ -127,6 +143,17 @@ class DohVpnService : VpnService() {
|
|||||||
DnsTileService.refresh(this)
|
DnsTileService.refresh(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The tunnel reader died while the session should be running. Dropping the VPN lets Android
|
||||||
|
// fall back to normal DNS instead of sending every lookup on the device into a dead tunnel.
|
||||||
|
private fun onSessionFailed(failed: Session) {
|
||||||
|
mainHandler.post {
|
||||||
|
if (session !== failed) return@post
|
||||||
|
Log.e(TAG, "Tunnel stopped working, disconnecting")
|
||||||
|
stopSession()
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun showNotification(provider: DohProvider) {
|
private fun showNotification(provider: DohProvider) {
|
||||||
val manager = getSystemService(NotificationManager::class.java) ?: return
|
val manager = getSystemService(NotificationManager::class.java) ?: return
|
||||||
manager.createNotificationChannel(
|
manager.createNotificationChannel(
|
||||||
@@ -177,6 +204,7 @@ class DohVpnService : VpnService() {
|
|||||||
private class Session(
|
private class Session(
|
||||||
private val tun: ParcelFileDescriptor,
|
private val tun: ParcelFileDescriptor,
|
||||||
private val doh: DohClient,
|
private val doh: DohClient,
|
||||||
|
private val onFailure: (Session) -> Unit,
|
||||||
) {
|
) {
|
||||||
private val alive = AtomicBoolean(true)
|
private val alive = AtomicBoolean(true)
|
||||||
private val pool = Executors.newFixedThreadPool(WORKERS)
|
private val pool = Executors.newFixedThreadPool(WORKERS)
|
||||||
@@ -189,8 +217,14 @@ private class Session(
|
|||||||
fun stop() {
|
fun stop() {
|
||||||
if (!alive.getAndSet(false)) return
|
if (!alive.getAndSet(false)) return
|
||||||
pool.shutdownNow()
|
pool.shutdownNow()
|
||||||
doh.shutdown()
|
|
||||||
runCatching { tun.close() }
|
runCatching { tun.close() }
|
||||||
|
closer.execute {
|
||||||
|
try {
|
||||||
|
doh.shutdown()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "DoH client shutdown failed", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun readLoop() {
|
private fun readLoop() {
|
||||||
@@ -201,25 +235,47 @@ private class Session(
|
|||||||
events = OsConstants.POLLIN.toShort()
|
events = OsConstants.POLLIN.toShort()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var badPackets = 0
|
||||||
|
|
||||||
while (alive.get()) {
|
while (alive.get()) {
|
||||||
try {
|
val n = try {
|
||||||
if (Os.poll(arrayOf(pollFd), 500) <= 0) continue
|
if (Os.poll(arrayOf(pollFd), 500) <= 0) continue
|
||||||
val n = input.read(buf)
|
input.read(buf)
|
||||||
if (n < 0) break
|
|
||||||
val query = Packet.parseDnsQuery(buf, n) ?: continue
|
|
||||||
dispatch(query)
|
|
||||||
} catch (e: ErrnoException) {
|
} catch (e: ErrnoException) {
|
||||||
if (e.errno != OsConstants.EINTR) break
|
if (e.errno == OsConstants.EINTR) continue
|
||||||
} catch (_: IOException) {
|
readerFailed(e)
|
||||||
break
|
return
|
||||||
} catch (_: RejectedExecutionException) {
|
} catch (e: IOException) {
|
||||||
break
|
readerFailed(e)
|
||||||
} catch (e: Exception) {
|
return
|
||||||
Log.e(TAG, "Tunnel reader failed", e)
|
}
|
||||||
break
|
if (n < 0) {
|
||||||
|
readerFailed(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Packet.parseDnsQuery(buf, n)?.let(::dispatch)
|
||||||
|
badPackets = 0
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
readerFailed(e)
|
||||||
|
return
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
// One packet the code cannot handle must not stop DNS for the whole device
|
||||||
|
Log.w(TAG, "Dropped a packet", e)
|
||||||
|
if (++badPackets >= MAX_BAD_PACKETS) {
|
||||||
|
readerFailed(e)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// stop() closes the tunnel, which also ends the loop; only an unexpected end is a failure
|
||||||
|
private fun readerFailed(cause: Throwable?) {
|
||||||
|
if (!alive.get()) return
|
||||||
|
Log.e(TAG, "Tunnel reader stopped", cause)
|
||||||
|
onFailure(this)
|
||||||
|
}
|
||||||
|
|
||||||
// Blocklist and cache are answered right here; only real lookups go to the worker pool
|
// Blocklist and cache are answered right here; only real lookups go to the worker pool
|
||||||
private fun dispatch(query: UdpPacket) {
|
private fun dispatch(query: UdpPacket) {
|
||||||
@@ -235,12 +291,21 @@ private class Session(
|
|||||||
QueryLog.add(question, QueryStatus.CACHED, 0)
|
QueryLog.add(question, QueryStatus.CACHED, 0)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
pool.execute { handle(query, question) }
|
val queued = SystemClock.elapsedRealtime()
|
||||||
|
pool.execute { handle(query, question, queued) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handle(query: UdpPacket, question: DnsMessage.Question?) {
|
private fun handle(query: UdpPacket, question: DnsMessage.Question?, queued: Long) {
|
||||||
try {
|
try {
|
||||||
val start = SystemClock.elapsedRealtime()
|
val start = SystemClock.elapsedRealtime()
|
||||||
|
// On a slow network lookups pile up behind the workers. Answer the stale ones with
|
||||||
|
// SERVFAIL at once instead of spending a worker on them, so the queue drains.
|
||||||
|
if (start - queued > QUEUE_TIMEOUT_MS) {
|
||||||
|
if (!alive.get()) return
|
||||||
|
QueryLog.add(question, QueryStatus.FAILED, (start - queued).toInt())
|
||||||
|
DnsMessage.servfail(query.payload)?.let { write(query, it) }
|
||||||
|
return
|
||||||
|
}
|
||||||
var status = QueryStatus.OK
|
var status = QueryStatus.OK
|
||||||
val answer = try {
|
val answer = try {
|
||||||
doh.query(query.payload).also { cache.put(query.payload, it) }
|
doh.query(query.payload).also { cache.put(query.payload, it) }
|
||||||
@@ -263,7 +328,9 @@ private class Session(
|
|||||||
val packet = Packet.buildReply(query, DnsMessage.withId(payload, query.payload))
|
val packet = Packet.buildReply(query, DnsMessage.withId(payload, query.payload))
|
||||||
try {
|
try {
|
||||||
synchronized(output) { output.write(packet) }
|
synchronized(output) { output.write(packet) }
|
||||||
} catch (_: IOException) {
|
} catch (e: IOException) {
|
||||||
|
// Expected while the session is being stopped
|
||||||
|
if (alive.get()) Log.w(TAG, "Cannot write an answer to the tunnel", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,556 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.net.VpnService
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.animation.AnimatedContent
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.animateColorAsState
|
||||||
|
import androidx.compose.animation.core.animateDpAsState
|
||||||
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.animation.togetherWith
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
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.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.offset
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.selection.toggleable
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
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.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.draw.drawBehind
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.Path
|
||||||
|
import androidx.compose.ui.graphics.PathEffect
|
||||||
|
import androidx.compose.ui.graphics.StrokeCap
|
||||||
|
import androidx.compose.ui.graphics.StrokeJoin
|
||||||
|
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.drawText
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.rememberTextMeasurer
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
private const val CHART_HOURS = 24
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifier = Modifier) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val prefs = remember { Prefs(context) }
|
||||||
|
val active by DohVpnService.active.collectAsStateWithLifecycle()
|
||||||
|
val running = active != null
|
||||||
|
val lists by Blocklist.lists.collectAsStateWithLifecycle()
|
||||||
|
val total by Blocklist.total.collectAsStateWithLifecycle()
|
||||||
|
val blocking by Blocklist.enabled.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
var summary by remember { mutableStateOf(StatsStore.summary(CHART_HOURS)) }
|
||||||
|
var points by remember { mutableStateOf(StatsStore.hourly(CHART_HOURS)) }
|
||||||
|
fun refreshStats() {
|
||||||
|
summary = StatsStore.summary(CHART_HOURS)
|
||||||
|
points = StatsStore.hourly(CHART_HOURS)
|
||||||
|
}
|
||||||
|
OnQueryLogChange { refreshStats() }
|
||||||
|
val statsVersion by StatsStore.version.collectAsStateWithLifecycle()
|
||||||
|
LaunchedEffect(statsVersion) { refreshStats() }
|
||||||
|
|
||||||
|
// The server is picked in Settings; this screen is composed anew each time it is shown
|
||||||
|
val selected = remember { prefs.resolve() }
|
||||||
|
val canConnect = selected.id != Providers.CUSTOM_ID || selected.url.toHttpUrlOrNull()?.isHttps == true
|
||||||
|
val shown = active ?: selected
|
||||||
|
val usesHttp3 = shown.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
|
||||||
|
|
||||||
|
val crashReport = remember { CrashLog.read(context) }
|
||||||
|
var crashVisible by remember { mutableStateOf(crashReport != null) }
|
||||||
|
// Strict Private DNS makes Android ignore the VPN's DNS server; followed while Home is visible
|
||||||
|
val privateDnsHost by remember { privateDnsHosts(context) }.collectAsStateWithLifecycle(initialValue = null)
|
||||||
|
|
||||||
|
// Set by a tap until the VPN state changes or the attempt gives up, so a double tap neither
|
||||||
|
// starts two connections nor switches the VPN back on right after turning it off
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
LaunchedEffect(active) { busy = false }
|
||||||
|
LaunchedEffect(busy) {
|
||||||
|
if (busy) {
|
||||||
|
delay(BUSY_TIMEOUT_MS)
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val vpnPermission = rememberLauncherForActivityResult(
|
||||||
|
ActivityResultContracts.StartActivityForResult()
|
||||||
|
) {
|
||||||
|
if (it.resultCode == Activity.RESULT_OK) sendAction(context, DohVpnService.ACTION_START)
|
||||||
|
else busy = false
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connectVpn() {
|
||||||
|
val permission = VpnService.prepare(context)
|
||||||
|
if (permission != null) vpnPermission.launch(permission)
|
||||||
|
else sendAction(context, DohVpnService.ACTION_START)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The status notification is optional: connect whatever the user answers
|
||||||
|
val notificationPermission = rememberLauncherForActivityResult(
|
||||||
|
ActivityResultContracts.RequestPermission()
|
||||||
|
) { connectVpn() }
|
||||||
|
|
||||||
|
fun toggle() {
|
||||||
|
if (busy) return
|
||||||
|
busy = true
|
||||||
|
if (running) {
|
||||||
|
sendAction(context, DohVpnService.ACTION_STOP)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val needsNotificationPermission = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||||
|
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
||||||
|
if (needsNotificationPermission) notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
else connectVpn()
|
||||||
|
}
|
||||||
|
|
||||||
|
val glow by animateFloatAsState(if (running) 1f else 0f, tween(600), label = "glow")
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = modifier
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
.drawBehind {
|
||||||
|
// Soft light behind the logo while protected
|
||||||
|
if (glow > 0f) {
|
||||||
|
drawCircle(
|
||||||
|
brush = Brush.radialGradient(
|
||||||
|
colors = listOf(Palette.Accent.copy(alpha = 0.22f * glow), Color.Transparent),
|
||||||
|
center = Offset(size.width / 2f, 0f),
|
||||||
|
radius = size.width * 0.65f,
|
||||||
|
),
|
||||||
|
radius = size.width * 0.65f,
|
||||||
|
center = Offset(size.width / 2f, 0f),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(top = 16.dp, bottom = bottomPadding),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(20.dp),
|
||||||
|
) {
|
||||||
|
Image(
|
||||||
|
painterResource(R.drawable.app_logo),
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier
|
||||||
|
.size(44.dp)
|
||||||
|
.align(Alignment.CenterHorizontally),
|
||||||
|
)
|
||||||
|
|
||||||
|
AnimatedVisibility(visible = crashVisible, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
|
val report = crashReport.orEmpty()
|
||||||
|
Box(Modifier.padding(horizontal = 20.dp)) {
|
||||||
|
CrashCard(
|
||||||
|
report = report,
|
||||||
|
onCopy = {
|
||||||
|
context.getSystemService(ClipboardManager::class.java)
|
||||||
|
.setPrimaryClip(ClipData.newPlainText("SparkleDNS crash", report))
|
||||||
|
},
|
||||||
|
onDismiss = { CrashLog.clear(context); crashVisible = false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
StatusCard(
|
||||||
|
running = running,
|
||||||
|
providerName = shown.displayName(context),
|
||||||
|
http3 = usesHttp3,
|
||||||
|
enabled = !busy && (running || canConnect),
|
||||||
|
onToggle = ::toggle,
|
||||||
|
modifier = Modifier.padding(horizontal = 20.dp),
|
||||||
|
)
|
||||||
|
|
||||||
|
PrivateDnsWarning(privateDnsHost, prefs, Modifier.padding(horizontal = 20.dp))
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 24.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
StatBlock(formatCompact(summary.total), stringResource(R.string.stat_requests), Modifier.weight(1f))
|
||||||
|
StatBlock(
|
||||||
|
formatCompact(summary.blocked),
|
||||||
|
stringResource(R.string.mon_blocked),
|
||||||
|
Modifier.weight(1f),
|
||||||
|
valueColor = Palette.Accent,
|
||||||
|
)
|
||||||
|
StatBlock(stringResource(R.string.mon_ms, summary.avgLatencyMs), stringResource(R.string.stat_avg), Modifier.weight(1f))
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 20.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(14.dp, Alignment.End),
|
||||||
|
) {
|
||||||
|
LegendItem(stringResource(R.string.stat_requests), Palette.Accent)
|
||||||
|
LegendItem(stringResource(R.string.mon_blocked), Palette.Muted)
|
||||||
|
}
|
||||||
|
TrafficChart(
|
||||||
|
points,
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(150.dp),
|
||||||
|
)
|
||||||
|
val startLabel = remember(points) {
|
||||||
|
val start = System.currentTimeMillis() - (CHART_HOURS - 1) * 3_600_000L
|
||||||
|
SimpleDateFormat("HH:00", Locale.getDefault()).format(Date(start))
|
||||||
|
}
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 20.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text(startLabel, color = Palette.Fg3, fontSize = 11.sp, modifier = Modifier.weight(1f))
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.period_24h),
|
||||||
|
color = Palette.Fg2,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
modifier = Modifier
|
||||||
|
.clip(RoundedCornerShape(16.dp))
|
||||||
|
.background(Palette.Card)
|
||||||
|
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.chart_now),
|
||||||
|
color = Palette.Fg3,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
textAlign = TextAlign.End,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
BlocklistRow(
|
||||||
|
info = if (blocking) {
|
||||||
|
stringResource(R.string.home_lists_info, lists.count { it.enabled }, formatCount(total.toLong()))
|
||||||
|
} else {
|
||||||
|
stringResource(R.string.blocking_off)
|
||||||
|
},
|
||||||
|
onClick = onOpenBlocklist,
|
||||||
|
modifier = Modifier.padding(horizontal = 20.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun StatusCard(
|
||||||
|
running: Boolean,
|
||||||
|
providerName: String,
|
||||||
|
http3: Boolean,
|
||||||
|
enabled: Boolean,
|
||||||
|
onToggle: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.appCard()
|
||||||
|
.padding(horizontal = 20.dp, vertical = 24.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
AnimatedContent(
|
||||||
|
targetState = running,
|
||||||
|
transitionSpec = { fadeIn(Motion.enterFade) togetherWith fadeOut(Motion.exitFade) },
|
||||||
|
label = "status",
|
||||||
|
) { on ->
|
||||||
|
Text(
|
||||||
|
stringResource(if (on) R.string.home_protected else R.string.home_unprotected),
|
||||||
|
color = Palette.Fg,
|
||||||
|
fontSize = 24.sp,
|
||||||
|
fontWeight = FontWeight.ExtraBold,
|
||||||
|
letterSpacing = (-0.3).sp,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val dot by animateColorAsState(if (running) Palette.Accent else Palette.Track, Motion.color, label = "dot")
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.size(7.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(dot)
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
val via = stringResource(R.string.home_via, providerName) + if (http3) " · HTTP/3" else ""
|
||||||
|
Text(
|
||||||
|
if (running) via else stringResource(R.string.home_off_desc),
|
||||||
|
color = Palette.Fg2,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
PowerToggle(on = running, enabled = enabled, onToggle = onToggle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The big ON / OFF switch; the white knob slides across
|
||||||
|
@Composable
|
||||||
|
private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
|
||||||
|
val track by animateColorAsState(if (on) Palette.Accent else Palette.Track, Motion.color, label = "track")
|
||||||
|
val knob by animateDpAsState(if (on) 70.dp else 0.dp, tween(320, easing = Motion.Emphasized), label = "knob")
|
||||||
|
val description = stringResource(if (on) R.string.disconnect else R.string.connect)
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(width = 120.dp, height = 50.dp)
|
||||||
|
.graphicsLayer { alpha = if (enabled) 1f else 0.5f }
|
||||||
|
.clip(RoundedCornerShape(25.dp))
|
||||||
|
.background(track)
|
||||||
|
.toggleable(value = on, enabled = enabled, role = Role.Switch, onValueChange = { onToggle() })
|
||||||
|
.semantics { contentDescription = description }
|
||||||
|
.padding(5.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
stringResource(if (on) R.string.toggle_on else R.string.toggle_off),
|
||||||
|
color = if (on) Palette.AccentInk else Palette.Fg2,
|
||||||
|
fontSize = 15.sp,
|
||||||
|
fontWeight = FontWeight.ExtraBold,
|
||||||
|
letterSpacing = 0.6.sp,
|
||||||
|
modifier = Modifier
|
||||||
|
.align(if (on) Alignment.CenterStart else Alignment.CenterEnd)
|
||||||
|
.padding(horizontal = 12.dp),
|
||||||
|
)
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.offset(x = knob)
|
||||||
|
.size(40.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(Color.White),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Canvas(Modifier.size(14.dp)) {
|
||||||
|
val stroke = 1.6.dp.toPx()
|
||||||
|
listOf(0.29f, 0.5f, 0.71f).forEach { fraction ->
|
||||||
|
drawLine(
|
||||||
|
color = Palette.Fg3,
|
||||||
|
start = Offset(size.width * fraction, size.height * 0.21f),
|
||||||
|
end = Offset(size.width * fraction, size.height * 0.79f),
|
||||||
|
strokeWidth = stroke,
|
||||||
|
cap = StrokeCap.Round,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PrivateDnsWarning(privateDnsHost: String?, prefs: Prefs, modifier: Modifier = Modifier) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val lastHost = remember { arrayOf("") }
|
||||||
|
privateDnsHost?.let { lastHost[0] = it }
|
||||||
|
var dismissedHost by remember { mutableStateOf(prefs.dismissedPrivateDns) }
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = privateDnsHost != null && privateDnsHost != dismissedHost,
|
||||||
|
enter = Motion.expandIn,
|
||||||
|
exit = Motion.collapseOut,
|
||||||
|
modifier = modifier,
|
||||||
|
) {
|
||||||
|
HintCard(
|
||||||
|
text = stringResource(R.string.hint, lastHost[0]),
|
||||||
|
icon = R.drawable.ic_alert,
|
||||||
|
tint = WarningColor,
|
||||||
|
action = {
|
||||||
|
TextButton(onClick = { openNetworkSettings(context) }) { Text(stringResource(R.string.open_settings)) }
|
||||||
|
},
|
||||||
|
onDismiss = {
|
||||||
|
dismissedHost = lastHost[0]
|
||||||
|
prefs.dismissedPrivateDns = lastHost[0]
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun StatBlock(value: String, label: String, modifier: Modifier = Modifier, valueColor: Color = Palette.Fg) {
|
||||||
|
Column(modifier, verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||||
|
Text(value, color = valueColor, fontSize = 21.sp, fontWeight = FontWeight.ExtraBold, maxLines = 1)
|
||||||
|
Text(label, color = Palette.Fg2, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LegendItem(label: String, color: Color) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.size(width = 12.dp, height = 3.dp)
|
||||||
|
.clip(RoundedCornerShape(2.dp))
|
||||||
|
.background(color)
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(label, color = Palette.Fg2, fontSize = 11.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Requests (accent line with a soft fill) and blocked queries (grey line) per hour
|
||||||
|
@Composable
|
||||||
|
private fun TrafficChart(points: List<HourPoint>, modifier: Modifier = Modifier) {
|
||||||
|
val measurer = rememberTextMeasurer()
|
||||||
|
val labelStyle = TextStyle(color = Palette.Fg3, fontSize = 10.sp)
|
||||||
|
Canvas(modifier) {
|
||||||
|
val n = points.size
|
||||||
|
if (n < 2) return@Canvas
|
||||||
|
val maxValue = niceCeiling(points.maxOf { it.total }.coerceAtLeast(1L))
|
||||||
|
val inset = 6.dp.toPx()
|
||||||
|
val top = 14.dp.toPx()
|
||||||
|
val base = size.height - 8.dp.toPx()
|
||||||
|
val span = base - top
|
||||||
|
val step = (size.width - 2 * inset) / (n - 1)
|
||||||
|
fun x(index: Int) = inset + index * step
|
||||||
|
fun y(value: Long) = base - value.toFloat() / maxValue * span
|
||||||
|
|
||||||
|
listOf(maxValue / 2, maxValue).forEach { value ->
|
||||||
|
val gridY = y(value)
|
||||||
|
drawLine(
|
||||||
|
color = Palette.Line,
|
||||||
|
start = Offset(0f, gridY),
|
||||||
|
end = Offset(size.width, gridY),
|
||||||
|
strokeWidth = 1.dp.toPx(),
|
||||||
|
pathEffect = PathEffect.dashPathEffect(floatArrayOf(3.dp.toPx(), 4.dp.toPx())),
|
||||||
|
)
|
||||||
|
drawText(
|
||||||
|
textMeasurer = measurer,
|
||||||
|
text = formatCompact(value),
|
||||||
|
topLeft = Offset(20.dp.toPx(), gridY - 15.dp.toPx()),
|
||||||
|
style = labelStyle,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val line = Path()
|
||||||
|
val area = Path()
|
||||||
|
val blocked = Path()
|
||||||
|
points.forEachIndexed { index, point ->
|
||||||
|
val px = x(index)
|
||||||
|
if (index == 0) {
|
||||||
|
line.moveTo(px, y(point.total))
|
||||||
|
area.moveTo(px, base)
|
||||||
|
area.lineTo(px, y(point.total))
|
||||||
|
blocked.moveTo(px, y(point.blocked))
|
||||||
|
} else {
|
||||||
|
line.lineTo(px, y(point.total))
|
||||||
|
area.lineTo(px, y(point.total))
|
||||||
|
blocked.lineTo(px, y(point.blocked))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
area.lineTo(x(n - 1), base)
|
||||||
|
area.close()
|
||||||
|
|
||||||
|
drawPath(area, Palette.Accent.copy(alpha = 0.14f))
|
||||||
|
drawPath(
|
||||||
|
blocked,
|
||||||
|
Palette.Muted,
|
||||||
|
style = Stroke(width = 1.6.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round),
|
||||||
|
)
|
||||||
|
drawPath(
|
||||||
|
line,
|
||||||
|
Palette.Accent,
|
||||||
|
style = Stroke(width = 2.4.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round),
|
||||||
|
)
|
||||||
|
val end = Offset(x(n - 1), y(points.last().total))
|
||||||
|
drawCircle(Palette.Bg, radius = 5.dp.toPx(), center = end)
|
||||||
|
drawCircle(Palette.Accent, radius = 5.dp.toPx(), center = end, style = Stroke(width = 2.4.dp.toPx()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1, 2 or 5 times a power of ten, at least [value]: keeps the grid labels round
|
||||||
|
private fun niceCeiling(value: Long): Long {
|
||||||
|
var magnitude = 1L
|
||||||
|
while (magnitude * 10 <= value) magnitude *= 10
|
||||||
|
for (factor in longArrayOf(1, 2, 5)) {
|
||||||
|
if (factor * magnitude >= value) return factor * magnitude
|
||||||
|
}
|
||||||
|
return 10 * magnitude
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun BlocklistRow(info: String, onClick: () -> Unit, modifier: Modifier = Modifier) {
|
||||||
|
Row(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.appCard()
|
||||||
|
.clickable(onClick = onClick)
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(40.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(Palette.Accent),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_privacy),
|
||||||
|
contentDescription = null,
|
||||||
|
tint = Palette.AccentInk,
|
||||||
|
modifier = Modifier.size(22.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(14.dp))
|
||||||
|
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||||
|
Text(stringResource(R.string.blocklist_title), color = Palette.Fg, fontSize = 15.sp, fontWeight = FontWeight.Bold)
|
||||||
|
Text(info, color = Palette.Fg2, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
Chevron()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
// Base for every OkHttp client in the app. Clients made with newBuilder() share its dispatcher
|
||||||
|
// and thread pools, and its connection pool unless they bring their own.
|
||||||
|
internal object Http {
|
||||||
|
val client: OkHttpClient by lazy {
|
||||||
|
OkHttpClient.Builder()
|
||||||
|
.connectTimeout(15, TimeUnit.SECONDS)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,97 +1,47 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
import android.Manifest
|
|
||||||
import android.app.Activity
|
|
||||||
import android.content.ClipData
|
|
||||||
import android.content.ClipboardManager
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.net.ConnectivityManager
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.LinkProperties
|
||||||
|
import android.net.Network
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.net.VpnService
|
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
|
||||||
import androidx.compose.animation.AnimatedContent
|
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
|
||||||
import androidx.compose.animation.animateColorAsState
|
|
||||||
import androidx.compose.animation.fadeIn
|
|
||||||
import androidx.compose.animation.fadeOut
|
|
||||||
import androidx.compose.animation.togetherWith
|
|
||||||
import androidx.compose.animation.core.LinearEasing
|
|
||||||
import androidx.compose.animation.core.animateFloatAsState
|
|
||||||
import androidx.compose.animation.core.animateFloat
|
|
||||||
import androidx.compose.animation.core.infiniteRepeatable
|
|
||||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
|
||||||
import androidx.compose.animation.core.tween
|
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.selection.selectable
|
|
||||||
import androidx.compose.foundation.selection.toggleable
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material3.Button
|
|
||||||
import androidx.compose.material3.Card
|
import androidx.compose.material3.Card
|
||||||
import androidx.compose.material3.CardDefaults
|
import androidx.compose.material3.CardDefaults
|
||||||
import androidx.compose.material3.HorizontalDivider
|
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedButton
|
|
||||||
import androidx.compose.material3.OutlinedTextField
|
|
||||||
import androidx.compose.material3.RadioButton
|
|
||||||
import androidx.compose.material3.Switch
|
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.darkColorScheme
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.saveable.Saver
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.produceState
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.graphicsLayer
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.semantics.Role
|
|
||||||
import androidx.compose.ui.text.font.FontFamily
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
|
||||||
import androidx.compose.ui.text.input.KeyboardType
|
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.flow.callbackFlow
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
import kotlinx.coroutines.flow.flowOf
|
||||||
|
|
||||||
class MainActivity : ComponentActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
@@ -103,445 +53,22 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private val AppColors = darkColorScheme(
|
internal class TestResult(val ok: Boolean, val text: String)
|
||||||
primary = Color(0xFF7FB2FF),
|
|
||||||
onPrimary = Color(0xFF00285C),
|
// How long a tap on Connect, Disconnect or Switch blocks further taps if the VPN state never changes
|
||||||
background = Color(0xFF0F1115),
|
internal const val BUSY_TIMEOUT_MS = 5000L
|
||||||
surface = Color(0xFF0F1115),
|
|
||||||
|
// Keeps test results across rotation and process death
|
||||||
|
internal val TestResultSaver = Saver<TestResult?, String>(
|
||||||
|
save = { result -> result?.let { (if (it.ok) "1" else "0") + it.text } },
|
||||||
|
restore = { saved -> TestResult(saved.startsWith("1"), saved.drop(1)) },
|
||||||
)
|
)
|
||||||
|
|
||||||
private val ProtectedContainer = Color(0xFF16233A)
|
|
||||||
|
|
||||||
private class TestResult(val ok: Boolean, val text: String)
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun HomeScreen(modifier: Modifier = Modifier) {
|
internal fun CrashCard(report: String, onCopy: () -> Unit, onDismiss: () -> Unit) {
|
||||||
val context = LocalContext.current
|
|
||||||
val prefs = remember { Prefs(context) }
|
|
||||||
val active by DohVpnService.active.collectAsState()
|
|
||||||
val running = active != null
|
|
||||||
val scope = rememberCoroutineScope()
|
|
||||||
val stats = rememberLiveStats()
|
|
||||||
|
|
||||||
var selected by remember { mutableStateOf(prefs.providerId) }
|
|
||||||
val servers by ServerList.servers.collectAsState()
|
|
||||||
var syncing by remember { mutableStateOf(false) }
|
|
||||||
var syncResult by remember { mutableStateOf<TestResult?>(null) }
|
|
||||||
var shownSync by remember { mutableStateOf<TestResult?>(null) }
|
|
||||||
var customUrl by remember { mutableStateOf(prefs.customUrl) }
|
|
||||||
var customBootstrap by remember { mutableStateOf(prefs.customBootstrap) }
|
|
||||||
var customHttp3 by remember { mutableStateOf(prefs.customHttp3) }
|
|
||||||
var testResult by remember { mutableStateOf<TestResult?>(null) }
|
|
||||||
var shownResult by remember { mutableStateOf<TestResult?>(null) } // kept while the card animates out
|
|
||||||
var testing by remember { mutableStateOf(false) }
|
|
||||||
val crashReport = remember { CrashLog.read(context) }
|
|
||||||
// Strict Private DNS makes Android ignore the VPN's DNS server; re-checked while Home is open
|
|
||||||
val privateDnsHost by produceState<String?>(null) {
|
|
||||||
while (true) {
|
|
||||||
value = readPrivateDnsHost(context)
|
|
||||||
delay(3000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var crashVisible by remember { mutableStateOf(crashReport != null) }
|
|
||||||
|
|
||||||
val isCustom = selected == Providers.CUSTOM_ID
|
|
||||||
val customValid = customUrl.trim().toHttpUrlOrNull()?.isHttps == true
|
|
||||||
val canConnect = !isCustom || customValid
|
|
||||||
val selectedProvider = remember(selected, customUrl, customBootstrap, customHttp3, servers) { prefs.resolve() }
|
|
||||||
val customName = stringResource(R.string.custom)
|
|
||||||
fun nameOf(p: DohProvider) = if (p.id == Providers.CUSTOM_ID) customName else p.name
|
|
||||||
val shownProvider = active ?: selectedProvider
|
|
||||||
val usesHttp3 = shownProvider.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
|
|
||||||
|
|
||||||
// Picking a server never touches a live connection; switching is an explicit action
|
|
||||||
val pendingSwitch = active?.let { it != selectedProvider && canConnect } == true
|
|
||||||
|
|
||||||
val vpnPermission = rememberLauncherForActivityResult(
|
|
||||||
ActivityResultContracts.StartActivityForResult()
|
|
||||||
) { if (it.resultCode == Activity.RESULT_OK) sendAction(context, DohVpnService.ACTION_START) }
|
|
||||||
|
|
||||||
fun connectVpn() {
|
|
||||||
val permission = VpnService.prepare(context)
|
|
||||||
if (permission != null) vpnPermission.launch(permission)
|
|
||||||
else sendAction(context, DohVpnService.ACTION_START)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The status notification is optional: connect whatever the user answers
|
|
||||||
val notificationPermission = rememberLauncherForActivityResult(
|
|
||||||
ActivityResultContracts.RequestPermission()
|
|
||||||
) { connectVpn() }
|
|
||||||
|
|
||||||
fun toggle() {
|
|
||||||
if (running) {
|
|
||||||
sendAction(context, DohVpnService.ACTION_STOP)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val needsNotificationPermission = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
|
||||||
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
|
||||||
if (needsNotificationPermission) notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
|
|
||||||
else connectVpn()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun select(id: String) {
|
|
||||||
selected = id
|
|
||||||
prefs.providerId = id
|
|
||||||
testResult = null
|
|
||||||
}
|
|
||||||
|
|
||||||
// A server removed from the list falls back to the default one
|
|
||||||
LaunchedEffect(servers) {
|
|
||||||
if (selected != Providers.CUSTOM_ID && servers.none { it.id == selected }) select(Providers.default.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
val syncOk = stringResource(R.string.servers_updated)
|
|
||||||
val syncFail = stringResource(R.string.servers_update_failed)
|
|
||||||
fun syncServers() {
|
|
||||||
syncing = true
|
|
||||||
syncResult = null
|
|
||||||
scope.launch {
|
|
||||||
val result = withContext(Dispatchers.IO) {
|
|
||||||
runCatching { ServerList.sync(context) }
|
|
||||||
.fold(
|
|
||||||
onSuccess = { TestResult(true, syncOk) },
|
|
||||||
onFailure = { TestResult(false, syncFail.format(it.message ?: it.javaClass.simpleName)) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
shownSync = result
|
|
||||||
syncResult = result
|
|
||||||
syncing = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun runTest() {
|
|
||||||
val provider = prefs.resolve()
|
|
||||||
testing = true
|
|
||||||
testResult = null
|
|
||||||
scope.launch {
|
|
||||||
val result = withContext(Dispatchers.IO) { testProvider(context, provider) }
|
|
||||||
shownResult = result
|
|
||||||
testResult = result
|
|
||||||
testing = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Column(
|
|
||||||
modifier = modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.verticalScroll(rememberScrollState())
|
|
||||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
|
||||||
) {
|
|
||||||
AnimatedVisibility(visible = crashVisible, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
val report = crashReport.orEmpty()
|
|
||||||
CrashCard(
|
|
||||||
report = report,
|
|
||||||
onCopy = {
|
|
||||||
context.getSystemService(ClipboardManager::class.java)
|
|
||||||
.setPrimaryClip(ClipData.newPlainText("SparkleDNS crash", report))
|
|
||||||
},
|
|
||||||
onDismiss = { CrashLog.clear(context); crashVisible = false },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
StatusHero(
|
|
||||||
running = running,
|
|
||||||
providerName = nameOf(shownProvider),
|
|
||||||
http3 = usesHttp3,
|
|
||||||
stats = stats,
|
|
||||||
canConnect = canConnect,
|
|
||||||
switchTo = if (pendingSwitch) nameOf(selectedProvider) else null,
|
|
||||||
onToggle = ::toggle,
|
|
||||||
onSwitch = { sendAction(context, DohVpnService.ACTION_START) },
|
|
||||||
)
|
|
||||||
|
|
||||||
SectionHeader(stringResource(R.string.servers)) {
|
|
||||||
if (syncing) {
|
|
||||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
|
||||||
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
IconButton(onClick = ::syncServers) {
|
|
||||||
Icon(
|
|
||||||
painterResource(R.drawable.ic_refresh),
|
|
||||||
contentDescription = stringResource(R.string.servers_update),
|
|
||||||
modifier = Modifier.size(20.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AnimatedVisibility(visible = syncResult != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
shownSync?.let { result ->
|
|
||||||
HintCard(
|
|
||||||
text = result.text,
|
|
||||||
icon = if (result.ok) R.drawable.ic_check else R.drawable.ic_alert,
|
|
||||||
tint = if (result.ok) CachedColor else MaterialTheme.colorScheme.error,
|
|
||||||
onDismiss = { syncResult = null },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Card(Modifier.fillMaxWidth()) {
|
|
||||||
Column(Modifier.padding(vertical = 6.dp)) {
|
|
||||||
servers.forEachIndexed { index, p ->
|
|
||||||
if (index > 0) RowDivider()
|
|
||||||
ProviderRow(
|
|
||||||
title = p.name,
|
|
||||||
subtitle = hostOf(p.url),
|
|
||||||
selected = selected == p.id,
|
|
||||||
onPolicy = p.policy?.let { url -> { openUrl(context, url) } },
|
|
||||||
) { select(p.id) }
|
|
||||||
}
|
|
||||||
RowDivider()
|
|
||||||
ProviderRow(
|
|
||||||
title = stringResource(R.string.custom),
|
|
||||||
subtitle = hostOf(customUrl),
|
|
||||||
selected = isCustom,
|
|
||||||
) { select(Providers.CUSTOM_ID) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AnimatedVisibility(visible = isCustom, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
Card(Modifier.fillMaxWidth()) {
|
|
||||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
||||||
OutlinedTextField(
|
|
||||||
value = customUrl,
|
|
||||||
onValueChange = { customUrl = it; prefs.customUrl = it },
|
|
||||||
label = { Text(stringResource(R.string.custom_url)) },
|
|
||||||
singleLine = true,
|
|
||||||
isError = !customValid,
|
|
||||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Next),
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
)
|
|
||||||
if (!customValid) {
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.invalid_url),
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.error,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
OutlinedTextField(
|
|
||||||
value = customBootstrap,
|
|
||||||
onValueChange = { customBootstrap = it; prefs.customBootstrap = it },
|
|
||||||
label = { Text(stringResource(R.string.custom_bootstrap)) },
|
|
||||||
singleLine = true,
|
|
||||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
)
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.toggleable(
|
|
||||||
value = customHttp3,
|
|
||||||
role = Role.Switch,
|
|
||||||
onValueChange = { customHttp3 = it; prefs.customHttp3 = it },
|
|
||||||
)
|
|
||||||
.padding(vertical = 4.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
Column(Modifier.weight(1f)) {
|
|
||||||
Text(stringResource(R.string.http3), style = MaterialTheme.typography.bodyLarge)
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.http3_note),
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.width(12.dp))
|
|
||||||
Switch(checked = customHttp3, onCheckedChange = null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = ::runTest,
|
|
||||||
enabled = !testing && canConnect,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.height(48.dp),
|
|
||||||
) { Text(stringResource(if (testing) R.string.testing else R.string.test)) }
|
|
||||||
|
|
||||||
AnimatedVisibility(visible = testResult != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
shownResult?.let { result ->
|
|
||||||
HintCard(
|
|
||||||
text = result.text,
|
|
||||||
icon = if (result.ok) R.drawable.ic_check else R.drawable.ic_alert,
|
|
||||||
tint = if (result.ok) CachedColor else MaterialTheme.colorScheme.error,
|
|
||||||
onDismiss = { testResult = null },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val lastHost = remember { arrayOf("") }
|
|
||||||
privateDnsHost?.let { lastHost[0] = it }
|
|
||||||
var dismissedDnsHost by remember { mutableStateOf(prefs.dismissedPrivateDns) }
|
|
||||||
AnimatedVisibility(
|
|
||||||
visible = privateDnsHost != null && privateDnsHost != dismissedDnsHost,
|
|
||||||
enter = Motion.expandIn,
|
|
||||||
exit = Motion.collapseOut,
|
|
||||||
) {
|
|
||||||
HintCard(
|
|
||||||
text = stringResource(R.string.hint, lastHost[0]),
|
|
||||||
icon = R.drawable.ic_alert,
|
|
||||||
tint = WarningColor,
|
|
||||||
action = {
|
|
||||||
TextButton(onClick = { openNetworkSettings(context) }) { Text(stringResource(R.string.open_settings)) }
|
|
||||||
},
|
|
||||||
onDismiss = {
|
|
||||||
dismissedDnsHost = lastHost[0]
|
|
||||||
prefs.dismissedPrivateDns = lastHost[0]
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun StatusHero(
|
|
||||||
running: Boolean,
|
|
||||||
providerName: String,
|
|
||||||
http3: Boolean,
|
|
||||||
stats: QueryStats,
|
|
||||||
canConnect: Boolean,
|
|
||||||
switchTo: String?,
|
|
||||||
onToggle: () -> Unit,
|
|
||||||
onSwitch: () -> Unit,
|
|
||||||
) {
|
|
||||||
val accent by animateColorAsState(
|
|
||||||
if (running) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
|
|
||||||
animationSpec = Motion.color,
|
|
||||||
label = "accent",
|
|
||||||
)
|
|
||||||
val container by animateColorAsState(
|
|
||||||
if (running) ProtectedContainer else MaterialTheme.colorScheme.surfaceContainerHighest,
|
|
||||||
animationSpec = Motion.color,
|
|
||||||
label = "container",
|
|
||||||
)
|
|
||||||
|
|
||||||
val ringAlpha by animateFloatAsState(if (running) 1f else 0f, Motion.rotation, label = "ring")
|
|
||||||
|
|
||||||
Card(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
colors = CardDefaults.cardColors(containerColor = container),
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(20.dp),
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
|
||||||
) {
|
|
||||||
Box(Modifier.size(124.dp), contentAlignment = Alignment.Center) {
|
|
||||||
if (ringAlpha > 0f) PulseRing(accent, ringAlpha)
|
|
||||||
Box(
|
|
||||||
modifier = Modifier
|
|
||||||
.size(92.dp)
|
|
||||||
.clip(CircleShape)
|
|
||||||
.background(accent.copy(alpha = 0.18f)),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
painterResource(R.drawable.ic_privacy),
|
|
||||||
contentDescription = null,
|
|
||||||
tint = accent,
|
|
||||||
modifier = Modifier.size(52.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AnimatedContent(
|
|
||||||
targetState = running,
|
|
||||||
transitionSpec = { fadeIn(Motion.enterFade) togetherWith fadeOut(Motion.exitFade) },
|
|
||||||
label = "status",
|
|
||||||
) { on ->
|
|
||||||
Text(
|
|
||||||
stringResource(if (on) R.string.status_on else R.string.status_off),
|
|
||||||
style = MaterialTheme.typography.headlineSmall,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.via, providerName),
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
if (http3) {
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
Pill("HTTP/3", accent)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AnimatedVisibility(visible = running, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(vertical = 4.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
StatColumn(formatCount(stats.total), stringResource(R.string.mon_queries), Modifier.weight(1f))
|
|
||||||
StatDivider()
|
|
||||||
StatColumn(formatCount(stats.blocked), stringResource(R.string.mon_blocked), Modifier.weight(1f))
|
|
||||||
StatDivider()
|
|
||||||
StatColumn(cachePercent(stats), stringResource(R.string.mon_cached), Modifier.weight(1f))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Button(
|
|
||||||
onClick = onToggle,
|
|
||||||
enabled = running || canConnect,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.height(52.dp),
|
|
||||||
) {
|
|
||||||
AnimatedContent(
|
|
||||||
targetState = running,
|
|
||||||
transitionSpec = { fadeIn(Motion.enterFade) togetherWith fadeOut(Motion.exitFade) },
|
|
||||||
label = "toggle",
|
|
||||||
) { on -> Text(stringResource(if (on) R.string.disconnect else R.string.connect)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remembers the last name so the button keeps its label while it animates out
|
|
||||||
val lastSwitch = remember { arrayOf("") }
|
|
||||||
if (switchTo != null) lastSwitch[0] = switchTo
|
|
||||||
AnimatedVisibility(visible = switchTo != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
|
||||||
OutlinedButton(onClick = onSwitch, modifier = Modifier.fillMaxWidth()) {
|
|
||||||
Icon(painterResource(R.drawable.ic_switch), contentDescription = null, modifier = Modifier.size(18.dp))
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
Text(stringResource(R.string.switch_to, lastSwitch[0]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun PulseRing(color: Color, visibility: Float) {
|
|
||||||
val transition = rememberInfiniteTransition(label = "pulse")
|
|
||||||
val progress by transition.animateFloat(
|
|
||||||
initialValue = 0f,
|
|
||||||
targetValue = 1f,
|
|
||||||
animationSpec = infiniteRepeatable(tween(1800, easing = LinearEasing)),
|
|
||||||
label = "progress",
|
|
||||||
)
|
|
||||||
Box(
|
|
||||||
Modifier
|
|
||||||
.size(124.dp)
|
|
||||||
.graphicsLayer {
|
|
||||||
val scale = 0.74f + 0.26f * progress
|
|
||||||
scaleX = scale
|
|
||||||
scaleY = scale
|
|
||||||
alpha = (1f - progress) * visibility
|
|
||||||
}
|
|
||||||
.clip(CircleShape)
|
|
||||||
.background(color.copy(alpha = 0.28f))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun CrashCard(report: String, onCopy: () -> Unit, onDismiss: () -> Unit) {
|
|
||||||
Card(
|
Card(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(20.dp),
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
|
||||||
) {
|
) {
|
||||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
@@ -565,74 +92,33 @@ private fun CrashCard(report: String, onCopy: () -> Unit, onDismiss: () -> Unit)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
// Hostname of strict Private DNS (DNS-over-TLS) on the current network, null when it is Automatic or Off.
|
||||||
private fun ProviderRow(
|
// Android reports the current state on registration and every change after it.
|
||||||
title: String,
|
internal fun privateDnsHosts(context: Context): Flow<String?> {
|
||||||
subtitle: String,
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return flowOf(null)
|
||||||
selected: Boolean,
|
val cm = context.applicationContext.getSystemService(ConnectivityManager::class.java) ?: return flowOf(null)
|
||||||
onPolicy: (() -> Unit)? = null,
|
return callbackFlow {
|
||||||
onClick: () -> Unit,
|
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||||
) {
|
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
|
||||||
val highlight by animateColorAsState(
|
trySend(linkProperties.privateDnsServerName)
|
||||||
if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.08f) else Color.Transparent,
|
|
||||||
animationSpec = Motion.color,
|
|
||||||
label = "highlight",
|
|
||||||
)
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.background(highlight)
|
|
||||||
.selectable(selected = selected, onClick = onClick, role = Role.RadioButton)
|
|
||||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
RadioButton(selected = selected, onClick = null)
|
|
||||||
Spacer(Modifier.width(12.dp))
|
|
||||||
Column(Modifier.weight(1f)) {
|
|
||||||
Text(title, style = MaterialTheme.typography.bodyLarge)
|
|
||||||
Text(
|
|
||||||
subtitle,
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
maxLines = 1,
|
|
||||||
overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (onPolicy != null) {
|
|
||||||
IconButton(onClick = onPolicy, modifier = Modifier.size(40.dp)) {
|
|
||||||
Icon(
|
|
||||||
painterResource(R.drawable.ic_policy),
|
|
||||||
contentDescription = stringResource(R.string.about_privacy_policy),
|
|
||||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
modifier = Modifier.size(18.dp),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
trySend(null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val registered = runCatching { cm.registerDefaultNetworkCallback(callback) }.isSuccess
|
||||||
|
awaitClose { if (registered) runCatching { cm.unregisterNetworkCallback(callback) } }
|
||||||
|
}.distinctUntilChanged()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
internal fun openNetworkSettings(context: Context) {
|
||||||
private fun RowDivider() {
|
|
||||||
HorizontalDivider(
|
|
||||||
modifier = Modifier.padding(start = 60.dp),
|
|
||||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hostname of strict Private DNS (DNS-over-TLS) on the current network, null when it is Automatic or Off
|
|
||||||
private fun readPrivateDnsHost(context: Context): String? {
|
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return null
|
|
||||||
val cm = context.getSystemService(ConnectivityManager::class.java) ?: return null
|
|
||||||
return runCatching { cm.getLinkProperties(cm.activeNetwork)?.privateDnsServerName }.getOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun openNetworkSettings(context: Context) {
|
|
||||||
runCatching {
|
runCatching {
|
||||||
context.startActivity(Intent(Settings.ACTION_WIRELESS_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
context.startActivity(Intent(Settings.ACTION_WIRELESS_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun hostOf(url: String): String =
|
internal fun hostOf(url: String): String =
|
||||||
runCatching { Uri.parse(url.trim()).host }.getOrNull()?.takeIf { it.isNotEmpty() } ?: url
|
runCatching { Uri.parse(url.trim()).host }.getOrNull()?.takeIf { it.isNotEmpty() } ?: url
|
||||||
|
|
||||||
internal fun sendAction(context: Context, action: String) {
|
internal fun sendAction(context: Context, action: String) {
|
||||||
@@ -640,7 +126,7 @@ internal fun sendAction(context: Context, action: String) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Runs from the app process, which is excluded from the VPN, so it tests the server directly
|
// Runs from the app process, which is excluded from the VPN, so it tests the server directly
|
||||||
private fun testProvider(context: Context, provider: DohProvider): TestResult {
|
internal fun testProvider(context: Context, provider: DohProvider): TestResult {
|
||||||
val client = DohClient(context, provider)
|
val client = DohClient(context, provider)
|
||||||
return try {
|
return try {
|
||||||
val t0 = SystemClock.elapsedRealtime()
|
val t0 = SystemClock.elapsedRealtime()
|
||||||
|
|||||||
@@ -1,301 +0,0 @@
|
|||||||
package cc.skysparkle.sparkledns
|
|
||||||
|
|
||||||
import android.widget.Toast
|
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.horizontalScroll
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.PaddingValues
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
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.layout.width
|
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
|
||||||
import androidx.compose.foundation.lazy.itemsIndexed
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material3.Card
|
|
||||||
import androidx.compose.material3.FilterChip
|
|
||||||
import androidx.compose.material3.HorizontalDivider
|
|
||||||
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.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
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.graphics.Color
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import java.text.SimpleDateFormat
|
|
||||||
import java.util.Date
|
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
private enum class MonitorFilter { ALL, BLOCKED, ERRORS }
|
|
||||||
|
|
||||||
private val TimeFormat = SimpleDateFormat("HH:mm:ss", Locale.ROOT)
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun MonitorScreen(modifier: Modifier = Modifier) {
|
|
||||||
val context = LocalContext.current
|
|
||||||
val scope = rememberCoroutineScope()
|
|
||||||
val custom by Blocklist.custom.collectAsState()
|
|
||||||
|
|
||||||
var entries by remember { mutableStateOf(QueryLog.snapshot()) }
|
|
||||||
var stats by remember { mutableStateOf(QueryLog.stats()) }
|
|
||||||
var filter by rememberSaveable { mutableStateOf(MonitorFilter.ALL) }
|
|
||||||
var search by rememberSaveable { mutableStateOf("") }
|
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
while (true) {
|
|
||||||
entries = QueryLog.snapshot()
|
|
||||||
stats = QueryLog.stats()
|
|
||||||
delay(1000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val visible = remember(entries, filter, search) {
|
|
||||||
val term = search.trim()
|
|
||||||
entries.filter { e ->
|
|
||||||
val matchesFilter = when (filter) {
|
|
||||||
MonitorFilter.ALL -> true
|
|
||||||
MonitorFilter.BLOCKED -> e.status == QueryStatus.BLOCKED
|
|
||||||
MonitorFilter.ERRORS -> e.status == QueryStatus.FAILED
|
|
||||||
}
|
|
||||||
matchesFilter && (term.isEmpty() || e.domain.contains(term, ignoreCase = true))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun toggleBlock(domain: String, unblock: Boolean) {
|
|
||||||
scope.launch {
|
|
||||||
val ok = withContext(Dispatchers.IO) {
|
|
||||||
if (unblock) {
|
|
||||||
Blocklist.removeCustom(context, domain)
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
Blocklist.addCustom(context, domain)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val message = when {
|
|
||||||
!ok -> context.getString(R.string.bl_invalid)
|
|
||||||
unblock -> context.getString(R.string.mon_unblocked, domain)
|
|
||||||
else -> context.getString(R.string.mon_blocked_added, domain)
|
|
||||||
}
|
|
||||||
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
LazyColumn(
|
|
||||||
modifier = modifier.fillMaxSize(),
|
|
||||||
contentPadding = PaddingValues(16.dp),
|
|
||||||
) {
|
|
||||||
item {
|
|
||||||
Card(Modifier.fillMaxWidth()) {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(vertical = 16.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
StatColumn(formatCount(stats.total), stringResource(R.string.mon_queries), Modifier.weight(1f))
|
|
||||||
StatDivider()
|
|
||||||
StatColumn(cachePercent(stats), stringResource(R.string.mon_cached), Modifier.weight(1f))
|
|
||||||
StatDivider()
|
|
||||||
StatColumn(formatCount(stats.blocked), stringResource(R.string.mon_blocked), Modifier.weight(1f))
|
|
||||||
StatDivider()
|
|
||||||
StatColumn(
|
|
||||||
stringResource(R.string.mon_ms, stats.avgLatencyMs),
|
|
||||||
stringResource(R.string.mon_latency),
|
|
||||||
Modifier.weight(1f),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
item {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(top = 12.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
// Chips scroll sideways on narrow screens instead of squeezing the clear button
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.weight(1f)
|
|
||||||
.horizontalScroll(rememberScrollState()),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
|
||||||
) {
|
|
||||||
FilterChip(
|
|
||||||
selected = filter == MonitorFilter.ALL,
|
|
||||||
onClick = { filter = MonitorFilter.ALL },
|
|
||||||
label = { Text(stringResource(R.string.mon_all)) },
|
|
||||||
)
|
|
||||||
FilterChip(
|
|
||||||
selected = filter == MonitorFilter.BLOCKED,
|
|
||||||
onClick = { filter = MonitorFilter.BLOCKED },
|
|
||||||
label = { Text(stringResource(R.string.status_blocked)) },
|
|
||||||
leadingIcon = { ChipIcon(R.drawable.ic_tab_block) },
|
|
||||||
)
|
|
||||||
FilterChip(
|
|
||||||
selected = filter == MonitorFilter.ERRORS,
|
|
||||||
onClick = { filter = MonitorFilter.ERRORS },
|
|
||||||
label = { Text(stringResource(R.string.mon_errors)) },
|
|
||||||
leadingIcon = { ChipIcon(R.drawable.ic_alert) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
IconButton(
|
|
||||||
onClick = {
|
|
||||||
QueryLog.clear()
|
|
||||||
entries = emptyList()
|
|
||||||
stats = QueryLog.stats()
|
|
||||||
},
|
|
||||||
enabled = entries.isNotEmpty() || stats.total > 0,
|
|
||||||
) {
|
|
||||||
Icon(painterResource(R.drawable.ic_clear), stringResource(R.string.mon_clear), Modifier.size(22.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
item {
|
|
||||||
OutlinedTextField(
|
|
||||||
value = search,
|
|
||||||
onValueChange = { search = it },
|
|
||||||
placeholder = { Text(stringResource(R.string.mon_search)) },
|
|
||||||
leadingIcon = { Icon(painterResource(R.drawable.ic_search), contentDescription = null) },
|
|
||||||
singleLine = true,
|
|
||||||
shape = RoundedCornerShape(50),
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(vertical = 12.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (visible.isEmpty()) {
|
|
||||||
item(key = "empty") {
|
|
||||||
val text = stringResource(if (entries.isEmpty()) R.string.mon_empty else R.string.mon_no_match)
|
|
||||||
Box(Modifier.animateItem()) { EmptyState(R.drawable.ic_tab_monitor, text) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
itemsIndexed(visible, key = { _, e -> e.id }) { index, entry ->
|
|
||||||
val inCustom = entry.domain in custom
|
|
||||||
QueryRow(
|
|
||||||
modifier = Modifier.animateItem(),
|
|
||||||
entry = entry,
|
|
||||||
first = index == 0,
|
|
||||||
last = index == visible.lastIndex,
|
|
||||||
showBlock = !inCustom && entry.status != QueryStatus.BLOCKED,
|
|
||||||
showUnblock = inCustom,
|
|
||||||
onBlock = { toggleBlock(entry.domain, unblock = false) },
|
|
||||||
onUnblock = { toggleBlock(entry.domain, unblock = true) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun ChipIcon(icon: Int) {
|
|
||||||
Icon(painterResource(icon), contentDescription = null, modifier = Modifier.size(18.dp))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun EmptyState(icon: Int, text: String) {
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(vertical = 40.dp),
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
) {
|
|
||||||
IconBadge(icon, MaterialTheme.colorScheme.onSurfaceVariant, size = 64.dp)
|
|
||||||
Spacer(Modifier.height(12.dp))
|
|
||||||
Text(
|
|
||||||
text,
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun QueryRow(
|
|
||||||
modifier: Modifier,
|
|
||||||
entry: QueryEntry,
|
|
||||||
first: Boolean,
|
|
||||||
last: Boolean,
|
|
||||||
showBlock: Boolean,
|
|
||||||
showUnblock: Boolean,
|
|
||||||
onBlock: () -> Unit,
|
|
||||||
onUnblock: () -> Unit,
|
|
||||||
) {
|
|
||||||
val (icon, color: Color) = when (entry.status) {
|
|
||||||
QueryStatus.OK -> R.drawable.ic_check to MaterialTheme.colorScheme.primary
|
|
||||||
QueryStatus.CACHED -> R.drawable.ic_check to CachedColor
|
|
||||||
QueryStatus.BLOCKED -> R.drawable.ic_tab_block to MaterialTheme.colorScheme.error
|
|
||||||
QueryStatus.FAILED -> R.drawable.ic_alert to WarningColor
|
|
||||||
}
|
|
||||||
val label = when (entry.status) {
|
|
||||||
QueryStatus.OK -> stringResource(R.string.mon_ms, entry.latencyMs)
|
|
||||||
QueryStatus.CACHED -> stringResource(R.string.status_cached)
|
|
||||||
QueryStatus.BLOCKED -> stringResource(R.string.status_blocked)
|
|
||||||
QueryStatus.FAILED -> stringResource(R.string.status_failed)
|
|
||||||
}
|
|
||||||
|
|
||||||
Column(
|
|
||||||
modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.background(groupedBackground, groupedShape(first, last))
|
|
||||||
) {
|
|
||||||
if (!first) {
|
|
||||||
HorizontalDivider(
|
|
||||||
modifier = Modifier.padding(start = 60.dp),
|
|
||||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(start = 12.dp, end = 4.dp, top = 8.dp, bottom = 8.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
IconBadge(icon, color, size = 36.dp)
|
|
||||||
Spacer(Modifier.width(12.dp))
|
|
||||||
Column(Modifier.weight(1f)) {
|
|
||||||
Text(entry.domain, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
|
||||||
Text(
|
|
||||||
"${TimeFormat.format(Date(entry.time))} · ${DnsMessage.typeName(entry.type)}",
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
Pill(label, color)
|
|
||||||
when {
|
|
||||||
showBlock -> IconButton(onClick = onBlock) {
|
|
||||||
Icon(painterResource(R.drawable.ic_tab_block), stringResource(R.string.mon_block), Modifier.size(20.dp))
|
|
||||||
}
|
|
||||||
showUnblock -> IconButton(onClick = onUnblock) {
|
|
||||||
Icon(painterResource(R.drawable.ic_check), stringResource(R.string.mon_unblock), Modifier.size(20.dp))
|
|
||||||
}
|
|
||||||
else -> Spacer(Modifier.width(48.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,10 +5,6 @@ import android.content.Context
|
|||||||
class Prefs(context: Context) {
|
class Prefs(context: Context) {
|
||||||
private val sp = context.applicationContext.getSharedPreferences("doh", Context.MODE_PRIVATE)
|
private val sp = context.applicationContext.getSharedPreferences("doh", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
init {
|
|
||||||
ServerList.ensureLoaded(context.applicationContext)
|
|
||||||
}
|
|
||||||
|
|
||||||
var providerId: String
|
var providerId: String
|
||||||
get() = sp.getString(KEY_PROVIDER, null) ?: Providers.default.id
|
get() = sp.getString(KEY_PROVIDER, null) ?: Providers.default.id
|
||||||
set(value) = sp.edit().putString(KEY_PROVIDER, value).apply()
|
set(value) = sp.edit().putString(KEY_PROVIDER, value).apply()
|
||||||
@@ -29,6 +25,15 @@ class Prefs(context: Context) {
|
|||||||
get() = sp.getStringSet(KEY_EXCLUDED, null)?.toSet() ?: emptySet()
|
get() = sp.getStringSet(KEY_EXCLUDED, null)?.toSet() ?: emptySet()
|
||||||
set(value) = sp.edit().putStringSet(KEY_EXCLUDED, value).apply()
|
set(value) = sp.edit().putStringSet(KEY_EXCLUDED, value).apply()
|
||||||
|
|
||||||
|
var updateInterval: UpdateInterval
|
||||||
|
get() = UpdateInterval.entries.getOrNull(sp.getInt(KEY_UPDATE_INTERVAL, UpdateInterval.DAILY.ordinal))
|
||||||
|
?: UpdateInterval.DAILY
|
||||||
|
set(value) = sp.edit().putInt(KEY_UPDATE_INTERVAL, value.ordinal).apply()
|
||||||
|
|
||||||
|
var updateWifiOnly: Boolean
|
||||||
|
get() = sp.getBoolean(KEY_UPDATE_WIFI_ONLY, true)
|
||||||
|
set(value) = sp.edit().putBoolean(KEY_UPDATE_WIFI_ONLY, value).apply()
|
||||||
|
|
||||||
// Hint cards the user closed with the X
|
// Hint cards the user closed with the X
|
||||||
fun isHintDismissed(key: String): Boolean =
|
fun isHintDismissed(key: String): Boolean =
|
||||||
sp.getStringSet(KEY_HINTS, null)?.contains(key) == true
|
sp.getStringSet(KEY_HINTS, null)?.contains(key) == true
|
||||||
@@ -58,5 +63,7 @@ class Prefs(context: Context) {
|
|||||||
const val KEY_EXCLUDED = "excluded_apps"
|
const val KEY_EXCLUDED = "excluded_apps"
|
||||||
const val KEY_HINTS = "dismissed_hints"
|
const val KEY_HINTS = "dismissed_hints"
|
||||||
const val KEY_PRIVATE_DNS = "dismissed_private_dns"
|
const val KEY_PRIVATE_DNS = "dismissed_private_dns"
|
||||||
|
const val KEY_UPDATE_INTERVAL = "update_interval"
|
||||||
|
const val KEY_UPDATE_WIFI_ONLY = "update_wifi_only"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,6 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
|
||||||
import okhttp3.OkHttpClient
|
|
||||||
import okhttp3.Request
|
|
||||||
import java.io.File
|
|
||||||
import java.io.IOException
|
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
|
|
||||||
data class DohProvider(
|
data class DohProvider(
|
||||||
val id: String,
|
val id: String,
|
||||||
@@ -17,13 +9,14 @@ data class DohProvider(
|
|||||||
val bootstrap: List<String> = emptyList(),
|
val bootstrap: List<String> = emptyList(),
|
||||||
val http3: Boolean = false,
|
val http3: Boolean = false,
|
||||||
val policy: String? = null,
|
val policy: String? = null,
|
||||||
|
val donate: String? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
object Providers {
|
object Providers {
|
||||||
const val CUSTOM_ID = "custom"
|
const val CUSTOM_ID = "custom"
|
||||||
const val DEFAULT_ID = "skysparkle"
|
const val DEFAULT_ID = "skysparkle"
|
||||||
|
|
||||||
// Shipped with the app and used until the list from the repository is downloaded
|
// Servers ship with the app; new ones arrive with app updates
|
||||||
val builtIn = listOf(
|
val builtIn = listOf(
|
||||||
DohProvider(
|
DohProvider(
|
||||||
"skysparkle", "SkySparkle", "https://blog.skysparkle.cc/dns-query",
|
"skysparkle", "SkySparkle", "https://blog.skysparkle.cc/dns-query",
|
||||||
@@ -32,11 +25,13 @@ object Providers {
|
|||||||
DohProvider(
|
DohProvider(
|
||||||
"quad9", "Quad9", "https://dns.quad9.net/dns-query", listOf("9.9.9.9", "149.112.112.112"),
|
"quad9", "Quad9", "https://dns.quad9.net/dns-query", listOf("9.9.9.9", "149.112.112.112"),
|
||||||
policy = "https://quad9.net/service/privacy/",
|
policy = "https://quad9.net/service/privacy/",
|
||||||
|
donate = "https://quad9.net/donate/",
|
||||||
),
|
),
|
||||||
DohProvider(
|
DohProvider(
|
||||||
"digitale-gesellschaft", "Digitale Gesellschaft", "https://dns.digitale-gesellschaft.ch/dns-query",
|
"digitale-gesellschaft", "Digitale Gesellschaft", "https://dns.digitale-gesellschaft.ch/dns-query",
|
||||||
listOf("185.95.218.42", "185.95.218.43"), http3 = true,
|
listOf("185.95.218.42", "185.95.218.43"), http3 = true,
|
||||||
policy = "https://www.digitale-gesellschaft.ch/dns/",
|
policy = "https://www.digitale-gesellschaft.ch/dns/",
|
||||||
|
donate = "https://www.digitale-gesellschaft.ch/uber-uns/unterstuetzer-werden/",
|
||||||
),
|
),
|
||||||
DohProvider(
|
DohProvider(
|
||||||
"uncensoreddns", "UncensoredDNS", "https://anycast.uncensoreddns.org/dns-query", listOf("91.239.100.100"),
|
"uncensoreddns", "UncensoredDNS", "https://anycast.uncensoreddns.org/dns-query", listOf("91.239.100.100"),
|
||||||
@@ -46,10 +41,11 @@ object Providers {
|
|||||||
"ffmuc", "Freifunk München", "https://doh.ffmuc.net/dns-query",
|
"ffmuc", "Freifunk München", "https://doh.ffmuc.net/dns-query",
|
||||||
listOf("5.1.66.255", "185.150.99.255"), http3 = true,
|
listOf("5.1.66.255", "185.150.99.255"), http3 = true,
|
||||||
policy = "https://ffmuc.net/dns-privacy/",
|
policy = "https://ffmuc.net/dns-privacy/",
|
||||||
|
donate = "https://spende.ffmuc.net/",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
val list: List<DohProvider> get() = ServerList.servers.value
|
val list: List<DohProvider> get() = builtIn
|
||||||
|
|
||||||
// The project's own server stays the default whatever order the list uses
|
// The project's own server stays the default whatever order the list uses
|
||||||
val default: DohProvider get() = list.firstOrNull { it.id == DEFAULT_ID } ?: list.first()
|
val default: DohProvider get() = list.firstOrNull { it.id == DEFAULT_ID } ?: list.first()
|
||||||
@@ -57,100 +53,6 @@ object Providers {
|
|||||||
fun byId(id: String): DohProvider = list.firstOrNull { it.id == id } ?: default
|
fun byId(id: String): DohProvider = list.firstOrNull { it.id == id } ?: default
|
||||||
}
|
}
|
||||||
|
|
||||||
// The server list kept in the project repository, so servers can change without an app update
|
|
||||||
object ServerList {
|
|
||||||
const val SOURCE = "https://git.skysparkle.cc/kalarina/Sparkledns/raw/branch/main/servers/servers.txt"
|
|
||||||
private const val FILE = "servers.txt"
|
|
||||||
private const val MAX_BYTES = 64 * 1024
|
|
||||||
private const val MAX_SERVERS = 50
|
|
||||||
|
|
||||||
private val _servers = MutableStateFlow(Providers.builtIn)
|
|
||||||
val servers: StateFlow<List<DohProvider>> = _servers
|
|
||||||
|
|
||||||
@Volatile private var loaded = false
|
|
||||||
|
|
||||||
private val client by lazy {
|
|
||||||
OkHttpClient.Builder()
|
|
||||||
.connectTimeout(15, TimeUnit.SECONDS)
|
|
||||||
.readTimeout(30, TimeUnit.SECONDS)
|
|
||||||
.build()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun ensureLoaded(context: Context) {
|
|
||||||
if (loaded) return
|
|
||||||
synchronized(this) {
|
|
||||||
if (loaded) return
|
|
||||||
val cached = runCatching { File(context.filesDir, FILE).readText() }.getOrNull()
|
|
||||||
cached?.let(::parse)?.takeIf { it.isNotEmpty() }?.let { _servers.value = it }
|
|
||||||
loaded = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Blocking: call off the main thread. Returns the number of servers in the new list.
|
|
||||||
fun sync(context: Context): Int {
|
|
||||||
val request = Request.Builder().url(SOURCE).build()
|
|
||||||
val text = client.newCall(request).execute().use { response ->
|
|
||||||
if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
|
|
||||||
val body = response.body ?: throw IOException("Empty response")
|
|
||||||
if (body.contentLength() > MAX_BYTES) throw IOException("List too large")
|
|
||||||
val bytes = body.byteStream().readNBytesCompat(MAX_BYTES + 1)
|
|
||||||
if (bytes.size > MAX_BYTES) throw IOException("List too large")
|
|
||||||
String(bytes, Charsets.UTF_8)
|
|
||||||
}
|
|
||||||
val parsed = parse(text)
|
|
||||||
if (parsed.isEmpty()) throw IOException("No servers found")
|
|
||||||
val file = File(context.filesDir, FILE)
|
|
||||||
val tmp = File(context.filesDir, "$FILE.tmp")
|
|
||||||
tmp.writeText(text)
|
|
||||||
if (!tmp.renameTo(file)) {
|
|
||||||
tmp.delete()
|
|
||||||
throw IOException("Cannot save list")
|
|
||||||
}
|
|
||||||
_servers.value = parsed
|
|
||||||
loaded = true
|
|
||||||
return parsed.size
|
|
||||||
}
|
|
||||||
|
|
||||||
// Format per line: Name | DoH URL | privacy policy URL | h3 (optional). See CONTRIBUTING.md.
|
|
||||||
fun parse(text: String): List<DohProvider> {
|
|
||||||
val builtInByHost = Providers.builtIn.associateBy { it.url.toHttpUrlOrNull()?.host }
|
|
||||||
val seen = HashSet<String>()
|
|
||||||
val result = ArrayList<DohProvider>()
|
|
||||||
for (raw in text.lineSequence()) {
|
|
||||||
val line = raw.trim()
|
|
||||||
if (line.isEmpty() || line.startsWith("#")) continue
|
|
||||||
val cols = line.split('|').map { it.trim() }
|
|
||||||
if (cols.size < 3) continue
|
|
||||||
val name = cols[0].take(40)
|
|
||||||
val url = cols[1].toHttpUrlOrNull()
|
|
||||||
val policy = cols[2].takeIf { it.toHttpUrlOrNull()?.isHttps == true }
|
|
||||||
if (name.isEmpty() || url == null || !url.isHttps) continue
|
|
||||||
// Shipped servers keep their address and id, so an edited list cannot redirect them
|
|
||||||
val pinned = builtInByHost[url.host]
|
|
||||||
val server = pinned
|
|
||||||
?: if (policy == null) continue
|
|
||||||
else DohProvider(url.host, name, cols[1], http3 = cols.getOrElse(3) { "" }.equals("h3", ignoreCase = true), policy = policy)
|
|
||||||
if (!seen.add(server.id)) continue
|
|
||||||
result += server
|
|
||||||
if (result.size >= MAX_SERVERS) break
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun java.io.InputStream.readNBytesCompat(limit: Int): ByteArray {
|
|
||||||
val out = java.io.ByteArrayOutputStream()
|
|
||||||
val buffer = ByteArray(8192)
|
|
||||||
var total = 0
|
|
||||||
while (total < limit) {
|
|
||||||
val read = read(buffer, 0, minOf(buffer.size, limit - total))
|
|
||||||
if (read < 0) break
|
|
||||||
out.write(buffer, 0, read)
|
|
||||||
total += read
|
|
||||||
}
|
|
||||||
return out.toByteArray()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun parseIps(raw: String): List<String> =
|
fun parseIps(raw: String): List<String> =
|
||||||
raw.split(',', ';', ' ').map { it.trim() }.filter { it.isNotEmpty() }
|
raw.split(',', ';', ' ').map { it.trim() }.filter { it.isNotEmpty() }
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
package cc.skysparkle.sparkledns
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.transform
|
||||||
|
|
||||||
enum class QueryStatus { OK, CACHED, BLOCKED, FAILED }
|
enum class QueryStatus { OK, CACHED, BLOCKED, FAILED }
|
||||||
|
|
||||||
class QueryEntry(
|
class QueryEntry(
|
||||||
@@ -19,7 +24,8 @@ data class QueryStats(
|
|||||||
val avgLatencyMs: Int,
|
val avgLatencyMs: Int,
|
||||||
)
|
)
|
||||||
|
|
||||||
// In-memory only: nothing is written to disk or sent anywhere
|
// In-memory only: nothing is written to disk or sent anywhere. StatsStore keeps hourly
|
||||||
|
// numbers without domains for the charts.
|
||||||
object QueryLog {
|
object QueryLog {
|
||||||
private const val MAX_ENTRIES = 500
|
private const val MAX_ENTRIES = 500
|
||||||
|
|
||||||
@@ -31,6 +37,14 @@ object QueryLog {
|
|||||||
private var failed = 0L
|
private var failed = 0L
|
||||||
private var latencySum = 0L
|
private var latencySum = 0L
|
||||||
private var latencyCount = 0L
|
private var latencyCount = 0L
|
||||||
|
private val version = MutableStateFlow(0L)
|
||||||
|
|
||||||
|
// Fires right away, then at most once a second while queries keep coming: a busy log refreshes
|
||||||
|
// the screen no more often than the old one-second polling did, and an idle one not at all
|
||||||
|
fun changes(): Flow<Long> = version.transform {
|
||||||
|
emit(it)
|
||||||
|
delay(1000)
|
||||||
|
}
|
||||||
|
|
||||||
fun add(question: DnsMessage.Question?, status: QueryStatus, latencyMs: Int) {
|
fun add(question: DnsMessage.Question?, status: QueryStatus, latencyMs: Int) {
|
||||||
if (question == null) return
|
if (question == null) return
|
||||||
@@ -46,7 +60,10 @@ object QueryLog {
|
|||||||
QueryStatus.BLOCKED -> blocked++
|
QueryStatus.BLOCKED -> blocked++
|
||||||
QueryStatus.FAILED -> failed++
|
QueryStatus.FAILED -> failed++
|
||||||
}
|
}
|
||||||
|
version.value++
|
||||||
}
|
}
|
||||||
|
// Hourly numbers for the charts; outside the lock above, as it takes a lock of its own
|
||||||
|
StatsStore.record(status, latencyMs, Companies.of(question.name))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Newest first. Builds a real copy: on API 35+ List.reversed() resolves to a live JDK view,
|
// Newest first. Builds a real copy: on API 35+ List.reversed() resolves to a live JDK view,
|
||||||
@@ -67,5 +84,6 @@ object QueryLog {
|
|||||||
fun clear() {
|
fun clear() {
|
||||||
entries.clear()
|
entries.clear()
|
||||||
total = 0; cached = 0; blocked = 0; failed = 0; latencySum = 0; latencyCount = 0
|
total = 0; cached = 0; blocked = 0; failed = 0; latencySum = 0; latencyCount = 0
|
||||||
|
version.value++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,340 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.animateColorAsState
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
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.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.selection.selectable
|
||||||
|
import androidx.compose.foundation.selection.toggleable
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
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.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SettingsScreen(
|
||||||
|
bottomPadding: Dp,
|
||||||
|
onOpenApps: () -> Unit,
|
||||||
|
onOpenAbout: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val prefs = remember { Prefs(context) }
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val active by DohVpnService.active.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
var selected by remember { mutableStateOf(prefs.providerId) }
|
||||||
|
var customUrl by remember { mutableStateOf(prefs.customUrl) }
|
||||||
|
var customBootstrap by remember { mutableStateOf(prefs.customBootstrap) }
|
||||||
|
var customHttp3 by remember { mutableStateOf(prefs.customHttp3) }
|
||||||
|
var testResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) }
|
||||||
|
var shownResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) } // kept while the card animates out
|
||||||
|
var testing by remember { mutableStateOf(false) }
|
||||||
|
val excludedCount = remember { prefs.excludedApps.size }
|
||||||
|
|
||||||
|
val isCustom = selected == Providers.CUSTOM_ID
|
||||||
|
val customValid = remember(customUrl) { customUrl.trim().toHttpUrlOrNull()?.isHttps == true }
|
||||||
|
val canConnect = !isCustom || customValid
|
||||||
|
val selectedProvider = remember(selected, customUrl, customBootstrap, customHttp3) { prefs.resolve() }
|
||||||
|
|
||||||
|
// Picking a server never touches a live connection; switching is an explicit action
|
||||||
|
val pendingSwitch = active?.let { it != selectedProvider && canConnect } == true
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
LaunchedEffect(active) { busy = false }
|
||||||
|
LaunchedEffect(busy) {
|
||||||
|
if (busy) {
|
||||||
|
delay(BUSY_TIMEOUT_MS)
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun select(id: String) {
|
||||||
|
selected = id
|
||||||
|
prefs.providerId = id
|
||||||
|
testResult = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun runTest() {
|
||||||
|
val provider = prefs.resolve()
|
||||||
|
testing = true
|
||||||
|
testResult = null
|
||||||
|
scope.launch {
|
||||||
|
val result = withContext(Dispatchers.IO) { testProvider(context, provider) }
|
||||||
|
shownResult = result
|
||||||
|
testResult = result
|
||||||
|
testing = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = modifier
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
.padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = bottomPadding),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||||
|
) {
|
||||||
|
ScreenTitle(stringResource(R.string.tab_settings), Modifier.heightIn(min = 44.dp))
|
||||||
|
|
||||||
|
SectionLabel(stringResource(R.string.servers), Modifier.padding(top = 8.dp))
|
||||||
|
Column(Modifier.fillMaxWidth().appCard()) {
|
||||||
|
Providers.list.forEachIndexed { index, provider ->
|
||||||
|
if (index > 0) ListDivider()
|
||||||
|
ServerRow(
|
||||||
|
title = provider.name,
|
||||||
|
subtitle = hostOf(provider.url) + if (provider.http3) " · HTTP/3" else "",
|
||||||
|
selected = selected == provider.id,
|
||||||
|
onPolicy = provider.policy?.let { url -> { openUrl(context, url) } },
|
||||||
|
onDonate = provider.donate?.let { url -> { openUrl(context, url) } },
|
||||||
|
onClick = { select(provider.id) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
ListDivider()
|
||||||
|
ServerRow(
|
||||||
|
title = stringResource(R.string.custom),
|
||||||
|
subtitle = if (customUrl.trim() == "https://" || customUrl.isBlank()) "DNS-over-HTTPS (RFC 8484)" else hostOf(customUrl),
|
||||||
|
selected = isCustom,
|
||||||
|
onClick = { select(Providers.CUSTOM_ID) },
|
||||||
|
)
|
||||||
|
AnimatedVisibility(visible = isCustom, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
|
Column(
|
||||||
|
Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = customUrl,
|
||||||
|
onValueChange = { customUrl = it; prefs.customUrl = it },
|
||||||
|
label = { Text(stringResource(R.string.custom_url)) },
|
||||||
|
singleLine = true,
|
||||||
|
isError = !customValid,
|
||||||
|
shape = RoundedCornerShape(14.dp),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Next),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
if (!customValid) {
|
||||||
|
Text(stringResource(R.string.invalid_url), color = Palette.Blocked, fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
OutlinedTextField(
|
||||||
|
value = customBootstrap,
|
||||||
|
onValueChange = { customBootstrap = it; prefs.customBootstrap = it },
|
||||||
|
label = { Text(stringResource(R.string.custom_bootstrap)) },
|
||||||
|
singleLine = true,
|
||||||
|
shape = RoundedCornerShape(14.dp),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.toggleable(
|
||||||
|
value = customHttp3,
|
||||||
|
role = Role.Switch,
|
||||||
|
onValueChange = { customHttp3 = it; prefs.customHttp3 = it },
|
||||||
|
)
|
||||||
|
.padding(vertical = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(stringResource(R.string.http3), color = Palette.Fg, fontSize = 15.sp)
|
||||||
|
Text(stringResource(R.string.http3_note), color = Palette.Fg3, fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
AppSwitch(checked = customHttp3, onCheckedChange = null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = ::runTest,
|
||||||
|
enabled = !testing && canConnect,
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
modifier = Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.height(48.dp),
|
||||||
|
) { Text(stringResource(if (testing) R.string.testing else R.string.test), maxLines = 1) }
|
||||||
|
|
||||||
|
// Remembers the last name so the button keeps its label while it animates out
|
||||||
|
val lastSwitch = remember { arrayOf("") }
|
||||||
|
if (pendingSwitch) lastSwitch[0] = selectedProvider.displayName(context)
|
||||||
|
AnimatedVisibility(visible = pendingSwitch, modifier = Modifier.weight(1f)) {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
if (!busy) {
|
||||||
|
busy = true
|
||||||
|
sendAction(context, DohVpnService.ACTION_START)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enabled = !busy,
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(48.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.switch_to, lastSwitch[0]),
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
AnimatedVisibility(visible = testResult != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||||
|
shownResult?.let { result ->
|
||||||
|
HintCard(
|
||||||
|
text = result.text,
|
||||||
|
icon = if (result.ok) R.drawable.ic_check else R.drawable.ic_alert,
|
||||||
|
tint = if (result.ok) CachedColor else Palette.Blocked,
|
||||||
|
onDismiss = { testResult = null },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SectionLabel(stringResource(R.string.settings_general), Modifier.padding(top = 8.dp))
|
||||||
|
Column(Modifier.fillMaxWidth().appCard()) {
|
||||||
|
NavRow(
|
||||||
|
title = stringResource(R.string.settings_apps),
|
||||||
|
subtitle = if (excludedCount > 0) stringResource(R.string.apps_count, excludedCount)
|
||||||
|
else stringResource(R.string.settings_apps_desc),
|
||||||
|
onClick = onOpenApps,
|
||||||
|
)
|
||||||
|
ListDivider()
|
||||||
|
NavRow(
|
||||||
|
title = stringResource(R.string.tab_about),
|
||||||
|
subtitle = "${stringResource(R.string.about_version)} ${BuildConfig.VERSION_NAME}",
|
||||||
|
onClick = onOpenAbout,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ServerRow(
|
||||||
|
title: String,
|
||||||
|
subtitle: String,
|
||||||
|
selected: Boolean,
|
||||||
|
onPolicy: (() -> Unit)? = null,
|
||||||
|
onDonate: (() -> Unit)? = null,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
) {
|
||||||
|
val highlight by animateColorAsState(
|
||||||
|
if (selected) Palette.Accent.copy(alpha = 0.06f) else Color.Transparent,
|
||||||
|
animationSpec = Motion.color,
|
||||||
|
label = "highlight",
|
||||||
|
)
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.background(highlight)
|
||||||
|
.selectable(selected = selected, onClick = onClick, role = Role.RadioButton)
|
||||||
|
.heightIn(min = 60.dp)
|
||||||
|
.padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
color = Palette.Fg,
|
||||||
|
fontSize = 15.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Text(subtitle, color = Palette.Fg3, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
if (onDonate != null) {
|
||||||
|
IconButton(onClick = onDonate, modifier = Modifier.size(40.dp)) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_donate),
|
||||||
|
contentDescription = stringResource(R.string.donate),
|
||||||
|
tint = Palette.Fg3,
|
||||||
|
modifier = Modifier.size(18.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (onPolicy != null) {
|
||||||
|
IconButton(onClick = onPolicy, modifier = Modifier.size(40.dp)) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_policy),
|
||||||
|
contentDescription = stringResource(R.string.about_privacy_policy),
|
||||||
|
tint = Palette.Fg3,
|
||||||
|
modifier = Modifier.size(18.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(4.dp))
|
||||||
|
if (selected) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_check),
|
||||||
|
contentDescription = null,
|
||||||
|
tint = Palette.Accent,
|
||||||
|
modifier = Modifier.size(22.dp),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Spacer(Modifier.size(22.dp))
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun NavRow(title: String, subtitle: String, onClick: () -> Unit) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable(onClick = onClick)
|
||||||
|
.heightIn(min = 60.dp)
|
||||||
|
.padding(start = 16.dp, end = 12.dp, top = 10.dp, bottom = 10.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(title, color = Palette.Fg, fontSize = 15.sp, fontWeight = FontWeight.Bold)
|
||||||
|
Text(subtitle, color = Palette.Fg3, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
Chevron()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import java.io.BufferedInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.DataInputStream
|
||||||
|
import java.io.DataOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileInputStream
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
|
||||||
|
class StatsSummary(
|
||||||
|
val total: Long,
|
||||||
|
val blocked: Long,
|
||||||
|
val cached: Long,
|
||||||
|
val avgLatencyMs: Int,
|
||||||
|
// Requests per company, indexed by Company.ordinal
|
||||||
|
val companies: LongArray,
|
||||||
|
)
|
||||||
|
|
||||||
|
class HourPoint(val total: Long, val blocked: Long)
|
||||||
|
|
||||||
|
// Hourly counters of the last 7 days for the charts. Only numbers are kept, never domains,
|
||||||
|
// and they never leave the device.
|
||||||
|
object StatsStore {
|
||||||
|
private const val HOURS = 24 * 7
|
||||||
|
private const val HOUR_MS = 3_600_000L
|
||||||
|
private const val FORMAT = 1
|
||||||
|
private const val FILE = "stats.bin"
|
||||||
|
private const val SAVE_INTERVAL_MS = 60_000L
|
||||||
|
|
||||||
|
// Per hour: total, blocked, cached, latency sum and count, then one counter per company
|
||||||
|
private const val TOTAL = 0
|
||||||
|
private const val BLOCKED = 1
|
||||||
|
private const val CACHED = 2
|
||||||
|
private const val LATENCY_SUM = 3
|
||||||
|
private const val LATENCY_COUNT = 4
|
||||||
|
private const val FIRST_COMPANY = 5
|
||||||
|
private val FIELDS = FIRST_COMPANY + Company.entries.size
|
||||||
|
|
||||||
|
// A ring of slots; each remembers which hour (since the epoch) it currently holds
|
||||||
|
private val hourIds = LongArray(HOURS) { -1L }
|
||||||
|
private val counters = Array(HOURS) { LongArray(FIELDS) }
|
||||||
|
private var file: File? = null
|
||||||
|
|
||||||
|
// Bumped when the numbers change without a new query: loaded from disk or cleared
|
||||||
|
private val _version = MutableStateFlow(0)
|
||||||
|
val version: StateFlow<Int> = _version
|
||||||
|
private var lastSave = 0L
|
||||||
|
private var dirty = false
|
||||||
|
|
||||||
|
// Saves happen off the VPN threads, one at a time
|
||||||
|
private val writer = Executors.newSingleThreadExecutor { Thread(it, "stats-writer").apply { isDaemon = true } }
|
||||||
|
|
||||||
|
fun init(context: Context) {
|
||||||
|
val target = File(context.filesDir, FILE)
|
||||||
|
synchronized(this) {
|
||||||
|
file = target
|
||||||
|
load(target)
|
||||||
|
}
|
||||||
|
_version.value++
|
||||||
|
}
|
||||||
|
|
||||||
|
fun record(status: QueryStatus, latencyMs: Int, company: Company?, now: Long = System.currentTimeMillis()) {
|
||||||
|
val snapshot = synchronized(this) {
|
||||||
|
val row = row(now / HOUR_MS)
|
||||||
|
row[TOTAL]++
|
||||||
|
when (status) {
|
||||||
|
QueryStatus.BLOCKED -> row[BLOCKED]++
|
||||||
|
QueryStatus.CACHED -> row[CACHED]++
|
||||||
|
QueryStatus.OK -> {
|
||||||
|
row[LATENCY_SUM] += latencyMs.toLong()
|
||||||
|
row[LATENCY_COUNT]++
|
||||||
|
}
|
||||||
|
QueryStatus.FAILED -> Unit
|
||||||
|
}
|
||||||
|
if (company != null) row[FIRST_COMPANY + company.ordinal]++
|
||||||
|
dirty = true
|
||||||
|
if (file != null && now - lastSave >= SAVE_INTERVAL_MS) {
|
||||||
|
lastSave = now
|
||||||
|
dirty = false
|
||||||
|
encode()
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
snapshot?.let(::save)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Totals of the last [hours] hours, the current one included
|
||||||
|
fun summary(hours: Int, now: Long = System.currentTimeMillis()): StatsSummary = synchronized(this) {
|
||||||
|
val current = now / HOUR_MS
|
||||||
|
val sums = LongArray(FIELDS)
|
||||||
|
for (back in 0 until hours.coerceIn(1, HOURS)) {
|
||||||
|
val id = current - back
|
||||||
|
val index = slot(id)
|
||||||
|
if (hourIds[index] != id) continue
|
||||||
|
val row = counters[index]
|
||||||
|
for (field in 0 until FIELDS) sums[field] += row[field]
|
||||||
|
}
|
||||||
|
StatsSummary(
|
||||||
|
total = sums[TOTAL],
|
||||||
|
blocked = sums[BLOCKED],
|
||||||
|
cached = sums[CACHED],
|
||||||
|
avgLatencyMs = if (sums[LATENCY_COUNT] == 0L) 0 else (sums[LATENCY_SUM] / sums[LATENCY_COUNT]).toInt(),
|
||||||
|
companies = sums.copyOfRange(FIRST_COMPANY, FIELDS),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// One point per hour, oldest first, ending with the current hour
|
||||||
|
fun hourly(hours: Int, now: Long = System.currentTimeMillis()): List<HourPoint> = synchronized(this) {
|
||||||
|
val count = hours.coerceIn(1, HOURS)
|
||||||
|
val current = now / HOUR_MS
|
||||||
|
List(count) { position ->
|
||||||
|
val id = current - (count - 1 - position)
|
||||||
|
val index = slot(id)
|
||||||
|
if (hourIds[index] == id) HourPoint(counters[index][TOTAL], counters[index][BLOCKED]) else HourPoint(0, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
val snapshot = synchronized(this) {
|
||||||
|
hourIds.fill(-1L)
|
||||||
|
counters.forEach { it.fill(0L) }
|
||||||
|
dirty = false
|
||||||
|
lastSave = System.currentTimeMillis()
|
||||||
|
if (file != null) encode() else null
|
||||||
|
}
|
||||||
|
snapshot?.let(::save)
|
||||||
|
_version.value++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Saves what is not on disk yet; called when the VPN stops
|
||||||
|
fun flush() {
|
||||||
|
val snapshot = synchronized(this) {
|
||||||
|
if (file != null && dirty) {
|
||||||
|
dirty = false
|
||||||
|
lastSave = System.currentTimeMillis()
|
||||||
|
encode()
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
snapshot?.let(::save)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun slot(id: Long): Int = (((id % HOURS) + HOURS) % HOURS).toInt()
|
||||||
|
|
||||||
|
private fun row(id: Long): LongArray {
|
||||||
|
val index = slot(id)
|
||||||
|
if (hourIds[index] != id) {
|
||||||
|
hourIds[index] = id
|
||||||
|
counters[index].fill(0L)
|
||||||
|
}
|
||||||
|
return counters[index]
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun encode(): ByteArray {
|
||||||
|
val bytes = ByteArrayOutputStream()
|
||||||
|
DataOutputStream(bytes).use { out ->
|
||||||
|
out.writeInt(FORMAT)
|
||||||
|
out.writeInt(FIELDS)
|
||||||
|
out.writeInt(HOURS)
|
||||||
|
for (index in 0 until HOURS) {
|
||||||
|
out.writeLong(hourIds[index])
|
||||||
|
counters[index].forEach { out.writeLong(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bytes.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun save(bytes: ByteArray) {
|
||||||
|
val target = file ?: return
|
||||||
|
writer.execute {
|
||||||
|
try {
|
||||||
|
val tmp = File(target.parentFile, "$FILE.tmp")
|
||||||
|
tmp.writeBytes(bytes)
|
||||||
|
if (!tmp.renameTo(target)) tmp.delete()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w("SparkleDNS", "Cannot save statistics", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Files from a version with fewer companies load fine: the new counters start at zero
|
||||||
|
private fun load(source: File) {
|
||||||
|
if (!source.exists()) return
|
||||||
|
try {
|
||||||
|
DataInputStream(BufferedInputStream(FileInputStream(source))).use { input ->
|
||||||
|
if (input.readInt() != FORMAT) return
|
||||||
|
val fields = input.readInt()
|
||||||
|
if (input.readInt() != HOURS || fields < FIRST_COMPANY) return
|
||||||
|
for (index in 0 until HOURS) {
|
||||||
|
hourIds[index] = input.readLong()
|
||||||
|
for (field in 0 until fields) {
|
||||||
|
val value = input.readLong()
|
||||||
|
if (field < FIELDS) counters[index][field] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w("SparkleDNS", "Cannot read statistics", e)
|
||||||
|
hourIds.fill(-1L)
|
||||||
|
counters.forEach { it.fill(0L) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.BoxScope
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.text.BasicTextField
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.Switch
|
||||||
|
import androidx.compose.material3.SwitchDefaults
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.darkColorScheme
|
||||||
|
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.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.SolidColor
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
||||||
|
// One dark palette for the whole app
|
||||||
|
object Palette {
|
||||||
|
val Bg = Color(0xFF08090B)
|
||||||
|
val Card = Color(0xFF17181C)
|
||||||
|
val CardHigh = Color(0xFF1E2026)
|
||||||
|
val Line = Color(0xFF24262C)
|
||||||
|
val Track = Color(0xFF3A3C44)
|
||||||
|
val Muted = Color(0xFF5B5F6B)
|
||||||
|
val Fg = Color(0xFFF2F3F5)
|
||||||
|
val Fg2 = Color(0xFF9A9DA6)
|
||||||
|
val Fg3 = Color(0xFF7E828C)
|
||||||
|
val Accent = Color(0xFF7FB2FF)
|
||||||
|
val AccentSoft = Color(0x297FB2FF)
|
||||||
|
val AccentInk = Color(0xFF0A0B0D)
|
||||||
|
val Blocked = Color(0xFFFF6B7D)
|
||||||
|
val Nav = Color(0xEB1E2026)
|
||||||
|
val NavIcon = Color(0xFF8A8E98)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal val AppColors = darkColorScheme(
|
||||||
|
primary = Palette.Accent,
|
||||||
|
onPrimary = Palette.AccentInk,
|
||||||
|
primaryContainer = Color(0xFF22324A),
|
||||||
|
onPrimaryContainer = Palette.Accent,
|
||||||
|
secondary = Palette.Accent,
|
||||||
|
onSecondary = Palette.AccentInk,
|
||||||
|
secondaryContainer = Color(0xFF22324A),
|
||||||
|
onSecondaryContainer = Palette.Accent,
|
||||||
|
background = Palette.Bg,
|
||||||
|
onBackground = Palette.Fg,
|
||||||
|
surface = Palette.Bg,
|
||||||
|
onSurface = Palette.Fg,
|
||||||
|
surfaceVariant = Palette.Card,
|
||||||
|
onSurfaceVariant = Palette.Fg2,
|
||||||
|
surfaceContainerLowest = Palette.Bg,
|
||||||
|
surfaceContainerLow = Palette.Card,
|
||||||
|
surfaceContainer = Palette.Card,
|
||||||
|
surfaceContainerHigh = Palette.CardHigh,
|
||||||
|
surfaceContainerHighest = Palette.Card,
|
||||||
|
outline = Palette.Track,
|
||||||
|
outlineVariant = Palette.Line,
|
||||||
|
error = Palette.Blocked,
|
||||||
|
onError = Palette.AccentInk,
|
||||||
|
errorContainer = Color(0xFF3A1C22),
|
||||||
|
onErrorContainer = Color(0xFFFFD9DE),
|
||||||
|
)
|
||||||
|
|
||||||
|
val CardShape = RoundedCornerShape(20.dp)
|
||||||
|
|
||||||
|
fun Modifier.appCard(): Modifier = clip(CardShape).background(Palette.Card)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AppSwitch(
|
||||||
|
checked: Boolean,
|
||||||
|
onCheckedChange: ((Boolean) -> Unit)?,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
enabled: Boolean = true,
|
||||||
|
) {
|
||||||
|
Switch(
|
||||||
|
checked = checked,
|
||||||
|
onCheckedChange = onCheckedChange,
|
||||||
|
modifier = modifier,
|
||||||
|
enabled = enabled,
|
||||||
|
colors = appSwitchColors(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun appSwitchColors() = SwitchDefaults.colors(
|
||||||
|
checkedThumbColor = Color.White,
|
||||||
|
checkedTrackColor = Palette.Accent,
|
||||||
|
checkedBorderColor = Palette.Accent,
|
||||||
|
uncheckedThumbColor = Palette.Fg2,
|
||||||
|
uncheckedTrackColor = Palette.Track,
|
||||||
|
uncheckedBorderColor = Palette.Track,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Big bold title of a main tab
|
||||||
|
@Composable
|
||||||
|
fun ScreenTitle(text: String, modifier: Modifier = Modifier) {
|
||||||
|
Text(
|
||||||
|
text,
|
||||||
|
modifier = modifier,
|
||||||
|
color = Palette.Fg,
|
||||||
|
fontSize = 24.sp,
|
||||||
|
fontWeight = FontWeight.ExtraBold,
|
||||||
|
letterSpacing = (-0.3).sp,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SectionLabel(text: String, modifier: Modifier = Modifier) {
|
||||||
|
Text(
|
||||||
|
text,
|
||||||
|
modifier = modifier.padding(start = 4.dp, top = 8.dp, bottom = 2.dp),
|
||||||
|
color = Palette.Fg2,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Back arrow and title of a page opened from a tab
|
||||||
|
@Composable
|
||||||
|
fun PageHeader(
|
||||||
|
title: String,
|
||||||
|
onBack: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
action: (@Composable () -> Unit)? = null,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.heightIn(min = 56.dp)
|
||||||
|
.padding(start = 4.dp, end = 12.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
IconButton(onClick = onBack) {
|
||||||
|
Icon(painterResource(R.drawable.ic_back), contentDescription = stringResource(R.string.back), tint = Palette.Fg)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
color = Palette.Fg,
|
||||||
|
fontSize = 20.sp,
|
||||||
|
fontWeight = FontWeight.ExtraBold,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
action?.invoke()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A page with a back header around content that is not built for one
|
||||||
|
@Composable
|
||||||
|
fun SubPage(title: String, onBack: () -> Unit, modifier: Modifier = Modifier, content: @Composable BoxScope.() -> Unit) {
|
||||||
|
Column(modifier) {
|
||||||
|
PageHeader(title, onBack)
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.fillMaxSize()
|
||||||
|
.navigationBarsPadding(),
|
||||||
|
content = content,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SearchField(
|
||||||
|
value: String,
|
||||||
|
onValueChange: (String) -> Unit,
|
||||||
|
placeholder: String,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
trailing: (@Composable () -> Unit)? = null,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(48.dp)
|
||||||
|
.clip(RoundedCornerShape(16.dp))
|
||||||
|
.background(Palette.Card)
|
||||||
|
.padding(start = 14.dp, end = if (trailing != null) 2.dp else 14.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_search),
|
||||||
|
contentDescription = null,
|
||||||
|
tint = Palette.Fg3,
|
||||||
|
modifier = Modifier.size(18.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
|
||||||
|
if (value.isEmpty()) {
|
||||||
|
Text(placeholder, color = Palette.Fg3, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
BasicTextField(
|
||||||
|
value = value,
|
||||||
|
onValueChange = onValueChange,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true,
|
||||||
|
textStyle = TextStyle(color = Palette.Fg, fontSize = 14.sp),
|
||||||
|
cursorBrush = SolidColor(Palette.Accent),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
trailing?.invoke()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Thin line between the rows of a card
|
||||||
|
@Composable
|
||||||
|
fun ListDivider(modifier: Modifier = Modifier) {
|
||||||
|
HorizontalDivider(modifier = modifier.padding(horizontal = 16.dp), color = Palette.Line)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The arrow at the end of a row that opens something
|
||||||
|
@Composable
|
||||||
|
fun Chevron(modifier: Modifier = Modifier) {
|
||||||
|
Icon(
|
||||||
|
painterResource(R.drawable.ic_chevron),
|
||||||
|
contentDescription = null,
|
||||||
|
tint = Palette.Fg3,
|
||||||
|
modifier = modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ import androidx.compose.foundation.layout.Column
|
|||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.heightIn
|
import androidx.compose.foundation.layout.heightIn
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
@@ -30,6 +31,7 @@ import androidx.compose.runtime.LaunchedEffect
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -42,8 +44,11 @@ import androidx.compose.ui.text.style.TextAlign
|
|||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import kotlinx.coroutines.delay
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||||
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
import java.text.NumberFormat
|
import java.text.NumberFormat
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
val CachedColor = Color(0xFF7FD1AE)
|
val CachedColor = Color(0xFF7FD1AE)
|
||||||
val WarningColor = Color(0xFFFFB86B)
|
val WarningColor = Color(0xFFFFB86B)
|
||||||
@@ -191,20 +196,35 @@ fun StatDivider() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Polls the in-memory query log once a second while the screen is visible
|
// Runs [onChange] when the query log changes, at most once a second and only while the screen
|
||||||
|
// is started: nothing runs while the app sits in the background
|
||||||
|
@Composable
|
||||||
|
fun OnQueryLogChange(onChange: () -> Unit) {
|
||||||
|
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||||
|
val current by rememberUpdatedState(onChange)
|
||||||
|
LaunchedEffect(lifecycle) {
|
||||||
|
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||||
|
QueryLog.changes().collect { current() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun rememberLiveStats(): QueryStats {
|
fun rememberLiveStats(): QueryStats {
|
||||||
var stats by remember { mutableStateOf(QueryLog.stats()) }
|
var stats by remember { mutableStateOf(QueryLog.stats()) }
|
||||||
LaunchedEffect(Unit) {
|
OnQueryLogChange { stats = QueryLog.stats() }
|
||||||
while (true) {
|
|
||||||
stats = QueryLog.stats()
|
|
||||||
delay(1000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return stats
|
return stats
|
||||||
}
|
}
|
||||||
|
|
||||||
fun formatCount(value: Long): String = NumberFormat.getIntegerInstance().format(value)
|
// Called from composition only, i.e. on the main thread; rebuilt when the locale changes
|
||||||
|
private var countFormat: Pair<Locale, NumberFormat>? = null
|
||||||
|
|
||||||
|
fun formatCount(value: Long): String {
|
||||||
|
val locale = Locale.getDefault()
|
||||||
|
val format = countFormat?.takeIf { it.first == locale }?.second
|
||||||
|
?: NumberFormat.getIntegerInstance(locale).also { countFormat = locale to it }
|
||||||
|
return format.format(value)
|
||||||
|
}
|
||||||
|
|
||||||
fun cachePercent(stats: QueryStats): String =
|
fun cachePercent(stats: QueryStats): String =
|
||||||
"${if (stats.total == 0L) 0 else stats.cached * 100 / stats.total}%"
|
"${if (stats.total == 0L) 0 else stats.cached * 100 / stats.total}%"
|
||||||
@@ -219,3 +239,34 @@ fun groupedShape(first: Boolean, last: Boolean, radius: Dp = 16.dp) = RoundedCor
|
|||||||
|
|
||||||
val groupedBackground: Color
|
val groupedBackground: Color
|
||||||
@Composable get() = MaterialTheme.colorScheme.surfaceContainerHighest
|
@Composable get() = MaterialTheme.colorScheme.surfaceContainerHighest
|
||||||
|
|
||||||
|
// Short numbers for stat tiles: 812, 7.27k, 48.1k, 312k, 1.2M (decimal separator of the locale)
|
||||||
|
fun formatCompact(value: Long): String {
|
||||||
|
val locale = Locale.getDefault()
|
||||||
|
return when {
|
||||||
|
value < 1_000 -> formatCount(value)
|
||||||
|
value < 10_000 -> String.format(locale, "%.2fk", value / 1_000.0)
|
||||||
|
value < 100_000 -> String.format(locale, "%.1fk", value / 1_000.0)
|
||||||
|
value < 1_000_000 -> String.format(locale, "%.0fk", value / 1_000.0)
|
||||||
|
else -> String.format(locale, "%.1fM", value / 1_000_000.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun EmptyState(icon: Int, text: String) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(vertical = 40.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
) {
|
||||||
|
IconBadge(icon, MaterialTheme.colorScheme.onSurfaceVariant, size = 64.dp)
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Text(
|
||||||
|
text,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 184 KiB |
|
After Width: | Height: | Size: 124 KiB |
@@ -1,10 +0,0 @@
|
|||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="24dp"
|
|
||||||
android:height="24dp"
|
|
||||||
android:viewportWidth="256"
|
|
||||||
android:viewportHeight="256">
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFFFF"
|
|
||||||
android:fillType="evenOdd"
|
|
||||||
android:pathData="M175.0,214.5L29.0,214.5L28.5,214.0L28.5,34.0L29.0,33.3L124.0,33.3L124.5,34.0L124.5,75.0L125.0,75.7L226.3,76.0L226.5,164.0L226.0,164.5L217.0,164.5L215.7,164.0L215.7,87.0L215.0,86.5L172.0,86.5L125.0,86.5L124.5,87.0L124.5,118.0L125.0,118.5L149.0,118.5L150.0,119.0L150.0,129.0L126.0,129.3L124.7,130.0L125.0,161.0L149.0,161.3L150.0,162.0L150.0,171.0L149.0,171.7L125.0,172.0L124.7,203.0L126.0,203.7L175.0,203.7L175.5,205.0L175.5,214.0ZM71.3,75.0L71.0,44.0L39.5,44.0L39.3,75.0L40.0,75.7L70.0,75.7ZM114.0,75.0L114.0,45.0L113.5,44.0L82.0,44.0L82.0,75.0L83.0,75.7L113.0,75.7ZM71.3,118.0L71.0,86.7L40.0,86.5L39.3,87.0L39.3,118.0L40.0,118.5L70.0,118.5ZM114.0,118.0L114.0,87.0L113.0,86.5L83.0,86.5L82.0,87.0L82.0,118.0L83.0,118.5L113.0,118.5ZM186.0,129.0L175.7,129.0L175.5,119.0L176.0,118.5L185.0,118.5L186.3,119.0ZM71.0,161.0L71.0,129.5L40.0,129.3L39.3,130.0L39.5,161.0ZM114.0,161.0L114.0,130.0L113.0,129.3L83.0,129.3L82.0,130.0L82.0,160.0L82.5,161.0ZM186.0,171.5L176.0,171.7L175.5,171.0L175.5,162.0L176.0,161.3L186.0,161.5ZM71.3,203.0L71.0,172.0L39.5,172.0L39.3,203.0L40.0,203.7L70.0,203.7ZM114.0,203.0L114.0,173.0L113.5,172.0L82.0,172.0L82.0,203.0L83.0,203.7L113.0,203.7ZM226.0,235.7L217.0,235.7L215.7,235.0L215.7,215.0L215.0,214.5L195.0,214.5L194.5,214.0L194.5,205.0L195.0,203.7L215.0,203.7L215.7,203.0L216.0,182.7L226.0,182.5L226.5,183.0L226.5,203.0L227.0,203.7L247.5,204.0L247.7,214.0L247.0,214.5L227.0,214.5L226.5,215.0L226.5,235.0Z" />
|
|
||||||
</vector>
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:autoMirrored="true"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M9,6l6,6l-6,6"
|
||||||
|
android:strokeWidth="2"
|
||||||
|
android:strokeColor="#FFFFFFFF"
|
||||||
|
android:strokeLineCap="round"
|
||||||
|
android:strokeLineJoin="round" />
|
||||||
|
</vector>
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="24dp"
|
|
||||||
android:height="24dp"
|
|
||||||
android:viewportWidth="256"
|
|
||||||
android:viewportHeight="256">
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFFFF"
|
|
||||||
android:fillType="evenOdd"
|
|
||||||
android:pathData="M127.0,202.3L49.0,202.3L48.0,202.0L32.0,186.0L30.0,183.0L28.3,179.0L27.7,176.0L28.0,171.0L30.0,166.0L35.0,160.0L142.0,49.0L147.0,45.7L152.0,44.7L157.0,45.0L160.0,46.0L165.0,49.7L209.3,94.0L213.3,100.0L214.0,104.0L214.0,109.0L211.0,116.0ZM227.0,202.3L167.7,202.0L178.0,191.5L227.0,191.5L227.5,192.0L227.5,201.0Z" />
|
|
||||||
</vector>
|
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="256"
|
||||||
|
android:viewportHeight="256">
|
||||||
|
<path
|
||||||
|
android:pathData="M128,38 A90,90 0 1,1 128,218 A90,90 0 1,1 128,38 Z"
|
||||||
|
android:strokeColor="#FFFFFFFF"
|
||||||
|
android:strokeWidth="11" />
|
||||||
|
<path
|
||||||
|
android:pathData="M156,99 C151,88 141,82 128,82 C112,82 100,91 100,105 C100,120 113,125 128,128 C144,131 158,137 158,153 C158,167 145,175 128,175 C113,175 101,168 97,156"
|
||||||
|
android:strokeColor="#FFFFFFFF"
|
||||||
|
android:strokeWidth="11"
|
||||||
|
android:strokeLineCap="round"
|
||||||
|
android:strokeLineJoin="round" />
|
||||||
|
<path
|
||||||
|
android:pathData="M128,64 L128,82 M128,175 L128,193"
|
||||||
|
android:strokeColor="#FFFFFFFF"
|
||||||
|
android:strokeWidth="11"
|
||||||
|
android:strokeLineCap="round" />
|
||||||
|
</vector>
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="24dp"
|
|
||||||
android:height="24dp"
|
|
||||||
android:viewportWidth="256"
|
|
||||||
android:viewportHeight="256">
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFFFF"
|
|
||||||
android:fillType="evenOdd"
|
|
||||||
android:pathData="M122.0,212.5L56.0,212.5L54.0,212.0L49.0,209.3L47.3,208.0L43.7,203.0L42.3,198.0L42.3,58.0L43.0,54.0L47.0,47.3L52.0,43.7L57.0,42.3L197.0,42.3L201.0,43.0L207.7,47.0L211.3,52.0L212.7,57.0L212.7,122.0L212.0,122.5L201.0,120.0L191.0,119.3L182.0,120.0L171.0,122.5L80.0,122.3L79.5,123.0L79.5,132.0L80.0,132.7L149.0,133.0L148.0,134.3L142.0,139.0L136.0,145.3L131.0,152.0L128.0,157.0L128.0,158.0L127.0,159.0L127.0,160.0L125.0,162.3L80.0,162.3L79.5,163.0L79.5,172.0L80.0,173.0L121.0,173.0L121.5,174.0L119.7,184.0L119.3,194.0L119.7,202.0L120.7,208.0L122.3,212.0ZM175.5,92.0L175.5,83.0L175.0,82.0L80.0,82.0L79.5,83.0L79.5,92.0L80.0,92.7L175.0,92.7ZM196.0,235.0L189.0,235.3L182.0,234.5L174.0,232.0L173.0,231.0L167.0,228.0L160.3,222.0L155.0,215.0L151.7,209.0L149.5,201.0L149.3,196.0L148.7,193.0L149.5,184.0L152.0,176.0L155.0,171.0L155.0,170.0L159.0,165.0L167.0,157.7L176.0,152.7L182.0,151.3L183.0,150.7L192.0,150.0L201.0,151.0L208.0,153.0L209.0,154.0L210.0,154.0L215.0,157.0L219.0,160.0L226.3,168.0L231.3,177.0L233.3,183.0L234.3,192.0L233.5,201.0L231.5,208.0L227.5,216.0L221.0,223.7L212.0,230.3L208.0,232.3L202.0,234.3ZM171.5,199.0L174.0,197.0L175.3,194.0L175.3,191.0L174.3,189.0L171.0,186.0L167.0,185.7L165.0,186.3L163.0,188.0L161.5,191.0L161.3,194.0L162.0,196.0L163.5,198.0L166.0,199.5L168.0,200.0ZM195.0,199.0L198.0,196.0L198.5,194.0L198.3,190.0L196.0,187.0L192.0,185.5L190.0,185.7L186.0,188.0L184.5,191.0L184.7,195.0L185.7,197.0L189.0,199.5L191.0,200.0ZM218.0,199.0L220.0,197.5L221.5,195.0L221.3,190.0L219.0,187.0L216.0,185.7L213.0,185.7L210.0,187.3L208.0,190.0L207.5,192.0L207.7,195.0L209.0,197.0L212.0,199.5L216.0,199.7Z" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="24dp"
|
|
||||||
android:height="24dp"
|
|
||||||
android:viewportWidth="256"
|
|
||||||
android:viewportHeight="256">
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFFFF"
|
|
||||||
android:fillType="evenOdd"
|
|
||||||
android:pathData="M178.0,144.3L177.0,144.0L170.3,137.0L202.0,105.0L201.0,104.0L125.0,104.0L124.3,103.0L124.3,94.0L125.0,93.5L202.0,93.5L202.7,93.0L170.7,61.0L170.3,60.0L177.0,53.3L178.0,53.3L223.3,99.0ZM78.0,201.3L77.0,201.7L31.7,156.0L77.0,110.7L78.0,110.7L84.3,117.0L84.7,118.0L52.7,150.0L53.0,150.5L130.0,150.7L130.7,152.0L130.7,160.0L130.0,161.3L53.0,161.5L52.7,162.0L84.7,194.0L84.3,195.0Z" />
|
|
||||||
</vector>
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M4,7h9M17,7h3M4,17h3M11,17h9"
|
||||||
|
android:strokeWidth="1.9"
|
||||||
|
android:strokeColor="#FFFFFFFF"
|
||||||
|
android:strokeLineCap="round" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:pathData="M13,7a2,2 0,1 0,4 0a2,2 0,1 0,-4 0zM7,17a2,2 0,1 0,4 0a2,2 0,1 0,-4 0z"
|
||||||
|
android:strokeWidth="1.9"
|
||||||
|
android:strokeColor="#FFFFFFFF" />
|
||||||
|
</vector>
|
||||||
|
Before Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
Before Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 62 KiB |
@@ -1,8 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<string name="status_on">Geschützt</string>
|
|
||||||
<string name="status_off">Getrennt</string>
|
|
||||||
<string name="via">über %1$s</string>
|
|
||||||
<string name="connect">Verbinden</string>
|
<string name="connect">Verbinden</string>
|
||||||
<string name="disconnect">Trennen</string>
|
<string name="disconnect">Trennen</string>
|
||||||
<string name="servers">DNS-over-HTTPS-Server</string>
|
<string name="servers">DNS-over-HTTPS-Server</string>
|
||||||
@@ -26,14 +23,10 @@
|
|||||||
<string name="notif_title">Geschützt über %1$s</string>
|
<string name="notif_title">Geschützt über %1$s</string>
|
||||||
<string name="notif_text">DNS über HTTPS ist aktiv</string>
|
<string name="notif_text">DNS über HTTPS ist aktiv</string>
|
||||||
<string name="tab_home">Start</string>
|
<string name="tab_home">Start</string>
|
||||||
<string name="tab_monitor">Monitor</string>
|
|
||||||
<string name="tab_apps">Apps</string>
|
|
||||||
<string name="tab_blocklist">Sperrliste</string>
|
<string name="tab_blocklist">Sperrliste</string>
|
||||||
<string name="tab_about">Info</string>
|
<string name="tab_about">Info</string>
|
||||||
<string name="mon_queries">Anfragen</string>
|
|
||||||
<string name="mon_cached">Aus dem Cache</string>
|
<string name="mon_cached">Aus dem Cache</string>
|
||||||
<string name="mon_blocked">Blockiert</string>
|
<string name="mon_blocked">Blockiert</string>
|
||||||
<string name="mon_latency">Ø Latenz</string>
|
|
||||||
<string name="mon_ms">%1$d ms</string>
|
<string name="mon_ms">%1$d ms</string>
|
||||||
<string name="mon_all">Alle</string>
|
<string name="mon_all">Alle</string>
|
||||||
<string name="mon_errors">Fehler</string>
|
<string name="mon_errors">Fehler</string>
|
||||||
@@ -60,12 +53,9 @@
|
|||||||
<string name="bl_invalid">Ungültige Domain</string>
|
<string name="bl_invalid">Ungültige Domain</string>
|
||||||
<string name="bl_empty_custom">Noch keine Domains</string>
|
<string name="bl_empty_custom">Noch keine Domains</string>
|
||||||
<string name="delete">Löschen</string>
|
<string name="delete">Löschen</string>
|
||||||
<string name="bl_lists">Listen</string>
|
|
||||||
<string name="bl_update_all">Alle aktualisieren</string>
|
|
||||||
<string name="bl_updating">Wird aktualisiert…</string>
|
<string name="bl_updating">Wird aktualisiert…</string>
|
||||||
<string name="bl_list_url">Listen-URL</string>
|
<string name="bl_list_url">Listen-URL</string>
|
||||||
<string name="bl_list_info">%1$s Domains · %2$s</string>
|
<string name="bl_list_info">%1$s Domains · %2$s</string>
|
||||||
<string name="bl_presets">Beliebte Listen</string>
|
|
||||||
<string name="bl_download_failed">Download fehlgeschlagen: %1$s</string>
|
<string name="bl_download_failed">Download fehlgeschlagen: %1$s</string>
|
||||||
<string name="about_desc">DNS-Anfragen verschlüsseln, ohne den gesamten Verkehr über ein VPN zu leiten.</string>
|
<string name="about_desc">DNS-Anfragen verschlüsseln, ohne den gesamten Verkehr über ein VPN zu leiten.</string>
|
||||||
<string name="about_version">Version</string>
|
<string name="about_version">Version</string>
|
||||||
@@ -84,17 +74,56 @@
|
|||||||
<string name="group_system">System</string>
|
<string name="group_system">System</string>
|
||||||
<string name="group_count">%1$d von %2$d über DNS</string>
|
<string name="group_count">%1$d von %2$d über DNS</string>
|
||||||
<string name="about_privacy_policy">Datenschutzerklärung</string>
|
<string name="about_privacy_policy">Datenschutzerklärung</string>
|
||||||
|
<string name="donate">Spenden</string>
|
||||||
<string name="licenses_title">Open-Source-Lizenzen</string>
|
<string name="licenses_title">Open-Source-Lizenzen</string>
|
||||||
<string name="licenses_hint">SparkleDNS basiert auf diesen Open-Source-Projekten. Tippe auf ein Projekt, um seine Seite zu öffnen.</string>
|
<string name="licenses_hint">SparkleDNS basiert auf diesen Open-Source-Projekten. Tippe auf ein Projekt, um seine Seite zu öffnen.</string>
|
||||||
<string name="licenses_data">Sperrlisten-Daten (bei Bedarf geladen, nicht enthalten)</string>
|
<string name="licenses_data">Sperrlisten-Daten (bei Bedarf geladen, nicht enthalten)</string>
|
||||||
<string name="license_view">Lizenz ansehen</string>
|
<string name="license_view">Lizenz ansehen</string>
|
||||||
<string name="back">Zurück</string>
|
<string name="back">Zurück</string>
|
||||||
<string name="bl_total_label">Domains blockiert</string>
|
|
||||||
<string name="about_source">Quellcode</string>
|
<string name="about_source">Quellcode</string>
|
||||||
<string name="open_settings">Einstellungen</string>
|
<string name="open_settings">Einstellungen</string>
|
||||||
<string name="mon_no_match">Nichts passt zum Filter</string>
|
<string name="mon_no_match">Nichts passt zum Filter</string>
|
||||||
<string name="bl_title">Blockierung</string>
|
<string name="no_browser">Keine App zum Öffnen dieses Links gefunden</string>
|
||||||
<string name="servers_update">Serverliste aktualisieren</string>
|
<string name="toggle_on">AN</string>
|
||||||
<string name="servers_updated">Serverliste aktualisiert</string>
|
<string name="toggle_off">AUS</string>
|
||||||
<string name="servers_update_failed">Serverliste konnte nicht aktualisiert werden: %1$s</string>
|
<string name="home_protected">Du bist geschützt</string>
|
||||||
|
<string name="home_unprotected">Du bist nicht geschützt</string>
|
||||||
|
<string name="home_via">Verschlüsselt über %1$s</string>
|
||||||
|
<string name="home_off_desc">DNS läuft wie gewohnt über dein Netzwerk</string>
|
||||||
|
<string name="stat_requests">Anfragen</string>
|
||||||
|
<string name="stat_avg">Ø Zeit</string>
|
||||||
|
<string name="chart_now">Jetzt</string>
|
||||||
|
<string name="period_24h">24 Stunden</string>
|
||||||
|
<string name="period_7d">7 Tage</string>
|
||||||
|
<string name="home_lists_info">Aktive Listen: %1$d · Regeln: %2$s</string>
|
||||||
|
<string name="blocking_off">Blockieren ist aus</string>
|
||||||
|
<string name="blocklist_title">DNS-Blocklisten</string>
|
||||||
|
<string name="tab_activity">Aktivität</string>
|
||||||
|
<string name="tab_settings">Einstellungen</string>
|
||||||
|
<string name="companies_title">Anteil der Konzerne</string>
|
||||||
|
<string name="companies_desc">Welcher Anteil deiner Anfragen an die größten Konzerne geht.</string>
|
||||||
|
<string name="companies_other">Andere</string>
|
||||||
|
<string name="no_data">Noch keine Daten</string>
|
||||||
|
<string name="recent_title">Letzte Anfragen</string>
|
||||||
|
<string name="filter">Filter</string>
|
||||||
|
<string name="bl_search">Listen suchen</string>
|
||||||
|
<string name="auto_update">Automatisch aktualisieren</string>
|
||||||
|
<string name="auto_off">Aus</string>
|
||||||
|
<string name="auto_daily">Täglich</string>
|
||||||
|
<string name="auto_weekly">Wöchentlich</string>
|
||||||
|
<string name="auto_wifi">Nur über WLAN</string>
|
||||||
|
<string name="auto_wifi_desc">Keine Updates über mobile Daten</string>
|
||||||
|
<string name="auto_update_now">Jetzt aktualisieren</string>
|
||||||
|
<string name="done">Fertig</string>
|
||||||
|
<string name="cancel">Abbrechen</string>
|
||||||
|
<string name="preset_pro_desc">Ausgewogener Schutz vor Werbung, Tracking und Malware. Die beste Wahl für jeden Tag.</string>
|
||||||
|
<string name="preset_proplus_desc">Maximaler Schutz. Kann Anmeldungen in manchen Apps und Links stören.</string>
|
||||||
|
<string name="preset_tif_desc">Bedrohungsdaten: Domains für Malware, Phishing, Betrug und Cryptojacking.</string>
|
||||||
|
<string name="list_added_by_you">Von dir per URL hinzugefügt.</string>
|
||||||
|
<string name="list_not_downloaded">Noch nicht heruntergeladen</string>
|
||||||
|
<string name="my_domains_desc">Domains, die du selbst blockiert hast. Subdomains werden ebenfalls blockiert.</string>
|
||||||
|
<string name="bl_add_list">Neue Blockliste hinzufügen</string>
|
||||||
|
<string name="settings_general">Allgemein</string>
|
||||||
|
<string name="settings_apps">Apps ohne SparkleDNS</string>
|
||||||
|
<string name="settings_apps_desc">Ausgewählte Apps nutzen das normale DNS des Netzwerks</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<string name="status_on">保護中</string>
|
|
||||||
<string name="status_off">未接続</string>
|
|
||||||
<string name="via">%1$s 経由</string>
|
|
||||||
<string name="connect">接続</string>
|
<string name="connect">接続</string>
|
||||||
<string name="disconnect">切断</string>
|
<string name="disconnect">切断</string>
|
||||||
<string name="servers">DNS-over-HTTPS サーバー</string>
|
<string name="servers">DNS-over-HTTPS サーバー</string>
|
||||||
@@ -26,14 +23,10 @@
|
|||||||
<string name="notif_title">%1$s 経由で保護中</string>
|
<string name="notif_title">%1$s 経由で保護中</string>
|
||||||
<string name="notif_text">DNS over HTTPS が有効です</string>
|
<string name="notif_text">DNS over HTTPS が有効です</string>
|
||||||
<string name="tab_home">ホーム</string>
|
<string name="tab_home">ホーム</string>
|
||||||
<string name="tab_monitor">モニター</string>
|
|
||||||
<string name="tab_apps">アプリ</string>
|
|
||||||
<string name="tab_blocklist">ブロックリスト</string>
|
<string name="tab_blocklist">ブロックリスト</string>
|
||||||
<string name="tab_about">情報</string>
|
<string name="tab_about">情報</string>
|
||||||
<string name="mon_queries">クエリ</string>
|
|
||||||
<string name="mon_cached">キャッシュから</string>
|
<string name="mon_cached">キャッシュから</string>
|
||||||
<string name="mon_blocked">ブロック済み</string>
|
<string name="mon_blocked">ブロック済み</string>
|
||||||
<string name="mon_latency">平均遅延</string>
|
|
||||||
<string name="mon_ms">%1$d ms</string>
|
<string name="mon_ms">%1$d ms</string>
|
||||||
<string name="mon_all">すべて</string>
|
<string name="mon_all">すべて</string>
|
||||||
<string name="mon_errors">エラー</string>
|
<string name="mon_errors">エラー</string>
|
||||||
@@ -60,12 +53,9 @@
|
|||||||
<string name="bl_invalid">無効なドメイン</string>
|
<string name="bl_invalid">無効なドメイン</string>
|
||||||
<string name="bl_empty_custom">まだドメインはありません</string>
|
<string name="bl_empty_custom">まだドメインはありません</string>
|
||||||
<string name="delete">削除</string>
|
<string name="delete">削除</string>
|
||||||
<string name="bl_lists">リスト</string>
|
|
||||||
<string name="bl_update_all">すべて更新</string>
|
|
||||||
<string name="bl_updating">更新中…</string>
|
<string name="bl_updating">更新中…</string>
|
||||||
<string name="bl_list_url">リストの URL</string>
|
<string name="bl_list_url">リストの URL</string>
|
||||||
<string name="bl_list_info">%1$s ドメイン · %2$s</string>
|
<string name="bl_list_info">%1$s ドメイン · %2$s</string>
|
||||||
<string name="bl_presets">人気のリスト</string>
|
|
||||||
<string name="bl_download_failed">ダウンロードに失敗しました: %1$s</string>
|
<string name="bl_download_failed">ダウンロードに失敗しました: %1$s</string>
|
||||||
<string name="about_desc">すべての通信をVPNに通さずに、DNSリクエストを暗号化します。</string>
|
<string name="about_desc">すべての通信をVPNに通さずに、DNSリクエストを暗号化します。</string>
|
||||||
<string name="about_version">バージョン</string>
|
<string name="about_version">バージョン</string>
|
||||||
@@ -84,17 +74,56 @@
|
|||||||
<string name="group_system">システム</string>
|
<string name="group_system">システム</string>
|
||||||
<string name="group_count">%2$d 件中 %1$d 件が DNS 経由</string>
|
<string name="group_count">%2$d 件中 %1$d 件が DNS 経由</string>
|
||||||
<string name="about_privacy_policy">プライバシーポリシー</string>
|
<string name="about_privacy_policy">プライバシーポリシー</string>
|
||||||
|
<string name="donate">寄付する</string>
|
||||||
<string name="licenses_title">オープンソースライセンス</string>
|
<string name="licenses_title">オープンソースライセンス</string>
|
||||||
<string name="licenses_hint">SparkleDNS は以下のオープンソースプロジェクトで作られています。タップするとプロジェクトのページを開きます。</string>
|
<string name="licenses_hint">SparkleDNS は以下のオープンソースプロジェクトで作られています。タップするとプロジェクトのページを開きます。</string>
|
||||||
<string name="licenses_data">ブロックリストのデータ(必要なときにダウンロード、同梱なし)</string>
|
<string name="licenses_data">ブロックリストのデータ(必要なときにダウンロード、同梱なし)</string>
|
||||||
<string name="license_view">ライセンスを見る</string>
|
<string name="license_view">ライセンスを見る</string>
|
||||||
<string name="back">戻る</string>
|
<string name="back">戻る</string>
|
||||||
<string name="bl_total_label">件のドメインをブロック</string>
|
|
||||||
<string name="about_source">ソースコード</string>
|
<string name="about_source">ソースコード</string>
|
||||||
<string name="open_settings">設定</string>
|
<string name="open_settings">設定</string>
|
||||||
<string name="mon_no_match">フィルターに一致するものはありません</string>
|
<string name="mon_no_match">フィルターに一致するものはありません</string>
|
||||||
<string name="bl_title">ブロック</string>
|
<string name="no_browser">このリンクを開けるアプリがありません</string>
|
||||||
<string name="servers_update">サーバーリストを更新</string>
|
<string name="toggle_on">オン</string>
|
||||||
<string name="servers_updated">サーバーリストを更新しました</string>
|
<string name="toggle_off">オフ</string>
|
||||||
<string name="servers_update_failed">サーバーリストを更新できませんでした: %1$s</string>
|
<string name="home_protected">保護されています</string>
|
||||||
|
<string name="home_unprotected">保護されていません</string>
|
||||||
|
<string name="home_via">%1$s で暗号化</string>
|
||||||
|
<string name="home_off_desc">DNS は通常どおりネットワークを経由します</string>
|
||||||
|
<string name="stat_requests">リクエスト</string>
|
||||||
|
<string name="stat_avg">平均時間</string>
|
||||||
|
<string name="chart_now">現在</string>
|
||||||
|
<string name="period_24h">24 時間</string>
|
||||||
|
<string name="period_7d">7 日間</string>
|
||||||
|
<string name="home_lists_info">有効なリスト: %1$d · ルール: %2$s</string>
|
||||||
|
<string name="blocking_off">ブロックはオフです</string>
|
||||||
|
<string name="blocklist_title">DNS ブロックリスト</string>
|
||||||
|
<string name="tab_activity">アクティビティ</string>
|
||||||
|
<string name="tab_settings">設定</string>
|
||||||
|
<string name="companies_title">企業の占有率</string>
|
||||||
|
<string name="companies_desc">リクエストのうち大手企業に送られる割合です。</string>
|
||||||
|
<string name="companies_other">その他</string>
|
||||||
|
<string name="no_data">まだデータがありません</string>
|
||||||
|
<string name="recent_title">最近のアクティビティ</string>
|
||||||
|
<string name="filter">フィルター</string>
|
||||||
|
<string name="bl_search">リストを検索</string>
|
||||||
|
<string name="auto_update">自動更新</string>
|
||||||
|
<string name="auto_off">オフ</string>
|
||||||
|
<string name="auto_daily">毎日</string>
|
||||||
|
<string name="auto_weekly">毎週</string>
|
||||||
|
<string name="auto_wifi">Wi-Fi のみ</string>
|
||||||
|
<string name="auto_wifi_desc">モバイルデータでは更新しない</string>
|
||||||
|
<string name="auto_update_now">今すぐ更新</string>
|
||||||
|
<string name="done">完了</string>
|
||||||
|
<string name="cancel">キャンセル</string>
|
||||||
|
<string name="preset_pro_desc">広告・トラッキング・マルウェアからのバランスの取れた保護。普段使いに最適です。</string>
|
||||||
|
<string name="preset_proplus_desc">最大限の保護。一部のアプリのログインやリンクが動かなくなることがあります。</string>
|
||||||
|
<string name="preset_tif_desc">脅威インテリジェンス: マルウェア、フィッシング、詐欺、クリプトジャッキングのドメイン。</string>
|
||||||
|
<string name="list_added_by_you">URL から追加したリストです。</string>
|
||||||
|
<string name="list_not_downloaded">未ダウンロード</string>
|
||||||
|
<string name="my_domains_desc">自分でブロックしたドメイン。サブドメインもブロックされます。</string>
|
||||||
|
<string name="bl_add_list">ブロックリストを追加</string>
|
||||||
|
<string name="settings_general">一般</string>
|
||||||
|
<string name="settings_apps">SparkleDNS を使わないアプリ</string>
|
||||||
|
<string name="settings_apps_desc">選んだアプリはネットワークの通常の DNS を使います</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<string name="status_on">Apsaugota</string>
|
|
||||||
<string name="status_off">Atsijungta</string>
|
|
||||||
<string name="via">per %1$s</string>
|
|
||||||
<string name="connect">Prisijungti</string>
|
<string name="connect">Prisijungti</string>
|
||||||
<string name="disconnect">Atsijungti</string>
|
<string name="disconnect">Atsijungti</string>
|
||||||
<string name="servers">DNS-over-HTTPS serveris</string>
|
<string name="servers">DNS-over-HTTPS serveris</string>
|
||||||
@@ -26,14 +23,10 @@
|
|||||||
<string name="notif_title">Apsaugota per %1$s</string>
|
<string name="notif_title">Apsaugota per %1$s</string>
|
||||||
<string name="notif_text">DNS per HTTPS įjungtas</string>
|
<string name="notif_text">DNS per HTTPS įjungtas</string>
|
||||||
<string name="tab_home">Pradžia</string>
|
<string name="tab_home">Pradžia</string>
|
||||||
<string name="tab_monitor">Stebėjimas</string>
|
|
||||||
<string name="tab_apps">Programėlės</string>
|
|
||||||
<string name="tab_blocklist">Blokavimo sąrašas</string>
|
<string name="tab_blocklist">Blokavimo sąrašas</string>
|
||||||
<string name="tab_about">Apie</string>
|
<string name="tab_about">Apie</string>
|
||||||
<string name="mon_queries">Užklausos</string>
|
|
||||||
<string name="mon_cached">Iš talpyklos</string>
|
<string name="mon_cached">Iš talpyklos</string>
|
||||||
<string name="mon_blocked">Užblokuota</string>
|
<string name="mon_blocked">Užblokuota</string>
|
||||||
<string name="mon_latency">Vid. delsa</string>
|
|
||||||
<string name="mon_ms">%1$d ms</string>
|
<string name="mon_ms">%1$d ms</string>
|
||||||
<string name="mon_all">Visos</string>
|
<string name="mon_all">Visos</string>
|
||||||
<string name="mon_errors">Klaidos</string>
|
<string name="mon_errors">Klaidos</string>
|
||||||
@@ -60,12 +53,9 @@
|
|||||||
<string name="bl_invalid">Netinkamas domenas</string>
|
<string name="bl_invalid">Netinkamas domenas</string>
|
||||||
<string name="bl_empty_custom">Domenų dar nėra</string>
|
<string name="bl_empty_custom">Domenų dar nėra</string>
|
||||||
<string name="delete">Ištrinti</string>
|
<string name="delete">Ištrinti</string>
|
||||||
<string name="bl_lists">Sąrašai</string>
|
|
||||||
<string name="bl_update_all">Atnaujinti visus</string>
|
|
||||||
<string name="bl_updating">Atnaujinama…</string>
|
<string name="bl_updating">Atnaujinama…</string>
|
||||||
<string name="bl_list_url">Sąrašo URL</string>
|
<string name="bl_list_url">Sąrašo URL</string>
|
||||||
<string name="bl_list_info">%1$s domenų · %2$s</string>
|
<string name="bl_list_info">%1$s domenų · %2$s</string>
|
||||||
<string name="bl_presets">Populiarūs sąrašai</string>
|
|
||||||
<string name="bl_download_failed">Atsisiųsti nepavyko: %1$s</string>
|
<string name="bl_download_failed">Atsisiųsti nepavyko: %1$s</string>
|
||||||
<string name="about_desc">Šifruokite DNS užklausas, nenukreipdami viso srauto per VPN.</string>
|
<string name="about_desc">Šifruokite DNS užklausas, nenukreipdami viso srauto per VPN.</string>
|
||||||
<string name="about_version">Versija</string>
|
<string name="about_version">Versija</string>
|
||||||
@@ -84,17 +74,56 @@
|
|||||||
<string name="group_system">Sistema</string>
|
<string name="group_system">Sistema</string>
|
||||||
<string name="group_count">%1$d iš %2$d per DNS</string>
|
<string name="group_count">%1$d iš %2$d per DNS</string>
|
||||||
<string name="about_privacy_policy">Privatumo politika</string>
|
<string name="about_privacy_policy">Privatumo politika</string>
|
||||||
|
<string name="donate">Paaukoti</string>
|
||||||
<string name="licenses_title">Atvirojo kodo licencijos</string>
|
<string name="licenses_title">Atvirojo kodo licencijos</string>
|
||||||
<string name="licenses_hint">SparkleDNS sukurta naudojant šiuos atvirojo kodo projektus. Palieskite projektą, kad atidarytumėte jo puslapį.</string>
|
<string name="licenses_hint">SparkleDNS sukurta naudojant šiuos atvirojo kodo projektus. Palieskite projektą, kad atidarytumėte jo puslapį.</string>
|
||||||
<string name="licenses_data">Blokavimo sąrašų duomenys (atsisiunčiami pagal poreikį, neįtraukti)</string>
|
<string name="licenses_data">Blokavimo sąrašų duomenys (atsisiunčiami pagal poreikį, neįtraukti)</string>
|
||||||
<string name="license_view">Peržiūrėti licenciją</string>
|
<string name="license_view">Peržiūrėti licenciją</string>
|
||||||
<string name="back">Atgal</string>
|
<string name="back">Atgal</string>
|
||||||
<string name="bl_total_label">užblokuotų domenų</string>
|
|
||||||
<string name="about_source">Šaltinio kodas</string>
|
<string name="about_source">Šaltinio kodas</string>
|
||||||
<string name="open_settings">Nustatymai</string>
|
<string name="open_settings">Nustatymai</string>
|
||||||
<string name="mon_no_match">Filtro neatitinka niekas</string>
|
<string name="mon_no_match">Filtro neatitinka niekas</string>
|
||||||
<string name="bl_title">Blokavimas</string>
|
<string name="no_browser">Nerasta programėlės šiai nuorodai atidaryti</string>
|
||||||
<string name="servers_update">Atnaujinti serverių sąrašą</string>
|
<string name="toggle_on">ĮJ.</string>
|
||||||
<string name="servers_updated">Serverių sąrašas atnaujintas</string>
|
<string name="toggle_off">IŠJ.</string>
|
||||||
<string name="servers_update_failed">Nepavyko atnaujinti serverių sąrašo: %1$s</string>
|
<string name="home_protected">Jūs apsaugoti</string>
|
||||||
|
<string name="home_unprotected">Jūs neapsaugoti</string>
|
||||||
|
<string name="home_via">Šifruojama per %1$s</string>
|
||||||
|
<string name="home_off_desc">DNS eina per jūsų tinklą kaip įprasta</string>
|
||||||
|
<string name="stat_requests">Užklausos</string>
|
||||||
|
<string name="stat_avg">Vid. laikas</string>
|
||||||
|
<string name="chart_now">Dabar</string>
|
||||||
|
<string name="period_24h">24 valandos</string>
|
||||||
|
<string name="period_7d">7 dienos</string>
|
||||||
|
<string name="home_lists_info">Įjungta sąrašų: %1$d · taisyklių: %2$s</string>
|
||||||
|
<string name="blocking_off">Blokavimas išjungtas</string>
|
||||||
|
<string name="blocklist_title">DNS blokavimo sąrašai</string>
|
||||||
|
<string name="tab_activity">Veikla</string>
|
||||||
|
<string name="tab_settings">Nustatymai</string>
|
||||||
|
<string name="companies_title">Įmonių dalis</string>
|
||||||
|
<string name="companies_desc">Kokia jūsų užklausų dalis tenka didžiausioms įmonėms.</string>
|
||||||
|
<string name="companies_other">Kitos</string>
|
||||||
|
<string name="no_data">Duomenų dar nėra</string>
|
||||||
|
<string name="recent_title">Naujausios užklausos</string>
|
||||||
|
<string name="filter">Filtras</string>
|
||||||
|
<string name="bl_search">Ieškoti sąrašų</string>
|
||||||
|
<string name="auto_update">Automatinis atnaujinimas</string>
|
||||||
|
<string name="auto_off">Išjungta</string>
|
||||||
|
<string name="auto_daily">Kasdien</string>
|
||||||
|
<string name="auto_weekly">Kas savaitę</string>
|
||||||
|
<string name="auto_wifi">Tik per Wi-Fi</string>
|
||||||
|
<string name="auto_wifi_desc">Neatnaujinti per mobiliuosius duomenis</string>
|
||||||
|
<string name="auto_update_now">Atnaujinti dabar</string>
|
||||||
|
<string name="done">Atlikta</string>
|
||||||
|
<string name="cancel">Atšaukti</string>
|
||||||
|
<string name="preset_pro_desc">Subalansuota apsauga nuo reklamų, sekimo ir kenkėjiškų svetainių. Geriausias pasirinkimas kasdien.</string>
|
||||||
|
<string name="preset_proplus_desc">Didžiausia apsauga. Gali sutrikdyti prisijungimą kai kuriose programėlėse ir nuorodas.</string>
|
||||||
|
<string name="preset_tif_desc">Grėsmių žvalgybos duomenys: kenkėjiški, sukčiavimo ir kriptovaliutų kasimo domenai.</string>
|
||||||
|
<string name="list_added_by_you">Pridėjote jūs pagal nuorodą.</string>
|
||||||
|
<string name="list_not_downloaded">Dar neatsisiųsta</string>
|
||||||
|
<string name="my_domains_desc">Domenai, kuriuos užblokavote patys. Blokuojami ir subdomenai.</string>
|
||||||
|
<string name="bl_add_list">Pridėti blokavimo sąrašą</string>
|
||||||
|
<string name="settings_general">Bendrieji</string>
|
||||||
|
<string name="settings_apps">Programėlės be SparkleDNS</string>
|
||||||
|
<string name="settings_apps_desc">Pasirinktos programėlės naudoja įprastą tinklo DNS</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<string name="status_on">Защищено</string>
|
|
||||||
<string name="status_off">Отключено</string>
|
|
||||||
<string name="via">через %1$s</string>
|
|
||||||
<string name="connect">Подключить</string>
|
<string name="connect">Подключить</string>
|
||||||
<string name="disconnect">Отключить</string>
|
<string name="disconnect">Отключить</string>
|
||||||
<string name="servers">Сервер DNS-over-HTTPS</string>
|
<string name="servers">Сервер DNS-over-HTTPS</string>
|
||||||
@@ -26,14 +23,10 @@
|
|||||||
<string name="notif_title">Защищено через %1$s</string>
|
<string name="notif_title">Защищено через %1$s</string>
|
||||||
<string name="notif_text">DNS через HTTPS активен</string>
|
<string name="notif_text">DNS через HTTPS активен</string>
|
||||||
<string name="tab_home">Главная</string>
|
<string name="tab_home">Главная</string>
|
||||||
<string name="tab_monitor">Монитор</string>
|
|
||||||
<string name="tab_apps">Приложения</string>
|
|
||||||
<string name="tab_blocklist">Блоклист</string>
|
<string name="tab_blocklist">Блоклист</string>
|
||||||
<string name="tab_about">О программе</string>
|
<string name="tab_about">О программе</string>
|
||||||
<string name="mon_queries">Запросы</string>
|
|
||||||
<string name="mon_cached">Из кэша</string>
|
<string name="mon_cached">Из кэша</string>
|
||||||
<string name="mon_blocked">Заблокировано</string>
|
<string name="mon_blocked">Заблокировано</string>
|
||||||
<string name="mon_latency">Средняя задержка</string>
|
|
||||||
<string name="mon_ms">%1$d мс</string>
|
<string name="mon_ms">%1$d мс</string>
|
||||||
<string name="mon_all">Все</string>
|
<string name="mon_all">Все</string>
|
||||||
<string name="mon_errors">Ошибки</string>
|
<string name="mon_errors">Ошибки</string>
|
||||||
@@ -60,12 +53,9 @@
|
|||||||
<string name="bl_invalid">Неверный домен</string>
|
<string name="bl_invalid">Неверный домен</string>
|
||||||
<string name="bl_empty_custom">Пока пусто</string>
|
<string name="bl_empty_custom">Пока пусто</string>
|
||||||
<string name="delete">Удалить</string>
|
<string name="delete">Удалить</string>
|
||||||
<string name="bl_lists">Списки</string>
|
|
||||||
<string name="bl_update_all">Обновить все</string>
|
|
||||||
<string name="bl_updating">Обновление…</string>
|
<string name="bl_updating">Обновление…</string>
|
||||||
<string name="bl_list_url">URL списка</string>
|
<string name="bl_list_url">URL списка</string>
|
||||||
<string name="bl_list_info">%1$s доменов · %2$s</string>
|
<string name="bl_list_info">%1$s доменов · %2$s</string>
|
||||||
<string name="bl_presets">Популярные списки</string>
|
|
||||||
<string name="bl_download_failed">Ошибка загрузки: %1$s</string>
|
<string name="bl_download_failed">Ошибка загрузки: %1$s</string>
|
||||||
<string name="about_desc">Шифруйте DNS-запросы, не пропуская весь трафик через VPN.</string>
|
<string name="about_desc">Шифруйте DNS-запросы, не пропуская весь трафик через VPN.</string>
|
||||||
<string name="about_version">Версия</string>
|
<string name="about_version">Версия</string>
|
||||||
@@ -84,17 +74,56 @@
|
|||||||
<string name="group_system">Системные</string>
|
<string name="group_system">Системные</string>
|
||||||
<string name="group_count">%1$d из %2$d через DNS</string>
|
<string name="group_count">%1$d из %2$d через DNS</string>
|
||||||
<string name="about_privacy_policy">Политика конфиденциальности</string>
|
<string name="about_privacy_policy">Политика конфиденциальности</string>
|
||||||
|
<string name="donate">Пожертвовать</string>
|
||||||
<string name="licenses_title">Лицензии открытого ПО</string>
|
<string name="licenses_title">Лицензии открытого ПО</string>
|
||||||
<string name="licenses_hint">SparkleDNS построен на этих проектах с открытым кодом. Нажмите на проект, чтобы открыть его страницу.</string>
|
<string name="licenses_hint">SparkleDNS построен на этих проектах с открытым кодом. Нажмите на проект, чтобы открыть его страницу.</string>
|
||||||
<string name="licenses_data">Данные блоклистов (загружаются по запросу, не входят в приложение)</string>
|
<string name="licenses_data">Данные блоклистов (загружаются по запросу, не входят в приложение)</string>
|
||||||
<string name="license_view">Текст лицензии</string>
|
<string name="license_view">Текст лицензии</string>
|
||||||
<string name="back">Назад</string>
|
<string name="back">Назад</string>
|
||||||
<string name="bl_total_label">доменов заблокировано</string>
|
|
||||||
<string name="about_source">Исходный код</string>
|
<string name="about_source">Исходный код</string>
|
||||||
<string name="open_settings">Настройки</string>
|
<string name="open_settings">Настройки</string>
|
||||||
<string name="mon_no_match">Ничего не найдено</string>
|
<string name="mon_no_match">Ничего не найдено</string>
|
||||||
<string name="bl_title">Блокировка</string>
|
<string name="no_browser">Не найдено приложение, чтобы открыть ссылку</string>
|
||||||
<string name="servers_update">Обновить список серверов</string>
|
<string name="toggle_on">ВКЛ</string>
|
||||||
<string name="servers_updated">Список серверов обновлён</string>
|
<string name="toggle_off">ВЫКЛ</string>
|
||||||
<string name="servers_update_failed">Не удалось обновить список серверов: %1$s</string>
|
<string name="home_protected">Вы защищены</string>
|
||||||
|
<string name="home_unprotected">Вы не защищены</string>
|
||||||
|
<string name="home_via">Шифруется через %1$s</string>
|
||||||
|
<string name="home_off_desc">DNS идёт через вашу сеть как обычно</string>
|
||||||
|
<string name="stat_requests">Запросы</string>
|
||||||
|
<string name="stat_avg">Среднее время</string>
|
||||||
|
<string name="chart_now">Сейчас</string>
|
||||||
|
<string name="period_24h">24 часа</string>
|
||||||
|
<string name="period_7d">7 дней</string>
|
||||||
|
<string name="home_lists_info">Включено списков: %1$d · правил: %2$s</string>
|
||||||
|
<string name="blocking_off">Блокировка выключена</string>
|
||||||
|
<string name="blocklist_title">Блок-листы DNS</string>
|
||||||
|
<string name="tab_activity">Активность</string>
|
||||||
|
<string name="tab_settings">Настройки</string>
|
||||||
|
<string name="companies_title">Доля компаний</string>
|
||||||
|
<string name="companies_desc">Какая часть ваших запросов уходит крупнейшим компаниям.</string>
|
||||||
|
<string name="companies_other">Другие</string>
|
||||||
|
<string name="no_data">Данных пока нет</string>
|
||||||
|
<string name="recent_title">Последние запросы</string>
|
||||||
|
<string name="filter">Фильтр</string>
|
||||||
|
<string name="bl_search">Поиск списков</string>
|
||||||
|
<string name="auto_update">Автообновление</string>
|
||||||
|
<string name="auto_off">Выкл</string>
|
||||||
|
<string name="auto_daily">Ежедневно</string>
|
||||||
|
<string name="auto_weekly">Еженедельно</string>
|
||||||
|
<string name="auto_wifi">Только по Wi-Fi</string>
|
||||||
|
<string name="auto_wifi_desc">Не обновлять через мобильный интернет</string>
|
||||||
|
<string name="auto_update_now">Обновить сейчас</string>
|
||||||
|
<string name="done">Готово</string>
|
||||||
|
<string name="cancel">Отмена</string>
|
||||||
|
<string name="preset_pro_desc">Сбалансированная защита от рекламы, трекинга и вредоносных сайтов. Лучший выбор на каждый день.</string>
|
||||||
|
<string name="preset_proplus_desc">Максимальная защита. Может ломать вход в некоторые приложения и ссылки.</string>
|
||||||
|
<string name="preset_tif_desc">Данные об угрозах: вредоносные, фишинговые, мошеннические и майнинговые домены.</string>
|
||||||
|
<string name="list_added_by_you">Добавлен вами по ссылке.</string>
|
||||||
|
<string name="list_not_downloaded">Ещё не загружен</string>
|
||||||
|
<string name="my_domains_desc">Домены, которые вы заблокировали сами. Поддомены блокируются тоже.</string>
|
||||||
|
<string name="bl_add_list">Добавить блок-лист</string>
|
||||||
|
<string name="settings_general">Общие</string>
|
||||||
|
<string name="settings_apps">Приложения без SparkleDNS</string>
|
||||||
|
<string name="settings_apps_desc">Выбранные приложения используют обычный DNS сети</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<string name="status_on">已保护</string>
|
|
||||||
<string name="status_off">未连接</string>
|
|
||||||
<string name="via">通过 %1$s</string>
|
|
||||||
<string name="connect">连接</string>
|
<string name="connect">连接</string>
|
||||||
<string name="disconnect">断开</string>
|
<string name="disconnect">断开</string>
|
||||||
<string name="servers">DNS-over-HTTPS 服务器</string>
|
<string name="servers">DNS-over-HTTPS 服务器</string>
|
||||||
@@ -26,14 +23,10 @@
|
|||||||
<string name="notif_title">已通过 %1$s 保护</string>
|
<string name="notif_title">已通过 %1$s 保护</string>
|
||||||
<string name="notif_text">DNS over HTTPS 已启用</string>
|
<string name="notif_text">DNS over HTTPS 已启用</string>
|
||||||
<string name="tab_home">首页</string>
|
<string name="tab_home">首页</string>
|
||||||
<string name="tab_monitor">监控</string>
|
|
||||||
<string name="tab_apps">应用</string>
|
|
||||||
<string name="tab_blocklist">屏蔽列表</string>
|
<string name="tab_blocklist">屏蔽列表</string>
|
||||||
<string name="tab_about">关于</string>
|
<string name="tab_about">关于</string>
|
||||||
<string name="mon_queries">查询</string>
|
|
||||||
<string name="mon_cached">来自缓存</string>
|
<string name="mon_cached">来自缓存</string>
|
||||||
<string name="mon_blocked">已屏蔽</string>
|
<string name="mon_blocked">已屏蔽</string>
|
||||||
<string name="mon_latency">平均延迟</string>
|
|
||||||
<string name="mon_ms">%1$d 毫秒</string>
|
<string name="mon_ms">%1$d 毫秒</string>
|
||||||
<string name="mon_all">全部</string>
|
<string name="mon_all">全部</string>
|
||||||
<string name="mon_errors">错误</string>
|
<string name="mon_errors">错误</string>
|
||||||
@@ -60,12 +53,9 @@
|
|||||||
<string name="bl_invalid">域名无效</string>
|
<string name="bl_invalid">域名无效</string>
|
||||||
<string name="bl_empty_custom">还没有域名</string>
|
<string name="bl_empty_custom">还没有域名</string>
|
||||||
<string name="delete">删除</string>
|
<string name="delete">删除</string>
|
||||||
<string name="bl_lists">列表</string>
|
|
||||||
<string name="bl_update_all">全部更新</string>
|
|
||||||
<string name="bl_updating">正在更新…</string>
|
<string name="bl_updating">正在更新…</string>
|
||||||
<string name="bl_list_url">列表 URL</string>
|
<string name="bl_list_url">列表 URL</string>
|
||||||
<string name="bl_list_info">%1$s 个域名 · %2$s</string>
|
<string name="bl_list_info">%1$s 个域名 · %2$s</string>
|
||||||
<string name="bl_presets">热门列表</string>
|
|
||||||
<string name="bl_download_failed">下载失败:%1$s</string>
|
<string name="bl_download_failed">下载失败:%1$s</string>
|
||||||
<string name="about_desc">加密 DNS 请求,无需让全部流量经过 VPN。</string>
|
<string name="about_desc">加密 DNS 请求,无需让全部流量经过 VPN。</string>
|
||||||
<string name="about_version">版本</string>
|
<string name="about_version">版本</string>
|
||||||
@@ -84,17 +74,56 @@
|
|||||||
<string name="group_system">系统</string>
|
<string name="group_system">系统</string>
|
||||||
<string name="group_count">%2$d 个中有 %1$d 个经过 DNS</string>
|
<string name="group_count">%2$d 个中有 %1$d 个经过 DNS</string>
|
||||||
<string name="about_privacy_policy">隐私政策</string>
|
<string name="about_privacy_policy">隐私政策</string>
|
||||||
|
<string name="donate">捐赠</string>
|
||||||
<string name="licenses_title">开源许可</string>
|
<string name="licenses_title">开源许可</string>
|
||||||
<string name="licenses_hint">SparkleDNS 使用了以下开源项目。点按项目可打开其页面。</string>
|
<string name="licenses_hint">SparkleDNS 使用了以下开源项目。点按项目可打开其页面。</string>
|
||||||
<string name="licenses_data">屏蔽列表数据(按需下载,未内置)</string>
|
<string name="licenses_data">屏蔽列表数据(按需下载,未内置)</string>
|
||||||
<string name="license_view">查看许可</string>
|
<string name="license_view">查看许可</string>
|
||||||
<string name="back">返回</string>
|
<string name="back">返回</string>
|
||||||
<string name="bl_total_label">个域名已屏蔽</string>
|
|
||||||
<string name="about_source">源代码</string>
|
<string name="about_source">源代码</string>
|
||||||
<string name="open_settings">设置</string>
|
<string name="open_settings">设置</string>
|
||||||
<string name="mon_no_match">没有符合筛选条件的内容</string>
|
<string name="mon_no_match">没有符合筛选条件的内容</string>
|
||||||
<string name="bl_title">屏蔽</string>
|
<string name="no_browser">没有可以打开此链接的应用</string>
|
||||||
<string name="servers_update">更新服务器列表</string>
|
<string name="toggle_on">开</string>
|
||||||
<string name="servers_updated">服务器列表已更新</string>
|
<string name="toggle_off">关</string>
|
||||||
<string name="servers_update_failed">无法更新服务器列表:%1$s</string>
|
<string name="home_protected">已受保护</string>
|
||||||
|
<string name="home_unprotected">未受保护</string>
|
||||||
|
<string name="home_via">通过 %1$s 加密</string>
|
||||||
|
<string name="home_off_desc">DNS 照常通过你的网络</string>
|
||||||
|
<string name="stat_requests">请求</string>
|
||||||
|
<string name="stat_avg">平均耗时</string>
|
||||||
|
<string name="chart_now">现在</string>
|
||||||
|
<string name="period_24h">24 小时</string>
|
||||||
|
<string name="period_7d">7 天</string>
|
||||||
|
<string name="home_lists_info">已启用列表:%1$d · 规则:%2$s</string>
|
||||||
|
<string name="blocking_off">屏蔽已关闭</string>
|
||||||
|
<string name="blocklist_title">DNS 屏蔽列表</string>
|
||||||
|
<string name="tab_activity">活动</string>
|
||||||
|
<string name="tab_settings">设置</string>
|
||||||
|
<string name="companies_title">公司占比</string>
|
||||||
|
<string name="companies_desc">你的请求中发往大公司的比例。</string>
|
||||||
|
<string name="companies_other">其他</string>
|
||||||
|
<string name="no_data">暂无数据</string>
|
||||||
|
<string name="recent_title">最近活动</string>
|
||||||
|
<string name="filter">筛选</string>
|
||||||
|
<string name="bl_search">搜索列表</string>
|
||||||
|
<string name="auto_update">自动更新</string>
|
||||||
|
<string name="auto_off">关闭</string>
|
||||||
|
<string name="auto_daily">每天</string>
|
||||||
|
<string name="auto_weekly">每周</string>
|
||||||
|
<string name="auto_wifi">仅限 Wi-Fi</string>
|
||||||
|
<string name="auto_wifi_desc">不使用移动数据更新</string>
|
||||||
|
<string name="auto_update_now">立即更新</string>
|
||||||
|
<string name="done">完成</string>
|
||||||
|
<string name="cancel">取消</string>
|
||||||
|
<string name="preset_pro_desc">均衡地拦截广告、跟踪和恶意软件。日常使用的最佳选择。</string>
|
||||||
|
<string name="preset_proplus_desc">最强保护。可能导致部分应用登录和链接失效。</string>
|
||||||
|
<string name="preset_tif_desc">威胁情报:恶意软件、钓鱼、诈骗和挖矿劫持域名。</string>
|
||||||
|
<string name="list_added_by_you">你通过网址添加。</string>
|
||||||
|
<string name="list_not_downloaded">尚未下载</string>
|
||||||
|
<string name="my_domains_desc">你自己屏蔽的域名。子域名也会被屏蔽。</string>
|
||||||
|
<string name="bl_add_list">添加屏蔽列表</string>
|
||||||
|
<string name="settings_general">通用</string>
|
||||||
|
<string name="settings_apps">不使用 SparkleDNS 的应用</string>
|
||||||
|
<string name="settings_apps_desc">选中的应用使用网络的常规 DNS</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<string name="app_name" translatable="false">SparkleDNS</string>
|
<string name="app_name" translatable="false">SparkleDNS</string>
|
||||||
<string name="status_on">Protected</string>
|
|
||||||
<string name="status_off">Disconnected</string>
|
|
||||||
<string name="via">via %1$s</string>
|
|
||||||
<string name="connect">Connect</string>
|
<string name="connect">Connect</string>
|
||||||
<string name="disconnect">Disconnect</string>
|
<string name="disconnect">Disconnect</string>
|
||||||
<string name="servers">DNS-over-HTTPS server</string>
|
<string name="servers">DNS-over-HTTPS server</string>
|
||||||
@@ -27,14 +24,10 @@
|
|||||||
<string name="notif_title">Protected via %1$s</string>
|
<string name="notif_title">Protected via %1$s</string>
|
||||||
<string name="notif_text">DNS over HTTPS is active</string>
|
<string name="notif_text">DNS over HTTPS is active</string>
|
||||||
<string name="tab_home">Home</string>
|
<string name="tab_home">Home</string>
|
||||||
<string name="tab_monitor">Monitor</string>
|
|
||||||
<string name="tab_apps">Apps</string>
|
|
||||||
<string name="tab_blocklist">Blocklist</string>
|
<string name="tab_blocklist">Blocklist</string>
|
||||||
<string name="tab_about">About</string>
|
<string name="tab_about">About</string>
|
||||||
<string name="mon_queries">Queries</string>
|
|
||||||
<string name="mon_cached">From cache</string>
|
<string name="mon_cached">From cache</string>
|
||||||
<string name="mon_blocked">Blocked</string>
|
<string name="mon_blocked">Blocked</string>
|
||||||
<string name="mon_latency">Avg latency</string>
|
|
||||||
<string name="mon_ms">%1$d ms</string>
|
<string name="mon_ms">%1$d ms</string>
|
||||||
<string name="mon_all">All</string>
|
<string name="mon_all">All</string>
|
||||||
<string name="mon_errors">Errors</string>
|
<string name="mon_errors">Errors</string>
|
||||||
@@ -61,12 +54,9 @@
|
|||||||
<string name="bl_invalid">Invalid domain</string>
|
<string name="bl_invalid">Invalid domain</string>
|
||||||
<string name="bl_empty_custom">No domains yet</string>
|
<string name="bl_empty_custom">No domains yet</string>
|
||||||
<string name="delete">Delete</string>
|
<string name="delete">Delete</string>
|
||||||
<string name="bl_lists">Lists</string>
|
|
||||||
<string name="bl_update_all">Update all</string>
|
|
||||||
<string name="bl_updating">Updating…</string>
|
<string name="bl_updating">Updating…</string>
|
||||||
<string name="bl_list_url">List URL</string>
|
<string name="bl_list_url">List URL</string>
|
||||||
<string name="bl_list_info">%1$s domains · %2$s</string>
|
<string name="bl_list_info">%1$s domains · %2$s</string>
|
||||||
<string name="bl_presets">Popular lists</string>
|
|
||||||
<string name="bl_download_failed">Download failed: %1$s</string>
|
<string name="bl_download_failed">Download failed: %1$s</string>
|
||||||
<string name="about_desc">Encrypt DNS requests without routing all your traffic through a VPN.</string>
|
<string name="about_desc">Encrypt DNS requests without routing all your traffic through a VPN.</string>
|
||||||
<string name="about_version">Version</string>
|
<string name="about_version">Version</string>
|
||||||
@@ -85,17 +75,56 @@
|
|||||||
<string name="group_system">System</string>
|
<string name="group_system">System</string>
|
||||||
<string name="group_count">%1$d of %2$d via DNS</string>
|
<string name="group_count">%1$d of %2$d via DNS</string>
|
||||||
<string name="about_privacy_policy">Privacy policy</string>
|
<string name="about_privacy_policy">Privacy policy</string>
|
||||||
|
<string name="donate">Donate</string>
|
||||||
<string name="licenses_title">Open-source licenses</string>
|
<string name="licenses_title">Open-source licenses</string>
|
||||||
<string name="licenses_hint">SparkleDNS is built with these open-source projects. Tap a project to open its page.</string>
|
<string name="licenses_hint">SparkleDNS is built with these open-source projects. Tap a project to open its page.</string>
|
||||||
<string name="licenses_data">Blocklist data (downloaded on demand, not bundled)</string>
|
<string name="licenses_data">Blocklist data (downloaded on demand, not bundled)</string>
|
||||||
<string name="license_view">View license</string>
|
<string name="license_view">View license</string>
|
||||||
<string name="back">Back</string>
|
<string name="back">Back</string>
|
||||||
<string name="bl_total_label">domains blocked</string>
|
|
||||||
<string name="about_source">Source code</string>
|
<string name="about_source">Source code</string>
|
||||||
<string name="open_settings">Settings</string>
|
<string name="open_settings">Settings</string>
|
||||||
<string name="mon_no_match">Nothing matches the filter</string>
|
<string name="mon_no_match">Nothing matches the filter</string>
|
||||||
<string name="bl_title">Blocking</string>
|
<string name="no_browser">No app found to open this link</string>
|
||||||
<string name="servers_update">Update server list</string>
|
<string name="toggle_on">ON</string>
|
||||||
<string name="servers_updated">Server list updated</string>
|
<string name="toggle_off">OFF</string>
|
||||||
<string name="servers_update_failed">Couldn\'t update the server list: %1$s</string>
|
<string name="home_protected">You\'re protected</string>
|
||||||
|
<string name="home_unprotected">You\'re not protected</string>
|
||||||
|
<string name="home_via">Encrypted via %1$s</string>
|
||||||
|
<string name="home_off_desc">DNS goes through your network as usual</string>
|
||||||
|
<string name="stat_requests">Requests</string>
|
||||||
|
<string name="stat_avg">Avg. time</string>
|
||||||
|
<string name="chart_now">Now</string>
|
||||||
|
<string name="period_24h">24 hours</string>
|
||||||
|
<string name="period_7d">7 days</string>
|
||||||
|
<string name="home_lists_info">Lists on: %1$d · rules: %2$s</string>
|
||||||
|
<string name="blocking_off">Blocking is off</string>
|
||||||
|
<string name="blocklist_title">DNS Blocklist</string>
|
||||||
|
<string name="tab_activity">Activity</string>
|
||||||
|
<string name="tab_settings">Settings</string>
|
||||||
|
<string name="companies_title">Company dominance</string>
|
||||||
|
<string name="companies_desc">Share of your requests that go to the biggest companies.</string>
|
||||||
|
<string name="companies_other">Other</string>
|
||||||
|
<string name="no_data">No data yet</string>
|
||||||
|
<string name="recent_title">Recent activity</string>
|
||||||
|
<string name="filter">Filter</string>
|
||||||
|
<string name="bl_search">Search lists</string>
|
||||||
|
<string name="auto_update">Auto-update</string>
|
||||||
|
<string name="auto_off">Off</string>
|
||||||
|
<string name="auto_daily">Daily</string>
|
||||||
|
<string name="auto_weekly">Weekly</string>
|
||||||
|
<string name="auto_wifi">Wi-Fi only</string>
|
||||||
|
<string name="auto_wifi_desc">Skip updates on mobile data</string>
|
||||||
|
<string name="auto_update_now">Update now</string>
|
||||||
|
<string name="done">Done</string>
|
||||||
|
<string name="cancel">Cancel</string>
|
||||||
|
<string name="preset_pro_desc">Balanced protection from ads, tracking and malware. The best choice for everyday use.</string>
|
||||||
|
<string name="preset_proplus_desc">Maximum protection. Can break some app logins and links.</string>
|
||||||
|
<string name="preset_tif_desc">Threat intelligence feeds: malware, phishing, scam and cryptojacking domains.</string>
|
||||||
|
<string name="list_added_by_you">Added by you from a URL.</string>
|
||||||
|
<string name="list_not_downloaded">Not downloaded yet</string>
|
||||||
|
<string name="my_domains_desc">Domains you blocked yourself. Subdomains are blocked too.</string>
|
||||||
|
<string name="bl_add_list">Add new blocklist</string>
|
||||||
|
<string name="settings_general">General</string>
|
||||||
|
<string name="settings_apps">Apps without SparkleDNS</string>
|
||||||
|
<string name="settings_apps_desc">Picked apps use the regular DNS of the network</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<style name="Theme.SparkleDNS" parent="android:Theme.Material.NoActionBar">
|
<style name="Theme.SparkleDNS" parent="android:Theme.Material.NoActionBar">
|
||||||
<item name="android:windowBackground">#FF0F1115</item>
|
<item name="android:windowBackground">#FF08090B</item>
|
||||||
</style>
|
</style>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class BlocklistMatchTest {
|
||||||
|
|
||||||
|
private fun set(vararg domains: String) = domains.map { DomainHash.of(it) }.sorted().toLongArray()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun blocksDomainsAndTheirSubdomains() {
|
||||||
|
val lists = set("ads.example.com")
|
||||||
|
val custom = set("tracker.net")
|
||||||
|
|
||||||
|
assertTrue(isBlockedIn("ads.example.com", lists, custom))
|
||||||
|
assertTrue(isBlockedIn("a.b.ads.example.com.", lists, custom))
|
||||||
|
assertTrue(isBlockedIn("cdn.tracker.net", lists, custom))
|
||||||
|
assertFalse(isBlockedIn("example.com", lists, custom))
|
||||||
|
assertFalse(isBlockedIn("badads.example.com", lists, custom))
|
||||||
|
assertFalse(isBlockedIn("tracker.network", lists, custom))
|
||||||
|
assertFalse(isBlockedIn("ads.example.com", LongArray(0), LongArray(0)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun mergesSortedListsWithoutDuplicates() {
|
||||||
|
val a = longArrayOf(-5, 1, 4, 9)
|
||||||
|
val b = longArrayOf(1, 2, 9, 12)
|
||||||
|
val c = longArrayOf(3)
|
||||||
|
|
||||||
|
assertArrayEquals(longArrayOf(-5, 1, 2, 3, 4, 9, 12), mergeSorted(listOf(a, b, c, LongArray(0))))
|
||||||
|
assertArrayEquals(LongArray(0), mergeSorted(emptyList()))
|
||||||
|
assertArrayEquals(a, mergeSorted(listOf(a)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sortsInputsThatAreNotSorted() {
|
||||||
|
assertArrayEquals(longArrayOf(1, 2, 3, 7), mergeSorted(listOf(longArrayOf(3, 1, 3), longArrayOf(7, 2))))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun countsEntriesInBothSetsOnce() {
|
||||||
|
assertEquals(5, unionSize(longArrayOf(1, 2, 3, 4), longArrayOf(2, 5)))
|
||||||
|
assertEquals(2, unionSize(LongArray(0), longArrayOf(2, 5)))
|
||||||
|
assertEquals(4, unionSize(longArrayOf(1, 2, 3, 4), LongArray(0)))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class BlocklistParserTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun understandsCommonListFormats() {
|
||||||
|
assertEquals("ads.example.com", BlocklistParser.parseLine("0.0.0.0 ads.example.com"))
|
||||||
|
assertEquals("ads.example.com", BlocklistParser.parseLine("127.0.0.1\tads.example.com # tracker"))
|
||||||
|
assertEquals("ads.example.com", BlocklistParser.parseLine("ads.example.com"))
|
||||||
|
assertEquals("tracker.example", BlocklistParser.parseLine("||tracker.example^"))
|
||||||
|
assertEquals("tracker.example", BlocklistParser.parseLine("||tracker.example^\$third-party"))
|
||||||
|
assertEquals("bad.example", BlocklistParser.parseLine("address=/bad.example/0.0.0.0"))
|
||||||
|
assertEquals("bad.example", BlocklistParser.parseLine("server=/bad.example/"))
|
||||||
|
assertEquals("bad.example", BlocklistParser.parseLine("local-zone: \"bad.example\" always_nxdomain"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun skipsCommentsRulesAndLocalNames() {
|
||||||
|
assertNull(BlocklistParser.parseLine(""))
|
||||||
|
assertNull(BlocklistParser.parseLine("# comment"))
|
||||||
|
assertNull(BlocklistParser.parseLine("! adblock comment"))
|
||||||
|
assertNull(BlocklistParser.parseLine("[Adblock Plus 2.0]"))
|
||||||
|
assertNull(BlocklistParser.parseLine("@@||allowed.example^"))
|
||||||
|
assertNull(BlocklistParser.parseLine("example.com##.banner"))
|
||||||
|
assertNull(BlocklistParser.parseLine("127.0.0.1 localhost"))
|
||||||
|
assertNull(BlocklistParser.parseLine("0.0.0.0 0.0.0.0"))
|
||||||
|
assertNull(BlocklistParser.parseLine("::1 ip6-localhost"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun normalizesUserInput() {
|
||||||
|
assertEquals("example.com", BlocklistParser.normalize(" HTTPS://Example.COM/path?q=1 "))
|
||||||
|
assertEquals("example.com", BlocklistParser.normalize("*.example.com"))
|
||||||
|
assertEquals("example.com", BlocklistParser.normalize("example.com."))
|
||||||
|
assertEquals("example.com", BlocklistParser.normalize("example.com:8080"))
|
||||||
|
assertNull(BlocklistParser.normalize("localhost"))
|
||||||
|
assertNull(BlocklistParser.normalize("bad..example"))
|
||||||
|
assertNull(BlocklistParser.normalize("-bad.example"))
|
||||||
|
assertNull(BlocklistParser.normalize("exa mple.com"))
|
||||||
|
assertNull(BlocklistParser.normalize("192.168.0.1"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun parentHashMatchesHashOfTheSuffix() {
|
||||||
|
val name = "a.b.example.com"
|
||||||
|
assertEquals(DomainHash.of("example.com"), DomainHash.of(name, name.indexOf("example")))
|
||||||
|
assertEquals(DomainHash.of(name), DomainHash.of(name, 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class DnsCacheTest {
|
||||||
|
|
||||||
|
private var now = 1_000_000L
|
||||||
|
private val cache = DnsCache(clock = { now })
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun answersWithTheNewQueryIdAndAgedTtl() {
|
||||||
|
val first = DnsMessage.buildQuery("example.com")
|
||||||
|
cache.put(first, dnsResponse(first, ttls = listOf(300)))
|
||||||
|
now += 10_000
|
||||||
|
|
||||||
|
val second = DnsMessage.buildQuery("EXAMPLE.com")
|
||||||
|
val hit = requireNotNull(cache.get(second))
|
||||||
|
|
||||||
|
assertEquals(second[0], hit[0])
|
||||||
|
assertEquals(second[1], hit[1])
|
||||||
|
assertEquals(290L, answerTtl(hit))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun expiresWithTheShortestTtl() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
cache.put(query, dnsResponse(query, ttls = listOf(300, 60)))
|
||||||
|
|
||||||
|
now += 59_000
|
||||||
|
val hit = requireNotNull(cache.get(query))
|
||||||
|
assertEquals(241L, answerTtl(hit, 0))
|
||||||
|
assertEquals(1L, answerTtl(hit, 1))
|
||||||
|
|
||||||
|
now += 1_000
|
||||||
|
assertNull(cache.get(query))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun capsTtlAtOneHour() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
cache.put(query, dnsResponse(query, ttls = listOf(86_400)))
|
||||||
|
|
||||||
|
now += 3_599_000
|
||||||
|
assertNotNull(cache.get(query))
|
||||||
|
now += 1_000
|
||||||
|
assertNull(cache.get(query))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun keepsEmptyNxdomainForThirtySeconds() {
|
||||||
|
val query = DnsMessage.buildQuery("nothing.example")
|
||||||
|
cache.put(query, dnsResponse(query, rcode = 3, ttls = emptyList()))
|
||||||
|
|
||||||
|
now += 29_000
|
||||||
|
assertEquals(3, DnsMessage.rcode(requireNotNull(cache.get(query))))
|
||||||
|
now += 1_000
|
||||||
|
assertNull(cache.get(query))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun skipsFailuresTruncatedAndZeroTtlAnswers() {
|
||||||
|
val failed = DnsMessage.buildQuery("a.example")
|
||||||
|
val truncated = DnsMessage.buildQuery("b.example")
|
||||||
|
val zero = DnsMessage.buildQuery("c.example")
|
||||||
|
|
||||||
|
cache.put(failed, dnsResponse(failed, rcode = 2))
|
||||||
|
cache.put(truncated, dnsResponse(truncated, truncated = true))
|
||||||
|
cache.put(zero, dnsResponse(zero, ttls = listOf(0)))
|
||||||
|
|
||||||
|
assertNull(cache.get(failed))
|
||||||
|
assertNull(cache.get(truncated))
|
||||||
|
assertNull(cache.get(zero))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun leavesTheOptRecordAlone() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
val response = dnsResponse(query, withOpt = true)
|
||||||
|
cache.put(query, response)
|
||||||
|
now += 10_000
|
||||||
|
|
||||||
|
val hit = requireNotNull(cache.get(query))
|
||||||
|
|
||||||
|
assertArrayEquals(response.copyOfRange(response.size - 11, response.size), hit.copyOfRange(hit.size - 11, hit.size))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun separatesRecordTypes() {
|
||||||
|
val a = DnsMessage.buildQuery("example.com", type = 1)
|
||||||
|
val aaaa = DnsMessage.buildQuery("example.com", type = 28)
|
||||||
|
cache.put(a, dnsResponse(a))
|
||||||
|
|
||||||
|
assertNull(cache.get(aaaa))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun evictsTheLeastRecentlyUsedEntry() {
|
||||||
|
val small = DnsCache(maxEntries = 2, clock = { now })
|
||||||
|
val a = DnsMessage.buildQuery("a.example")
|
||||||
|
val b = DnsMessage.buildQuery("b.example")
|
||||||
|
val c = DnsMessage.buildQuery("c.example")
|
||||||
|
small.put(a, dnsResponse(a))
|
||||||
|
small.put(b, dnsResponse(b))
|
||||||
|
small.get(a)
|
||||||
|
small.put(c, dnsResponse(c))
|
||||||
|
|
||||||
|
assertNotNull(small.get(a))
|
||||||
|
assertNull(small.get(b))
|
||||||
|
assertNotNull(small.get(c))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertSame
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class DnsMessageTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun questionIsReadBackLowercase() {
|
||||||
|
val question = requireNotNull(DnsMessage.question(DnsMessage.buildQuery("WWW.Example.COM.", type = 28)))
|
||||||
|
|
||||||
|
assertEquals("www.example.com", question.name)
|
||||||
|
assertEquals(28, question.type)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun questionRejectsCompressedOrCutNames() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
val compressed = query.copyOf(12) + byteArrayOf(0xC0.toByte(), 0x0C, 0, 1, 0, 1)
|
||||||
|
|
||||||
|
assertNull(DnsMessage.question(compressed))
|
||||||
|
assertNull(DnsMessage.question(query.copyOf(16)))
|
||||||
|
assertNull(DnsMessage.question(query.copyOf(11)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun withIdCopiesTheQueryId() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
val response = dnsResponse(query)
|
||||||
|
response[0] = (query[0] + 1).toByte()
|
||||||
|
|
||||||
|
val fixed = DnsMessage.withId(response, query)
|
||||||
|
|
||||||
|
assertEquals(query[0], fixed[0])
|
||||||
|
assertEquals(query[1], fixed[1])
|
||||||
|
assertSame(fixed, DnsMessage.withId(fixed, query))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun errorReplyKeepsOnlyTheQuestion() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
// An EDNS OPT record in the additional section must not be echoed back
|
||||||
|
val withOpt = query.copyOf().also { it[11] = 1 } + byteArrayOf(0, 0, 41, 0x10, 0, 0, 0, 0, 0, 0, 0)
|
||||||
|
|
||||||
|
val reply = requireNotNull(DnsMessage.errorReply(withOpt, DnsMessage.RCODE_NXDOMAIN))
|
||||||
|
|
||||||
|
assertEquals(query.size, reply.size)
|
||||||
|
assertTrue(DnsMessage.isResponse(reply))
|
||||||
|
assertEquals(DnsMessage.RCODE_NXDOMAIN, DnsMessage.rcode(reply))
|
||||||
|
assertEquals(1, u16(reply, 4))
|
||||||
|
assertArrayEquals(ByteArray(6), reply.copyOfRange(6, 12))
|
||||||
|
assertArrayEquals(query.copyOfRange(12, query.size), reply.copyOfRange(12, reply.size))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun servfailAndResponseFlags() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
|
||||||
|
assertFalse(DnsMessage.isResponse(query))
|
||||||
|
assertEquals(DnsMessage.RCODE_SERVFAIL, DnsMessage.rcode(requireNotNull(DnsMessage.servfail(query))))
|
||||||
|
assertNull(DnsMessage.servfail(ByteArray(5)))
|
||||||
|
assertEquals(-1, DnsMessage.rcode(ByteArray(2)))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class PacketTest {
|
||||||
|
|
||||||
|
private val client = byteArrayOf(10, 111, 222.toByte(), 1)
|
||||||
|
private val server = byteArrayOf(10, 111, 222.toByte(), 2)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun parsesDnsQuery() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
val packet = ipv4Udp(client, server, 40000, 53, query)
|
||||||
|
|
||||||
|
val parsed = requireNotNull(Packet.parseDnsQuery(packet, packet.size))
|
||||||
|
|
||||||
|
assertArrayEquals(query, parsed.payload)
|
||||||
|
assertArrayEquals(client, parsed.srcIp)
|
||||||
|
assertArrayEquals(server, parsed.dstIp)
|
||||||
|
assertEquals(40000, parsed.srcPort)
|
||||||
|
assertEquals(53, parsed.dstPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun usesOnlyTheBytesThatWereRead() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
val packet = ipv4Udp(client, server, 40000, 53, query)
|
||||||
|
val buffer = packet + ByteArray(100) { 0x55 }
|
||||||
|
|
||||||
|
val parsed = requireNotNull(Packet.parseDnsQuery(buffer, packet.size))
|
||||||
|
|
||||||
|
assertArrayEquals(query, parsed.payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ignoresEverythingThatIsNotADnsQuery() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
val otherPort = ipv4Udp(client, server, 40000, 443, query)
|
||||||
|
val tcp = ipv4Udp(client, server, 40000, 53, query, protocol = 6)
|
||||||
|
val fragment = ipv4Udp(client, server, 40000, 53, query, flagsAndOffset = 0x2000)
|
||||||
|
val ipv6 = ipv4Udp(client, server, 40000, 53, query).also { it[0] = 0x60 }
|
||||||
|
|
||||||
|
assertNull(Packet.parseDnsQuery(otherPort, otherPort.size))
|
||||||
|
assertNull(Packet.parseDnsQuery(tcp, tcp.size))
|
||||||
|
assertNull(Packet.parseDnsQuery(fragment, fragment.size))
|
||||||
|
assertNull(Packet.parseDnsQuery(ipv6, ipv6.size))
|
||||||
|
assertNull(Packet.parseDnsQuery(otherPort, 27))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun replySwapsEndpointsAndHasValidChecksums() {
|
||||||
|
val query = DnsMessage.buildQuery("example.com")
|
||||||
|
val packet = ipv4Udp(client, server, 40000, 53, query)
|
||||||
|
val parsed = requireNotNull(Packet.parseDnsQuery(packet, packet.size))
|
||||||
|
// Odd length exercises the checksum padding
|
||||||
|
val answer = dnsResponse(query) + byteArrayOf(7)
|
||||||
|
|
||||||
|
val reply = Packet.buildReply(parsed, answer)
|
||||||
|
|
||||||
|
assertEquals(28 + answer.size, reply.size)
|
||||||
|
assertEquals(0x45, reply[0].toInt())
|
||||||
|
assertEquals(reply.size, u16(reply, 2))
|
||||||
|
assertArrayEquals(server, reply.copyOfRange(12, 16))
|
||||||
|
assertArrayEquals(client, reply.copyOfRange(16, 20))
|
||||||
|
assertEquals(53, u16(reply, 20))
|
||||||
|
assertEquals(40000, u16(reply, 22))
|
||||||
|
assertArrayEquals(answer, reply.copyOfRange(28, reply.size))
|
||||||
|
assertEquals(0xFFFF, onesSum(reply.copyOfRange(0, 20)))
|
||||||
|
|
||||||
|
val udp = reply.copyOfRange(20, reply.size)
|
||||||
|
val pseudo = reply.copyOfRange(12, 20) + byteArrayOf(0, 17) + byteArrayOf((udp.size shr 8).toByte(), udp.size.toByte())
|
||||||
|
assertEquals(0xFFFF, onesSum(pseudo, udp))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package cc.skysparkle.sparkledns
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
|
||||||
|
// Hand-built DNS messages and IPv4/UDP packets for the tests
|
||||||
|
|
||||||
|
internal fun dnsResponse(
|
||||||
|
query: ByteArray,
|
||||||
|
rcode: Int = 0,
|
||||||
|
ttls: List<Int> = listOf(300),
|
||||||
|
withOpt: Boolean = false,
|
||||||
|
truncated: Boolean = false,
|
||||||
|
): ByteArray {
|
||||||
|
val questionEnd = requireNotNull(skipName(query, 12)) + 4
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
out.write(query, 0, 2)
|
||||||
|
out.write(0x81 or if (truncated) 0x02 else 0) // QR + RD (+ TC)
|
||||||
|
out.write(0x80 or rcode) // RA + RCODE
|
||||||
|
out.write(byteArrayOf(0, 1, 0, ttls.size.toByte(), 0, 0, 0, (if (withOpt) 1 else 0).toByte()))
|
||||||
|
out.write(query, 12, questionEnd - 12)
|
||||||
|
for (ttl in ttls) {
|
||||||
|
out.write(byteArrayOf(0xC0.toByte(), 0x0C, 0, 1, 0, 1))
|
||||||
|
out.write(be32(ttl))
|
||||||
|
out.write(byteArrayOf(0, 4, 93, 184.toByte(), 216.toByte(), 34))
|
||||||
|
}
|
||||||
|
if (withOpt) {
|
||||||
|
// Root name, type OPT, UDP size 4096, extended flags with the DO bit, no data
|
||||||
|
out.write(byteArrayOf(0, 0, 41, 0x10, 0, 0, 0, 0x80.toByte(), 0, 0, 0))
|
||||||
|
}
|
||||||
|
return out.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ipv4Udp(
|
||||||
|
src: ByteArray,
|
||||||
|
dst: ByteArray,
|
||||||
|
srcPort: Int,
|
||||||
|
dstPort: Int,
|
||||||
|
payload: ByteArray,
|
||||||
|
protocol: Int = 17,
|
||||||
|
flagsAndOffset: Int = 0,
|
||||||
|
): ByteArray {
|
||||||
|
val p = ByteArray(28 + payload.size)
|
||||||
|
p[0] = 0x45
|
||||||
|
put16(p, 2, p.size)
|
||||||
|
put16(p, 6, flagsAndOffset)
|
||||||
|
p[8] = 64
|
||||||
|
p[9] = protocol.toByte()
|
||||||
|
src.copyInto(p, 12)
|
||||||
|
dst.copyInto(p, 16)
|
||||||
|
put16(p, 20, srcPort)
|
||||||
|
put16(p, 22, dstPort)
|
||||||
|
put16(p, 24, 8 + payload.size)
|
||||||
|
payload.copyInto(p, 28)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// One's complement sum of 16-bit words; a correct checksum makes it 0xFFFF
|
||||||
|
internal fun onesSum(vararg parts: ByteArray): Int {
|
||||||
|
var sum = 0L
|
||||||
|
for (part in parts) {
|
||||||
|
var i = 0
|
||||||
|
while (i + 1 < part.size) {
|
||||||
|
sum += u16(part, i)
|
||||||
|
i += 2
|
||||||
|
}
|
||||||
|
if (i < part.size) sum += (part[i].toInt() and 0xFF) shl 8
|
||||||
|
}
|
||||||
|
while (sum shr 16 != 0L) sum = (sum and 0xFFFF) + (sum shr 16)
|
||||||
|
return sum.toInt()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun be32(value: Int) = ByteArray(4).also { put32(it, 0, value) }
|
||||||
|
|
||||||
|
// TTL field of the n-th answer of a message built by dnsResponse
|
||||||
|
internal fun answerTtl(message: ByteArray, index: Int = 0): Long {
|
||||||
|
val first = requireNotNull(skipName(message, 12)) + 4
|
||||||
|
return u32(message, first + index * 16 + 6)
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
|
After Width: | Height: | Size: 143 KiB |
|
Before Width: | Height: | Size: 166 KiB |
|
Before Width: | Height: | Size: 214 KiB After Width: | Height: | Size: 132 KiB |
|
After Width: | Height: | Size: 205 KiB |
|
Before Width: | Height: | Size: 177 KiB |
|
After Width: | Height: | Size: 158 KiB |
|
Before Width: | Height: | Size: 171 KiB |
|
Before Width: | Height: | Size: 198 KiB |
@@ -0,0 +1,5 @@
|
|||||||
|
• Spendenlinks neben der Datenschutzerklärung bei Servern, die Spenden annehmen
|
||||||
|
• Einfachere Serverliste
|
||||||
|
• Neues Symbol für die Datenschutzerklärung bei den Servern
|
||||||
|
• HTTP/3-Kennzeichnung aus der Serverliste entfernt
|
||||||
|
• Kürzere Beschreibung unter „Info“
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• DNS funktioniert weiter, wenn ein unerwartetes Paket ankommt; fällt der Tunnel aus, schaltet sich das VPN ab, statt DNS still zu blockieren
|
||||||
|
• Anfragen erholen sich schneller nach einem Wechsel zwischen WLAN und Mobilfunk und in langsamen Netzen
|
||||||
|
• Weniger Arbeit im Hintergrund: ausgeblendete Bildschirme werden nicht mehr aktualisiert
|
||||||
|
• Blocklisten werden nur noch erneut geladen, wenn sie sich geändert haben
|
||||||
|
• Schärfere App-Symbole, kleinere App
|
||||||
|
• Ein Doppeltipp auf „Verbinden“ verbindet nicht mehr doppelt; voller Speicher lässt die App nicht mehr abstürzen
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• Neues Design: dunkler Look mit schwebender Leiste für Start, Aktivität und Einstellungen
|
||||||
|
• Der Startbildschirm zeigt den aktuellen Server und ein 24-Stunden-Diagramm
|
||||||
|
• Aktivität: Statistik für 24 Stunden oder 7 Tage und der Anteil der größten Konzerne
|
||||||
|
• Neue Vorlage HaGeZi Pro; Listen lassen sich ausschalten, ohne sie zu löschen
|
||||||
|
• Blocklisten werden automatisch täglich oder wöchentlich aktualisiert, auf Wunsch nur über WLAN
|
||||||
|
• Die Serverliste kommt mit der App und wird nicht mehr geladen
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
<li>Sende DNS-Anfragen per RFC 8484 an den DoH-Server deiner Wahl.</li>
|
<li>Sende DNS-Anfragen per RFC 8484 an den DoH-Server deiner Wahl.</li>
|
||||||
<li>Prüfe Protokoll und Latenz eines Servers, bevor du dich verbindest.</li>
|
<li>Prüfe Protokoll und Latenz eines Servers, bevor du dich verbindest.</li>
|
||||||
<li>Sieh Anfragen und Statistiken live, filtere die Aktivität und blockiere Domains mit einem Tippen.</li>
|
<li>Sieh Anfragen und Statistiken live, filtere die Aktivität und blockiere Domains mit einem Tippen.</li>
|
||||||
<li>Füge eigene Domainregeln oder Blocklisten per URL hinzu, inklusive der Vorlagen HaGeZi Pro++ und TIF.</li>
|
<li>Füge eigene Domainregeln oder Blocklisten per URL hinzu, inklusive der Vorlagen HaGeZi Pro, Pro++ und TIF, die sich täglich oder wöchentlich automatisch aktualisieren.</li>
|
||||||
<li>Lass ausgewählte Apps den DNS-Tunnel umgehen.</li>
|
<li>Lass ausgewählte Apps den DNS-Tunnel umgehen.</li>
|
||||||
<li>Verbinde oder trenne mit einem Tippen oder über die Kachel in den Schnelleinstellungen.</li>
|
<li>Verbinde oder trenne mit einem Tippen oder über die Kachel in den Schnelleinstellungen.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
• Donation links next to the privacy policy for servers that accept donations
|
||||||
|
• Simpler server list
|
||||||
|
• New privacy policy icon on servers
|
||||||
|
• HTTP/3 badge removed from the server list
|
||||||
|
• Shorter About description
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• DNS keeps working when an unexpected packet arrives; if the tunnel fails, the VPN turns off instead of silently blocking DNS
|
||||||
|
• Lookups recover faster after switching between Wi-Fi and mobile data and on slow networks
|
||||||
|
• Less work in the background: hidden screens are no longer refreshed
|
||||||
|
• Blocklists are downloaded again only when they changed
|
||||||
|
• Sharper app icons, smaller app
|
||||||
|
• A double tap on Connect no longer connects twice; a full storage no longer crashes the app
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• New design: a dark look with a floating panel for Home, Activity and Settings
|
||||||
|
• Home shows the current server and a 24-hour chart
|
||||||
|
• Activity: stats for 24 hours or 7 days and the share of the biggest companies
|
||||||
|
• New HaGeZi Pro preset; lists can be switched off without deleting them
|
||||||
|
• Blocklists update automatically every day or week, on Wi-Fi only if you like
|
||||||
|
• The server list ships with the app and is no longer downloaded
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
<li>Send DNS queries to your chosen DoH server using RFC 8484.</li>
|
<li>Send DNS queries to your chosen DoH server using RFC 8484.</li>
|
||||||
<li>Check server protocol and latency before you connect.</li>
|
<li>Check server protocol and latency before you connect.</li>
|
||||||
<li>See live queries and stats, filter activity, and block domains with a tap.</li>
|
<li>See live queries and stats, filter activity, and block domains with a tap.</li>
|
||||||
<li>Add custom domain rules or blocklists by URL, including HaGeZi Pro++ and TIF presets.</li>
|
<li>Add custom domain rules or blocklists by URL, including HaGeZi Pro, Pro++ and TIF presets, updated automatically every day or week.</li>
|
||||||
<li>Let selected apps bypass the DNS tunnel.</li>
|
<li>Let selected apps bypass the DNS tunnel.</li>
|
||||||
<li>Connect or disconnect in one tap, or use the Quick Settings tile.</li>
|
<li>Connect or disconnect in one tap, or use the Quick Settings tile.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 166 KiB After Width: | Height: | Size: 143 KiB |
|
Before Width: | Height: | Size: 214 KiB After Width: | Height: | Size: 132 KiB |
|
Before Width: | Height: | Size: 177 KiB After Width: | Height: | Size: 205 KiB |
|
Before Width: | Height: | Size: 171 KiB After Width: | Height: | Size: 158 KiB |
|
Before Width: | Height: | Size: 198 KiB |
@@ -0,0 +1,5 @@
|
|||||||
|
• 寄付を受け付けているサーバーには、プライバシーポリシーの横に寄付リンクを表示
|
||||||
|
• サーバーリストをシンプルに
|
||||||
|
• サーバーのプライバシーポリシーアイコンを新しく
|
||||||
|
• サーバーリストから HTTP/3 の表示を削除
|
||||||
|
• 「情報」の説明を短く
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• 想定外のパケットが届いても DNS は動作し続けます。トンネルが故障した場合は、DNS を黙って止めずに VPN をオフにします
|
||||||
|
• Wi-Fi とモバイルデータの切り替え後や遅いネットワークで、名前解決がより早く回復します
|
||||||
|
• バックグラウンドでの処理を削減:表示されていない画面は更新しません
|
||||||
|
• ブロックリストは変更があったときだけ再ダウンロードします
|
||||||
|
• アプリアイコンがより鮮明に、アプリサイズが小さく
|
||||||
|
• 「接続」をダブルタップしても二重に接続しません。ストレージがいっぱいでもアプリが落ちなくなりました
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• 新デザイン:ダークな外観と、ホーム・アクティビティ・設定のフローティングパネル
|
||||||
|
• ホームに現在のサーバーと 24 時間のグラフを表示
|
||||||
|
• アクティビティ:24 時間または 7 日間の統計と大手企業の占有率
|
||||||
|
• HaGeZi Pro プリセットを追加。リストは削除せずにオフにできます
|
||||||
|
• ブロックリストを毎日または毎週自動更新(Wi-Fi のみも選択可)
|
||||||
|
• サーバーリストはアプリに内蔵され、ダウンロードしなくなりました
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
<li>選んだDoHサーバーへRFC 8484でDNSクエリを送信。</li>
|
<li>選んだDoHサーバーへRFC 8484でDNSクエリを送信。</li>
|
||||||
<li>接続前にサーバーのプロトコルと遅延を確認。</li>
|
<li>接続前にサーバーのプロトコルと遅延を確認。</li>
|
||||||
<li>クエリと統計をリアルタイムで表示し、アクティビティを絞り込み、ワンタップでドメインをブロック。</li>
|
<li>クエリと統計をリアルタイムで表示し、アクティビティを絞り込み、ワンタップでドメインをブロック。</li>
|
||||||
<li>独自のドメインルールやURL指定のブロックリストを追加。HaGeZi Pro++やTIFのプリセットも利用可能。</li>
|
<li>独自のドメインルールやURL指定のブロックリストを追加。HaGeZi Pro、Pro++、TIFのプリセットも利用可能で、毎日または毎週自動更新されます。</li>
|
||||||
<li>選んだアプリだけDNSトンネルを経由しないよう設定。</li>
|
<li>選んだアプリだけDNSトンネルを経由しないよう設定。</li>
|
||||||
<li>ワンタップ、またはクイック設定タイルで接続・切断。</li>
|
<li>ワンタップ、またはクイック設定タイルで接続・切断。</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
• Prie serverių, kurie priima aukas, šalia privatumo politikos – nuoroda aukoti
|
||||||
|
• Paprastesnis serverių sąrašas
|
||||||
|
• Nauja privatumo politikos piktograma prie serverių
|
||||||
|
• HTTP/3 žymė pašalinta iš serverių sąrašo
|
||||||
|
• Trumpesnis aprašymas skiltyje „Apie“
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• DNS veikia toliau, net jei atkeliauja netikėtas paketas; sugedus tuneliui VPN išsijungia, užuot tyliai blokavęs DNS
|
||||||
|
• Užklausos greičiau atsigauna perjungus „Wi-Fi“ ir mobiliuosius duomenis bei lėtuose tinkluose
|
||||||
|
• Mažiau darbo fone: paslėpti ekranai nebeatnaujinami
|
||||||
|
• Blokavimo sąrašai atsisiunčiami iš naujo tik pasikeitus
|
||||||
|
• Ryškesnės programėlių piktogramos, mažesnė programėlė
|
||||||
|
• Dvigubas paspaudimas „Prisijungti“ nebejungia dukart; dėl pilnos atminties programėlė nebeužsidaro
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• Naujas dizainas: tamsi išvaizda ir slankus skydelis su skirtukais „Pradžia“, „Veikla“ ir „Nustatymai“
|
||||||
|
• Pradžios ekrane matyti dabartinis serveris ir 24 valandų grafikas
|
||||||
|
• Veikla: 24 valandų arba 7 dienų statistika ir didžiausių įmonių dalis
|
||||||
|
• Naujas HaGeZi Pro šablonas; sąrašus galima išjungti jų neištrinant
|
||||||
|
• Blokavimo sąrašai atnaujinami automatiškai kasdien arba kas savaitę, jei norite – tik per „Wi-Fi“
|
||||||
|
• Serverių sąrašas yra programėlėje ir nebeatsisiunčiamas
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
<li>Siųskite DNS užklausas pasirinktam DoH serveriui pagal RFC 8484.</li>
|
<li>Siųskite DNS užklausas pasirinktam DoH serveriui pagal RFC 8484.</li>
|
||||||
<li>Prieš jungdamiesi patikrinkite serverio protokolą ir delsą.</li>
|
<li>Prieš jungdamiesi patikrinkite serverio protokolą ir delsą.</li>
|
||||||
<li>Stebėkite užklausas ir statistiką realiuoju laiku, filtruokite veiklą ir blokuokite domenus vienu palietimu.</li>
|
<li>Stebėkite užklausas ir statistiką realiuoju laiku, filtruokite veiklą ir blokuokite domenus vienu palietimu.</li>
|
||||||
<li>Pridėkite savo domenų taisykles arba blokavimo sąrašus pagal URL, įskaitant HaGeZi Pro++ ir TIF šablonus.</li>
|
<li>Pridėkite savo domenų taisykles arba blokavimo sąrašus pagal URL, įskaitant HaGeZi Pro, Pro++ ir TIF šablonus, automatiškai atnaujinamus kasdien arba kas savaitę.</li>
|
||||||
<li>Leiskite pasirinktoms programėlėms apeiti DNS tunelį.</li>
|
<li>Leiskite pasirinktoms programėlėms apeiti DNS tunelį.</li>
|
||||||
<li>Prisijunkite ar atsijunkite vienu palietimu arba per sparčiųjų nustatymų plytelę.</li>
|
<li>Prisijunkite ar atsijunkite vienu palietimu arba per sparčiųjų nustatymų plytelę.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
• У серверов, которые принимают пожертвования, рядом с политикой конфиденциальности появилась ссылка на пожертвование
|
||||||
|
• Упрощённый список серверов
|
||||||
|
• Новый значок политики конфиденциальности у серверов
|
||||||
|
• Значок HTTP/3 убран из списка серверов
|
||||||
|
• Короче описание в «О программе»
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• DNS продолжает работать, если пришёл неожиданный пакет; при сбое туннеля VPN отключается, а не блокирует DNS молча
|
||||||
|
• Запросы быстрее восстанавливаются после переключения между Wi-Fi и мобильной сетью и в медленных сетях
|
||||||
|
• Меньше работы в фоне: скрытые экраны больше не обновляются
|
||||||
|
• Блоклисты скачиваются заново, только если изменились
|
||||||
|
• Чётче значки приложений, меньше размер приложения
|
||||||
|
• Двойное нажатие «Подключить» больше не подключает дважды; переполненная память больше не роняет приложение
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
• Новый дизайн: тёмный вид и плавающая панель с вкладками «Главная», «Активность» и «Настройки»
|
||||||
|
• На главной видно текущий сервер и график за 24 часа
|
||||||
|
• Активность: статистика за 24 часа или 7 дней и доля крупнейших компаний
|
||||||
|
• Новый пресет HaGeZi Pro; списки можно выключать без удаления
|
||||||
|
• Блок-листы обновляются автоматически раз в день или в неделю, при желании только по Wi-Fi
|
||||||
|
• Список серверов встроен в приложение и больше не скачивается
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
<li>Отправляйте DNS-запросы на выбранный DoH-сервер по RFC 8484.</li>
|
<li>Отправляйте DNS-запросы на выбранный DoH-сервер по RFC 8484.</li>
|
||||||
<li>Проверяйте протокол и задержку сервера перед подключением.</li>
|
<li>Проверяйте протокол и задержку сервера перед подключением.</li>
|
||||||
<li>Смотрите запросы и статистику в реальном времени, фильтруйте активность и блокируйте домены одним касанием.</li>
|
<li>Смотрите запросы и статистику в реальном времени, фильтруйте активность и блокируйте домены одним касанием.</li>
|
||||||
<li>Добавляйте свои правила для доменов или блок-листы по URL, включая пресеты HaGeZi Pro++ и TIF.</li>
|
<li>Добавляйте свои правила для доменов или блок-листы по URL, включая пресеты HaGeZi Pro, Pro++ и TIF, с автообновлением раз в день или в неделю.</li>
|
||||||
<li>Разрешайте выбранным приложениям обходить DNS-туннель.</li>
|
<li>Разрешайте выбранным приложениям обходить DNS-туннель.</li>
|
||||||
<li>Подключайтесь и отключайтесь одним касанием или через плитку быстрых настроек.</li>
|
<li>Подключайтесь и отключайтесь одним касанием или через плитку быстрых настроек.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
• 接受捐赠的服务器在隐私政策旁显示捐赠链接
|
||||||
|
• 服务器列表更简洁
|
||||||
|
• 服务器的隐私政策图标焕新
|
||||||
|
• 服务器列表中移除 HTTP/3 标识
|
||||||
|
• “关于”中的介绍更简短
|
||||||