39 Commits
Author SHA1 Message Date
kalarina eccc98b3aa Receive the sign-in callback on skysparkle.cc
The site now returns through an intent:// link that names this package,
so no separate subdomain or domain verification is needed and no other
app can receive the one-time code.
2026-11-18 14:50:50 +02:00
kalarina e36b9de154 Return from the Skysparkle sign-in through a verified App Link
Replace the cc.skysparkle.sparkledns:// callback with
https://app.skysparkle.cc/app/callback (autoVerify), so only the app
signed with the release key can receive the one-time code.
2026-11-18 14:47:51 +02:00
kalarina 7f02ec606c Harden the Skysparkle key exchange
Turn unexpected errors during the exchange into a sign-in error instead
of a crash, and keep the progress shown when a second callback arrives
while the first code is still being exchanged.
2026-11-18 14:42:22 +02:00
kalarina 430d7b8d59 Calmer key field once a key is present
Show "Sign in again" as an outlined button so it does not compete with
the filled "Switch to" button, and animate the key line in and out.
2026-11-18 14:39:13 +02:00
kalarina 361d82a4ed Get the Skysparkle key only by signing in
Remove manual key entry from settings and the first-launch guide. When a
key is present, settings show its first characters and can copy the
full address for use in a browser or on another device.
2026-11-18 14:31:34 +02:00
kalarina 005768f18a Sign in with Skysparkle to get the access key
The key field now starts a browser sign-in at skysparkle.cc/app/connect
(PKCE). The site returns to cc.skysparkle.sparkledns://connect with a
one-time code, and the app exchanges it for a new key. Pasting a key by
hand still works.

Remove the Gitea templates; the project lives on GitHub.
2026-11-18 14:11:48 +02:00
kalarina a6f22ddfb2 Add donation card and move repository links to GitHub 2026-11-17 09:41:21 +02:00
kalarina 572e5e224b Release 1.1.6 2026-11-16 15:59:20 +02:00
kalarina 92dfd31faf Personal access key for the SkySparkle server and first-launch guide
The SkySparkle server no longer has a shared public address: each user
creates a key in their account at skysparkle.cc and the app connects to
https://skysparkle.cc/dns/<key>. The key is entered in Settings under the
server or in the new two-page guide shown on first launch. Without a key
the home screen shows a hint and the service explains why it did not start.
2026-11-16 10:54:48 +02:00
kalarina 3b4d9b049b Screenshot: drop ads from the HaGeZi Pro description 2026-11-14 22:11:27 +02:00
kalarina 618a9403c7 Screenshot: block trackers and malware instead of ads 2026-11-14 21:58:39 +02:00
kalarina 582511607c Revert "Remove block ads screenshot"
This reverts commit d6f77045e3.
2026-11-14 21:56:11 +02:00
kalarina d6f77045e3 Remove block ads screenshot 2026-11-14 21:55:08 +02:00
kalarina f3000b7706 README: point Obtainium link to GitHub 2026-11-14 19:23:20 +02:00
kalarina 3c026aaec3 Merge pull request #9 from kalarina-bit/dns-host
Release 1.1.5: use skysparkle.cc/dns-query
2026-11-13 18:30:59 +02:00
kalarina 1818973abc Release 1.1.5 2026-11-13 18:29:34 +02:00
kalarina f6a98b8785 Use skysparkle.cc/dns-query for the SkySparkle server 2026-11-13 18:29:34 +02:00
kalarina 1fb87a1e99 Merge pull request #8 from kalarina-bit/readme-sponsor
Add Skysparkle sponsor section to README
2026-11-13 17:23:44 +02:00
kalarina 667b1b2dc5 Add Skysparkle sponsor section to README 2026-11-13 17:22:31 +02:00
kalarina 399fc5ea36 Release 1.1.4 2026-11-12 17:41:54 +02:00
kalarina 83789c8510 Update dependencies, add a version catalog, backup rules and locale config
- Compose BOM 2026.09.00, Activity 1.13.0, Lifecycle 2.11.0, coroutines
  1.11.0, OkHttp 5.4.0, Kotlin 2.4.20; compileSdk 37 for the new AndroidX.
- Versions move to gradle/libs.versions.toml.
- The VPN service runs as a systemExempted foreground service, the type
  Android provides for active VPN apps, instead of specialUse.
- dataExtractionRules keep everything out of backups and device transfer;
  localeConfig lets the language be picked in Android settings.
- .gitignore keeps signing keys (*.jks, *.keystore) out of the repository.
2026-11-12 17:24:21 +02:00
kalarina 64728e5fcd Tell the user when protection stops and check the server address in the service
- When the tunnel stops working, a notification says that DNS is no longer
  encrypted (new "Protection alerts" channel).
- The service no longer brings up a tunnel for a server address that is
  not a valid HTTPS URL (always-on VPN or a restart by the system), and
  says so in a notification.
- With "Block connections without VPN" on, a notification explains that
  the DNS server cannot be reached.
- The tunnel is closed only after its reader thread has left.
- Turning protection off from the quick settings tile needs an unlocked phone.
2026-11-12 17:24:21 +02:00
kalarina 2578af2bed Make bootstrap addresses work with HTTP/3 and bound response and list sizes
- HttpEngine resolves the server with system DNS and ignores bootstrap
  addresses. When it cannot resolve the name and the server has bootstrap
  addresses, the session switches to OkHttp, which connects to them.
- AdBlock and URL rules with a path (||example.com/ads/, |http://example.com/x|)
  are skipped instead of blocking the whole domain.
- A DoH response without Content-Length is read only up to the DNS size
  limit; blocklist downloads are limited to 256 MB, and lines over 4 KB are
  skipped without being read into memory.
2026-11-12 17:24:21 +02:00
kalarina 6d015e9527 Keep blocklists out of the heap to fix out-of-memory crash on large lists
The merged blocklist was built as one LongArray next to every per-list
array and the merge copies; with ~7M domains this ran out of memory on
256 MB heaps (Galaxy A07) and the uncaught error took the VPN down.

Lists and the merged set are now memory-mapped files: the merge streams
from the list files into merged.bin, which is reused at start-up while
the switched-on lists are unchanged. Downloads sort in their own buffer
instead of copying, and the update job no longer crashes the app if it
still runs out of memory.
2026-11-12 10:46:27 +02:00
kalarina fb0c13bbcc Add dnsforge.de (unfiltered) to built-in DoH servers 2026-11-11 21:15:21 +02:00
kalarina 4ef8cef4e8 Expand call for volunteer designers 2026-11-10 15:33:26 +02:00
kalarina 64a122fe25 Add call for volunteer designers to README 2026-11-10 15:30:49 +02:00
kalarina 180a9a65fd Move Google Play notice to the top of README 2026-11-08 17:26:06 +02:00
kalarina 845e975c05 Add Google Play closed testing notice to README 2026-11-08 17:23:02 +02:00
kalarina 0ceeb84e98 Fix unreadable app names on the Apps screen (#6) 2026-11-06 17:16:51 +02:00
kalarina 5ddff1b257 Release 1.1.3 2026-11-06 16:15:02 +02:00
kalarina bc9d855997 Name other sites in Company dominance
The share outside the known companies is now split by site names taken from
the domains of recent queries (cdn.example.co.uk shows as Example). Domains
are read only from the in-memory log; the saved statistics still keep numbers
only.
2026-11-06 16:11:58 +02:00
kalarina 8f4355a624 Group recent activity by domain
Queries for the same domain (A, AAAA, HTTPS and other types) now share one
row that shows all requested types, the number of queries and the status
and time of the newest one. Refs #4
2026-11-05 19:08:33 +02:00
kalarina 359bd09b9e Add GitHub issue and pull request templates 2026-11-05 18:44:17 +02:00
kalarina d09a6bac6b Update README screenshots 2026-11-03 13:08:44 +02:00
kalarina 25dcb5cb7f Update store screenshots 2026-11-03 13:06:47 +02:00
kalarina 95c4a1b1ba Fit the German 1.0.10 changelog into 500 characters 2026-11-03 12:45:59 +02:00
kalarina 33eca31c65 Add the 1.1.2 changelog and shorten the German 1.0.10 one to F-Droid's limit 2026-11-03 12:45:52 +02:00
kalarina 54b600b1ca Release v1.1.2 2026-11-02 16:01:22 +02:00
105 changed files with 2984 additions and 1050 deletions
+1
View File
@@ -0,0 +1 @@
ko_fi: skysparkle
@@ -19,7 +19,7 @@ title: "[Bug] "
**Environment** **Environment**
- App version: - App version:
- Installed from: Gitea / F-Droid - Installed from: GitHub / F-Droid / Google Play
- Device and Android version: - Device and Android version:
- DoH server in use: - DoH server in use:
- Network: Wi-Fi / mobile data - Network: Wi-Fi / mobile data
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Support the project on Ko-fi
url: https://ko-fi.com/skysparkle
about: Donations keep the apps and the Skysparkle server running.
+3
View File
@@ -4,3 +4,6 @@ local.properties
.idea/ .idea/
*.iml *.iml
.DS_Store .DS_Store
# Signing keys must never be committed
*.jks
*.keystore
+1 -1
View File
@@ -4,7 +4,7 @@ Thanks for wanting to help! This guide explains where to contribute, what fits t
## Where to contribute ## Where to contribute
Issues and pull requests go to the repository on [Gitea](https://git.skysparkle.cc/kalarina/Sparkledns). Issues and pull requests go to the repository on [GitHub](https://github.com/kalarina-bit/Sparkledns).
## Ways to help ## Ways to help
+32 -8
View File
@@ -9,22 +9,30 @@
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. 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">
<a href="https://ko-fi.com/skysparkle"><img src="https://ko-fi.com/img/githubbutton_sm.svg" alt="Support me on Ko-fi"></a>
</p>
> [!IMPORTANT]
> **SparkleDNS is coming to Google Play!** The app is now in closed testing there ahead of the public release. Ideas, wishes and suggestions for improvement are very welcome — send them wherever is easiest for you: an [issue on GitHub](https://github.com/kalarina-bit/Sparkledns/issues), or an email to [cuken107@proton.me](mailto:cuken107@proton.me).
> [!NOTE]
> **Looking for designers!** SparkleDNS is looking for volunteer designers to help with icons, logos, animations, cover art (store graphics) and UI design. This is unpaid help for an open-source project. If you're interested, write to [cuken107@proton.me](mailto:cuken107@proton.me).
<p align="center"> <p align="center">
<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> <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>
</p> </p>
<p align="center"> <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://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://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://github.com/kalarina-bit/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://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> </p>
<p align="center"> <p align="center">
<img src="assets/screenshots/1-private-dns-control.png" width="160" alt="Private DNS control"> <img src="assets/screenshots/1-private-dns-left.png" width="160" alt="Private DNS in one tap"><img src="assets/screenshots/2-private-dns-right.png" width="160" alt="You're protected">
<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/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"> <img src="assets/screenshots/4-block-trackers-and-malware.png" width="160" alt="Block trackers and malware">
</p> </p>
> [!TIP] > [!TIP]
@@ -43,8 +51,8 @@
## <img src="assets/icon-install.png" width="32" alt=""> Installation ## <img src="assets/icon-install.png" width="32" alt=""> Installation
- **[F-Droid](https://f-droid.org/packages/cc.skysparkle.sparkledns/)** — install and update through the F-Droid client. - **[F-Droid](https://f-droid.org/packages/cc.skysparkle.sparkledns/)** — install and update through the F-Droid client.
- **[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. - **[Obtainium](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://github.com/kalarina-bit/Sparkledns)** — installs the APK straight from GitHub releases and keeps it up to date.
- **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. - **Manually** — download the latest APK from [GitHub Releases](https://github.com/kalarina-bit/Sparkledns/releases/latest), 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/icon-verify.png" width="32" alt=""> Verifying a download ## <img src="assets/icon-verify.png" width="32" alt=""> Verifying a download
@@ -78,7 +86,23 @@ Requires JDK 17+ and Android SDK 36.
## 🤝 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://github.com/kalarina-bit/Sparkledns/issues). Please read [CONTRIBUTING.md](CONTRIBUTING.md) first — it explains what fits the project and how to send changes.
## 💙 Sponsor
<p align="center">
<a href="https://skysparkle.cc"><img src="assets/skysparkle.svg" width="72" alt="Skysparkle"></a>
</p>
<p align="center">
SparkleDNS is sponsored and supported by <a href="https://skysparkle.cc"><b>Skysparkle</b></a> — independent encrypted DNS from Lithuania and the app’s default DoH server.
</p>
## ☕ Support
SparkleDNS is free, open source and has no ads. If it is useful to you, you can support the project on [Ko-fi](https://ko-fi.com/skysparkle) — donations pay for the Skysparkle server and the time spent on the apps.
<a href="https://ko-fi.com/skysparkle"><img src="https://ko-fi.com/img/githubbutton_sm.svg" alt="Support me on Ko-fi"></a>
## 📄 License ## 📄 License
+30 -14
View File
@@ -1,11 +1,12 @@
plugins { plugins {
id("com.android.application") alias(libs.plugins.android.application)
id("org.jetbrains.kotlin.plugin.compose") alias(libs.plugins.kotlin.compose)
} }
android { android {
namespace = "cc.skysparkle.sparkledns" namespace = "cc.skysparkle.sparkledns"
compileSdk = 36 // The current AndroidX libraries require it
compileSdk = 37
defaultConfig { defaultConfig {
applicationId = "cc.skysparkle.sparkledns" applicationId = "cc.skysparkle.sparkledns"
@@ -13,8 +14,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 = 10101 versionCode = 10106
versionName = "1.1.1" versionName = "1.1.6"
} }
buildTypes { buildTypes {
@@ -49,6 +50,21 @@ android {
includeInBundle = false includeInBundle = false
} }
packaging {
resources {
// Library files the app never reads: Kotlin metadata for reflection, the coroutines debug
// agent, version markers for tooling and OkHttp's public suffix list, which only cookies use
excludes += listOf(
"/META-INF/*.version",
"/META-INF/*.kotlin_module",
"/kotlin/**",
"/kotlin-tooling-metadata.json",
"/DebugProbesKt.bin",
"/okhttp3/internal/publicsuffix/**",
)
}
}
testOptions { testOptions {
// android.util.Log and friends are no-ops in JVM unit tests // android.util.Log and friends are no-ops in JVM unit tests
unitTests.isReturnDefaultValues = true unitTests.isReturnDefaultValues = true
@@ -56,17 +72,17 @@ android {
} }
dependencies { dependencies {
implementation(platform("androidx.compose:compose-bom:2025.09.00")) implementation(platform(libs.androidx.compose.bom))
implementation("androidx.activity:activity-compose:1.10.1") implementation(libs.androidx.activity.compose)
implementation("androidx.compose.ui:ui") implementation(libs.androidx.compose.ui)
implementation("androidx.compose.material3:material3") implementation(libs.androidx.compose.material3)
// Already pulled in by Compose at this version; declared because the app uses it directly // 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(libs.androidx.lifecycle.runtime.compose)
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") implementation(libs.kotlinx.coroutines.android)
implementation("com.squareup.okhttp3:okhttp:4.12.0") implementation(libs.okhttp)
// Debug builds only, never part of a release // Debug builds only, never part of a release
debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14") debugImplementation(libs.leakcanary.android)
testImplementation("junit:junit:4.13.2") testImplementation(libs.junit)
} }
+15 -5
View File
@@ -6,7 +6,7 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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_SYSTEM_EXEMPTED" />
<!-- Keeps the scheduled blocklist update after a reboot --> <!-- Keeps the scheduled blocklist update after a reboot -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
@@ -21,6 +21,8 @@
<application <application
android:name=".SparkleApp" android:name=".SparkleApp"
android:allowBackup="false" android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:localeConfig="@xml/locales_config"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name" android:label="@string/app_name"
@@ -30,17 +32,28 @@
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"> android:windowSoftInputMode="adjustResize">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
<!-- End of the Skysparkle sign-in: the site sends the browser back with a one-time code
through an intent:// link that names this package, so Android hands it only to this
app. No autoVerify: a link with a package needs no domain verification, and plain
visits to skysparkle.cc stay in the browser -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="skysparkle.cc" android:path="/app/callback" />
</intent-filter>
</activity> </activity>
<service <service
android:name=".DohVpnService" android:name=".DohVpnService"
android:exported="false" android:exported="false"
android:foregroundServiceType="specialUse" android:foregroundServiceType="systemExempted"
android:permission="android.permission.BIND_VPN_SERVICE"> android:permission="android.permission.BIND_VPN_SERVICE">
<intent-filter> <intent-filter>
<action android:name="android.net.VpnService" /> <action android:name="android.net.VpnService" />
@@ -48,9 +61,6 @@
<meta-data <meta-data
android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON" android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
android:value="true" /> android:value="true" />
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Local DNS-over-HTTPS VPN that keeps encrypted DNS active while the user has it enabled" />
</service> </service>
<service <service
@@ -30,6 +30,7 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
@@ -40,6 +41,7 @@ import androidx.compose.material3.TextButton
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.remember
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
@@ -52,7 +54,8 @@ import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
private const val PRIVACY_POLICY = "https://skysparkle.cc/privacy?lang=en" private const val PRIVACY_POLICY = "https://skysparkle.cc/privacy?lang=en"
private const val SOURCE_CODE = "https://git.skysparkle.cc/kalarina/Sparkledns" private const val SOURCE_CODE = "https://github.com/kalarina-bit/Sparkledns"
private const val DONATE = "https://ko-fi.com/skysparkle"
private const val APACHE_2 = "Apache License 2.0" private const val APACHE_2 = "Apache License 2.0"
private const val APACHE_2_URL = "https://www.apache.org/licenses/LICENSE-2.0" private const val APACHE_2_URL = "https://www.apache.org/licenses/LICENSE-2.0"
@@ -126,7 +129,7 @@ private fun AboutContent(modifier: Modifier, onOpenLicenses: () -> Unit) {
verticalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
Image( Image(
painterResource(R.drawable.app_logo), remember { AppLogo.get(context) },
contentDescription = null, contentDescription = null,
modifier = Modifier modifier = Modifier
.size(104.dp) .size(104.dp)
@@ -155,6 +158,8 @@ private fun AboutContent(modifier: Modifier, onOpenLicenses: () -> Unit) {
} }
} }
SupportCard(onDonate = { openUrl(context, DONATE) })
OutlinedButton(onClick = { openUrl(context, PRIVACY_POLICY) }, modifier = Modifier.fillMaxWidth()) { OutlinedButton(onClick = { openUrl(context, PRIVACY_POLICY) }, modifier = Modifier.fillMaxWidth()) {
Icon(painterResource(R.drawable.ic_policy), contentDescription = null, modifier = Modifier.size(18.dp)) Icon(painterResource(R.drawable.ic_policy), contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp)) Spacer(Modifier.width(8.dp))
@@ -191,6 +196,43 @@ private fun AboutContent(modifier: Modifier, onOpenLicenses: () -> Unit) {
} }
} }
// The server costs money every month; the card asks for help without getting in the way
@Composable
private fun SupportCard(onDonate: () -> Unit) {
val context = LocalContext.current
Card(Modifier.fillMaxWidth()) {
Row(
modifier = Modifier.padding(start = 16.dp, top = 16.dp, end = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Image(
remember { AppLogo.get(context) },
contentDescription = null,
modifier = Modifier.size(48.dp),
)
Spacer(Modifier.width(14.dp))
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.support_title), style = MaterialTheme.typography.titleMedium)
Text(
stringResource(R.string.support_text),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Button(
onClick = onDonate,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
) {
Icon(painterResource(R.drawable.ic_donate), contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text(stringResource(R.string.support_button))
}
}
}
@Composable @Composable
private fun LicensesScreen(modifier: Modifier, onBack: () -> Unit) { private fun LicensesScreen(modifier: Modifier, onBack: () -> Unit) {
val context = LocalContext.current val context = LocalContext.current
@@ -5,9 +5,7 @@ import android.content.ClipboardManager
import android.widget.Toast import android.widget.Toast
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable 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.Box
@@ -15,32 +13,39 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues 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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
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
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
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.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
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.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
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.runtime.structuralEqualityPolicy
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.drawWithCache
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
@@ -54,12 +59,12 @@ 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.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.Date import java.util.Date
import java.util.Locale import java.util.Locale
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
private enum class ActivityFilter(@StringRes val label: Int) { private enum class ActivityFilter(@StringRes val label: Int) {
ALL(R.string.mon_all), ALL(R.string.mon_all),
@@ -68,11 +73,6 @@ private enum class ActivityFilter(@StringRes val label: Int) {
ERRORS(R.string.mon_errors), 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) private val TimeFormat = SimpleDateFormat("HH:mm:ss", Locale.ROOT)
// Colors of the company slices, then the rest // Colors of the company slices, then the rest
@@ -81,6 +81,28 @@ private val OtherColor = Palette.Track
private class Slice(val label: String, val share: Float, val color: Color) private class Slice(val label: String, val share: Float, val color: Color)
// One row of the log: every query for a domain, shown by its newest one. A data class, so a
// rebuilt list with the same groups counts as unchanged.
private data class DomainGroup(val latest: QueryEntry, val types: List<Int>, val count: Int)
// The log is newest first, so the first entry of a domain is its newest one and the groups come
// out in the order their domains were last asked for. Names differ only in letter case when a
// resolver randomizes it, so they are compared in lower case.
private fun groupByDomain(entries: List<QueryEntry>): List<DomainGroup> {
class Builder(val latest: QueryEntry) {
val types = LinkedHashSet<Int>()
var count = 0
}
val groups = LinkedHashMap<String, Builder>()
for (entry in entries) {
val group = groups.getOrPut(entry.domain.lowercase(Locale.ROOT)) { Builder(entry) }
group.types += entry.type
group.count++
}
// Types in numeric order: A, then AAAA, then HTTPS
return groups.values.map { DomainGroup(it.latest, it.types.sorted(), it.count) }
}
@Composable @Composable
fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) { fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
val context = LocalContext.current val context = LocalContext.current
@@ -88,12 +110,11 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
val custom by Blocklist.custom.collectAsStateWithLifecycle() val custom by Blocklist.custom.collectAsStateWithLifecycle()
val customSet = remember(custom) { custom.toHashSet() } val customSet = remember(custom) { custom.toHashSet() }
var period by rememberSaveable { mutableStateOf(Period.DAY) } var period by rememberSaveable { mutableStateOf(StatsPeriod.DAY) }
var entries by remember { mutableStateOf(QueryLog.snapshot()) } var entries by remember { mutableStateOf(QueryLog.snapshot()) }
var summary by remember { mutableStateOf(StatsStore.summary(period.hours)) } var summary by remember { mutableStateOf(StatsStore.summary(period.hours)) }
var filter by rememberSaveable { mutableStateOf(ActivityFilter.ALL) } var filter by rememberSaveable { mutableStateOf(ActivityFilter.ALL) }
var search by rememberSaveable { mutableStateOf("") } var search by rememberSaveable { mutableStateOf("") }
var filterMenu by remember { mutableStateOf(false) }
OnQueryLogChange { OnQueryLogChange {
entries = QueryLog.snapshot() entries = QueryLog.snapshot()
@@ -102,9 +123,13 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
val statsVersion by StatsStore.version.collectAsStateWithLifecycle() val statsVersion by StatsStore.version.collectAsStateWithLifecycle()
LaunchedEffect(period, statsVersion) { summary = StatsStore.summary(period.hours) } LaunchedEffect(period, statsVersion) { summary = StatsStore.summary(period.hours) }
val visible = remember(entries, filter, search) { // Filtered and grouped by domain again only when the log, the filter or the search changes,
// and the list below is updated only when the result differs: new entries that the filter
// hides change nothing
val visible by remember {
derivedStateOf(structuralEqualityPolicy()) {
val term = search.trim() val term = search.trim()
entries.filter { e -> val matching = entries.filter { e ->
val matchesFilter = when (filter) { val matchesFilter = when (filter) {
ActivityFilter.ALL -> true ActivityFilter.ALL -> true
ActivityFilter.BLOCKED -> e.status == QueryStatus.BLOCKED ActivityFilter.BLOCKED -> e.status == QueryStatus.BLOCKED
@@ -113,7 +138,10 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
} }
matchesFilter && (term.isEmpty() || e.domain.contains(term, ignoreCase = true)) matchesFilter && (term.isEmpty() || e.domain.contains(term, ignoreCase = true))
} }
groupByDomain(matching)
} }
}
val canClear by remember { derivedStateOf { entries.isNotEmpty() } }
fun toggleBlock(domain: String, unblock: Boolean) { fun toggleBlock(domain: String, unblock: Boolean) {
scope.launch { scope.launch {
@@ -145,11 +173,96 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
.setPrimaryClip(ClipData.newPlainText("domain", domain)) .setPrimaryClip(ClipData.newPlainText("domain", domain))
} }
val wide = windowWidth() >= WideLayoutWidth
val side = sidePadding(windowWidth(), if (wide) MaxWideContentWidth else MaxContentWidth)
val clear = {
QueryLog.clear()
entries = emptyList()
}
// The log rows, shared by the one- and two-column layouts
val log: LazyListScope.() -> Unit = {
item(key = "recent") {
RecentHeader(canClear, clear, Modifier.padding(top = if (wide) 0.dp else 24.dp))
}
item(key = "search") {
LogSearch(
search = search,
onSearch = { search = it },
filter = filter,
onFilter = { filter = it },
modifier = Modifier.padding(top = 6.dp, bottom = 4.dp),
)
}
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),
)
}
}
// Keyed by domain, so a new query for a domain moves its row to the top instead of adding one
itemsIndexed(
visible,
key = { _, group -> "domain:" + group.latest.domain.lowercase(Locale.ROOT) },
contentType = { _, _ -> "query" },
) { index, group ->
val entry = group.latest
val blockedByMe = entry.domain in customSet
QueryRow(
modifier = Modifier.animateItem(),
entry = entry,
types = group.types,
count = group.count,
first = index == 0,
blockedByMe = blockedByMe,
onBlock = { toggleBlock(entry.domain, unblock = false) },
onUnblock = { toggleBlock(entry.domain, unblock = true) },
onCopy = { copy(entry.domain) },
)
}
}
if (wide) {
Row(
modifier = modifier.padding(horizontal = side),
horizontalArrangement = Arrangement.spacedBy(24.dp),
) {
Column(
Modifier
.weight(1f)
.fillMaxHeight()
.verticalScroll(rememberScrollState())
.padding(top = 16.dp, bottom = bottomPadding),
) {
ActivityHeader(period) { period = it }
ActivityStats(summary, Modifier.padding(top = 20.dp))
CompanyCard(summary, entries, Modifier.padding(top = 20.dp))
}
LazyColumn(
modifier = Modifier
.weight(1f)
.fillMaxHeight(),
contentPadding = PaddingValues(top = 16.dp, bottom = bottomPadding),
content = log,
)
}
} else {
LazyColumn( LazyColumn(
modifier = modifier, modifier = modifier,
contentPadding = PaddingValues(start = 20.dp, end = 20.dp, top = 16.dp, bottom = bottomPadding), contentPadding = PaddingValues(start = side, end = side, top = 16.dp, bottom = bottomPadding),
) { ) {
item(key = "header") { item(key = "header") { ActivityHeader(period) { period = it } }
item(key = "stats") { ActivityStats(summary, Modifier.padding(top = 20.dp)) }
item(key = "companies") { CompanyCard(summary, entries, Modifier.padding(top = 20.dp)) }
log()
}
}
}
@Composable
private fun ActivityHeader(period: StatsPeriod, onPeriod: (StatsPeriod) -> Unit) {
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@@ -157,17 +270,16 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
ScreenTitle(stringResource(R.string.tab_activity), Modifier.weight(1f)) ScreenTitle(stringResource(R.string.tab_activity), Modifier.weight(1f))
PeriodChip(stringResource(period.label)) { PeriodChip(period, onPeriod)
period = if (period == Period.DAY) Period.WEEK else Period.DAY
}
} }
} }
item(key = "stats") { @Composable
private fun ActivityStats(summary: StatsSummary, modifier: Modifier = Modifier) {
Row( Row(
modifier = Modifier modifier = modifier
.fillMaxWidth() .fillMaxWidth()
.padding(top = 20.dp, start = 4.dp, end = 4.dp), .padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.spacedBy(6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp),
) { ) {
StatBlock(formatCompact(summary.total), stringResource(R.string.stat_requests), Modifier.weight(1f)) StatBlock(formatCompact(summary.total), stringResource(R.string.stat_requests), Modifier.weight(1f))
@@ -178,15 +290,12 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
} }
} }
item(key = "companies") { @Composable
CompanyCard(summary, Modifier.padding(top = 20.dp)) private fun RecentHeader(canClear: Boolean, onClear: () -> Unit, modifier: Modifier = Modifier) {
}
item(key = "recent") {
Row( Row(
modifier = Modifier modifier = modifier
.fillMaxWidth() .fillMaxWidth()
.padding(top = 24.dp), .heightIn(min = 44.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
Text( Text(
@@ -196,13 +305,7 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
fontWeight = FontWeight.ExtraBold, fontWeight = FontWeight.ExtraBold,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
IconButton( IconButton(onClick = onClear, enabled = canClear) {
onClick = {
QueryLog.clear()
entries = emptyList()
},
enabled = entries.isNotEmpty(),
) {
Icon( Icon(
painterResource(R.drawable.ic_delete_sweep), painterResource(R.drawable.ic_delete_sweep),
contentDescription = stringResource(R.string.mon_clear), contentDescription = stringResource(R.string.mon_clear),
@@ -213,15 +316,23 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
} }
} }
item(key = "search") { @Composable
private fun LogSearch(
search: String,
onSearch: (String) -> Unit,
filter: ActivityFilter,
onFilter: (ActivityFilter) -> Unit,
modifier: Modifier = Modifier,
) {
var menu by remember { mutableStateOf(false) }
SearchField( SearchField(
value = search, value = search,
onValueChange = { search = it }, onValueChange = onSearch,
placeholder = stringResource(R.string.mon_search), placeholder = stringResource(R.string.mon_search),
modifier = Modifier.padding(top = 6.dp, bottom = 4.dp), modifier = modifier,
trailing = { trailing = {
Box { Box {
IconButton(onClick = { filterMenu = true }) { IconButton(onClick = { menu = true }) {
Icon( Icon(
painterResource(R.drawable.ic_filter), painterResource(R.drawable.ic_filter),
contentDescription = stringResource(R.string.filter), contentDescription = stringResource(R.string.filter),
@@ -229,7 +340,7 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
modifier = Modifier.size(18.dp), modifier = Modifier.size(18.dp),
) )
} }
DropdownMenu(expanded = filterMenu, onDismissRequest = { filterMenu = false }) { DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
ActivityFilter.entries.forEach { option -> ActivityFilter.entries.forEach { option ->
DropdownMenuItem( DropdownMenuItem(
text = { text = {
@@ -240,8 +351,8 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
) )
}, },
onClick = { onClick = {
filter = option onFilter(option)
filterMenu = false menu = false
}, },
) )
} }
@@ -251,50 +362,13 @@ fun ActivityScreen(bottomPadding: Dp, modifier: Modifier = Modifier) {
) )
} }
if (visible.isEmpty()) { // Below this many requests the shares say more about chance than about habits
item(key = "empty") { private const val MIN_COMPANY_REQUESTS = 50L
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 @Composable
private fun PeriodChip(text: String, onClick: () -> Unit) { private fun CompanyCard(summary: StatsSummary, recent: List<QueryEntry>, modifier: Modifier = Modifier) {
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 other = stringResource(R.string.companies_other)
val slices = remember(summary, other) { companySlices(summary, other) } val slices = remember(summary, recent, other) { companySlices(summary, recent, other) }
Column( Column(
modifier = modifier modifier = modifier
.fillMaxWidth() .fillMaxWidth()
@@ -305,12 +379,19 @@ private fun CompanyCard(summary: StatsSummary, modifier: Modifier = Modifier) {
Text(stringResource(R.string.companies_title), color = Palette.Fg, fontSize = 15.sp, fontWeight = FontWeight.Bold) 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) Text(stringResource(R.string.companies_desc), color = Palette.Fg2, fontSize = 12.sp, lineHeight = 17.sp)
Spacer(Modifier.size(10.dp)) Spacer(Modifier.size(10.dp))
if (summary.total == 0L) { if (summary.total < MIN_COMPANY_REQUESTS) {
Text( Text(
stringResource(R.string.no_data), stringResource(R.string.companies_wait, summary.total, MIN_COMPANY_REQUESTS),
color = Palette.Fg3, color = Palette.Fg3,
fontSize = 13.sp, fontSize = 13.sp,
modifier = Modifier.padding(vertical = 12.dp), )
LinearProgressIndicator(
progress = { summary.total.toFloat() / MIN_COMPANY_REQUESTS },
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp, bottom = 4.dp),
color = Palette.Accent,
trackColor = Palette.Track,
) )
} else { } else {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
@@ -334,12 +415,7 @@ private fun CompanyCard(summary: StatsSummary, modifier: Modifier = Modifier) {
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
Text( Text(percentLabel(slice.share), color = Palette.Fg, fontSize = 12.sp, fontWeight = FontWeight.Bold)
String.format(Locale.getDefault(), "%.1f%%", slice.share * 100f),
color = Palette.Fg,
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
)
} }
} }
} }
@@ -348,44 +424,73 @@ private fun CompanyCard(summary: StatsSummary, modifier: Modifier = Modifier) {
} }
} }
// The four companies with most requests, then everything else // Whole percents; a sliver above zero shows as "<1%" rather than "0%"
private fun companySlices(summary: StatsSummary, otherLabel: String): List<Slice> { private fun percentLabel(share: Float): String {
if (summary.total == 0L) return emptyList() val percent = share * 100f
val top = Company.entries return if (percent < 1f) "<1%" else "${Math.round(percent)}%"
.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])
} }
// Shares of the known companies over the period. The statistics keep no domains, so the share
// left over is split by the names of the recent queries to other domains, from the log in memory.
// Then the four largest slices and everything else; empty slices are left out.
private fun companySlices(summary: StatsSummary, recent: List<QueryEntry>, otherLabel: String): List<Slice> {
if (summary.total == 0L) return emptyList()
val shares = HashMap<String, Float>()
for (company in Company.entries) {
val count = summary.companies[company.ordinal]
if (count > 0) shares[company.label] = count.toFloat() / summary.total
}
val unknownShare = (1f - shares.values.sum()).coerceAtLeast(0f)
val names = HashMap<String, Int>()
var unknownCount = 0
for (entry in recent) {
if (Companies.of(entry.domain) != null) continue
unknownCount++
Companies.nameOf(entry.domain)?.let { names.merge(it, 1, Int::plus) }
}
// Queries without a name (local names, reverse lookups) stay in the rest
if (unknownCount > 0) {
for ((name, count) in names) shares.merge(name, unknownShare * count / unknownCount, Float::plus)
}
val slices = shares.entries
.sortedByDescending { it.value }
.take(SliceColors.size)
.mapIndexed { index, (label, share) -> Slice(label, share, SliceColors[index]) }
val rest = (1f - slices.sumOf { it.share.toDouble() }.toFloat()).coerceAtLeast(0f) val rest = (1f - slices.sumOf { it.share.toDouble() }.toFloat()).coerceAtLeast(0f)
return slices + Slice(otherLabel, rest, OtherColor) return if (rest >= 0.005f) slices + Slice(otherLabel, rest, OtherColor) else slices
} }
@Composable @Composable
private fun Donut(slices: List<Slice>, modifier: Modifier = Modifier) { private fun Donut(slices: List<Slice>, modifier: Modifier = Modifier) {
Canvas(modifier) { // The ring's geometry is worked out when the size changes, not every frame
val stroke = 14.dp.toPx() Spacer(
val diameter = size.minDimension - stroke modifier.drawWithCache {
val width = 14.dp.toPx()
val stroke = Stroke(width = width)
val diameter = size.minDimension - width
val topLeft = Offset((size.width - diameter) / 2f, (size.height - diameter) / 2f) val topLeft = Offset((size.width - diameter) / 2f, (size.height - diameter) / 2f)
val arcSize = Size(diameter, diameter) val arcSize = Size(diameter, diameter)
drawArc(OtherColor, 0f, 360f, useCenter = false, topLeft = topLeft, size = arcSize, style = Stroke(width = stroke)) onDrawBehind {
drawArc(OtherColor, 0f, 360f, useCenter = false, topLeft = topLeft, size = arcSize, style = stroke)
var start = -90f var start = -90f
slices.forEach { slice -> slices.forEach { slice ->
val sweep = slice.share * 360f val sweep = slice.share * 360f
if (sweep > 0f) { if (sweep > 0f) {
drawArc(slice.color, start, sweep, useCenter = false, topLeft = topLeft, size = arcSize, style = Stroke(width = stroke)) drawArc(slice.color, start, sweep, useCenter = false, topLeft = topLeft, size = arcSize, style = stroke)
} }
start += sweep start += sweep
} }
} }
} }
)
}
@Composable @Composable
private fun QueryRow( private fun QueryRow(
modifier: Modifier, modifier: Modifier,
entry: QueryEntry, entry: QueryEntry,
types: List<Int>,
count: Int,
first: Boolean, first: Boolean,
blockedByMe: Boolean, blockedByMe: Boolean,
onBlock: () -> Unit, onBlock: () -> Unit,
@@ -405,6 +510,9 @@ private fun QueryRow(
QueryStatus.BLOCKED -> stringResource(if (blockedByMe) R.string.bl_my else R.string.tab_blocklist) QueryStatus.BLOCKED -> stringResource(if (blockedByMe) R.string.bl_my else R.string.tab_blocklist)
QueryStatus.FAILED -> stringResource(R.string.status_failed) QueryStatus.FAILED -> stringResource(R.string.status_failed)
} }
// "A, AAAA, HTTPS · ×3 · 256 ms"; the status and time are those of the newest query
val typeNames = types.joinToString(", ") { DnsMessage.typeName(it) }
val summary = if (count > 1) "$typeNames · ×$count · $detail" else "$typeNames · $detail"
Box(modifier.fillMaxWidth()) { Box(modifier.fillMaxWidth()) {
Column { Column {
@@ -436,7 +544,7 @@ private fun QueryRow(
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
Text( Text(
"${DnsMessage.typeName(entry.type)} · $detail", summary,
color = Palette.Fg3, color = Palette.Fg3,
fontSize = 12.sp, fontSize = 12.sp,
maxLines = 1, maxLines = 1,
@@ -39,6 +39,7 @@ 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.drawBehind
import androidx.compose.ui.draw.shadow import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
@@ -59,6 +60,8 @@ private enum class Screen(@StringRes val label: Int, @DrawableRes val icon: Int,
ABOUT(R.string.tab_about, R.drawable.ic_tab_info, false), ABOUT(R.string.tab_about, R.drawable.ic_tab_info, false),
} }
private val Tabs = Screen.entries.filter { it.isTab }
@Composable @Composable
fun AppShell() { fun AppShell() {
var tab by rememberSaveable { mutableStateOf(Screen.HOME) } var tab by rememberSaveable { mutableStateOf(Screen.HOME) }
@@ -101,6 +104,7 @@ fun AppShell() {
Screen.HOME -> HomeScreen( Screen.HOME -> HomeScreen(
bottomPadding = tabBottom, bottomPadding = tabBottom,
onOpenBlocklist = { page = Screen.BLOCKLIST }, onOpenBlocklist = { page = Screen.BLOCKLIST },
onOpenServers = { tab = Screen.SETTINGS },
modifier = modifier, modifier = modifier,
) )
Screen.ACTIVITY -> ActivityScreen(bottomPadding = tabBottom, modifier = modifier) Screen.ACTIVITY -> ActivityScreen(bottomPadding = tabBottom, modifier = modifier)
@@ -160,8 +164,14 @@ private fun NavPill(current: Screen, onSelect: (Screen) -> Unit, modifier: Modif
.selectableGroup(), .selectableGroup(),
horizontalArrangement = Arrangement.spacedBy(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp),
) { ) {
Screen.entries.filter { it.isTab }.forEach { item -> Tabs.forEach { item -> NavItem(item, selected = item == current, onSelect = onSelect) }
val selected = item == current }
}
// One tab of the panel. Its own composable, so a color animation recomposes only the tabs that
// change instead of the whole panel; the background is read only when drawing.
@Composable
private fun NavItem(item: Screen, selected: Boolean, onSelect: (Screen) -> Unit) {
val background by animateColorAsState( val background by animateColorAsState(
if (selected) Palette.AccentSoft else Color.Transparent, if (selected) Palette.AccentSoft else Color.Transparent,
animationSpec = Motion.color, animationSpec = Motion.color,
@@ -177,7 +187,7 @@ private fun NavPill(current: Screen, onSelect: (Screen) -> Unit, modifier: Modif
modifier = Modifier modifier = Modifier
.size(width = 58.dp, height = 44.dp) .size(width = 58.dp, height = 44.dp)
.clip(RoundedCornerShape(22.dp)) .clip(RoundedCornerShape(22.dp))
.background(background) .drawBehind { drawRect(background) }
.selectable(selected = selected, onClick = { onSelect(item) }, role = Role.Tab) .selectable(selected = selected, onClick = { onSelect(item) }, role = Role.Tab)
.semantics { contentDescription = label }, .semantics { contentDescription = label },
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
@@ -185,5 +195,3 @@ private fun NavPill(current: Screen, onSelect: (Screen) -> Unit, modifier: Modif
Icon(painterResource(item.icon), contentDescription = null, tint = tint, modifier = Modifier.size(22.dp)) Icon(painterResource(item.icon), contentDescription = null, tint = tint, modifier = Modifier.size(22.dp))
} }
} }
}
}
@@ -33,7 +33,6 @@ import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
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.TriStateCheckbox import androidx.compose.material3.TriStateCheckbox
@@ -338,7 +337,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, colors = appSwitchColors()) AppSwitch(checked = enabled, onCheckedChange = null)
} }
} }
} }
@@ -49,14 +49,18 @@ object AutoUpdate {
class BlocklistUpdateJob : JobService() { class BlocklistUpdateJob : JobService() {
override fun onStartJob(params: JobParameters): Boolean { override fun onStartJob(params: JobParameters): Boolean {
Thread({ Thread({
val ok = try { // A failed download is retried later with the system's back-off
Blocklist.updateAllNow(applicationContext) val retry = try {
!Blocklist.updateAllNow(applicationContext)
} catch (e: Exception) { } catch (e: Exception) {
Log.w("SparkleDNS", "Blocklist update failed", e) Log.w("SparkleDNS", "Blocklist update failed", e)
true
} catch (e: OutOfMemoryError) {
// Must not take the VPN down with it; retrying would only run out of memory again
Log.e("SparkleDNS", "Blocklist update ran out of memory", e)
false false
} }
// A failed run is retried later with the system's back-off jobFinished(params, retry)
jobFinished(params, !ok)
}, "blocklist-update").start() }, "blocklist-update").start()
return true return true
} }
@@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.Request import okhttp3.Request
import okio.BufferedSource
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.io.BufferedOutputStream import java.io.BufferedOutputStream
@@ -20,6 +21,7 @@ import java.io.File
import java.io.FileInputStream import java.io.FileInputStream
import java.io.FileOutputStream import java.io.FileOutputStream
import java.io.IOException import java.io.IOException
import java.nio.LongBuffer
import java.nio.channels.FileChannel import java.nio.channels.FileChannel
import java.security.MessageDigest import java.security.MessageDigest
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
@@ -28,7 +30,8 @@ import java.util.concurrent.TimeUnit
data class RemoteList(val url: String, val count: Int, val updated: Long, val enabled: Boolean = true) 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 in files that are memory-mapped, not read into the heap:
// lists with millions of entries cost page cache, not app memory, so low-end phones cope too.
object Blocklist { object Blocklist {
const val ALL_LISTS = "*" const val ALL_LISTS = "*"
@@ -60,15 +63,22 @@ object Blocklist {
// Downloaded lists and own domains are kept apart, so editing a few own domains // 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 // does not rebuild a set that can hold millions of entries
@Volatile @Volatile
private var listHashes = LongArray(0) private var listHashes: LongBuffer = EMPTY_SET
@Volatile @Volatile
private var customHashes = LongArray(0) private var customHashes = LongArray(0)
private var loaded = false private var loaded = false
// False until the saved lists have been read at start-up
private val _ready = MutableStateFlow(false)
val ready: StateFlow<Boolean> = _ready
fun isBlocked(name: String): Boolean = _enabled.value && isBlockedIn(name, listHashes, customHashes) fun isBlocked(name: String): Boolean = _enabled.value && isBlockedIn(name, listHashes, customHashes)
fun reload(context: Context) = synchronized(lock) { load(BlocklistStore(context)) } // Reads the saved lists unless something did already, such as the background update job
fun ensureLoaded(context: Context) {
synchronized(lock) { ensureLoaded(BlocklistStore(context)) }
}
fun setEnabled(context: Context, value: Boolean) { fun setEnabled(context: Context, value: Boolean) {
BlocklistStore(context).enabled = value BlocklistStore(context).enabled = value
@@ -212,10 +222,16 @@ object Blocklist {
customHashes = LongArray(custom.size) { DomainHash.of(custom[it]) }.sortUnique() customHashes = LongArray(custom.size) { DomainHash.of(custom[it]) }.sortUnique()
reloadListHashes(store) reloadListHashes(store)
loaded = true loaded = true
_ready.value = true
} }
private fun reloadListHashes(store: BlocklistStore) { private fun reloadListHashes(store: BlocklistStore) {
listHashes = mergeSorted(_lists.value.filter { it.enabled }.map { store.loadListHashes(it.url) }) try {
listHashes = store.mergedHashes(_lists.value.filter { it.enabled })
} catch (e: IOException) {
// Out of storage: the lists in use stay active until the next change
Log.w("SparkleDNS", "Cannot merge blocklists", e)
}
_total.value = unionSize(listHashes, customHashes) _total.value = unionSize(listHashes, customHashes)
} }
@@ -226,51 +242,81 @@ object Blocklist {
} }
} }
// True when the name or one of its parent domains is in either sorted hash set // True when the name or one of its parent domains is in either sorted hash set. Runs for every
internal fun isBlockedIn(name: String, lists: LongArray, custom: LongArray): Boolean { // query, so trailing dots are skipped by index rather than trimmed off a copy of the name.
if (lists.isEmpty() && custom.isEmpty()) return false internal fun isBlockedIn(name: String, lists: LongBuffer, custom: LongArray): Boolean {
val domain = name.trimEnd('.') if (lists.limit() == 0 && custom.isEmpty()) return false
val end = nameEnd(name)
var start = 0 var start = 0
while (true) { while (true) {
val hash = DomainHash.of(domain, start) val hash = DomainHash.of(name, start, end)
if (lists.binarySearch(hash) >= 0 || custom.binarySearch(hash) >= 0) return true if (lists.containsSorted(hash) || custom.binarySearch(hash) >= 0) return true
val dot = domain.indexOf('.', start) val dot = name.indexOf('.', start)
if (dot < 0) return false if (dot < 0 || dot >= end) return false
start = dot + 1 start = dot + 1
} }
} }
// Number of distinct entries in both sorted sets; the custom set is small // Length of the name without trailing dots
internal fun unionSize(lists: LongArray, custom: LongArray): Int = internal fun nameEnd(name: String): Int {
lists.size + custom.count { lists.binarySearch(it) < 0 } var end = name.length
while (end > 0 && name[end - 1] == '.') end--
// Merges sorted, duplicate-free arrays in linear time instead of sorting their concatenation return end
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 { internal val EMPTY_SET: LongBuffer = LongBuffer.wrap(LongArray(0))
val out = LongArray(a.size + b.size)
var i = 0 // Binary search by absolute index, so several threads can read the same buffer at once
var j = 0 internal fun LongBuffer.containsSorted(value: Long): Boolean {
var n = 0 var low = 0
while (i < a.size && j < b.size) { var high = limit() - 1
val x = a[i] while (low <= high) {
val y = b[j] val mid = (low + high) ushr 1
val v = get(mid)
when { when {
x < y -> { out[n++] = x; i++ } v < value -> low = mid + 1
x > y -> { out[n++] = y; j++ } v > value -> high = mid - 1
else -> { out[n++] = x; i++; j++ } else -> return true
} }
} }
while (i < a.size) out[n++] = a[i++] return false
while (j < b.size) out[n++] = b[j++] }
return if (n == out.size) out else out.copyOf(n)
// Number of distinct entries in both sorted sets; the custom set is small
internal fun unionSize(lists: LongBuffer, custom: LongArray): Int =
lists.limit() + custom.count { !lists.containsSorted(it) }
// Merges sorted, duplicate-free sets in one pass and hands each value to [emit] once, in order.
// Only the read positions are kept in memory, so inputs and output can be files of any size.
internal fun mergeSortedInto(parts: List<LongBuffer>, emit: (Long) -> Unit): Int {
val sets = parts.filter { it.limit() > 0 }
val pos = IntArray(sets.size)
var count = 0
while (true) {
var min = 0L
var found = false
for (i in sets.indices) {
if (pos[i] < sets[i].limit()) {
val v = sets[i].get(pos[i])
if (!found || v < min) {
min = v
found = true
}
}
}
if (!found) return count
for (i in sets.indices) if (pos[i] < sets[i].limit() && sets[i].get(pos[i]) == min) pos[i]++
emit(min)
count++
}
}
// In-memory variant for small sets; inputs that are not sorted yet are sorted first
internal fun mergeSorted(parts: List<LongArray>): LongArray {
val sorted = parts.map { LongBuffer.wrap(if (it.isSortedUnique()) it else it.copyOf().sortUnique()) }
val out = LongList()
mergeSortedInto(sorted) { out.add(it) }
return out.toArray()
} }
private fun LongArray.isSortedUnique(): Boolean { private fun LongArray.isSortedUnique(): Boolean {
@@ -282,10 +328,10 @@ 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
// FNV-1a over the domain starting at [start], so parent domains are hashed without substrings // FNV-1a over the characters from [start] to [end], so parent domains are hashed without substrings
fun of(s: String, start: Int = 0): Long { fun of(s: String, start: Int = 0, end: Int = s.length): Long {
var h = FNV_OFFSET var h = FNV_OFFSET
for (i in start until s.length) { for (i in start until end) {
h = h xor s[i].code.toLong() h = h xor s[i].code.toLong()
h *= FNV_PRIME h *= FNV_PRIME
} }
@@ -304,6 +350,20 @@ private class LongList {
} }
fun toArray(): LongArray = data.copyOf(size) fun toArray(): LongArray = data.copyOf(size)
// Sorts the filled part in place and drops duplicates, without copying; returns the new size
fun sortUnique(): Int {
if (size < 2) return size
java.util.Arrays.sort(data, 0, size)
var n = 1
for (i in 1 until size) if (data[i] != data[n - 1]) data[n++] = data[i]
size = n
return n
}
fun writeTo(out: DataOutputStream) {
for (i in 0 until size) out.writeLong(data[i])
}
} }
// Sorts in place and drops duplicates // Sorts in place and drops duplicates
@@ -316,8 +376,12 @@ private fun LongArray.sortUnique(): LongArray {
} }
private class BlocklistStore(context: Context) { private class BlocklistStore(context: Context) {
private val dir = File(context.filesDir, "blocklist").apply { mkdirs() } private val appContext = context.applicationContext
private val sp = context.getSharedPreferences("blocklist", Context.MODE_PRIVATE)
// Created on first use: switching blocking on or off, which happens on the main thread,
// touches only the settings
private val dir by lazy { File(appContext.filesDir, "blocklist").apply { mkdirs() } }
private val sp = appContext.getSharedPreferences("blocklist", Context.MODE_PRIVATE)
var enabled: Boolean var enabled: Boolean
get() = sp.getBoolean("enabled", true) get() = sp.getBoolean("enabled", true)
@@ -340,7 +404,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"), o.optBoolean("enabled", true)) RemoteList(o.getString("url"), o.getInt("count"), o.getLong("updated"), o.getBoolean("enabled"))
} }
}.getOrDefault(emptyList()) }.getOrDefault(emptyList())
} }
@@ -355,23 +419,46 @@ private class BlocklistStore(context: Context) {
sp.edit().putString("lists", array.toString()).commit() sp.edit().putString("lists", array.toString()).commit()
} }
fun loadListHashes(url: String): LongArray { fun loadListHashes(url: String): LongBuffer = map(binFile(url)) ?: EMPTY_SET
val file = binFile(url)
if (!file.exists()) migrateText(url)?.let { return it } // One list is used as it is; several are merged into one file, which is reused at the next
if (!file.exists()) return LongArray(0) // start as long as the switched-on lists have not changed
fun mergedHashes(lists: List<RemoteList>): LongBuffer {
if (lists.size < 2) {
mergedFile.delete()
return lists.firstOrNull()?.let { loadListHashes(it.url) } ?: EMPTY_SET
}
val signature = hash(lists.sortedBy { it.url }.joinToString("\n") { "${it.url} ${it.count} ${it.updated}" })
if (sp.getString(MERGED_KEY, null) == signature) map(mergedFile)?.let { return it }
val parts = lists.map { loadListHashes(it.url) }
val tmp = File.createTempFile("merged_", ".tmp", dir)
try {
DataOutputStream(BufferedOutputStream(FileOutputStream(tmp), 64 * 1024)).use { out ->
mergeSortedInto(parts) { out.writeLong(it) }
}
if (!tmp.renameTo(mergedFile)) throw IOException("Cannot save lists")
} finally {
tmp.delete()
}
sp.edit().putString(MERGED_KEY, signature).commit()
return map(mergedFile) ?: EMPTY_SET
}
// The mapping stays valid after the file is replaced or deleted, so readers are never cut off
private fun map(file: File): LongBuffer? {
if (!file.exists()) return null
return runCatching { return runCatching {
FileInputStream(file).use { stream -> FileInputStream(file).use { stream ->
val channel = stream.channel val channel = stream.channel
val result = LongArray((channel.size() / 8).toInt()) val bytes = channel.size() / 8 * 8
channel.map(FileChannel.MapMode.READ_ONLY, 0, result.size * 8L).asLongBuffer().get(result) if (bytes == 0L) EMPTY_SET else channel.map(FileChannel.MapMode.READ_ONLY, 0, bytes).asLongBuffer()
result
} }
}.getOrDefault(LongArray(0)) }.getOrNull()
} }
fun deleteListFile(url: String) { fun deleteListFile(url: String) {
binFile(url).delete() binFile(url).delete()
textFile(url).delete()
sp.edit().remove(etagKey(url)).remove(modifiedKey(url)).apply() sp.edit().remove(etagKey(url)).remove(modifiedKey(url)).apply()
} }
@@ -389,30 +476,29 @@ private class BlocklistStore(context: Context) {
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 -> BlocklistParser.readLimitedLines(body.source()) { line ->
lines.forEach { line -> val domain = BlocklistParser.parseLine(line) ?: return@readLimitedLines
val domain = BlocklistParser.parseLine(line) ?: return@forEach
// Far above the largest common lists; keeps a wrong URL from exhausting memory // Far above the largest common lists; keeps a wrong URL from exhausting memory
if (parsed.size >= MAX_LIST_DOMAINS) throw IOException("List too large") if (parsed.size >= MAX_LIST_DOMAINS) throw IOException("List too large")
parsed.add(DomainHash.of(domain)) parsed.add(DomainHash.of(domain))
} }
} // Sorted inside the download buffer: a list with millions of entries is never copied
val result = parsed.toArray().sortUnique() val count = parsed.sortUnique()
if (result.isEmpty()) throw IOException("No domains found") if (count == 0) throw IOException("No domains found")
write(url, result) write(url, parsed)
sp.edit() sp.edit()
.putOrRemove(etagKey(url), response.header("ETag")) .putOrRemove(etagKey(url), response.header("ETag"))
.putOrRemove(modifiedKey(url), response.header("Last-Modified")) .putOrRemove(modifiedKey(url), response.header("Last-Modified"))
.apply() .apply()
return RemoteList(url, result.size, System.currentTimeMillis()) return RemoteList(url, count, System.currentTimeMillis())
} }
} }
private fun write(url: String, data: LongArray) { private fun write(url: String, data: LongList) {
val tmp = File.createTempFile("list_", ".tmp", dir) val tmp = File.createTempFile("list_", ".tmp", dir)
try { try {
DataOutputStream(BufferedOutputStream(FileOutputStream(tmp), 64 * 1024)).use { out -> DataOutputStream(BufferedOutputStream(FileOutputStream(tmp), 64 * 1024)).use { out ->
data.forEach { out.writeLong(it) } data.writeTo(out)
} }
if (!tmp.renameTo(binFile(url))) throw IOException("Cannot save list") if (!tmp.renameTo(binFile(url))) throw IOException("Cannot save list")
} finally { } finally {
@@ -420,16 +506,6 @@ private class BlocklistStore(context: Context) {
} }
} }
// Lists saved by older versions as plain text are converted once
private fun migrateText(url: String): LongArray? {
val text = textFile(url)
if (!text.exists()) return null
val result = text.readLines().map { DomainHash.of(it) }.toLongArray().sortUnique()
runCatching { write(url, result) }
text.delete()
return result
}
private fun etagKey(url: String) = "etag_${hash(url)}" private fun etagKey(url: String) = "etag_${hash(url)}"
private fun modifiedKey(url: String) = "modified_${hash(url)}" private fun modifiedKey(url: String) = "modified_${hash(url)}"
@@ -437,7 +513,7 @@ private class BlocklistStore(context: Context) {
if (value == null) remove(key) else putString(key, value) 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 val mergedFile get() = File(dir, "merged.bin")
private fun hash(url: String) = MessageDigest.getInstance("SHA-256").digest(url.toByteArray()) private fun hash(url: String) = MessageDigest.getInstance("SHA-256").digest(url.toByteArray())
.take(8).joinToString("") { "%02x".format(it) } .take(8).joinToString("") { "%02x".format(it) }
@@ -445,6 +521,8 @@ private class BlocklistStore(context: Context) {
companion object { companion object {
const val MAX_LIST_DOMAINS = 4_000_000 const val MAX_LIST_DOMAINS = 4_000_000
private const val MERGED_KEY = "merged"
val client: OkHttpClient by lazy { val client: OkHttpClient by lazy {
Http.client.newBuilder() Http.client.newBuilder()
.readTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS)
@@ -455,6 +533,59 @@ private class BlocklistStore(context: Context) {
// Understands hosts files, plain domain lists, AdBlock rules (||domain^) and dnsmasq / unbound syntax // Understands hosts files, plain domain lists, AdBlock rules (||domain^) and dnsmasq / unbound syntax
object BlocklistParser { object BlocklistParser {
/** A list larger than this is refused; the biggest common lists are well below it. */
const val MAX_LIST_BYTES = 256L * 1024 * 1024
/** Longer lines (no blocklist entry is that long) are skipped, not read into memory. */
const val MAX_LINE_BYTES = 4096L
/**
* Reads [source] line by line within [MAX_LIST_BYTES] in total and [MAX_LINE_BYTES] per
* line, so a wrong URL (a binary file, a page with no line breaks) cannot fill the memory.
*/
fun readLimitedLines(source: BufferedSource, onLine: (String) -> Unit) {
var total = 0L
fun consumed(bytes: Long) {
total += bytes
if (total > MAX_LIST_BYTES) throw IOException("List too large")
}
while (true) {
val newline = source.indexOf('\n'.code.toByte(), 0, MAX_LINE_BYTES + 1)
when {
newline >= 0 -> {
onLine(source.readUtf8(newline))
source.skip(1)
consumed(newline + 1)
}
source.exhausted() -> return
source.request(MAX_LINE_BYTES + 1) -> {
// Overlong line: drop it piece by piece up to its end
while (true) {
// Only what is already buffered: the next line may start right after the break
val end = source.buffer.indexOf('\n'.code.toByte())
if (end >= 0) {
source.skip(end + 1)
consumed(end + 1)
break
}
val chunk = source.buffer.size
if (chunk == 0L) return
source.skip(chunk)
consumed(chunk)
if (!source.request(1)) return
}
}
else -> {
// Last line without a line break
val rest = source.buffer.size
onLine(source.readUtf8())
consumed(rest)
return
}
}
}
}
private val WHITESPACE = Regex("\\s+") private val WHITESPACE = Regex("\\s+")
private val IGNORED = setOf( private val IGNORED = setOf(
"localhost", "localhost.localdomain", "local", "broadcasthost", "localhost", "localhost.localdomain", "local", "broadcasthost",
@@ -470,6 +601,8 @@ object BlocklistParser {
// Fast path for AdBlock-style lists such as HaGeZi: ||domain^ // Fast path for AdBlock-style lists such as HaGeZi: ||domain^
if (line.startsWith("||")) { if (line.startsWith("||")) {
val end = line.indexOfAny(charArrayOf('^', '$', '/'), 2) val end = line.indexOfAny(charArrayOf('^', '$', '/'), 2)
// ||example.com/ads/ blocks one path in a browser; as DNS it would block the whole site
if (end >= 0 && line[end] == '/' && hasPath(line.substring(end))) return null
return normalize(if (end >= 0) line.substring(2, end) else line.substring(2)) return normalize(if (end >= 0) line.substring(2, end) else line.substring(2))
} }
if (DNSMASQ.any { line.startsWith(it) }) return normalize(line.substringAfter("=/").substringBefore('/')) if (DNSMASQ.any { line.startsWith(it) }) return normalize(line.substringAfter("=/").substringBefore('/'))
@@ -479,9 +612,17 @@ object BlocklistParser {
val parts = line.substringBefore('#').trim().split(WHITESPACE) val parts = line.substringBefore('#').trim().split(WHITESPACE)
val candidate = if (parts.size >= 2 && looksLikeIp(parts[0])) parts[1] else parts[0] val candidate = if (parts.size >= 2 && looksLikeIp(parts[0])) parts[1] else parts[0]
if (candidate.lowercase() in IGNORED) return null if (candidate.lowercase() in IGNORED) return null
// A URL with a path (|http://example.com/x|) stands for one page, not for the domain
val afterScheme = candidate.substringAfter("://")
val slash = afterScheme.indexOf('/')
if (slash >= 0 && hasPath(afterScheme.substring(slash))) return null
return normalize(candidate) return normalize(candidate)
} }
// "/", "/^" or "/|" only end the host; anything longer is a path
private fun hasPath(fromSlash: String): Boolean =
fromSlash.trimEnd('^', '|').length > 1
fun normalize(input: String): String? { fun normalize(input: String): String? {
var s = input.trim().lowercase() var s = input.trim().lowercase()
s = s.substringAfter("://") s = s.substringAfter("://")
@@ -75,8 +75,11 @@ private class Preset(val name: String, val url: String, @StringRes val descripti
private const val HAGEZI_HOME = "https://github.com/hagezi/dns-blocklists" private const val HAGEZI_HOME = "https://github.com/hagezi/dns-blocklists"
// Offered on Home when no list is switched on
internal const val HAGEZI_PRO_URL = "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/pro.txt"
private val Presets = listOf( private val Presets = listOf(
Preset("HaGeZi Pro", "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/pro.txt", R.string.preset_pro_desc), Preset("HaGeZi Pro", HAGEZI_PRO_URL, R.string.preset_pro_desc),
Preset("HaGeZi Pro++", "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/pro.plus.txt", R.string.preset_proplus_desc), 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), Preset("HaGeZi TIF", "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/tif.txt", R.string.preset_tif_desc),
) )
@@ -89,6 +92,7 @@ fun BlocklistScreen(bottomPadding: Dp, onBack: () -> Unit, 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) }
val side = sidePadding(windowWidth())
val enabled by Blocklist.enabled.collectAsStateWithLifecycle() val enabled by Blocklist.enabled.collectAsStateWithLifecycle()
val custom by Blocklist.custom.collectAsStateWithLifecycle() val custom by Blocklist.custom.collectAsStateWithLifecycle()
@@ -96,8 +100,7 @@ fun BlocklistScreen(bottomPadding: Dp, onBack: () -> Unit, modifier: Modifier =
// Downloads live in Blocklist, so they keep running and stay visible when the page is closed // Downloads live in Blocklist, so they keep running and stay visible when the page is closed
val busy by Blocklist.busy.collectAsStateWithLifecycle() val busy by Blocklist.busy.collectAsStateWithLifecycle()
val error by Blocklist.error.collectAsStateWithLifecycle() val error by Blocklist.error.collectAsStateWithLifecycle()
val lastError = remember { arrayOf("") } // kept while the card animates out val shownError = rememberLast(error).orEmpty()
error?.let { lastError[0] = it }
var search by rememberSaveable { mutableStateOf("") } var search by rememberSaveable { mutableStateOf("") }
var domainsOpen by rememberSaveable { mutableStateOf(false) } var domainsOpen by rememberSaveable { mutableStateOf(false) }
@@ -129,7 +132,7 @@ fun BlocklistScreen(bottomPadding: Dp, onBack: () -> Unit, modifier: Modifier =
LazyColumn( LazyColumn(
modifier = modifier, modifier = modifier,
contentPadding = PaddingValues(start = 20.dp, end = 20.dp, bottom = bottomPadding), contentPadding = PaddingValues(start = side, end = side, bottom = bottomPadding),
) { ) {
item(key = "header") { item(key = "header") {
PageHeader( PageHeader(
@@ -163,7 +166,7 @@ fun BlocklistScreen(bottomPadding: Dp, onBack: () -> Unit, modifier: Modifier =
AnimatedVisibility(visible = error != null, enter = Motion.expandIn, exit = Motion.collapseOut) { AnimatedVisibility(visible = error != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
Box(Modifier.padding(top = 12.dp)) { Box(Modifier.padding(top = 12.dp)) {
HintCard( HintCard(
stringResource(R.string.bl_download_failed, lastError[0]), stringResource(R.string.bl_download_failed, shownError),
icon = R.drawable.ic_alert, icon = R.drawable.ic_alert,
tint = Palette.Blocked, tint = Palette.Blocked,
) )
@@ -430,16 +433,7 @@ private fun BlocklistCard(
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
if (onDelete != null) { if (onDelete != null) DeleteButton(onDelete)
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) AppSwitch(checked = checked, onCheckedChange = onCheckedChange, enabled = switchEnabled)
} }
Text( Text(
@@ -547,7 +541,7 @@ private fun DomainRow(domain: String, shape: Shape, onDelete: () -> Unit, modifi
.clip(shape) .clip(shape)
.background(Palette.Card) .background(Palette.Card)
) { ) {
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp), color = Palette.Line) ListDivider()
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,
@@ -560,7 +554,14 @@ private fun DomainRow(domain: String, shape: Shape, onDelete: () -> Unit, modifi
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
IconButton(onClick = onDelete) { DeleteButton(onDelete)
}
}
}
@Composable
private fun DeleteButton(onClick: () -> Unit) {
IconButton(onClick = onClick) {
Icon( Icon(
painterResource(R.drawable.ic_delete), painterResource(R.drawable.ic_delete),
contentDescription = stringResource(R.string.delete), contentDescription = stringResource(R.string.delete),
@@ -569,8 +570,6 @@ private fun DomainRow(domain: String, shape: Shape, onDelete: () -> Unit, modifi
) )
} }
} }
}
}
@Composable @Composable
private fun AddListDialog(busy: Boolean, onAdd: (String) -> Boolean, onDismiss: () -> Unit) { private fun AddListDialog(busy: Boolean, onAdd: (String) -> Boolean, onDismiss: () -> Unit) {
@@ -1,5 +1,8 @@
package cc.skysparkle.sparkledns package cc.skysparkle.sparkledns
import java.util.Locale
import java.util.TreeMap
// The position of each company is saved in StatsStore: add new ones at the end only // The position of each company is saved in StatsStore: add new ones at the end only
enum class Company(val label: String) { enum class Company(val label: String) {
GOOGLE("Google"), GOOGLE("Google"),
@@ -17,8 +20,22 @@ enum class Company(val label: String) {
// Tells which big company a domain belongs to, for the Company dominance card. // 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. // Matches the domain and every parent of it against a small built-in table.
object Companies { object Companies {
private val bySuffix = HashMap<String, Company>().apply { private const val GOOGLE_PREFIX = "google."
fun add(company: Company, vararg domains: String) = domains.forEach { put(it, company) }
// Second-level labels that belong to a country's suffix: example.co.uk, example.com.br
private val COUNTRY_SECOND_LEVELS = setOf("co", "com", "net", "org", "gov", "edu", "ac", "or", "ne", "go")
// Names that are not public sites: reverse lookups and local networks
private val PRIVATE_TLDS = setOf("arpa", "local", "lan", "home", "internal", "localhost")
// Hashes of the domains, sorted, with the company of each at the same index: this runs for
// every query, and parent domains are looked up by hash without copying the name
private val hashes: LongArray
private val owners: Array<Company>
init {
val table = TreeMap<Long, Company>()
fun add(company: Company, vararg domains: String) = domains.forEach { table[DomainHash.of(it)] = company }
add( add(
Company.GOOGLE, Company.GOOGLE,
@@ -62,18 +79,37 @@ object Companies {
add(Company.YANDEX, "yandex.ru", "yandex.net", "yandex.com", "ya.ru", "yastatic.net", "yandex.by", "yandex.kz") 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.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") add(Company.XIAOMI, "xiaomi.com", "xiaomi.net", "mi.com", "miui.com", "mi-img.com")
hashes = table.keys.toLongArray()
owners = table.values.toTypedArray()
} }
fun of(name: String): Company? { fun of(name: String): Company? {
var domain = name.lowercase().trimEnd('.') // Names from the tunnel are lowercase already; anything else is lowercased once
while (domain.isNotEmpty()) { val domain = if (name.any { it.isUpperCase() }) name.lowercase() else name
bySuffix[domain]?.let { return it } val end = nameEnd(domain)
var start = 0
while (start < end) {
val index = hashes.binarySearch(DomainHash.of(domain, start, end))
if (index >= 0) return owners[index]
// Google's country sites: google.de, google.co.uk, google.com.br // Google's country sites: google.de, google.co.uk, google.com.br
if (domain.startsWith("google.") && domain.length - "google.".length <= 6) return Company.GOOGLE if (end - start - GOOGLE_PREFIX.length in 1..6 && domain.startsWith(GOOGLE_PREFIX, start)) return Company.GOOGLE
val dot = domain.indexOf('.') val dot = domain.indexOf('.', start)
if (dot < 0) return null if (dot < 0 || dot >= end) return null
domain = domain.substring(dot + 1) start = dot + 1
} }
return null return null
} }
// A readable name for a domain of no known company, taken from its main label:
// "cdn.example.co.uk" gives "Example". Null for IP addresses, local names and bare labels.
fun nameOf(name: String): String? {
val labels = name.lowercase(Locale.ROOT).split('.').filter { it.isNotEmpty() }
if (labels.size < 2) return null
val tld = labels.last()
if (tld in PRIVATE_TLDS || tld.all { it.isDigit() }) return null
var index = labels.size - 2
if (tld.length == 2 && labels.size >= 3 && labels[index] in COUNTRY_SECOND_LEVELS) index--
return labels[index].replaceFirstChar { it.titlecase(Locale.ROOT) }
}
} }
@@ -5,6 +5,8 @@ import android.content.Context
import android.os.Build import android.os.Build
import android.os.Process import android.os.Process
import android.os.StrictMode import android.os.StrictMode
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.io.File import java.io.File
import java.io.PrintWriter import java.io.PrintWriter
import java.io.StringWriter import java.io.StringWriter
@@ -17,22 +19,23 @@ class SparkleApp : Application() {
Thread({ Thread({
// Reads what the first screen needs before it asks, so its first frame does not wait on storage // Reads what the first screen needs before it asks, so its first frame does not wait on storage
Prefs(this).providerId Prefs(this).providerId
CrashLog.preload(this) CrashLog.load(this)
StatsStore.init(this) StatsStore.init(this)
// Older versions cached a server list downloaded from the repository
File(filesDir, "servers.txt").delete()
AutoUpdate.apply(this) AutoUpdate.apply(this)
// Lists can hold millions of entries; loading them should not take CPU from the first frames // Lists can hold millions of entries; loading them should not take CPU from the first frames
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND) Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
runCatching { Blocklist.reload(this) } runCatching { Blocklist.ensureLoaded(this) }
}, "startup-load").start() }, "startup-load").start()
} }
// The VPN keeps the process running long after the screens are gone; decoded app icons // 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 // (up to 10 MB) and the logo can be rendered again the next time they are shown
override fun onTrimMemory(level: Int) { override fun onTrimMemory(level: Int) {
super.onTrimMemory(level) super.onTrimMemory(level)
if (level >= TRIM_MEMORY_UI_HIDDEN) clearAppIconCache() if (level >= TRIM_MEMORY_UI_HIDDEN) {
clearAppIconCache()
AppLogo.clear()
}
} }
// Debug builds only: logs disk and network access on the main thread, leaked closeables and the like // Debug builds only: logs disk and network access on the main thread, leaked closeables and the like
@@ -46,13 +49,18 @@ class SparkleApp : Application() {
object CrashLog { object CrashLog {
private const val FILE_NAME = "last_crash.txt" private const val FILE_NAME = "last_crash.txt"
// Null when there is no report, and until the startup thread has read it
private val _report = MutableStateFlow<String?>(null)
val report: StateFlow<String?> = _report
fun install(context: Context) { fun install(context: Context) {
val file = File(context.filesDir, FILE_NAME) val appContext = context.applicationContext
val previous = Thread.getDefaultUncaughtExceptionHandler() val previous = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, error -> Thread.setDefaultUncaughtExceptionHandler { thread, error ->
runCatching { runCatching {
val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString() val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
file.writeText( // Looked up only now: install() runs on the main thread at start-up
File(appContext.filesDir, FILE_NAME).writeText(
"Thread: ${thread.name}\n" + "Thread: ${thread.name}\n" +
"Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT}), " + "Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT}), " +
"${Build.MANUFACTURER} ${Build.MODEL}\n\n$trace" "${Build.MANUFACTURER} ${Build.MODEL}\n\n$trace"
@@ -62,24 +70,14 @@ object CrashLog {
} }
} }
@Volatile // Runs on the startup thread, so the main thread never reads the file
private var preloaded = false fun load(context: Context) {
_report.value = runCatching { File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText() }.getOrNull()
@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 _report.value = null
File(context.filesDir, FILE_NAME).delete() val appContext = context.applicationContext
Thread({ File(appContext.filesDir, FILE_NAME).delete() }, "crash-clear").start()
} }
private fun load(context: Context): String? =
runCatching { File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText() }.getOrNull()
} }
@@ -10,7 +10,7 @@ class DnsCache(
private class Entry( private class Entry(
val response: ByteArray, val response: ByteArray,
val ttlOffsets: IntArray, // Offset and value of each TTL field, one pair after another
val ttls: IntArray, val ttls: IntArray,
val storedAt: Long, val storedAt: Long,
val expiresAt: Long, val expiresAt: Long,
@@ -35,7 +35,12 @@ class DnsCache(
out[0] = query[0] out[0] = query[0]
out[1] = query[1] out[1] = query[1]
val elapsed = ((now - entry.storedAt) / 1000).toInt() val elapsed = ((now - entry.storedAt) / 1000).toInt()
entry.ttlOffsets.forEachIndexed { i, off -> put32(out, off, maxOf(entry.ttls[i] - elapsed, 0)) } val ttls = entry.ttls
var i = 0
while (i < ttls.size) {
put32(out, ttls[i], maxOf(ttls[i + 1] - elapsed, 0))
i += 2
}
return out return out
} }
@@ -45,26 +50,32 @@ class DnsCache(
val rcode = response[3].toInt() and 0x0F val rcode = response[3].toInt() and 0x0F
if (rcode != 0 && rcode != 3) return // only NOERROR and NXDOMAIN if (rcode != 0 && rcode != 3) return // only NOERROR and NXDOMAIN
val records = parseTtls(response) ?: return val ttls = parseTtls(response) ?: return
val minTtl = if (records.first.isEmpty()) NO_RECORDS_TTL else records.second.min() var minTtl = if (ttls.isEmpty()) NO_RECORDS_TTL else Int.MAX_VALUE
var i = 1
while (i < ttls.size) {
minTtl = minOf(minTtl, ttls[i])
i += 2
}
val ttl = minOf(minTtl, MAX_TTL) val ttl = minOf(minTtl, MAX_TTL)
if (ttl <= 0) return if (ttl <= 0) return
val now = clock() val now = clock()
val entry = Entry(response.copyOf(), records.first, records.second, now, now + ttl * 1000L) val entry = Entry(response.copyOf(), ttls, now, now + ttl * 1000L)
synchronized(map) { map[key] = entry } synchronized(map) { map[key] = entry }
} }
// Offsets and values of every TTL field except the EDNS OPT pseudo-record // Offset and value of every TTL field except the EDNS OPT pseudo-record, as pairs in one array
private fun parseTtls(msg: ByteArray): Pair<IntArray, IntArray>? { private fun parseTtls(msg: ByteArray): IntArray? {
var pos = 12 var pos = 12
repeat(u16(msg, 4)) { repeat(u16(msg, 4)) {
pos = skipName(msg, pos) ?: return null pos = skipName(msg, pos) ?: return null
pos += 4 pos += 4
} }
val total = u16(msg, 6) + u16(msg, 8) + u16(msg, 10) val total = u16(msg, 6) + u16(msg, 8) + u16(msg, 10)
val offsets = ArrayList<Int>(total) // The counts come from the server; the array grows only if a message really has that many
val values = ArrayList<Int>(total) var ttls = IntArray(2 * minOf(total, 16))
var n = 0
repeat(total) { repeat(total) {
pos = skipName(msg, pos) ?: return null pos = skipName(msg, pos) ?: return null
if (pos + 10 > msg.size) return null if (pos + 10 > msg.size) return null
@@ -72,13 +83,14 @@ class DnsCache(
val ttlOffset = pos + 4 val ttlOffset = pos + 4
val rdLength = u16(msg, pos + 8) val rdLength = u16(msg, pos + 8)
if (type != TYPE_OPT) { if (type != TYPE_OPT) {
offsets += ttlOffset if (n == ttls.size) ttls = ttls.copyOf(n * 2)
values += minOf(u32(msg, ttlOffset), Int.MAX_VALUE.toLong()).toInt() ttls[n++] = ttlOffset
ttls[n++] = minOf(u32(msg, ttlOffset), Int.MAX_VALUE.toLong()).toInt()
} }
pos += 10 + rdLength pos += 10 + rdLength
if (pos > msg.size) return null if (pos > msg.size) return null
} }
return offsets.toIntArray() to values.toIntArray() return if (n == ttls.size) ttls else ttls.copyOf(n)
} }
private fun keyOf(query: ByteArray): String? { private fun keyOf(query: ByteArray): String? {
@@ -59,6 +59,15 @@ class DnsTileService : TileService() {
return return
} }
} }
// Turning protection off needs an unlocked phone, like other security toggles
if (running && isLocked) {
unlockAndRun { toggle(running) }
return
}
toggle(running)
}
private fun toggle(running: Boolean) {
val action = if (running) DohVpnService.ACTION_STOP else DohVpnService.ACTION_START val action = if (running) DohVpnService.ACTION_STOP else DohVpnService.ACTION_START
try { try {
startService(Intent(this, DohVpnService::class.java).setAction(action)) startService(Intent(this, DohVpnService::class.java).setAction(action))
@@ -5,6 +5,7 @@ import android.net.ConnectivityManager
import android.net.Network 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.NetworkException
import android.net.http.UploadDataProvider import android.net.http.UploadDataProvider
import android.net.http.UploadDataSink import android.net.http.UploadDataSink
import android.net.http.UrlRequest import android.net.http.UrlRequest
@@ -74,7 +75,10 @@ class DohClient(context: Context, provider: DohProvider) {
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) {
try { try {
return Http3Transport(context, provider) val http3 = Http3Transport(context, provider)
// HttpEngine resolves the host with system DNS and cannot use fixed addresses
return if (provider.bootstrap.isEmpty()) http3
else BootstrapFallbackTransport(http3) { OkHttpTransport(context, provider) }
} catch (e: Throwable) { } catch (e: Throwable) {
Log.w(TAG, "HttpEngine unavailable, falling back to HTTP/2", e) Log.w(TAG, "HttpEngine unavailable, falling back to HTTP/2", e)
} }
@@ -89,6 +93,38 @@ private interface Transport {
fun shutdown() fun shutdown()
} }
private class UnresolvedHostException(cause: Throwable) : IOException("Host not resolved", cause)
// HTTP/3 first; once the network fails to resolve the server's name, the rest of the session
// goes over OkHttp, which connects to the bootstrap addresses instead
private class BootstrapFallbackTransport(
private val http3: Transport,
createFallback: () -> Transport,
) : Transport {
private val fallback = lazy(createFallback)
@Volatile private var useFallback = false
override val lastProtocol: String?
get() = if (useFallback) fallback.value.lastProtocol else http3.lastProtocol
override fun query(message: ByteArray): ByteArray {
if (!useFallback) {
try {
return http3.query(message)
} catch (e: UnresolvedHostException) {
Log.w(TAG, "Server name not resolved over HTTP/3, using bootstrap addresses")
useFallback = true
}
}
return fallback.value.query(message)
}
override fun shutdown() {
http3.shutdown()
if (fallback.isInitialized()) fallback.value.shutdown()
}
}
private class OkHttpTransport(context: Context, 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() }
@@ -140,7 +176,11 @@ private class OkHttpTransport(context: Context, private val provider: DohProvide
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")
if (body.contentLength() > MAX_DNS_SIZE) throw IOException("Response too large") if (body.contentLength() > MAX_DNS_SIZE) throw IOException("Response too large")
return body.bytes() // Without Content-Length the size is only known while reading: stop one byte past the limit
val source = body.source()
source.request(MAX_DNS_SIZE + 1L)
if (source.buffer.size > MAX_DNS_SIZE) throw IOException("Response too large")
return source.buffer.readByteArray()
} }
} }
@@ -220,7 +260,11 @@ private class Http3Transport(context: Context, private val provider: DohProvider
} }
override fun onFailed(request: UrlRequest, info: UrlResponseInfo?, error: HttpException) { override fun onFailed(request: UrlRequest, info: UrlResponseInfo?, error: HttpException) {
result.completeExceptionally(IOException(error.message, error)) val unresolved = error is NetworkException &&
error.errorCode == NetworkException.ERROR_HOSTNAME_NOT_RESOLVED
result.completeExceptionally(
if (unresolved) UnresolvedHostException(error) else IOException(error.message, error)
)
} }
override fun onCanceled(request: UrlRequest, info: UrlResponseInfo?) { override fun onCanceled(request: UrlRequest, info: UrlResponseInfo?) {
@@ -20,6 +20,7 @@ import android.system.StructPollfd
import android.util.Log import android.util.Log
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.io.FileInputStream import java.io.FileInputStream
import java.io.FileOutputStream import java.io.FileOutputStream
import java.io.IOException import java.io.IOException
@@ -34,7 +35,11 @@ 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
// Separate channel with normal importance: losing protection must not go unnoticed
private const val ALERT_CHANNEL_ID = "vpn_alerts"
private const val ALERT_NOTIFICATION_ID = 2
private const val MAX_BAD_PACKETS = 100 private const val MAX_BAD_PACKETS = 100
private const val READER_JOIN_MS = 1000L
// Android's resolver retries after 5 s, so an older lookup no longer has anyone waiting for it // 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 private const val QUEUE_TIMEOUT_MS = 5000L
@@ -96,6 +101,19 @@ class DohVpnService : VpnService() {
val provider = prefs.resolve() val provider = prefs.resolve()
val excluded = prefs.excludedApps val excluded = prefs.excludedApps
// The app checks the address before connecting, but always-on VPN and a restart by the
// system start the service directly. A tunnel with a broken URL would fail every lookup.
if (provider.url.toHttpUrlOrNull()?.isHttps != true) {
Log.e(TAG, "Server address is not a valid HTTPS URL, not starting")
stopSession()
showAlert(
R.string.alert_bad_url_title,
if (provider.id == Providers.DEFAULT_ID) R.string.alert_no_key_text else R.string.alert_bad_url_text,
)
stopSelf()
return
}
val builder = Builder() val builder = Builder()
.setSession(provider.displayName(this)) .setSession(provider.displayName(this))
.addAddress(TUN_ADDRESS, 32) .addAddress(TUN_ADDRESS, 32)
@@ -124,13 +142,28 @@ class DohVpnService : VpnService() {
stopSelf() stopSelf()
return return
} }
session = Session(tun, DohClient(this, provider), ::onSessionFailed).also { it.start() } val next = try {
Session(tun, DohClient(this, provider), ::onSessionFailed)
} catch (e: IOException) {
// A tunnel nobody reads would swallow every DNS lookup on the device
runCatching { tun.close() }
throw e
}
session = next.also { it.start() }
runCatching { previous?.stop() } runCatching { previous?.stop() }
_active.value = provider _active.value = provider
_activeExcluded.value = excluded _activeExcluded.value = excluded
showNotification(provider) showNotification(provider)
DnsTileService.refresh(this) DnsTileService.refresh(this)
getSystemService(NotificationManager::class.java)?.cancel(ALERT_NOTIFICATION_ID)
// With "Block connections without VPN" the app, excluded from its own tunnel, cannot reach
// the DoH server, so every lookup would fail
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isLockdownEnabled) {
Log.w(TAG, "Lockdown mode is on, the DoH server is not reachable")
showAlert(R.string.alert_lockdown_title, R.string.alert_lockdown_text)
}
} }
private fun stopSession() { private fun stopSession() {
@@ -150,10 +183,34 @@ class DohVpnService : VpnService() {
if (session !== failed) return@post if (session !== failed) return@post
Log.e(TAG, "Tunnel stopped working, disconnecting") Log.e(TAG, "Tunnel stopped working, disconnecting")
stopSession() stopSession()
// DNS goes unencrypted from here on; the user has to know
showAlert(R.string.alert_stopped_title, R.string.alert_stopped_text)
stopSelf() stopSelf()
} }
} }
private fun showAlert(titleRes: Int, textRes: Int) {
val manager = getSystemService(NotificationManager::class.java) ?: return
manager.createNotificationChannel(
NotificationChannel(ALERT_CHANNEL_ID, getString(R.string.alert_channel), NotificationManager.IMPORTANCE_DEFAULT)
)
val openApp = PendingIntent.getActivity(
this, 2,
Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_IMMUTABLE,
)
val text = getString(textRes)
val notification = Notification.Builder(this, ALERT_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(titleRes))
.setContentText(text)
.setStyle(Notification.BigTextStyle().bigText(text))
.setContentIntent(openApp)
.setAutoCancel(true)
.build()
runCatching { manager.notify(ALERT_NOTIFICATION_ID, notification) }
}
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(
@@ -189,7 +246,7 @@ class DohVpnService : VpnService() {
try { try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED)
} else { } else {
startForeground(NOTIFICATION_ID, notification) startForeground(NOTIFICATION_ID, notification)
} }
@@ -210,6 +267,10 @@ private class Session(
private val pool = Executors.newFixedThreadPool(WORKERS) private val pool = Executors.newFixedThreadPool(WORKERS)
private val cache = DnsCache() private val cache = DnsCache()
private val output = FileOutputStream(tun.fileDescriptor) private val output = FileOutputStream(tun.fileDescriptor)
// stop() closes the write end, which wakes the reader at once. Otherwise the reader would have
// to wake up on a timer to notice that the session ended, also while the device sleeps.
private val wakeup = ParcelFileDescriptor.createPipe()
private val reader = Thread(::readLoop, "tun-reader") private val reader = Thread(::readLoop, "tun-reader")
fun start() = reader.start() fun start() = reader.start()
@@ -217,6 +278,10 @@ private class Session(
fun stop() { fun stop() {
if (!alive.getAndSet(false)) return if (!alive.getAndSet(false)) return
pool.shutdownNow() pool.shutdownNow()
runCatching { wakeup[1].close() }
// The pipe wakes the reader at once; let it leave before its descriptor is closed and
// possibly reused by something else
if (Thread.currentThread() !== reader) runCatching { reader.join(READER_JOIN_MS) }
runCatching { tun.close() } runCatching { tun.close() }
closer.execute { closer.execute {
try { try {
@@ -230,16 +295,28 @@ private class Session(
private fun readLoop() { private fun readLoop() {
val input = FileInputStream(tun.fileDescriptor) val input = FileInputStream(tun.fileDescriptor)
val buf = ByteArray(MTU) val buf = ByteArray(MTU)
val pollFd = StructPollfd().apply { val tunFd = StructPollfd().apply {
fd = tun.fileDescriptor fd = tun.fileDescriptor
events = OsConstants.POLLIN.toShort() events = OsConstants.POLLIN.toShort()
} }
val wakeupFd = StructPollfd().apply {
fd = wakeup[0].fileDescriptor
events = OsConstants.POLLIN.toShort()
}
val fds = arrayOf(tunFd, wakeupFd)
var badPackets = 0 var badPackets = 0
try {
while (alive.get()) { while (alive.get()) {
val n = try { val n = try {
if (Os.poll(arrayOf(pollFd), 500) <= 0) continue // Sleeps until a packet arrives or stop() closes the pipe
if (Os.poll(fds, -1) <= 0) continue
if (wakeupFd.revents.toInt() != 0) {
// Only stop() touches the pipe, so this ends the loop
readerFailed(null)
return
}
input.read(buf) input.read(buf)
} catch (e: ErrnoException) { } catch (e: ErrnoException) {
if (e.errno == OsConstants.EINTR) continue if (e.errno == OsConstants.EINTR) continue
@@ -268,6 +345,9 @@ private class Session(
} }
} }
} }
} finally {
runCatching { wakeup[0].close() }
}
} }
// stop() closes the tunnel, which also ends the loop; only an unexpected end is a failure // stop() closes the tunnel, which also ends the loop; only an unexpected end is a failure
@@ -25,11 +25,12 @@ 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.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.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
@@ -39,6 +40,8 @@ import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
@@ -47,85 +50,110 @@ 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.rememberCoroutineScope
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.drawBehind import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.StrokeCap 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.graphics.graphicsLayer
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
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.semantics.contentDescription import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign 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.Constraints
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.delay
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date import java.util.Date
import java.util.Locale import java.util.Locale
import java.util.TimeZone
import kotlin.math.ceil
import kotlin.math.roundToInt
private const val CHART_HOURS = 24 private const val HOUR_MS = 3_600_000L
// One bar of the chart: an hour, or a day in the 7-day view
private data class Bar(val total: Long, val blocked: Long)
// Bars with the labels under them: the first hour of the day view, or every day of the week.
// A refresh that brings equal data leaves the chart alone.
private data class Chart(val period: StatsPeriod, val bars: List<Bar>, val labels: List<String>)
private val ChartLabelStyle = TextStyle(color = Palette.Fg3, fontSize = 10.sp)
// Where the three grip lines on the knob of the power switch sit, as fractions of its width
private val KnobLines = floatArrayOf(0.29f, 0.5f, 0.71f)
@Composable @Composable
fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifier = Modifier) { fun HomeScreen(
bottomPadding: Dp,
onOpenBlocklist: () -> Unit,
onOpenServers: () -> Unit,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current val context = LocalContext.current
val prefs = remember { Prefs(context) } val prefs = remember { Prefs(context) }
val haptics = LocalHapticFeedback.current
val scope = rememberCoroutineScope()
val active by DohVpnService.active.collectAsStateWithLifecycle() val active by DohVpnService.active.collectAsStateWithLifecycle()
val running = active != null val running = active != null
val lists by Blocklist.lists.collectAsStateWithLifecycle() val lists by Blocklist.lists.collectAsStateWithLifecycle()
val total by Blocklist.total.collectAsStateWithLifecycle() val total by Blocklist.total.collectAsStateWithLifecycle()
val blocking by Blocklist.enabled.collectAsStateWithLifecycle() val blocking by Blocklist.enabled.collectAsStateWithLifecycle()
val listsReady by Blocklist.ready.collectAsStateWithLifecycle()
val download by Blocklist.busy.collectAsStateWithLifecycle()
val downloadError by Blocklist.error.collectAsStateWithLifecycle()
var summary by remember { mutableStateOf(StatsStore.summary(CHART_HOURS)) } var period by rememberSaveable { mutableStateOf(StatsPeriod.DAY) }
var points by remember { mutableStateOf(StatsStore.hourly(CHART_HOURS)) } var summary by remember { mutableStateOf(StatsStore.summary(period.hours)) }
var chartData by remember { mutableStateOf(buildChart(period)) }
fun refreshStats() { fun refreshStats() {
summary = StatsStore.summary(CHART_HOURS) summary = StatsStore.summary(period.hours)
points = StatsStore.hourly(CHART_HOURS) chartData = buildChart(period)
} }
OnQueryLogChange { refreshStats() } OnQueryLogChange { refreshStats() }
val statsVersion by StatsStore.version.collectAsStateWithLifecycle() val statsVersion by StatsStore.version.collectAsStateWithLifecycle()
LaunchedEffect(statsVersion) { refreshStats() } LaunchedEffect(statsVersion, period) { refreshStats() }
// The server is picked in Settings; this screen is composed anew each time it is shown // The server is picked in Settings; this screen is composed anew each time it is shown
val selected = remember { prefs.resolve() } val selected = remember { prefs.resolve() }
val canConnect = selected.id != Providers.CUSTOM_ID || selected.url.toHttpUrlOrNull()?.isHttps == true val canConnect = selected.url.toHttpUrlOrNull()?.isHttps == true
val needsKey = selected.id == Providers.DEFAULT_ID && !canConnect
val shown = active ?: selected val shown = active ?: selected
val usesHttp3 = shown.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE val usesHttp3 = shown.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
val crashReport = remember { CrashLog.read(context) } val crashReport by CrashLog.report.collectAsStateWithLifecycle()
var crashVisible by remember { mutableStateOf(crashReport != null) } val shownReport = rememberLast(crashReport).orEmpty() // kept while the card animates out
// Strict Private DNS makes Android ignore the VPN's DNS server; followed while Home is visible // 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) 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 var busy by rememberVpnBusy(active)
// 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( val vpnPermission = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult() ActivityResultContracts.StartActivityForResult()
@@ -148,6 +176,7 @@ fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifie
fun toggle() { fun toggle() {
if (busy) return if (busy) return
busy = true busy = true
haptics.performHapticFeedback(if (running) HapticFeedbackType.ToggleOff else HapticFeedbackType.ToggleOn)
if (running) { if (running) {
sendAction(context, DohVpnService.ACTION_STOP) sendAction(context, DohVpnService.ACTION_STOP)
return return
@@ -158,65 +187,58 @@ fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifie
else connectVpn() else connectVpn()
} }
// What the blocklist card offers: nothing, switching blocking back on, or a first list
val proList = lists.firstOrNull { it.url == HAGEZI_PRO_URL }
val offer = when {
!listsReady -> BlocklistOffer.NONE
!blocking -> BlocklistOffer.SWITCH_ON
total == 0 && lists.none { it.enabled } -> BlocklistOffer.FIRST_LIST
else -> BlocklistOffer.NONE
}
fun acceptOffer() {
when (offer) {
BlocklistOffer.SWITCH_ON -> Blocklist.setEnabled(context, true)
BlocklistOffer.FIRST_LIST ->
if (proList != null) scope.editBlocklist(context) { Blocklist.setListEnabled(context, HAGEZI_PRO_URL, true) }
else Blocklist.download(context, HAGEZI_PRO_URL)
BlocklistOffer.NONE -> Unit
}
}
val glow by animateFloatAsState(if (running) 1f else 0f, tween(600), label = "glow") val glow by animateFloatAsState(if (running) 1f else 0f, tween(600), label = "glow")
val wide = windowWidth() >= WideLayoutWidth
Column( val side = sidePadding(windowWidth(), if (wide) MaxWideContentWidth else MaxContentWidth)
modifier = modifier // A tall screen gets a taller chart instead of empty space under the content
.verticalScroll(rememberScrollState()) val chartHeight = if (wide) {
.drawBehind { (windowHeight() - 420.dp).coerceIn(160.dp, 360.dp)
// Soft light behind the logo while protected } else {
if (glow > 0f) { (windowHeight() - 700.dp).coerceIn(150.dp, 320.dp)
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 },
)
}
} }
val status: @Composable () -> Unit = {
StatusCard( StatusCard(
running = running, running = running,
providerName = shown.displayName(context), providerName = shown.displayName(context),
http3 = usesHttp3, http3 = usesHttp3,
enabled = !busy && (running || canConnect), enabled = !busy && (running || canConnect),
onToggle = ::toggle, onToggle = ::toggle,
modifier = Modifier.padding(horizontal = 20.dp), onOpenServers = onOpenServers,
) )
if (needsKey && !running) {
PrivateDnsWarning(privateDnsHost, prefs, Modifier.padding(horizontal = 20.dp)) HintCard(
text = stringResource(R.string.key_needed),
icon = R.drawable.ic_alert,
tint = Palette.Accent,
action = { TextButton(onClick = onOpenServers) { Text(stringResource(R.string.key_add)) } },
)
}
PrivateDnsWarning(privateDnsHost, prefs)
}
val stats: @Composable () -> Unit = {
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 24.dp), .padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
) { ) {
StatBlock(formatCompact(summary.total), stringResource(R.string.stat_requests), Modifier.weight(1f)) StatBlock(formatCompact(summary.total), stringResource(R.string.stat_requests), Modifier.weight(1f))
@@ -228,64 +250,79 @@ fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifie
) )
StatBlock(stringResource(R.string.mon_ms, summary.avgLatencyMs), stringResource(R.string.stat_avg), Modifier.weight(1f)) 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( val chart: @Composable () -> Unit = {
points, ChartSection(chartData, period, chartHeight, onPeriod = { period = it })
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( val blocklist: @Composable () -> Unit = {
modifier = Modifier BlocklistCard(
.fillMaxWidth() info = stringResource(R.string.home_lists_info, lists.count { it.enabled }, formatCount(total.toLong())),
.padding(horizontal = 20.dp), offer = offer,
verticalAlignment = Alignment.CenterVertically, downloading = download == HAGEZI_PRO_URL,
) { error = if (offer == BlocklistOffer.FIRST_LIST) downloadError else null,
Text(startLabel, color = Palette.Fg3, fontSize = 11.sp, modifier = Modifier.weight(1f)) canAccept = download == null,
Text( onAccept = ::acceptOffer,
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, onClick = onOpenBlocklist,
modifier = Modifier.padding(horizontal = 20.dp),
) )
} }
Column(
modifier = modifier
.verticalScroll(rememberScrollState())
.drawWithCache {
// Soft light behind the logo while protected. The gradient depends on the size only;
// the fade is applied as alpha when drawing.
val center = Offset(size.width / 2f, 0f)
val radius = size.width * 0.65f
val light = Brush.radialGradient(
colors = listOf(Palette.Accent.copy(alpha = 0.22f), Color.Transparent),
center = center,
radius = radius,
)
onDrawBehind {
if (glow > 0f) drawCircle(brush = light, radius = radius, center = center, alpha = glow)
}
}
.padding(start = side, end = side, top = 16.dp, bottom = bottomPadding),
verticalArrangement = Arrangement.spacedBy(20.dp),
) {
Image(
remember { AppLogo.get(context) },
contentDescription = null,
modifier = Modifier
.size(44.dp)
.align(Alignment.CenterHorizontally),
)
AnimatedVisibility(visible = crashReport != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
CrashCard(
report = shownReport,
onCopy = {
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("SparkleDNS crash", shownReport))
},
onDismiss = { CrashLog.clear(context) },
)
}
if (wide) {
Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(20.dp)) {
status()
blocklist()
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(20.dp)) {
stats()
chart()
}
}
} else {
status()
stats()
chart()
blocklist()
}
}
} }
@Composable @Composable
@@ -295,15 +332,15 @@ private fun StatusCard(
http3: Boolean, http3: Boolean,
enabled: Boolean, enabled: Boolean,
onToggle: () -> Unit, onToggle: () -> Unit,
modifier: Modifier = Modifier, onOpenServers: () -> Unit,
) { ) {
Column( Column(
modifier = modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.appCard() .appCard()
.padding(horizontal = 20.dp, vertical = 24.dp), .padding(horizontal = 20.dp, vertical = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp),
) { ) {
AnimatedContent( AnimatedContent(
targetState = running, targetState = running,
@@ -319,13 +356,21 @@ private fun StatusCard(
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
} }
// Tapping the server opens the server list in Settings
val dot by animateColorAsState(if (running) Palette.Accent else Palette.Track, Motion.color, label = "dot") val dot by animateColorAsState(if (running) Palette.Accent else Palette.Track, Motion.color, label = "dot")
Row(verticalAlignment = Alignment.CenterVertically) { Row(
modifier = Modifier
.clip(RoundedCornerShape(12.dp))
.clickable(onClickLabel = stringResource(R.string.change_server), onClick = onOpenServers)
.heightIn(min = 40.dp)
.padding(start = 10.dp, end = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box( Box(
Modifier Modifier
.size(7.dp) .size(7.dp)
.clip(CircleShape) .clip(CircleShape)
.background(dot) .drawBehind { drawRect(dot) }
) )
Spacer(Modifier.width(8.dp)) Spacer(Modifier.width(8.dp))
val via = stringResource(R.string.home_via, providerName) + if (http3) " · HTTP/3" else "" val via = stringResource(R.string.home_via, providerName) + if (http3) " · HTTP/3" else ""
@@ -336,14 +381,18 @@ private fun StatusCard(
maxLines = 2, maxLines = 2,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
modifier = Modifier.weight(1f, fill = false),
) )
Spacer(Modifier.width(2.dp))
Chevron(Modifier.size(16.dp))
} }
Spacer(Modifier.height(10.dp)) Spacer(Modifier.height(8.dp))
PowerToggle(on = running, enabled = enabled, onToggle = onToggle) PowerToggle(on = running, enabled = enabled, onToggle = onToggle)
} }
} }
// The big ON / OFF switch; the white knob slides across // The big ON / OFF switch; the white knob slides across. The animated color and position are
// read only when drawing and placing, so the animation does not recompose the switch every frame.
@Composable @Composable
private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) { 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 track by animateColorAsState(if (on) Palette.Accent else Palette.Track, Motion.color, label = "track")
@@ -354,7 +403,7 @@ private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
.size(width = 120.dp, height = 50.dp) .size(width = 120.dp, height = 50.dp)
.graphicsLayer { alpha = if (enabled) 1f else 0.5f } .graphicsLayer { alpha = if (enabled) 1f else 0.5f }
.clip(RoundedCornerShape(25.dp)) .clip(RoundedCornerShape(25.dp))
.background(track) .drawBehind { drawRect(track) }
.toggleable(value = on, enabled = enabled, role = Role.Switch, onValueChange = { onToggle() }) .toggleable(value = on, enabled = enabled, role = Role.Switch, onValueChange = { onToggle() })
.semantics { contentDescription = description } .semantics { contentDescription = description }
.padding(5.dp), .padding(5.dp),
@@ -371,7 +420,7 @@ private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
) )
Box( Box(
modifier = Modifier modifier = Modifier
.offset(x = knob) .offset { IntOffset(knob.roundToPx(), 0) }
.size(40.dp) .size(40.dp)
.clip(CircleShape) .clip(CircleShape)
.background(Color.White), .background(Color.White),
@@ -379,7 +428,7 @@ private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
) { ) {
Canvas(Modifier.size(14.dp)) { Canvas(Modifier.size(14.dp)) {
val stroke = 1.6.dp.toPx() val stroke = 1.6.dp.toPx()
listOf(0.29f, 0.5f, 0.71f).forEach { fraction -> KnobLines.forEach { fraction ->
drawLine( drawLine(
color = Palette.Fg3, color = Palette.Fg3,
start = Offset(size.width * fraction, size.height * 0.21f), start = Offset(size.width * fraction, size.height * 0.21f),
@@ -394,27 +443,25 @@ private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
} }
@Composable @Composable
private fun PrivateDnsWarning(privateDnsHost: String?, prefs: Prefs, modifier: Modifier = Modifier) { private fun PrivateDnsWarning(privateDnsHost: String?, prefs: Prefs) {
val context = LocalContext.current val context = LocalContext.current
val lastHost = remember { arrayOf("") } val shownHost = rememberLast(privateDnsHost).orEmpty()
privateDnsHost?.let { lastHost[0] = it }
var dismissedHost by remember { mutableStateOf(prefs.dismissedPrivateDns) } var dismissedHost by remember { mutableStateOf(prefs.dismissedPrivateDns) }
AnimatedVisibility( AnimatedVisibility(
visible = privateDnsHost != null && privateDnsHost != dismissedHost, visible = privateDnsHost != null && privateDnsHost != dismissedHost,
enter = Motion.expandIn, enter = Motion.expandIn,
exit = Motion.collapseOut, exit = Motion.collapseOut,
modifier = modifier,
) { ) {
HintCard( HintCard(
text = stringResource(R.string.hint, lastHost[0]), text = stringResource(R.string.hint, shownHost),
icon = R.drawable.ic_alert, icon = R.drawable.ic_alert,
tint = WarningColor, tint = WarningColor,
action = { action = {
TextButton(onClick = { openNetworkSettings(context) }) { Text(stringResource(R.string.open_settings)) } TextButton(onClick = { openNetworkSettings(context) }) { Text(stringResource(R.string.open_settings)) }
}, },
onDismiss = { onDismiss = {
dismissedHost = lastHost[0] dismissedHost = shownHost
prefs.dismissedPrivateDns = lastHost[0] prefs.dismissedPrivateDns = shownHost
}, },
) )
} }
@@ -428,12 +475,62 @@ fun StatBlock(value: String, label: String, modifier: Modifier = Modifier, value
} }
} }
@Composable
private fun ChartSection(chart: Chart, period: StatsPeriod, height: Dp, onPeriod: (StatsPeriod) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
PeriodChip(period, onPeriod)
Spacer(Modifier.weight(1f))
LegendItem(stringResource(R.string.stat_requests), Palette.Accent)
Spacer(Modifier.width(14.dp))
LegendItem(stringResource(R.string.mon_blocked), Palette.Blocked)
}
Box(
Modifier
.fillMaxWidth()
.height(height),
contentAlignment = Alignment.Center,
) {
if (chart.bars.all { it.total == 0L }) {
Text(
stringResource(R.string.chart_empty),
color = Palette.Fg3,
fontSize = 13.sp,
lineHeight = 18.sp,
textAlign = TextAlign.Center,
modifier = Modifier.padding(horizontal = 24.dp),
)
} else {
TrafficChart(chart.bars, Modifier.fillMaxWidth().height(height))
}
}
// Hours: first hour on the left, now on the right. Days: a label under every bar.
Row(Modifier.fillMaxWidth()) {
if (chart.period == StatsPeriod.DAY) {
Text(chart.labels.firstOrNull().orEmpty(), color = Palette.Fg3, fontSize = 11.sp, modifier = Modifier.weight(1f))
Text(stringResource(R.string.chart_now), color = Palette.Fg3, fontSize = 11.sp)
} else {
chart.labels.forEachIndexed { index, label ->
Text(
label,
color = if (index == chart.labels.lastIndex) Palette.Fg else Palette.Fg3,
fontSize = 11.sp,
maxLines = 1,
textAlign = TextAlign.Center,
modifier = Modifier.weight(1f),
)
}
}
}
}
}
@Composable @Composable
private fun LegendItem(label: String, color: Color) { private fun LegendItem(label: String, color: Color) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Box( Box(
Modifier Modifier
.size(width = 12.dp, height = 3.dp) .size(8.dp)
.clip(RoundedCornerShape(2.dp)) .clip(RoundedCornerShape(2.dp))
.background(color) .background(color)
) )
@@ -442,75 +539,88 @@ private fun LegendItem(label: String, color: Color) {
} }
} }
// Requests (accent line with a soft fill) and blocked queries (grey line) per hour // One bar per hour or day: requests in the accent color with the blocked part at the bottom.
// Empty slots show a short stub, so a mostly empty day reads as empty instead of broken.
@Composable @Composable
private fun TrafficChart(points: List<HourPoint>, modifier: Modifier = Modifier) { private fun TrafficChart(bars: List<Bar>, modifier: Modifier = Modifier) {
val measurer = rememberTextMeasurer() val measurer = rememberTextMeasurer()
val labelStyle = TextStyle(color = Palette.Fg3, fontSize = 10.sp) // Scale, grid and grid labels are worked out when the bars or the size change, not every frame
Canvas(modifier) { Spacer(
val n = points.size modifier.drawWithCache {
if (n < 2) return@Canvas val n = bars.size
val maxValue = niceCeiling(points.maxOf { it.total }.coerceAtLeast(1L)) if (n == 0) return@drawWithCache onDrawBehind {}
val inset = 6.dp.toPx() val maxValue = niceCeiling(bars.maxOf { it.total }.coerceAtLeast(1L))
val top = 14.dp.toPx() val top = 16.dp.toPx()
val base = size.height - 8.dp.toPx() val base = size.height - 2.dp.toPx()
val span = base - top val span = base - top
val step = (size.width - 2 * inset) / (n - 1) val slot = size.width / n
fun x(index: Int) = inset + index * step val barWidth = (slot * if (n > 10) 0.62f else 0.5f).coerceAtLeast(2.dp.toPx())
fun y(value: Long) = base - value.toFloat() / maxValue * span val radius = CornerRadius((barWidth / 2).coerceAtMost(4.dp.toPx()))
val stub = 2.dp.toPx()
val minBar = 4.dp.toPx()
val minBlocked = 2.dp.toPx()
val gridWidth = 1.dp.toPx()
val dash = PathEffect.dashPathEffect(floatArrayOf(3.dp.toPx(), 4.dp.toPx()))
fun height(value: Long) = value.toFloat() / maxValue * span
listOf(maxValue / 2, maxValue).forEach { value -> val grid = listOf(maxValue / 2, maxValue).filter { it > 0 }.map { value ->
val gridY = y(value) val y = base - height(value)
val labelTop = y - 14.dp.toPx()
// The same constraints drawText() would use for a label at this spot
val label = measurer.measure(
text = formatCompact(value),
style = ChartLabelStyle,
constraints = Constraints(
maxWidth = ceil(size.width).roundToInt().coerceAtLeast(0),
maxHeight = ceil(size.height - labelTop).roundToInt().coerceAtLeast(0),
),
layoutDirection = layoutDirection,
density = this,
)
GridLine(y, labelTop, label)
}
onDrawBehind {
grid.forEach { line ->
drawLine( drawLine(
color = Palette.Line, color = Palette.Line,
start = Offset(0f, gridY), start = Offset(0f, line.y),
end = Offset(size.width, gridY), end = Offset(size.width, line.y),
strokeWidth = 1.dp.toPx(), strokeWidth = gridWidth,
pathEffect = PathEffect.dashPathEffect(floatArrayOf(3.dp.toPx(), 4.dp.toPx())), pathEffect = dash,
)
drawText(
textMeasurer = measurer,
text = formatCompact(value),
topLeft = Offset(20.dp.toPx(), gridY - 15.dp.toPx()),
style = labelStyle,
) )
drawText(line.label, topLeft = Offset(0f, line.labelTop))
} }
val line = Path() bars.forEachIndexed { index, bar ->
val area = Path() val x = index * slot + (slot - barWidth) / 2
val blocked = Path() if (bar.total == 0L) {
points.forEachIndexed { index, point -> drawRoundRect(Palette.Line, Offset(x, base - stub), Size(barWidth, stub), CornerRadius(stub / 2))
val px = x(index) return@forEachIndexed
if (index == 0) { }
line.moveTo(px, y(point.total)) val current = index == n - 1
area.moveTo(px, base) val h = height(bar.total).coerceAtLeast(minBar)
area.lineTo(px, y(point.total)) drawRoundRect(
blocked.moveTo(px, y(point.blocked)) if (current) Palette.Accent else Palette.Accent.copy(alpha = 0.6f),
Offset(x, base - h),
Size(barWidth, h),
radius,
)
if (bar.blocked > 0) {
val hb = height(bar.blocked).coerceIn(minBlocked, h)
if (hb >= h - radius.x) {
drawRoundRect(Palette.Blocked, Offset(x, base - hb), Size(barWidth, hb), radius)
} else { } else {
line.lineTo(px, y(point.total)) drawRect(Palette.Blocked, Offset(x, base - hb), Size(barWidth, hb))
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)) private class GridLine(val y: Float, val labelTop: Float, val label: TextLayoutResult)
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 // 1, 2 or 5 times a power of ten, at least [value]: keeps the grid labels round
private fun niceCeiling(value: Long): Long { private fun niceCeiling(value: Long): Long {
@@ -522,35 +632,127 @@ private fun niceCeiling(value: Long): Long {
return 10 * magnitude return 10 * magnitude
} }
// Date formats of the chart for the current locale and time zone. The chart is refreshed up to
// once a second, so they are kept rather than built anew each time. Main thread only.
private class ChartFormats(val locale: Locale, val zone: String) {
val hour = SimpleDateFormat("HH:00", locale)
val day = SimpleDateFormat("EEE", locale)
}
private var chartFormats: ChartFormats? = null
private fun chartFormats(): ChartFormats {
val locale = Locale.getDefault()
val zone = TimeZone.getDefault().id
return chartFormats?.takeIf { it.locale == locale && it.zone == zone }
?: ChartFormats(locale, zone).also { chartFormats = it }
}
// 24 hourly bars, or 7 bars for the calendar days of the last week (today last)
private fun buildChart(period: StatsPeriod, now: Long = System.currentTimeMillis()): Chart {
val hours = StatsStore.hourly(period.hours, now)
val firstHour = now / HOUR_MS - (hours.size - 1)
val formats = chartFormats()
if (period == StatsPeriod.DAY) {
// Only the first hour gets a label; the other end of the axis says "now"
val label = formats.hour.format(Date(firstHour * HOUR_MS))
return Chart(period, hours.map { Bar(it.total, it.blocked) }, listOf(label))
}
val calendar = Calendar.getInstance()
fun dayKey(time: Long): Int {
calendar.timeInMillis = time
return calendar.get(Calendar.YEAR) * 1000 + calendar.get(Calendar.DAY_OF_YEAR)
}
val dayStarts = (6 downTo 0).map { back ->
calendar.timeInMillis = now
calendar.add(Calendar.DAY_OF_YEAR, -back)
calendar.timeInMillis
}
val keys = dayStarts.map { dayKey(it) }
val totals = LongArray(7)
val blocked = LongArray(7)
hours.forEachIndexed { index, point ->
val day = keys.indexOf(dayKey((firstHour + index) * HOUR_MS))
if (day >= 0) {
totals[day] += point.total
blocked[day] += point.blocked
}
}
return Chart(period, List(7) { Bar(totals[it], blocked[it]) }, dayStarts.map { formats.day.format(Date(it)) })
}
private enum class BlocklistOffer { NONE, SWITCH_ON, FIRST_LIST }
@Composable @Composable
private fun BlocklistRow(info: String, onClick: () -> Unit, modifier: Modifier = Modifier) { private fun BlocklistCard(
info: String,
offer: BlocklistOffer,
downloading: Boolean,
error: String?,
canAccept: Boolean,
onAccept: () -> Unit,
onClick: () -> Unit,
) {
val subtitle = when {
error != null -> stringResource(R.string.bl_download_failed, error)
offer == BlocklistOffer.SWITCH_ON -> stringResource(R.string.blocklist_cta_master)
offer == BlocklistOffer.FIRST_LIST -> stringResource(R.string.blocklist_cta_lists)
else -> info
}
Row( Row(
modifier = modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.appCard() .appCard()
.clickable(onClick = onClick) .clickable(onClick = onClick)
.padding(16.dp), .padding(16.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
val idle = offer != BlocklistOffer.NONE
Box( Box(
modifier = Modifier modifier = Modifier
.size(40.dp) .size(40.dp)
.clip(CircleShape) .clip(CircleShape)
.background(Palette.Accent), .background(if (idle) Palette.Track else Palette.Accent),
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
) { ) {
Icon( Icon(
painterResource(R.drawable.ic_privacy), painterResource(R.drawable.ic_privacy),
contentDescription = null, contentDescription = null,
tint = Palette.AccentInk, tint = if (idle) Palette.Fg2 else Palette.AccentInk,
modifier = Modifier.size(22.dp), modifier = Modifier.size(22.dp),
) )
} }
Spacer(Modifier.width(14.dp)) Spacer(Modifier.width(14.dp))
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.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(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) Text(
subtitle,
color = if (error != null) Palette.Blocked else Palette.Fg2,
fontSize = 12.sp,
lineHeight = 16.sp,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
} }
Spacer(Modifier.width(10.dp))
if (offer == BlocklistOffer.NONE) {
Chevron() Chevron()
} else {
Button(
onClick = onAccept,
enabled = canAccept && !downloading,
shape = RoundedCornerShape(14.dp),
contentPadding = PaddingValues(horizontal = 14.dp),
modifier = Modifier.heightIn(min = 40.dp),
) {
if (downloading) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp, color = Palette.Fg2)
Spacer(Modifier.width(8.dp))
Text(stringResource(R.string.downloading), fontSize = 13.sp, maxLines = 1)
} else {
Text(stringResource(R.string.turn_on), fontWeight = FontWeight.Bold, fontSize = 13.sp, maxLines = 1)
}
}
}
} }
} }
@@ -25,11 +25,20 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
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.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
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.res.painterResource import androidx.compose.ui.res.painterResource
@@ -38,6 +47,7 @@ import androidx.compose.ui.text.font.FontFamily
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.channels.awaitClose import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
@@ -46,9 +56,41 @@ import kotlinx.coroutines.flow.flowOf
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AppLogo.preload(this)
// Opened by the browser at the end of the Skysparkle sign-in (not again after rotation)
if (savedInstanceState == null) handleSignIn(intent)
enableEdgeToEdge() enableEdgeToEdge()
setContent { setContent {
MaterialTheme(colorScheme = AppColors) { AppShell() } MaterialTheme(colorScheme = AppColors) {
// There is no Surface at the root, so text and icons without an explicit color
// would fall back to black and disappear on the dark background
CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface) {
// First launch: the guide explains the access key before the app opens
var onboarded by rememberSaveable { mutableStateOf(Prefs(this@MainActivity).onboardingDone) }
if (onboarded) AppShell() else OnboardingScreen(onDone = { onboarded = true })
}
}
}
}
// singleTask: the sign-in callback reaches the running activity instead of opening a second one
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleSignIn(intent)
}
// Back from the browser without finishing the sign-in. A real callback arrives in
// onNewIntent, which always runs before this
override fun onResume() {
super.onResume()
SkysparkleSignIn.cancelWaiting()
}
private fun handleSignIn(intent: Intent?) {
val uri = intent?.data
if (intent?.action == Intent.ACTION_VIEW && SkysparkleSignIn.isCallback(uri)) {
SkysparkleSignIn.handle(this, uri!!)
} }
} }
} }
@@ -56,7 +98,22 @@ class MainActivity : ComponentActivity() {
internal class TestResult(val ok: Boolean, val text: String) internal class TestResult(val ok: Boolean, val text: String)
// How long a tap on Connect, Disconnect or Switch blocks further taps if the VPN state never changes // How long a tap on Connect, Disconnect or Switch blocks further taps if the VPN state never changes
internal const val BUSY_TIMEOUT_MS = 5000L private const val BUSY_TIMEOUT_MS = 5000L
// 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
@Composable
internal fun rememberVpnBusy(active: DohProvider?): MutableState<Boolean> {
val busy = remember { mutableStateOf(false) }
LaunchedEffect(active) { busy.value = false }
LaunchedEffect(busy.value) {
if (busy.value) {
delay(BUSY_TIMEOUT_MS)
busy.value = false
}
}
return busy
}
// Keeps test results across rotation and process death // Keeps test results across rotation and process death
internal val TestResultSaver = Saver<TestResult?, String>( internal val TestResultSaver = Saver<TestResult?, String>(
@@ -1,6 +1,5 @@
package cc.skysparkle.sparkledns package cc.skysparkle.sparkledns
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.core.CubicBezierEasing import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.FiniteAnimationSpec
import androidx.compose.animation.core.tween import androidx.compose.animation.core.tween
@@ -25,6 +24,4 @@ object Motion {
val expandIn = fadeIn(enterFade) + expandVertically(size) val expandIn = fadeIn(enterFade) + expandVertically(size)
val collapseOut = fadeOut(exitFade) + shrinkVertically(size) val collapseOut = fadeOut(exitFade) + shrinkVertically(size)
fun sizeTransform() = SizeTransform(clip = false) { _, _ -> size }
} }
@@ -0,0 +1,201 @@
package cc.skysparkle.sparkledns
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
// Shown once on first launch: what the app does, then how to get the personal access key
// for the Skysparkle server. Skipping leaves the key empty; other servers stay available.
@Composable
fun OnboardingScreen(onDone: () -> Unit) {
val context = LocalContext.current
val prefs = remember { Prefs(context) }
var page by rememberSaveable { mutableIntStateOf(0) }
var keyInput by rememberSaveable { mutableStateOf(prefs.skysparkleKey) }
val keyValid = SkysparkleKey.parse(keyInput) != null
fun finish(useKey: Boolean) {
if (useKey) {
prefs.skysparkleKey = SkysparkleKey.parse(keyInput) ?: ""
prefs.providerId = Providers.DEFAULT_ID
}
prefs.onboardingDone = true
onDone()
}
// Signed in from the guide: the key is saved, nothing is left to do here
SignInResult { key ->
keyInput = key
finish(useKey = true)
}
BackHandler(enabled = page > 0) { page-- }
Box(
Modifier
.fillMaxSize()
.background(Palette.Bg)
.statusBarsPadding()
.navigationBarsPadding()
.imePadding(),
contentAlignment = Alignment.TopCenter,
) {
Column(
Modifier
.widthIn(max = 520.dp)
.fillMaxSize()
.padding(horizontal = 24.dp, vertical = 20.dp),
) {
Dots(count = 2, current = page)
AnimatedContent(
targetState = page,
transitionSpec = {
val forward = targetState > initialState
(fadeIn(Motion.enterFade) + slideInHorizontally(Motion.slide) { if (forward) it / 4 else -it / 4 }) togetherWith
(fadeOut(Motion.exitFade) + slideOutHorizontally(Motion.slide) { if (forward) -it / 4 else it / 4 })
},
modifier = Modifier.weight(1f),
label = "onboarding",
) { current ->
Column(
Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(top = 40.dp, bottom = 16.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
if (current == 0) {
Image(
bitmap = AppLogo.get(context),
contentDescription = null,
modifier = Modifier
.size(72.dp)
.clip(RoundedCornerShape(20.dp)),
)
Spacer(Modifier.height(8.dp))
Title(stringResource(R.string.onb_welcome_title))
Body(stringResource(R.string.onb_welcome_text))
Spacer(Modifier.height(8.dp))
Step(1, stringResource(R.string.onb_point_encrypt))
Step(2, stringResource(R.string.onb_point_block))
Step(3, stringResource(R.string.onb_point_independent))
} else {
Title(stringResource(R.string.onb_key_title))
Body(stringResource(R.string.onb_key_text))
Spacer(Modifier.height(4.dp))
Step(1, stringResource(R.string.onb_key_step1))
Step(2, stringResource(R.string.onb_key_step2))
Step(3, stringResource(R.string.onb_key_step3))
}
}
}
if (page == 0) {
Button(
onClick = { page = 1 },
shape = RoundedCornerShape(16.dp),
modifier = Modifier.fillMaxWidth().height(52.dp),
) { Text(stringResource(R.string.onb_next), fontWeight = FontWeight.Bold) }
} else {
// The key comes only from signing in; a successful sign-in closes the guide by itself
if (keyValid) {
Button(
onClick = { finish(useKey = true) },
shape = RoundedCornerShape(16.dp),
modifier = Modifier.fillMaxWidth().height(52.dp),
) { Text(stringResource(R.string.onb_done), fontWeight = FontWeight.Bold) }
} else {
SignInButton(again = false, shape = RoundedCornerShape(16.dp), modifier = Modifier.fillMaxWidth().height(52.dp))
}
TextButton(onClick = { finish(useKey = false) }, modifier = Modifier.fillMaxWidth()) {
Text(stringResource(R.string.onb_skip), color = Palette.Fg3)
}
}
}
}
}
@Composable
private fun Title(text: String) {
Text(text, color = Palette.Fg, fontSize = 30.sp, lineHeight = 34.sp, fontWeight = FontWeight.ExtraBold, letterSpacing = (-0.5).sp)
}
@Composable
private fun Body(text: String) {
Text(text, color = Palette.Fg2, fontSize = 16.sp, lineHeight = 23.sp)
}
@Composable
private fun Step(number: Int, text: String) {
Row(verticalAlignment = Alignment.Top) {
Box(
Modifier
.size(26.dp)
.clip(CircleShape)
.background(Palette.AccentSoft),
contentAlignment = Alignment.Center,
) {
Text(number.toString(), color = Palette.Accent, fontSize = 13.sp, fontWeight = FontWeight.Bold)
}
Spacer(Modifier.width(12.dp))
Text(text, color = Palette.Fg, fontSize = 15.sp, lineHeight = 21.sp, modifier = Modifier.padding(top = 2.dp))
}
}
@Composable
private fun Dots(count: Int, current: Int) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
repeat(count) { i ->
Box(
Modifier
.height(4.dp)
.width(if (i == current) 22.dp else 10.dp)
.clip(CircleShape)
.background(if (i == current) Palette.Accent else Palette.Track),
)
}
}
}
@@ -3,9 +3,10 @@ package cc.skysparkle.sparkledns
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import kotlin.random.Random import kotlin.random.Random
// IPv4 addresses are kept as plain numbers, so parsing a query allocates only its payload
class UdpPacket( class UdpPacket(
val srcIp: ByteArray, val srcIp: Int,
val dstIp: ByteArray, val dstIp: Int,
val srcPort: Int, val srcPort: Int,
val dstPort: Int, val dstPort: Int,
val payload: ByteArray, val payload: ByteArray,
@@ -29,8 +30,8 @@ object Packet {
if (end <= ihl + 8) return null if (end <= ihl + 8) return null
return UdpPacket( return UdpPacket(
srcIp = buf.copyOfRange(12, 16), srcIp = i32(buf, 12),
dstIp = buf.copyOfRange(16, 20), dstIp = i32(buf, 16),
srcPort = u16(buf, ihl), srcPort = u16(buf, ihl),
dstPort = dstPort, dstPort = dstPort,
payload = buf.copyOfRange(ihl + 8, end), payload = buf.copyOfRange(ihl + 8, end),
@@ -47,8 +48,8 @@ object Packet {
p[6] = 0x40 // don't fragment p[6] = 0x40 // don't fragment
p[8] = 64 p[8] = 64
p[9] = 17 p[9] = 17
query.dstIp.copyInto(p, 12) put32(p, 12, query.dstIp)
query.srcIp.copyInto(p, 16) put32(p, 16, query.srcIp)
put16(p, 10, checksum(p, 0, 20, 0)) put16(p, 10, checksum(p, 0, 20, 0))
put16(p, 20, query.dstPort) put16(p, 20, query.dstPort)
@@ -123,7 +124,9 @@ object DnsMessage {
fun question(msg: ByteArray): Question? { fun question(msg: ByteArray): Question? {
if (msg.size < 12 || u16(msg, 4) < 1) return null if (msg.size < 12 || u16(msg, 4) < 1) return null
val name = StringBuilder() // Sized up front, so the builder does not grow: a valid name has at most 253 characters,
// and never more than the message has bytes after the header
val name = StringBuilder(minOf(msg.size - 12, 253))
var p = 12 var p = 12
while (true) { while (true) {
if (p >= msg.size) return null if (p >= msg.size) return null
@@ -180,6 +183,8 @@ internal fun put32(b: ByteArray, off: Int, value: Int) {
internal fun u32(b: ByteArray, off: Int): Long = internal fun u32(b: ByteArray, off: Int): Long =
((u16(b, off).toLong()) shl 16) or u16(b, off + 2).toLong() ((u16(b, off).toLong()) shl 16) or u16(b, off + 2).toLong()
internal fun i32(b: ByteArray, off: Int): Int = (u16(b, off) shl 16) or u16(b, off + 2)
// Returns the offset right after a (possibly compressed) DNS name // Returns the offset right after a (possibly compressed) DNS name
internal fun skipName(b: ByteArray, start: Int): Int? { internal fun skipName(b: ByteArray, start: Int): Int? {
var p = start var p = start
@@ -21,6 +21,16 @@ class Prefs(context: Context) {
get() = sp.getBoolean(KEY_HTTP3, false) get() = sp.getBoolean(KEY_HTTP3, false)
set(value) = sp.edit().putBoolean(KEY_HTTP3, value).apply() set(value) = sp.edit().putBoolean(KEY_HTTP3, value).apply()
// Access key for the Skysparkle server, created in the account at skysparkle.cc
var skysparkleKey: String
get() = sp.getString(KEY_SKYSPARKLE, null) ?: ""
set(value) = sp.edit().putString(KEY_SKYSPARKLE, value).apply()
// The first-launch guide was finished or skipped
var onboardingDone: Boolean
get() = sp.getBoolean(KEY_ONBOARDING, false)
set(value) = sp.edit().putBoolean(KEY_ONBOARDING, value).apply()
var excludedApps: Set<String> var excludedApps: Set<String>
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()
@@ -48,11 +58,13 @@ class Prefs(context: Context) {
get() = sp.getString(KEY_PRIVATE_DNS, null) ?: "" get() = sp.getString(KEY_PRIVATE_DNS, null) ?: ""
set(value) = sp.edit().putString(KEY_PRIVATE_DNS, value).apply() set(value) = sp.edit().putString(KEY_PRIVATE_DNS, value).apply()
fun resolve(): DohProvider = // Without a key the Skysparkle entry has an empty address, so it cannot connect
if (providerId == Providers.CUSTOM_ID) { fun resolve(): DohProvider = when (providerId) {
Providers.CUSTOM_ID ->
DohProvider(Providers.CUSTOM_ID, "Custom", customUrl.trim(), parseIps(customBootstrap), customHttp3) DohProvider(Providers.CUSTOM_ID, "Custom", customUrl.trim(), parseIps(customBootstrap), customHttp3)
} else { else -> Providers.byId(providerId).let {
Providers.byId(providerId) if (it.id == Providers.DEFAULT_ID) it.copy(url = SkysparkleKey.url(skysparkleKey)) else it
}
} }
private companion object { private companion object {
@@ -61,6 +73,8 @@ class Prefs(context: Context) {
const val KEY_BOOTSTRAP = "custom_bootstrap" const val KEY_BOOTSTRAP = "custom_bootstrap"
const val KEY_HTTP3 = "custom_http3" const val KEY_HTTP3 = "custom_http3"
const val KEY_EXCLUDED = "excluded_apps" const val KEY_EXCLUDED = "excluded_apps"
const val KEY_SKYSPARKLE = "skysparkle_key"
const val KEY_ONBOARDING = "onboarding_done"
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_INTERVAL = "update_interval"
@@ -18,12 +18,14 @@ object Providers {
// Servers ship with the app; new ones arrive with app updates // Servers ship with the app; new ones arrive with app updates
val builtIn = listOf( val builtIn = listOf(
// The address is personal: Prefs.resolve() adds the access key from skysparkle.cc
DohProvider( DohProvider(
"skysparkle", "SkySparkle", "https://blog.skysparkle.cc/dns-query", "skysparkle", "SkySparkle", SkysparkleKey.BASE_URL,
http3 = true, policy = "https://skysparkle.cc/privacy?lang=en", http3 = true, policy = "https://skysparkle.cc/privacy?lang=en",
), ),
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"),
http3 = true,
policy = "https://quad9.net/service/privacy/", policy = "https://quad9.net/service/privacy/",
donate = "https://quad9.net/donate/", donate = "https://quad9.net/donate/",
), ),
@@ -43,14 +45,35 @@ object Providers {
policy = "https://ffmuc.net/dns-privacy/", policy = "https://ffmuc.net/dns-privacy/",
donate = "https://spende.ffmuc.net/", donate = "https://spende.ffmuc.net/",
), ),
DohProvider(
"dnsforge", "dnsforge.de", "https://blank.dnsforge.de/dns-query",
listOf("78.47.71.194", "138.199.149.249"),
policy = "https://adminforge.de/datenschutz/",
donate = "https://adminforge.de/unterstuetzen/",
),
) )
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 = builtIn.firstOrNull { it.id == DEFAULT_ID } ?: builtIn.first()
fun byId(id: String): DohProvider = list.firstOrNull { it.id == id } ?: default fun byId(id: String): DohProvider = builtIn.firstOrNull { it.id == id } ?: default
}
// Personal access keys for the Skysparkle server. Each account at skysparkle.cc creates its own
// keys; the server answers only /dns/<key>, there is no shared public address.
object SkysparkleKey {
const val BASE_URL = "https://skysparkle.cc/dns/"
private val KEY = Regex("^[A-Za-z0-9_-]{24}$")
private val IN_URL = Regex("/dns/([A-Za-z0-9_-]{24})(?:[/?#].*)?$")
// Accepts the key itself or the whole address copied from the account page
fun parse(input: String): String? {
val text = input.trim()
if (KEY.matches(text)) return text
return IN_URL.find(text)?.groupValues?.get(1)
}
fun url(key: String): String = parse(key)?.let { BASE_URL + it } ?: ""
} }
fun parseIps(raw: String): List<String> = fun parseIps(raw: String): List<String> =
@@ -16,14 +16,6 @@ class QueryEntry(
val latencyMs: Int, val latencyMs: Int,
) )
data class QueryStats(
val total: Long,
val cached: Long,
val blocked: Long,
val failed: Long,
val avgLatencyMs: Int,
)
// In-memory only: nothing is written to disk or sent anywhere. StatsStore keeps hourly // In-memory only: nothing is written to disk or sent anywhere. StatsStore keeps hourly
// numbers without domains for the charts. // numbers without domains for the charts.
object QueryLog { object QueryLog {
@@ -31,14 +23,12 @@ object QueryLog {
private val entries = ArrayDeque<QueryEntry>() private val entries = ArrayDeque<QueryEntry>()
private var nextId = 0L private var nextId = 0L
private var total = 0L
private var cached = 0L
private var blocked = 0L
private var failed = 0L
private var latencySum = 0L
private var latencyCount = 0L
private val version = MutableStateFlow(0L) private val version = MutableStateFlow(0L)
// The last snapshot, handed out again while the log has not changed
private var lastSnapshot: List<QueryEntry> = emptyList()
private var snapshotVersion = 0L
// Fires right away, then at most once a second while queries keep coming: a busy log refreshes // 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 // 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 { fun changes(): Flow<Long> = version.transform {
@@ -48,42 +38,32 @@ object QueryLog {
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
val time = System.currentTimeMillis()
synchronized(this) { synchronized(this) {
if (entries.size >= MAX_ENTRIES) entries.removeFirst() if (entries.size >= MAX_ENTRIES) entries.removeFirst()
entries.addLast( entries.addLast(QueryEntry(nextId++, time, question.name.ifEmpty { "." }, question.type, status, latencyMs))
QueryEntry(nextId++, System.currentTimeMillis(), question.name.ifEmpty { "." }, question.type, status, latencyMs)
)
total++
when (status) {
QueryStatus.OK -> { latencySum += latencyMs; latencyCount++ }
QueryStatus.CACHED -> cached++
QueryStatus.BLOCKED -> blocked++
QueryStatus.FAILED -> failed++
}
version.value++ version.value++
} }
// Hourly numbers for the charts; outside the lock above, as it takes a lock of its own // 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)) StatsStore.record(status, latencyMs, Companies.of(question.name), time)
} }
// 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,
// and on older devices that method does not exist at all // and on older devices that method does not exist at all. While the log does not change the
// same list comes back, so a screen refreshed with it has nothing to update.
@Synchronized @Synchronized
fun snapshot(): List<QueryEntry> = List(entries.size) { entries[entries.size - 1 - it] } fun snapshot(): List<QueryEntry> {
val current = version.value
@Synchronized if (snapshotVersion != current) {
fun stats() = QueryStats( lastSnapshot = List(entries.size) { entries[entries.size - 1 - it] }
total = total, snapshotVersion = current
cached = cached, }
blocked = blocked, return lastSnapshot
failed = failed, }
avgLatencyMs = if (latencyCount == 0L) 0 else (latencySum / latencyCount).toInt(),
)
@Synchronized @Synchronized
fun clear() { fun clear() {
entries.clear() entries.clear()
total = 0; cached = 0; blocked = 0; failed = 0; latencySum = 0; latencyCount = 0
version.value++ version.value++
} }
} }
@@ -1,13 +1,20 @@
package cc.skysparkle.sparkledns package cc.skysparkle.sparkledns
import android.content.ClipData
import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.os.PersistableBundle
import android.widget.Toast
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
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.RowScope
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.height
@@ -22,11 +29,14 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -37,7 +47,9 @@ 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.drawBehind
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
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
@@ -51,7 +63,6 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
@@ -66,12 +77,14 @@ fun SettingsScreen(
val context = LocalContext.current val context = LocalContext.current
val prefs = remember { Prefs(context) } val prefs = remember { Prefs(context) }
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val side = sidePadding(windowWidth())
val active by DohVpnService.active.collectAsStateWithLifecycle() val active by DohVpnService.active.collectAsStateWithLifecycle()
var selected by remember { mutableStateOf(prefs.providerId) } var selected by remember { mutableStateOf(prefs.providerId) }
var customUrl by remember { mutableStateOf(prefs.customUrl) } var customUrl by remember { mutableStateOf(prefs.customUrl) }
var customBootstrap by remember { mutableStateOf(prefs.customBootstrap) } var customBootstrap by remember { mutableStateOf(prefs.customBootstrap) }
var customHttp3 by remember { mutableStateOf(prefs.customHttp3) } var customHttp3 by remember { mutableStateOf(prefs.customHttp3) }
var keyInput by remember { mutableStateOf(prefs.skysparkleKey) }
var testResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) } 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 shownResult by rememberSaveable(stateSaver = TestResultSaver) { mutableStateOf<TestResult?>(null) } // kept while the card animates out
var testing by remember { mutableStateOf(false) } var testing by remember { mutableStateOf(false) }
@@ -79,19 +92,12 @@ fun SettingsScreen(
val isCustom = selected == Providers.CUSTOM_ID val isCustom = selected == Providers.CUSTOM_ID
val customValid = remember(customUrl) { customUrl.trim().toHttpUrlOrNull()?.isHttps == true } val customValid = remember(customUrl) { customUrl.trim().toHttpUrlOrNull()?.isHttps == true }
val canConnect = !isCustom || customValid val selectedProvider = remember(selected, customUrl, customBootstrap, customHttp3, keyInput) { prefs.resolve() }
val selectedProvider = remember(selected, customUrl, customBootstrap, customHttp3) { prefs.resolve() } val canConnect = selectedProvider.url.toHttpUrlOrNull()?.isHttps == true
// Picking a server never touches a live connection; switching is an explicit action // Picking a server never touches a live connection; switching is an explicit action
val pendingSwitch = active?.let { it != selectedProvider && canConnect } == true val pendingSwitch = active?.let { it != selectedProvider && canConnect } == true
var busy by remember { mutableStateOf(false) } var busy by rememberVpnBusy(active)
LaunchedEffect(active) { busy = false }
LaunchedEffect(busy) {
if (busy) {
delay(BUSY_TIMEOUT_MS)
busy = false
}
}
fun select(id: String) { fun select(id: String) {
selected = id selected = id
@@ -99,6 +105,13 @@ fun SettingsScreen(
testResult = null testResult = null
} }
// Signed in from the key field: the key is already saved, show it and select the server
SignInResult { key ->
keyInput = key
selected = Providers.DEFAULT_ID
testResult = null
}
fun runTest() { fun runTest() {
val provider = prefs.resolve() val provider = prefs.resolve()
testing = true testing = true
@@ -114,14 +127,14 @@ fun SettingsScreen(
Column( Column(
modifier = modifier modifier = modifier
.verticalScroll(rememberScrollState()) .verticalScroll(rememberScrollState())
.padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = bottomPadding), .padding(start = side, end = side, top = 16.dp, bottom = bottomPadding),
verticalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
) { ) {
ScreenTitle(stringResource(R.string.tab_settings), Modifier.heightIn(min = 44.dp)) ScreenTitle(stringResource(R.string.tab_settings), Modifier.heightIn(min = 44.dp))
SectionLabel(stringResource(R.string.servers), Modifier.padding(top = 8.dp)) SectionLabel(stringResource(R.string.servers), Modifier.padding(top = 8.dp))
Column(Modifier.fillMaxWidth().appCard()) { Column(Modifier.fillMaxWidth().appCard()) {
Providers.list.forEachIndexed { index, provider -> Providers.builtIn.forEachIndexed { index, provider ->
if (index > 0) ListDivider() if (index > 0) ListDivider()
ServerRow( ServerRow(
title = provider.name, title = provider.name,
@@ -131,6 +144,11 @@ fun SettingsScreen(
onDonate = provider.donate?.let { url -> { openUrl(context, url) } }, onDonate = provider.donate?.let { url -> { openUrl(context, url) } },
onClick = { select(provider.id) }, onClick = { select(provider.id) },
) )
if (provider.id == Providers.DEFAULT_ID) {
AnimatedVisibility(visible = selected == Providers.DEFAULT_ID, enter = Motion.expandIn, exit = Motion.collapseOut) {
KeyField(key = keyInput)
}
}
} }
ListDivider() ListDivider()
ServerRow( ServerRow(
@@ -202,9 +220,8 @@ fun SettingsScreen(
Text(stringResource(if (testing) R.string.testing else R.string.test), maxLines = 1) 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 // The button keeps its label while it animates out
val lastSwitch = remember { arrayOf("") } val switchName = rememberLast(if (pendingSwitch) selectedProvider.displayName(context) else null).orEmpty()
if (pendingSwitch) lastSwitch[0] = selectedProvider.displayName(context)
AnimatedVisibility(visible = pendingSwitch, modifier = Modifier.weight(1f)) { AnimatedVisibility(visible = pendingSwitch, modifier = Modifier.weight(1f)) {
Button( Button(
onClick = { onClick = {
@@ -222,7 +239,7 @@ fun SettingsScreen(
Icon(painterResource(R.drawable.ic_swap), contentDescription = null, modifier = Modifier.size(18.dp)) Icon(painterResource(R.drawable.ic_swap), contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp)) Spacer(Modifier.width(8.dp))
Text( Text(
stringResource(R.string.switch_to, lastSwitch[0]), stringResource(R.string.switch_to, switchName),
maxLines = 1, maxLines = 1,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
@@ -261,6 +278,95 @@ fun SettingsScreen(
} }
} }
// Access key for the Skysparkle server. It comes only from signing in; the address can be
// copied to use the same key in a browser or on another device
@Composable
internal fun KeyField(key: String, modifier: Modifier = Modifier) {
val context = LocalContext.current
val hasKey = SkysparkleKey.parse(key) != null
Column(
modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
// The line keeps its text while it animates out
val shownKey = rememberLast(key.takeIf { hasKey }).orEmpty()
AnimatedVisibility(visible = hasKey, enter = Motion.expandIn, exit = Motion.collapseOut) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
stringResource(R.string.key_status, shownKey.take(4)),
color = Palette.Fg2,
fontSize = 13.sp,
modifier = Modifier.weight(1f),
)
TextButton(onClick = { copyKeyAddress(context, shownKey) }) {
Text(stringResource(R.string.key_copy))
}
}
}
SignInButton(again = hasKey, modifier = Modifier.fillMaxWidth())
}
}
// Starts the browser sign-in; shows progress while the app waits for it. Filled while there is
// no key yet; once there is one, signing in again is a rare action and must not compete with
// the filled "Switch to" button below the server list
@Composable
internal fun SignInButton(again: Boolean, modifier: Modifier = Modifier, shape: Shape = RoundedCornerShape(14.dp)) {
val context = LocalContext.current
val signIn by SkysparkleSignIn.state.collectAsStateWithLifecycle()
val working = signIn == SkysparkleSignIn.State.Waiting || signIn == SkysparkleSignIn.State.Exchanging
val onClick = { SkysparkleSignIn.start(context) }
val content: @Composable RowScope.() -> Unit = {
if (working) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp, color = LocalContentColor.current)
Spacer(Modifier.width(10.dp))
}
Text(
stringResource(if (working) R.string.sign_in_working else if (again) R.string.sign_in_again else R.string.sign_in),
fontWeight = if (again) null else FontWeight.Bold,
)
}
if (again) {
OutlinedButton(onClick = onClick, enabled = !working, shape = shape, modifier = modifier, content = content)
} else {
Button(onClick = onClick, enabled = !working, shape = shape, modifier = modifier, content = content)
}
}
// The key is personal, so the clipboard is told to hide it from previews (Android 13+),
// and Android 13+ confirms the copy itself
private fun copyKeyAddress(context: Context, key: String) {
val clip = ClipData.newPlainText("SkySparkle", SkysparkleKey.url(key))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
clip.description.extras = PersistableBundle().apply { putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true) }
}
context.getSystemService(ClipboardManager::class.java).setPrimaryClip(clip)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
Toast.makeText(context, R.string.key_copied, Toast.LENGTH_SHORT).show()
}
}
// Result of the Skysparkle sign-in, shown once on the screen that started it
@Composable
internal fun SignInResult(onKey: (String) -> Unit) {
val context = LocalContext.current
val signIn by SkysparkleSignIn.state.collectAsStateWithLifecycle()
LaunchedEffect(signIn) {
when (val s = signIn) {
is SkysparkleSignIn.State.Done -> {
onKey(s.key)
Toast.makeText(context, R.string.sign_in_done, Toast.LENGTH_SHORT).show()
SkysparkleSignIn.consume()
}
is SkysparkleSignIn.State.Failed -> {
Toast.makeText(context, s.message, Toast.LENGTH_LONG).show()
SkysparkleSignIn.consume()
}
else -> Unit
}
}
}
@Composable @Composable
private fun ServerRow( private fun ServerRow(
title: String, title: String,
@@ -278,7 +384,8 @@ private fun ServerRow(
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.background(highlight) // Read when drawing, so the fade does not recompose the row every frame
.drawBehind { drawRect(highlight) }
.selectable(selected = selected, onClick = onClick, role = Role.RadioButton) .selectable(selected = selected, onClick = onClick, role = Role.RadioButton)
.heightIn(min = 60.dp) .heightIn(min = 60.dp)
.padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp), .padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
@@ -295,26 +402,8 @@ private fun ServerRow(
) )
Text(subtitle, color = Palette.Fg3, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) Text(subtitle, color = Palette.Fg3, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
} }
if (onDonate != null) { if (onDonate != null) LinkButton(R.drawable.ic_donate, stringResource(R.string.donate), onDonate)
IconButton(onClick = onDonate, modifier = Modifier.size(40.dp)) { if (onPolicy != null) LinkButton(R.drawable.ic_policy, stringResource(R.string.about_privacy_policy), onPolicy)
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)) Spacer(Modifier.width(4.dp))
if (selected) { if (selected) {
Icon( Icon(
@@ -330,6 +419,14 @@ private fun ServerRow(
} }
} }
// Small button next to a server that opens one of its pages
@Composable
private fun LinkButton(@DrawableRes icon: Int, description: String, onClick: () -> Unit) {
IconButton(onClick = onClick, modifier = Modifier.size(40.dp)) {
Icon(painterResource(icon), contentDescription = description, tint = Palette.Fg3, modifier = Modifier.size(18.dp))
}
}
@Composable @Composable
private fun NavRow(@DrawableRes icon: Int, title: String, subtitle: String, onClick: () -> Unit) { private fun NavRow(@DrawableRes icon: Int, title: String, subtitle: String, onClick: () -> Unit) {
Row( Row(
@@ -0,0 +1,179 @@
package cc.skysparkle.sparkledns
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.util.Base64
import android.util.Log
import androidx.annotation.StringRes
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.security.MessageDigest
import java.security.SecureRandom
// Sign-in with a Skysparkle account: the app gets its access key without copying it by hand.
//
// OAuth for native apps (RFC 8252) with PKCE (RFC 7636): the account page opens in the browser,
// so the password never passes through the app. After "Connect" the site opens
// https://skysparkle.cc/app/callback?code=…&state=… through an intent:// link that names this
// package, so Android delivers it only to this app, and the app trades the one-time code for a
// new key. Only this app knows the verifier, so even a code that leaked somewhere is useless.
object SkysparkleSignIn {
private const val CONNECT_URL = "https://skysparkle.cc/app/connect"
private const val TOKEN_URL = "https://skysparkle.cc/api/app/token"
private const val CALLBACK_HOST = "skysparkle.cc"
private const val CALLBACK_PATH = "/app/callback"
// The browser step must be finished within this time (the site keeps codes for 5 minutes)
private const val PENDING_TTL_MS = 30 * 60_000L
sealed interface State {
data object Idle : State
data object Waiting : State
data object Exchanging : State
data class Done(val key: String) : State
data class Failed(@StringRes val message: Int) : State
}
private val _state = MutableStateFlow<State>(State.Idle)
val state: StateFlow<State> = _state.asStateFlow()
// Not tied to a screen: rotating or leaving the screen must not cancel the exchange
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
fun isCallback(uri: Uri?): Boolean =
uri?.scheme == "https" && uri.host == CALLBACK_HOST && uri.path == CALLBACK_PATH
// Opens the account page. Verifier and state are kept on disk: the system may stop the app
// while the browser is in front.
fun start(context: Context) {
val verifier = randomToken(32)
val state = randomToken(24)
pending(context).edit()
.putString(P_VERIFIER, verifier)
.putString(P_STATE, state)
.putLong(P_AT, System.currentTimeMillis())
.apply()
val url = Uri.parse(CONNECT_URL).buildUpon()
.appendQueryParameter("challenge", challengeOf(verifier))
.appendQueryParameter("state", state)
.appendQueryParameter("device", Build.MODEL.take(40))
.build()
_state.value = State.Waiting
try {
context.startActivity(Intent(Intent.ACTION_VIEW, url).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
} catch (e: RuntimeException) {
Log.w("SparkleDNS", "Cannot open the sign-in page", e)
_state.value = State.Failed(R.string.no_browser)
}
}
// The browser came back to the app: check state, then trade the code for a key.
fun handle(context: Context, uri: Uri) {
val app = context.applicationContext
val p = pending(app)
val state = p.getString(P_STATE, null)
val verifier = p.getString(P_VERIFIER, null)
val fresh = System.currentTimeMillis() - p.getLong(P_AT, 0) < PENDING_TTL_MS
if (state == null || verifier == null || !fresh || uri.getQueryParameter("state") != state) {
// A link that this app did not start, an old one, or a second tap on "Open SparkleDNS"
// while the first code is still being exchanged: ignore it, keep any progress shown
cancelWaiting()
return
}
p.edit().clear().apply()
if (uri.getQueryParameter("error") != null) {
_state.value = State.Idle // "Cancel" on the site
return
}
val code = uri.getQueryParameter("code")
if (code.isNullOrEmpty()) {
_state.value = State.Failed(R.string.sign_in_failed)
return
}
_state.value = State.Exchanging
scope.launch {
_state.value = when (val r = exchange(code, verifier)) {
is Result.Key -> {
Prefs(app).apply {
skysparkleKey = r.key
providerId = Providers.DEFAULT_ID
}
State.Done(r.key)
}
is Result.Error -> State.Failed(r.message)
}
}
}
// The screen showed the result; the next sign-in starts clean
fun consume() {
val s = _state.value
if (s is State.Done || s is State.Failed) _state.value = State.Idle
}
// Returning from the browser without finishing (back button) should not leave a spinner
fun cancelWaiting() {
if (_state.value == State.Waiting) _state.value = State.Idle
}
private sealed interface Result {
class Key(val key: String) : Result
class Error(@StringRes val message: Int) : Result
}
private fun exchange(code: String, verifier: String): Result {
val body = JSONObject().put("code", code).put("verifier", verifier).toString()
.toRequestBody("application/json".toMediaType())
val request = Request.Builder().url(TOKEN_URL).post(body).build()
return try {
Http.client.newCall(request).execute().use { response ->
val json = runCatching { JSONObject(response.body.string()) }.getOrNull()
val key = json?.optString("key").orEmpty()
when {
response.isSuccessful && SkysparkleKey.parse(key) != null -> Result.Key(key)
json?.optString("error") == "verify_email_first" -> Result.Error(R.string.sign_in_verify)
json?.optString("error") == "invalid_grant" -> Result.Error(R.string.sign_in_expired)
json?.optString("error") == "account_suspended" -> Result.Error(R.string.sign_in_suspended)
else -> Result.Error(R.string.sign_in_failed)
}
}
} catch (e: IOException) {
Log.w("SparkleDNS", "Key exchange failed", e)
Result.Error(R.string.sign_in_network)
} catch (e: RuntimeException) {
// Runs in a scope without an exception handler: anything that escaped would crash the app
Log.w("SparkleDNS", "Key exchange failed", e)
Result.Error(R.string.sign_in_failed)
}
}
private fun pending(context: Context) =
context.applicationContext.getSharedPreferences("sign_in", Context.MODE_PRIVATE)
private val random = SecureRandom()
private fun randomToken(bytes: Int): String =
b64url(ByteArray(bytes).also(random::nextBytes))
private fun challengeOf(verifier: String): String =
b64url(MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray(Charsets.US_ASCII)))
private fun b64url(data: ByteArray): String =
Base64.encodeToString(data, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)
private const val P_VERIFIER = "verifier"
private const val P_STATE = "state"
private const val P_AT = "at"
}
@@ -4,12 +4,11 @@ import android.content.Context
import android.util.Log import android.util.Log
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import java.io.BufferedInputStream import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import java.io.DataInputStream import java.io.DataInputStream
import java.io.DataOutputStream import java.io.DataOutputStream
import java.io.File import java.io.File
import java.io.FileInputStream
import java.util.concurrent.Executors import java.util.concurrent.Executors
class StatsSummary( class StatsSummary(
@@ -26,47 +25,123 @@ class HourPoint(val total: Long, val blocked: Long)
// Hourly counters of the last 7 days for the charts. Only numbers are kept, never domains, // Hourly counters of the last 7 days for the charts. Only numbers are kept, never domains,
// and they never leave the device. // and they never leave the device.
object StatsStore { object StatsStore {
private const val HOURS = 24 * 7
private const val HOUR_MS = 3_600_000L private const val HOUR_MS = 3_600_000L
private const val FORMAT = 1
private const val FILE = "stats.bin" private const val FILE = "stats.bin"
private const val SAVE_INTERVAL_MS = 60_000L private const val SAVE_INTERVAL_MS = 60_000L
// Per hour: total, blocked, cached, latency sum and count, then one counter per company private val counters = HourlyCounters()
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 private var file: File? = null
// Bumped when the numbers change without a new query: loaded from disk or cleared // Bumped when the numbers change without a new query: loaded from disk
private val _version = MutableStateFlow(0) private val _version = MutableStateFlow(0)
val version: StateFlow<Int> = _version val version: StateFlow<Int> = _version
private var lastSave = 0L private var lastSave = 0L
private var dirty = false private var dirty = false
// Counts every change, so summary() can hand out its last result while nothing changed
private var changes = 0L
private var lastSummary: StatsSummary? = null
private var summaryChanges = 0L
private var summaryHours = 0
private var summaryHour = 0L
// Saves happen off the VPN threads, one at a time // Saves happen off the VPN threads, one at a time
private val writer = Executors.newSingleThreadExecutor { Thread(it, "stats-writer").apply { isDaemon = true } } private val writer = Executors.newSingleThreadExecutor { Thread(it, "stats-writer").apply { isDaemon = true } }
// The file is read outside the lock, so neither the DNS threads nor the screens wait for
// storage. Queries counted before it was read are added to the saved numbers.
fun init(context: Context) { fun init(context: Context) {
val target = File(context.filesDir, FILE) val target = File(context.filesDir, FILE)
val saved = read(target)
synchronized(this) { synchronized(this) {
file = target file = target
load(target) if (saved != null) counters.merge(saved)
changes++
} }
_version.value++ _version.value++
} }
fun record(status: QueryStatus, latencyMs: Int, company: Company?, now: Long = System.currentTimeMillis()) { fun record(status: QueryStatus, latencyMs: Int, company: Company?, now: Long = System.currentTimeMillis()) {
val snapshot = synchronized(this) { val save = synchronized(this) {
val row = row(now / HOUR_MS) counters.record(status, latencyMs, company, now / HOUR_MS)
changes++
dirty = true
if (file != null && now - lastSave >= SAVE_INTERVAL_MS) {
lastSave = now
true
} else {
false
}
}
// The writer thread encodes the numbers itself, so this DNS thread only hands the job over
if (save) writer.execute(::save)
}
// Totals of the last [hours] hours, the current one included. While nothing changed the same
// object comes back, so a screen refreshed with it has nothing to recompose.
fun summary(hours: Int, now: Long = System.currentTimeMillis()): StatsSummary = synchronized(this) {
val current = now / HOUR_MS
lastSummary?.takeIf { summaryChanges == changes && summaryHours == hours && summaryHour == current }
?: counters.summary(hours, current).also {
lastSummary = it
summaryChanges = changes
summaryHours = hours
summaryHour = current
}
}
// One point per hour, oldest first, ending with the current hour
fun hourly(hours: Int, now: Long = System.currentTimeMillis()): List<HourPoint> =
synchronized(this) { counters.hourly(hours, now / HOUR_MS) }
// Saves what is not on disk yet; called when the VPN stops
fun flush() {
val save = synchronized(this) {
if (file != null && dirty) {
lastSave = System.currentTimeMillis()
true
} else {
false
}
}
if (save) writer.execute(::save)
}
// Runs on the writer thread
private fun save() {
val (target, bytes) = synchronized(this) {
val current = file ?: return
dirty = false
current to counters.encode()
}
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)
}
}
private fun read(source: File): HourlyCounters? {
if (!source.exists()) return null
return try {
HourlyCounters.decode(source.readBytes())
} catch (e: Exception) {
Log.w("SparkleDNS", "Cannot read statistics", e)
null
}
}
}
// The numbers behind StatsStore: a ring of hourly rows, each remembering which hour (since the
// epoch) it holds. Plain data without locks or Android; StatsStore takes care of both.
internal class HourlyCounters {
val hourIds = LongArray(HOURS) { -1L }
val rows = Array(HOURS) { LongArray(FIELDS) }
fun record(status: QueryStatus, latencyMs: Int, company: Company?, hour: Long) {
val row = row(hour)
row[TOTAL]++ row[TOTAL]++
when (status) { when (status) {
QueryStatus.BLOCKED -> row[BLOCKED]++ QueryStatus.BLOCKED -> row[BLOCKED]++
@@ -78,30 +153,19 @@ object StatsStore {
QueryStatus.FAILED -> Unit QueryStatus.FAILED -> Unit
} }
if (company != null) row[FIRST_COMPANY + company.ordinal]++ 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 // Totals of the last [hours] hours up to [currentHour]
fun summary(hours: Int, now: Long = System.currentTimeMillis()): StatsSummary = synchronized(this) { fun summary(hours: Int, currentHour: Long): StatsSummary {
val current = now / HOUR_MS
val sums = LongArray(FIELDS) val sums = LongArray(FIELDS)
for (back in 0 until hours.coerceIn(1, HOURS)) { for (back in 0 until hours.coerceIn(1, HOURS)) {
val id = current - back val id = currentHour - back
val index = slot(id) val index = slot(id)
if (hourIds[index] != id) continue if (hourIds[index] != id) continue
val row = counters[index] val row = rows[index]
for (field in 0 until FIELDS) sums[field] += row[field] for (field in 0 until FIELDS) sums[field] += row[field]
} }
StatsSummary( return StatsSummary(
total = sums[TOTAL], total = sums[TOTAL],
blocked = sums[BLOCKED], blocked = sums[BLOCKED],
cached = sums[CACHED], cached = sums[CACHED],
@@ -110,41 +174,43 @@ object StatsStore {
) )
} }
// One point per hour, oldest first, ending with the current hour // One point per hour, oldest first, ending with [currentHour]
fun hourly(hours: Int, now: Long = System.currentTimeMillis()): List<HourPoint> = synchronized(this) { fun hourly(hours: Int, currentHour: Long): List<HourPoint> {
val count = hours.coerceIn(1, HOURS) val count = hours.coerceIn(1, HOURS)
val current = now / HOUR_MS return List(count) { position ->
List(count) { position -> val id = currentHour - (count - 1 - position)
val id = current - (count - 1 - position)
val index = slot(id) val index = slot(id)
if (hourIds[index] == id) HourPoint(counters[index][TOTAL], counters[index][BLOCKED]) else HourPoint(0, 0) if (hourIds[index] == id) HourPoint(rows[index][TOTAL], rows[index][BLOCKED]) else HourPoint(0, 0)
} }
} }
fun clear() { // Saved hours are added to the ones counted since the start; a slot keeps the newer hour
val snapshot = synchronized(this) { fun merge(saved: HourlyCounters) {
hourIds.fill(-1L) for (index in 0 until HOURS) {
counters.forEach { it.fill(0L) } val id = saved.hourIds[index]
dirty = false when {
lastSave = System.currentTimeMillis() id < 0 || id < hourIds[index] -> Unit
if (file != null) encode() else null id == hourIds[index] -> for (field in 0 until FIELDS) rows[index][field] += saved.rows[index][field]
else -> {
hourIds[index] = id
saved.rows[index].copyInto(rows[index])
}
}
} }
snapshot?.let(::save)
_version.value++
} }
// Saves what is not on disk yet; called when the VPN stops fun encode(): ByteArray {
fun flush() { val bytes = ByteArrayOutputStream(12 + HOURS * (FIELDS + 1) * 8)
val snapshot = synchronized(this) { DataOutputStream(bytes).use { out ->
if (file != null && dirty) { out.writeInt(FORMAT)
dirty = false out.writeInt(FIELDS)
lastSave = System.currentTimeMillis() out.writeInt(HOURS)
encode() for (index in 0 until HOURS) {
} else { out.writeLong(hourIds[index])
null rows[index].forEach { out.writeLong(it) }
} }
} }
snapshot?.let(::save) return bytes.toByteArray()
} }
private fun slot(id: Long): Int = (((id % HOURS) + HOURS) % HOURS).toInt() private fun slot(id: Long): Int = (((id % HOURS) + HOURS) % HOURS).toInt()
@@ -153,58 +219,41 @@ object StatsStore {
val index = slot(id) val index = slot(id)
if (hourIds[index] != id) { if (hourIds[index] != id) {
hourIds[index] = id hourIds[index] = id
counters[index].fill(0L) rows[index].fill(0L)
} }
return counters[index] return rows[index]
} }
private fun encode(): ByteArray { companion object {
val bytes = ByteArrayOutputStream() const val HOURS = 24 * 7
DataOutputStream(bytes).use { out -> private const val FORMAT = 1
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) { // Per hour: total, blocked, cached, latency sum and count, then one counter per company
val target = file ?: return private const val TOTAL = 0
writer.execute { private const val BLOCKED = 1
try { private const val CACHED = 2
val tmp = File(target.parentFile, "$FILE.tmp") private const val LATENCY_SUM = 3
tmp.writeBytes(bytes) private const val LATENCY_COUNT = 4
if (!tmp.renameTo(target)) tmp.delete() const val FIRST_COMPANY = 5
} catch (e: Exception) { val FIELDS = FIRST_COMPANY + Company.entries.size
Log.w("SparkleDNS", "Cannot save statistics", e)
}
}
}
// Files from a version with fewer companies load fine: the new counters start at zero // Files from a version with fewer companies load fine: the new counters start at zero.
private fun load(source: File) { // Null for a file of another format.
if (!source.exists()) return fun decode(bytes: ByteArray): HourlyCounters? {
try { DataInputStream(ByteArrayInputStream(bytes)).use { input ->
DataInputStream(BufferedInputStream(FileInputStream(source))).use { input -> if (input.readInt() != FORMAT) return null
if (input.readInt() != FORMAT) return
val fields = input.readInt() val fields = input.readInt()
if (input.readInt() != HOURS || fields < FIRST_COMPANY) return if (input.readInt() != HOURS || fields < FIRST_COMPANY) return null
val result = HourlyCounters()
for (index in 0 until HOURS) { for (index in 0 until HOURS) {
hourIds[index] = input.readLong() result.hourIds[index] = input.readLong()
for (field in 0 until fields) { for (field in 0 until fields) {
val value = input.readLong() val value = input.readLong()
if (field < FIELDS) counters[index][field] = value if (field < FIELDS) result.rows[index][field] = value
}
}
return result
} }
} }
} }
} catch (e: Exception) {
Log.w("SparkleDNS", "Cannot read statistics", e)
hourIds.fill(-1L)
counters.forEach { it.fill(0L) }
}
}
} }
@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.BoxScope
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize 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.height
@@ -14,6 +15,7 @@ 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.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
@@ -29,11 +31,13 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalConfiguration
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.TextStyle import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
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.compose.ui.unit.sp
@@ -44,7 +48,6 @@ object Palette {
val CardHigh = Color(0xFF1E2026) val CardHigh = Color(0xFF1E2026)
val Line = Color(0xFF24262C) val Line = Color(0xFF24262C)
val Track = Color(0xFF3A3C44) val Track = Color(0xFF3A3C44)
val Muted = Color(0xFF5B5F6B)
val Fg = Color(0xFFF2F3F5) val Fg = Color(0xFFF2F3F5)
val Fg2 = Color(0xFF9A9DA6) val Fg2 = Color(0xFF9A9DA6)
val Fg3 = Color(0xFF7E828C) val Fg3 = Color(0xFF7E828C)
@@ -86,6 +89,24 @@ internal val AppColors = darkColorScheme(
val CardShape = RoundedCornerShape(20.dp) val CardShape = RoundedCornerShape(20.dp)
// On tablets content stays this wide and sits in the middle, so rows do not stretch across the screen
val MaxContentWidth = 560.dp
// From this width Home and Activity show two columns side by side
val WideLayoutWidth = 840.dp
val MaxWideContentWidth = 1040.dp
// Size of the app window in dp
@Composable
fun windowWidth(): Dp = LocalConfiguration.current.screenWidthDp.dp
@Composable
fun windowHeight(): Dp = LocalConfiguration.current.screenHeightDp.dp
// Side padding that keeps content at most [max] wide and at least [min] away from the edges
fun sidePadding(available: Dp, max: Dp = MaxContentWidth, min: Dp = 20.dp): Dp =
maxOf(min, (available - max) / 2)
fun Modifier.appCard(): Modifier = clip(CardShape).background(Palette.Card) fun Modifier.appCard(): Modifier = clip(CardShape).background(Palette.Card)
@Composable @Composable
@@ -105,7 +126,7 @@ fun AppSwitch(
} }
@Composable @Composable
fun appSwitchColors() = SwitchDefaults.colors( private fun appSwitchColors() = SwitchDefaults.colors(
checkedThumbColor = Color.White, checkedThumbColor = Color.White,
checkedTrackColor = Palette.Accent, checkedTrackColor = Palette.Accent,
checkedBorderColor = Palette.Accent, checkedBorderColor = Palette.Accent,
@@ -174,7 +195,13 @@ fun PageHeader(
// A page with a back header around content that is not built for one // A page with a back header around content that is not built for one
@Composable @Composable
fun SubPage(title: String, onBack: () -> Unit, modifier: Modifier = Modifier, content: @Composable BoxScope.() -> Unit) { fun SubPage(title: String, onBack: () -> Unit, modifier: Modifier = Modifier, content: @Composable BoxScope.() -> Unit) {
Column(modifier) { Box(modifier, contentAlignment = Alignment.TopCenter) {
Column(
Modifier
.fillMaxHeight()
.widthIn(max = MaxContentWidth + 32.dp)
.fillMaxWidth()
) {
PageHeader(title, onBack) PageHeader(title, onBack)
Box( Box(
Modifier Modifier
@@ -185,6 +212,9 @@ fun SubPage(title: String, onBack: () -> Unit, modifier: Modifier = Modifier, co
) )
} }
} }
}
private val SearchTextStyle = TextStyle(color = Palette.Fg, fontSize = 14.sp)
@Composable @Composable
fun SearchField( fun SearchField(
@@ -219,7 +249,7 @@ fun SearchField(
onValueChange = onValueChange, onValueChange = onValueChange,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
singleLine = true, singleLine = true,
textStyle = TextStyle(color = Palette.Fg, fontSize = 14.sp), textStyle = SearchTextStyle,
cursorBrush = SolidColor(Palette.Accent), cursorBrush = SolidColor(Palette.Accent),
) )
} }
@@ -1,13 +1,11 @@
package cc.skysparkle.sparkledns package cc.skysparkle.sparkledns
import android.content.Context
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import androidx.compose.animation.AnimatedContent import androidx.annotation.StringRes
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box 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
@@ -29,21 +27,21 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.rememberUpdatedState
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.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
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.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign 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.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.repeatOnLifecycle
@@ -53,6 +51,28 @@ import java.util.Locale
val CachedColor = Color(0xFF7FD1AE) val CachedColor = Color(0xFF7FD1AE)
val WarningColor = Color(0xFFFFB86B) val WarningColor = Color(0xFFFFB86B)
// The 512 px logo, decoded once while the screens are in use. Home shows it each time the tab
// opens, and decoding it there would cost the main thread a frame.
object AppLogo {
@Volatile
private var bitmap: ImageBitmap? = null
// Started with the activity, so the first frame of Home usually finds the logo decoded
fun preload(context: Context) {
if (bitmap != null) return
val appContext = context.applicationContext
Thread({ runCatching { get(appContext) } }, "logo-load").start()
}
@Synchronized
fun get(context: Context): ImageBitmap =
bitmap ?: ImageBitmap.imageResource(context.resources, R.drawable.app_logo).also { bitmap = it }
fun clear() {
bitmap = null
}
}
// Icon on a soft circle of its own color // Icon on a soft circle of its own color
@Composable @Composable
fun IconBadge(@DrawableRes icon: Int, tint: Color = MaterialTheme.colorScheme.primary, size: Dp = 40.dp) { fun IconBadge(@DrawableRes icon: Int, tint: Color = MaterialTheme.colorScheme.primary, size: Dp = 40.dp) {
@@ -67,52 +87,6 @@ fun IconBadge(@DrawableRes icon: Int, tint: Color = MaterialTheme.colorScheme.pr
} }
} }
@Composable
fun SectionHeader(
title: String,
@DrawableRes icon: Int? = null,
modifier: Modifier = Modifier,
action: (@Composable () -> Unit)? = null,
) {
Row(
modifier = modifier
.fillMaxWidth()
.heightIn(min = 40.dp)
.padding(top = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (icon != null) {
Icon(
painterResource(icon),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp),
)
Spacer(Modifier.width(8.dp))
}
Text(
title,
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
action?.invoke()
}
}
@Composable
fun Pill(text: String, color: Color) {
Text(
text,
style = MaterialTheme.typography.labelMedium,
color = color,
modifier = Modifier
.clip(RoundedCornerShape(50))
.background(color.copy(alpha = 0.14f))
.padding(horizontal = 10.dp, vertical = 3.dp),
)
}
@Composable @Composable
fun HintCard( fun HintCard(
text: String, text: String,
@@ -161,39 +135,14 @@ fun HintCard(
} }
} }
@Composable private class Last<T>(var value: T?)
fun StatColumn(value: String, label: String, modifier: Modifier = Modifier) {
Column(modifier, horizontalAlignment = Alignment.CenterHorizontally) {
// Numbers roll up when they change
AnimatedContent(
targetState = value,
transitionSpec = {
(slideInVertically(Motion.slide) { it / 2 } + fadeIn(Motion.enterFade)) togetherWith
(slideOutVertically(Motion.slide) { -it / 2 } + fadeOut(Motion.exitFade)) using
Motion.sizeTransform()
},
label = "stat",
) { shown ->
Text(shown, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold, maxLines = 1)
}
Text(
label,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
// The last non-null value, so a card can keep showing its text while it animates out
@Composable @Composable
fun StatDivider() { fun <T : Any> rememberLast(value: T?): T? {
Box( val last = remember { Last<T>(null) }
Modifier if (value != null) last.value = value
.size(width = 1.dp, height = 32.dp) return last.value
.background(MaterialTheme.colorScheme.outlineVariant)
)
} }
// Runs [onChange] when the query log changes, at most once a second and only while the screen // Runs [onChange] when the query log changes, at most once a second and only while the screen
@@ -209,13 +158,6 @@ fun OnQueryLogChange(onChange: () -> Unit) {
} }
} }
@Composable
fun rememberLiveStats(): QueryStats {
var stats by remember { mutableStateOf(QueryLog.stats()) }
OnQueryLogChange { stats = QueryLog.stats() }
return stats
}
// Called from composition only, i.e. on the main thread; rebuilt when the locale changes // Called from composition only, i.e. on the main thread; rebuilt when the locale changes
private var countFormat: Pair<Locale, NumberFormat>? = null private var countFormat: Pair<Locale, NumberFormat>? = null
@@ -226,9 +168,6 @@ fun formatCount(value: Long): String {
return format.format(value) return format.format(value)
} }
fun cachePercent(stats: QueryStats): String =
"${if (stats.total == 0L) 0 else stats.cached * 100 / stats.total}%"
// Rows of one visual group share a background; only the outer corners are rounded // Rows of one visual group share a background; only the outer corners are rounded
fun groupedShape(first: Boolean, last: Boolean, radius: Dp = 16.dp) = RoundedCornerShape( fun groupedShape(first: Boolean, last: Boolean, radius: Dp = 16.dp) = RoundedCornerShape(
topStart = if (first) radius else 0.dp, topStart = if (first) radius else 0.dp,
@@ -270,3 +209,27 @@ fun EmptyState(icon: Int, text: String) {
) )
} }
} }
enum class StatsPeriod(val hours: Int, @StringRes val label: Int) {
DAY(24, R.string.period_24h),
WEEK(24 * 7, R.string.period_7d),
}
// Switches between the last 24 hours and the last 7 days
@Composable
fun PeriodChip(period: StatsPeriod, onChange: (StatsPeriod) -> Unit) {
val shape = RoundedCornerShape(18.dp)
Row(
modifier = Modifier
.clip(shape)
.border(1.dp, Palette.Track, shape)
.clickable { onChange(if (period == StatsPeriod.DAY) StatsPeriod.WEEK else StatsPeriod.DAY) }
.heightIn(min = 36.dp)
.padding(start = 14.dp, end = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(stringResource(period.label), 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(16.dp))
}
}
+46 -3
View File
@@ -96,14 +96,12 @@
<string name="period_24h">24 Stunden</string> <string name="period_24h">24 Stunden</string>
<string name="period_7d">7 Tage</string> <string name="period_7d">7 Tage</string>
<string name="home_lists_info">Aktive Listen: %1$d · Regeln: %2$s</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="blocklist_title">DNS-Blocklisten</string>
<string name="tab_activity">Aktivität</string> <string name="tab_activity">Aktivität</string>
<string name="tab_settings">Einstellungen</string> <string name="tab_settings">Einstellungen</string>
<string name="companies_title">Anteil der Konzerne</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_desc">Welcher Anteil deiner Anfragen an die größten Konzerne und andere Websites geht.</string>
<string name="companies_other">Andere</string> <string name="companies_other">Andere</string>
<string name="no_data">Noch keine Daten</string>
<string name="recent_title">Letzte Anfragen</string> <string name="recent_title">Letzte Anfragen</string>
<string name="filter">Filter</string> <string name="filter">Filter</string>
<string name="bl_search">Listen suchen</string> <string name="bl_search">Listen suchen</string>
@@ -126,4 +124,49 @@
<string name="settings_general">Allgemein</string> <string name="settings_general">Allgemein</string>
<string name="settings_apps">Apps ohne SparkleDNS</string> <string name="settings_apps">Apps ohne SparkleDNS</string>
<string name="settings_apps_desc">Ausgewählte Apps nutzen das normale DNS des Netzwerks</string> <string name="settings_apps_desc">Ausgewählte Apps nutzen das normale DNS des Netzwerks</string>
<string name="chart_empty">Noch keine Daten. Nach dem Verbinden füllt sich das Diagramm Stunde für Stunde.</string>
<string name="companies_wait">Daten werden gesammelt: %1$d von %2$d Anfragen</string>
<string name="blocklist_cta_lists">Keine Liste ist aktiv. Schalte HaGeZi Pro ein, um Werbung und Tracker zu blockieren.</string>
<string name="blocklist_cta_master">Blockieren ist aus. Schalte es ein, um Werbung und Tracker zu filtern.</string>
<string name="turn_on">Einschalten</string>
<string name="downloading">Wird geladen…</string>
<string name="change_server">Server wechseln</string>
<string name="alert_channel">Schutzwarnungen</string>
<string name="alert_stopped_title">DNS-Schutz beendet</string>
<string name="alert_stopped_text">Der Tunnel funktioniert nicht mehr, DNS ist nicht mehr verschlüsselt. Öffne SparkleDNS, um dich erneut zu verbinden.</string>
<string name="alert_bad_url_title">DNS-Schutz nicht gestartet</string>
<string name="alert_bad_url_text">Die Serveradresse ist keine gültige HTTPS-URL. Öffne SparkleDNS und prüfe den Server.</string>
<string name="alert_lockdown_title">DNS-Server nicht erreichbar</string>
<string name="alert_lockdown_text">„Verbindungen ohne VPN blockieren“ ist aktiv, daher erreicht SparkleDNS den DNS-Server nicht und Anfragen schlagen fehl. Schalte es in den VPN-Einstellungen von Android aus.</string>
<string name="sign_in">Mit Skysparkle anmelden</string>
<string name="sign_in_again">Erneut anmelden</string>
<string name="sign_in_working">Anmeldung läuft…</string>
<string name="key_status">Schlüssel hinzugefügt: %1$s…</string>
<string name="key_copy">Adresse kopieren</string>
<string name="key_copied">Adresse kopiert. Füge sie im Browser oder auf einem anderen Gerät ein.</string>
<string name="sign_in_done">Angemeldet. Der Schlüssel wurde hinzugefügt.</string>
<string name="sign_in_failed">Anmeldung fehlgeschlagen. Bitte versuche es erneut.</string>
<string name="sign_in_expired">Die Anmeldung hat zu lange gedauert. Bitte starte sie neu.</string>
<string name="sign_in_verify">Bestätige zuerst deine E-Mail-Adresse und melde dich dann erneut an.</string>
<string name="sign_in_suspended">Dieses Skysparkle-Konto ist gesperrt.</string>
<string name="sign_in_network">Keine Verbindung zu skysparkle.cc. Prüfe das Internet und versuche es erneut.</string>
<string name="key_needed">Der SkySparkle-Server braucht einen persönlichen Zugangsschlüssel. Er ist kostenlos: Melde dich mit Skysparkle an, und die App holt den Schlüssel selbst.</string>
<string name="key_add">Anmelden</string>
<string name="alert_no_key_text">Der SkySparkle-Server braucht einen Zugangsschlüssel. Öffne SparkleDNS und melde dich unter Einstellungen mit Skysparkle an.</string>
<string name="onb_welcome_title">Willkommen bei SparkleDNS</string>
<string name="onb_welcome_text">Privates DNS für dein ganzes Handy, ohne Server der großen Tech-Konzerne.</string>
<string name="onb_point_encrypt">Verschlüsselt jede DNS-Anfrage mit DNS-over-HTTPS</string>
<string name="onb_point_block">Blockiert Werbung und Tracker in allen Apps</string>
<string name="onb_point_independent">Nur unabhängige Server, nie Google oder Cloudflare</string>
<string name="onb_key_title">Hol dir deinen Zugangsschlüssel</string>
<string name="onb_key_text">Der SkySparkle-Server arbeitet mit einem persönlichen Schlüssel. Er ist kostenlos: Melde dich an, und die App holt den Schlüssel selbst.</string>
<string name="onb_key_step1">Tippe auf „Mit Skysparkle anmelden“ – die Seite öffnet sich im Browser</string>
<string name="onb_key_step2">Melde dich an oder erstelle ein kostenloses Konto</string>
<string name="onb_key_step3">Tippe auf „Connect“ – du kommst mit dem Schlüssel hierher zurück</string>
<string name="onb_next">Weiter</string>
<string name="onb_done">Starten</string>
<string name="onb_skip">Überspringen, ich wähle einen anderen Server</string>
<string name="support_title">SparkleDNS unterstützen</string>
<string name="support_text">SparkleDNS ist kostenlos, quelloffen und werbefrei. Spenden finanzieren den Skysparkle-Server und halten die App am Leben.</string>
<string name="support_button">Auf Ko-fi spenden</string>
</resources> </resources>
+46 -3
View File
@@ -96,14 +96,12 @@
<string name="period_24h">24 時間</string> <string name="period_24h">24 時間</string>
<string name="period_7d">7 日間</string> <string name="period_7d">7 日間</string>
<string name="home_lists_info">有効なリスト: %1$d · ルール: %2$s</string> <string name="home_lists_info">有効なリスト: %1$d · ルール: %2$s</string>
<string name="blocking_off">ブロックはオフです</string>
<string name="blocklist_title">DNS ブロックリスト</string> <string name="blocklist_title">DNS ブロックリスト</string>
<string name="tab_activity">アクティビティ</string> <string name="tab_activity">アクティビティ</string>
<string name="tab_settings">設定</string> <string name="tab_settings">設定</string>
<string name="companies_title">企業の占有率</string> <string name="companies_title">企業の占有率</string>
<string name="companies_desc">リクエストのうち大手企業に送られる割合です。</string> <string name="companies_desc">リクエストのうち大手企業やその他のサイトに送られる割合です。</string>
<string name="companies_other">その他</string> <string name="companies_other">その他</string>
<string name="no_data">まだデータがありません</string>
<string name="recent_title">最近のアクティビティ</string> <string name="recent_title">最近のアクティビティ</string>
<string name="filter">フィルター</string> <string name="filter">フィルター</string>
<string name="bl_search">リストを検索</string> <string name="bl_search">リストを検索</string>
@@ -126,4 +124,49 @@
<string name="settings_general">一般</string> <string name="settings_general">一般</string>
<string name="settings_apps">SparkleDNS を使わないアプリ</string> <string name="settings_apps">SparkleDNS を使わないアプリ</string>
<string name="settings_apps_desc">選んだアプリはネットワークの通常の DNS を使います</string> <string name="settings_apps_desc">選んだアプリはネットワークの通常の DNS を使います</string>
<string name="chart_empty">まだデータがありません。接続すると 1 時間ごとにグラフが埋まっていきます。</string>
<string name="companies_wait">データ収集中: %2$d 件中 %1$d 件</string>
<string name="blocklist_cta_lists">有効なリストがありません。HaGeZi Pro をオンにして広告とトラッカーをブロックしましょう。</string>
<string name="blocklist_cta_master">ブロックはオフです。オンにすると広告とトラッカーをフィルタリングします。</string>
<string name="turn_on">オンにする</string>
<string name="downloading">ダウンロード中…</string>
<string name="change_server">サーバーを変更</string>
<string name="alert_channel">保護に関する警告</string>
<string name="alert_stopped_title">DNS 保護が停止しました</string>
<string name="alert_stopped_text">トンネルが動作しなくなったため、DNS は暗号化されていません。SparkleDNS を開いて再接続してください。</string>
<string name="alert_bad_url_title">DNS 保護を開始できません</string>
<string name="alert_bad_url_text">サーバーのアドレスが有効な HTTPS URL ではありません。SparkleDNS を開いてサーバーを確認してください。</string>
<string name="alert_lockdown_title">DNS サーバーに接続できません</string>
<string name="alert_lockdown_text">「VPN なしの接続をブロック」がオンのため、SparkleDNS は DNS サーバーに接続できず、名前解決に失敗します。Android の VPN 設定でオフにしてください。</string>
<string name="sign_in">Skysparkle でサインイン</string>
<string name="sign_in_again">もう一度サインイン</string>
<string name="sign_in_working">サインイン中…</string>
<string name="key_status">キーを追加済み:%1$s…</string>
<string name="key_copy">アドレスをコピー</string>
<string name="key_copied">アドレスをコピーしました。ブラウザや他のデバイスに貼り付けてください。</string>
<string name="sign_in_done">サインインしました。キーを追加しました。</string>
<string name="sign_in_failed">サインインに失敗しました。もう一度お試しください。</string>
<string name="sign_in_expired">サインインに時間がかかりすぎました。最初からやり直してください。</string>
<string name="sign_in_verify">先にメールアドレスを確認してから、もう一度サインインしてください。</string>
<string name="sign_in_suspended">この Skysparkle アカウントは停止されています。</string>
<string name="sign_in_network">skysparkle.cc に接続できません。インターネット接続を確認して、もう一度お試しください。</string>
<string name="key_needed">SkySparkle サーバーには個人用のアクセスキーが必要です。無料です:Skysparkle でサインインすると、アプリが自動でキーを取得します。</string>
<string name="key_add">サインイン</string>
<string name="alert_no_key_text">SkySparkle サーバーにはアクセスキーが必要です。SparkleDNS を開き、「設定」で Skysparkle にサインインしてください。</string>
<string name="onb_welcome_title">SparkleDNS へようこそ</string>
<string name="onb_welcome_text">大手 IT 企業のサーバーを使わない、スマホ全体のプライベート DNS。</string>
<string name="onb_point_encrypt">DNS-over-HTTPS ですべての DNS 問い合わせを暗号化</string>
<string name="onb_point_block">すべてのアプリで広告とトラッカーをブロック</string>
<string name="onb_point_independent">独立系サーバーのみ。Google や Cloudflare は使いません</string>
<string name="onb_key_title">アクセスキーを取得</string>
<string name="onb_key_text">SkySparkle サーバーは個人用キーで動作します。無料です:サインインすると、アプリが自動でキーを取得します。</string>
<string name="onb_key_step1">「Skysparkle でサインイン」をタップ — ブラウザでサイトが開きます</string>
<string name="onb_key_step2">サインインするか、無料アカウントを作成</string>
<string name="onb_key_step3">「Connect」をタップ — キーを持ってここに戻ります</string>
<string name="onb_next">次へ</string>
<string name="onb_done">開始</string>
<string name="onb_skip">スキップして別のサーバーを選ぶ</string>
<string name="support_title">SparkleDNS を応援する</string>
<string name="support_text">SparkleDNS は無料・オープンソースで、広告もありません。寄付は Skysparkle サーバーの運営とアプリの開発に使われます。</string>
<string name="support_button">Ko-fi で寄付する</string>
</resources> </resources>
+46 -3
View File
@@ -96,14 +96,12 @@
<string name="period_24h">24 valandos</string> <string name="period_24h">24 valandos</string>
<string name="period_7d">7 dienos</string> <string name="period_7d">7 dienos</string>
<string name="home_lists_info">Įjungta sąrašų: %1$d · taisyklių: %2$s</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="blocklist_title">DNS blokavimo sąrašai</string>
<string name="tab_activity">Veikla</string> <string name="tab_activity">Veikla</string>
<string name="tab_settings">Nustatymai</string> <string name="tab_settings">Nustatymai</string>
<string name="companies_title">Įmonių dalis</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_desc">Kokia jūsų užklausų dalis tenka didžiausioms įmonėms ir kitoms svetainėms.</string>
<string name="companies_other">Kitos</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="recent_title">Naujausios užklausos</string>
<string name="filter">Filtras</string> <string name="filter">Filtras</string>
<string name="bl_search">Ieškoti sąrašų</string> <string name="bl_search">Ieškoti sąrašų</string>
@@ -126,4 +124,49 @@
<string name="settings_general">Bendrieji</string> <string name="settings_general">Bendrieji</string>
<string name="settings_apps">Programėlės be SparkleDNS</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> <string name="settings_apps_desc">Pasirinktos programėlės naudoja įprastą tinklo DNS</string>
<string name="chart_empty">Duomenų dar nėra. Prisijungus grafikas pildysis kas valandą.</string>
<string name="companies_wait">Renkami duomenys: %1$d iš %2$d užklausų</string>
<string name="blocklist_cta_lists">Neįjungtas nė vienas sąrašas. Įjunkite HaGeZi Pro, kad blokuotumėte reklamas ir sekiklius.</string>
<string name="blocklist_cta_master">Blokavimas išjungtas. Įjunkite jį, kad filtruotumėte reklamas ir sekiklius.</string>
<string name="turn_on">Įjungti</string>
<string name="downloading">Atsisiunčiama…</string>
<string name="change_server">Keisti serverį</string>
<string name="alert_channel">Apsaugos įspėjimai</string>
<string name="alert_stopped_title">DNS apsauga išjungta</string>
<string name="alert_stopped_text">Tunelis nustojo veikti, DNS nebešifruojamas. Atidarykite SparkleDNS, kad prisijungtumėte iš naujo.</string>
<string name="alert_bad_url_title">DNS apsauga nepaleista</string>
<string name="alert_bad_url_text">Serverio adresas nėra tinkamas HTTPS adresas. Atidarykite SparkleDNS ir patikrinkite serverį.</string>
<string name="alert_lockdown_title">DNS serveris nepasiekiamas</string>
<string name="alert_lockdown_text">Įjungta „Blokuoti ryšius be VPN“, todėl SparkleDNS negali pasiekti DNS serverio ir užklausos nepavyksta. Išjunkite tai Android VPN nustatymuose.</string>
<string name="sign_in">Prisijungti su Skysparkle</string>
<string name="sign_in_again">Prisijungti iš naujo</string>
<string name="sign_in_working">Jungiamasi…</string>
<string name="key_status">Raktas pridėtas: %1$s…</string>
<string name="key_copy">Kopijuoti adresą</string>
<string name="key_copied">Adresas nukopijuotas. Įklijuokite jį naršyklėje arba kitame įrenginyje.</string>
<string name="sign_in_done">Prisijungta. Raktas pridėtas.</string>
<string name="sign_in_failed">Prisijungti nepavyko. Bandykite dar kartą.</string>
<string name="sign_in_expired">Prisijungimas užtruko per ilgai. Pradėkite iš naujo.</string>
<string name="sign_in_verify">Pirmiausia patvirtinkite el. paštą, tada prisijunkite dar kartą.</string>
<string name="sign_in_suspended">Ši Skysparkle paskyra sustabdyta.</string>
<string name="sign_in_network">Nėra ryšio su skysparkle.cc. Patikrinkite internetą ir bandykite dar kartą.</string>
<string name="key_needed">SkySparkle serveriui reikia asmeninio prieigos rakto. Tai nemokama: prisijunkite su Skysparkle, ir programėlė gaus raktą pati.</string>
<string name="key_add">Prisijungti</string>
<string name="alert_no_key_text">SkySparkle serveriui reikia prieigos rakto. Atidarykite SparkleDNS ir skiltyje „Nustatymai“ prisijunkite su Skysparkle.</string>
<string name="onb_welcome_title">Sveiki atvykę į SparkleDNS</string>
<string name="onb_welcome_text">Privatus DNS visam telefonui, be didžiųjų technologijų įmonių serverių.</string>
<string name="onb_point_encrypt">Šifruoja kiekvieną DNS užklausą per DNS-over-HTTPS</string>
<string name="onb_point_block">Blokuoja reklamas ir sekiklius visose programėlėse</string>
<string name="onb_point_independent">Tik nepriklausomi serveriai, jokio Google ar Cloudflare</string>
<string name="onb_key_title">Gaukite prieigos raktą</string>
<string name="onb_key_text">SkySparkle serveris veikia su asmeniniu raktu. Tai nemokama: prisijunkite, ir programėlė gaus raktą pati.</string>
<string name="onb_key_step1">Paspauskite „Prisijungti su Skysparkle“ – svetainė atsidarys naršyklėje</string>
<string name="onb_key_step2">Prisijunkite arba susikurkite nemokamą paskyrą</string>
<string name="onb_key_step3">Paspauskite „Prijungti“ – grįšite čia su raktu</string>
<string name="onb_next">Toliau</string>
<string name="onb_done">Pradėti</string>
<string name="onb_skip">Praleisti, pasirinksiu kitą serverį</string>
<string name="support_title">Paremti SparkleDNS</string>
<string name="support_text">SparkleDNS nemokama, atvirojo kodo ir be reklamų. Aukos padengia Skysparkle serverio išlaidas ir padeda programėlei gyvuoti.</string>
<string name="support_button">Paaukoti per Ko-fi</string>
</resources> </resources>
+46 -3
View File
@@ -96,14 +96,12 @@
<string name="period_24h">24 часа</string> <string name="period_24h">24 часа</string>
<string name="period_7d">7 дней</string> <string name="period_7d">7 дней</string>
<string name="home_lists_info">Включено списков: %1$d · правил: %2$s</string> <string name="home_lists_info">Включено списков: %1$d · правил: %2$s</string>
<string name="blocking_off">Блокировка выключена</string>
<string name="blocklist_title">Блок-листы DNS</string> <string name="blocklist_title">Блок-листы DNS</string>
<string name="tab_activity">Активность</string> <string name="tab_activity">Активность</string>
<string name="tab_settings">Настройки</string> <string name="tab_settings">Настройки</string>
<string name="companies_title">Доля компаний</string> <string name="companies_title">Доля компаний</string>
<string name="companies_desc">Какая часть ваших запросов уходит крупнейшим компаниям.</string> <string name="companies_desc">Какая часть ваших запросов уходит крупнейшим компаниям и другим сайтам.</string>
<string name="companies_other">Другие</string> <string name="companies_other">Другие</string>
<string name="no_data">Данных пока нет</string>
<string name="recent_title">Последние запросы</string> <string name="recent_title">Последние запросы</string>
<string name="filter">Фильтр</string> <string name="filter">Фильтр</string>
<string name="bl_search">Поиск списков</string> <string name="bl_search">Поиск списков</string>
@@ -126,4 +124,49 @@
<string name="settings_general">Общие</string> <string name="settings_general">Общие</string>
<string name="settings_apps">Приложения без SparkleDNS</string> <string name="settings_apps">Приложения без SparkleDNS</string>
<string name="settings_apps_desc">Выбранные приложения используют обычный DNS сети</string> <string name="settings_apps_desc">Выбранные приложения используют обычный DNS сети</string>
<string name="chart_empty">Данных пока нет. После подключения график будет заполняться по часам.</string>
<string name="companies_wait">Собираем данные: %1$d из %2$d запросов</string>
<string name="blocklist_cta_lists">Ни один список не включён. Включите HaGeZi Pro, чтобы блокировать рекламу и трекеры.</string>
<string name="blocklist_cta_master">Блокировка выключена. Включите её, чтобы фильтровать рекламу и трекеры.</string>
<string name="turn_on">Включить</string>
<string name="downloading">Загрузка…</string>
<string name="change_server">Сменить сервер</string>
<string name="alert_channel">Предупреждения о защите</string>
<string name="alert_stopped_title">Защита DNS отключена</string>
<string name="alert_stopped_text">Туннель перестал работать, DNS больше не шифруется. Откройте SparkleDNS, чтобы подключиться снова.</string>
<string name="alert_bad_url_title">Защита DNS не запущена</string>
<string name="alert_bad_url_text">Адрес сервера не является корректным HTTPS-адресом. Откройте SparkleDNS и проверьте сервер.</string>
<string name="alert_lockdown_title">DNS-сервер недоступен</string>
<string name="alert_lockdown_text">Включено «Блокировать соединения без VPN», поэтому SparkleDNS не может связаться с DNS-сервером и запросы не проходят. Отключите это в настройках VPN Android.</string>
<string name="sign_in">Войти через Skysparkle</string>
<string name="sign_in_again">Войти заново</string>
<string name="sign_in_working">Выполняется вход…</string>
<string name="key_status">Ключ добавлен: %1$s…</string>
<string name="key_copy">Скопировать адрес</string>
<string name="key_copied">Адрес скопирован. Вставьте его в браузер или на другом устройстве.</string>
<string name="sign_in_done">Вход выполнен. Ключ добавлен.</string>
<string name="sign_in_failed">Не удалось войти. Попробуйте ещё раз.</string>
<string name="sign_in_expired">Вход занял слишком много времени. Начните заново.</string>
<string name="sign_in_verify">Сначала подтвердите e-mail, затем войдите ещё раз.</string>
<string name="sign_in_suspended">Этот аккаунт Skysparkle заблокирован.</string>
<string name="sign_in_network">Нет связи с skysparkle.cc. Проверьте интернет и попробуйте ещё раз.</string>
<string name="key_needed">Серверу SkySparkle нужен личный ключ доступа. Это бесплатно: войдите через Skysparkle, и приложение получит ключ само.</string>
<string name="key_add">Войти</string>
<string name="alert_no_key_text">Серверу SkySparkle нужен ключ доступа. Откройте SparkleDNS и войдите через Skysparkle в разделе «Настройки».</string>
<string name="onb_welcome_title">Добро пожаловать в SparkleDNS</string>
<string name="onb_welcome_text">Приватный DNS для всего телефона, без серверов крупных корпораций.</string>
<string name="onb_point_encrypt">Шифрует каждый DNS-запрос через DNS-over-HTTPS</string>
<string name="onb_point_block">Блокирует рекламу и трекеры во всех приложениях</string>
<string name="onb_point_independent">Только независимые серверы, без Google и Cloudflare</string>
<string name="onb_key_title">Получите ключ доступа</string>
<string name="onb_key_text">Сервер SkySparkle работает по личному ключу. Это бесплатно: войдите, и приложение получит ключ само.</string>
<string name="onb_key_step1">Нажмите «Войти через Skysparkle» — сайт откроется в браузере</string>
<string name="onb_key_step2">Войдите или создайте бесплатный аккаунт</string>
<string name="onb_key_step3">Нажмите «Connect» — вы вернётесь сюда уже с ключом</string>
<string name="onb_next">Далее</string>
<string name="onb_done">Начать</string>
<string name="onb_skip">Пропустить, выберу другой сервер</string>
<string name="support_title">Поддержать SparkleDNS</string>
<string name="support_text">SparkleDNS бесплатное, с открытым кодом и без рекламы. Пожертвования оплачивают сервер Skysparkle и помогают приложению развиваться.</string>
<string name="support_button">Пожертвовать через Ko-fi</string>
</resources> </resources>
+46 -3
View File
@@ -96,14 +96,12 @@
<string name="period_24h">24 小时</string> <string name="period_24h">24 小时</string>
<string name="period_7d">7 天</string> <string name="period_7d">7 天</string>
<string name="home_lists_info">已启用列表:%1$d · 规则:%2$s</string> <string name="home_lists_info">已启用列表:%1$d · 规则:%2$s</string>
<string name="blocking_off">屏蔽已关闭</string>
<string name="blocklist_title">DNS 屏蔽列表</string> <string name="blocklist_title">DNS 屏蔽列表</string>
<string name="tab_activity">活动</string> <string name="tab_activity">活动</string>
<string name="tab_settings">设置</string> <string name="tab_settings">设置</string>
<string name="companies_title">公司占比</string> <string name="companies_title">公司占比</string>
<string name="companies_desc">你的请求中发往大公司的比例。</string> <string name="companies_desc">你的请求中发往大公司和其他网站的比例。</string>
<string name="companies_other">其他</string> <string name="companies_other">其他</string>
<string name="no_data">暂无数据</string>
<string name="recent_title">最近活动</string> <string name="recent_title">最近活动</string>
<string name="filter">筛选</string> <string name="filter">筛选</string>
<string name="bl_search">搜索列表</string> <string name="bl_search">搜索列表</string>
@@ -126,4 +124,49 @@
<string name="settings_general">通用</string> <string name="settings_general">通用</string>
<string name="settings_apps">不使用 SparkleDNS 的应用</string> <string name="settings_apps">不使用 SparkleDNS 的应用</string>
<string name="settings_apps_desc">选中的应用使用网络的常规 DNS</string> <string name="settings_apps_desc">选中的应用使用网络的常规 DNS</string>
<string name="chart_empty">暂无数据。连接后,图表会按小时逐步填充。</string>
<string name="companies_wait">正在收集数据:%1$d / %2$d 个请求</string>
<string name="blocklist_cta_lists">没有启用任何列表。开启 HaGeZi Pro 以屏蔽广告和跟踪器。</string>
<string name="blocklist_cta_master">屏蔽已关闭。开启后即可过滤广告和跟踪器。</string>
<string name="turn_on">开启</string>
<string name="downloading">正在下载…</string>
<string name="change_server">更换服务器</string>
<string name="alert_channel">保护警告</string>
<string name="alert_stopped_title">DNS 保护已停止</string>
<string name="alert_stopped_text">隧道已停止工作,DNS 不再加密。请打开 SparkleDNS 重新连接。</string>
<string name="alert_bad_url_title">DNS 保护未启动</string>
<string name="alert_bad_url_text">服务器地址不是有效的 HTTPS 网址。请打开 SparkleDNS 检查服务器。</string>
<string name="alert_lockdown_title">无法连接 DNS 服务器</string>
<string name="alert_lockdown_text">已开启“屏蔽未使用 VPN 的连接”,SparkleDNS 无法连接 DNS 服务器,解析会失败。请在 Android 的 VPN 设置中关闭该选项。</string>
<string name="sign_in">使用 Skysparkle 登录</string>
<string name="sign_in_again">重新登录</string>
<string name="sign_in_working">正在登录…</string>
<string name="key_status">已添加密钥:%1$s…</string>
<string name="key_copy">复制地址</string>
<string name="key_copied">地址已复制。可粘贴到浏览器或其他设备中。</string>
<string name="sign_in_done">已登录,密钥已添加。</string>
<string name="sign_in_failed">登录失败,请重试。</string>
<string name="sign_in_expired">登录耗时过长,请重新开始。</string>
<string name="sign_in_verify">请先确认电子邮箱,然后重新登录。</string>
<string name="sign_in_suspended">此 Skysparkle 账户已被暂停。</string>
<string name="sign_in_network">无法连接 skysparkle.cc。请检查网络后重试。</string>
<string name="key_needed">SkySparkle 服务器需要个人访问密钥。完全免费:使用 Skysparkle 登录,应用会自动获取密钥。</string>
<string name="key_add">登录</string>
<string name="alert_no_key_text">SkySparkle 服务器需要访问密钥。请打开 SparkleDNS,在“设置”中使用 Skysparkle 登录。</string>
<string name="onb_welcome_title">欢迎使用 SparkleDNS</string>
<string name="onb_welcome_text">为整部手机提供私密 DNS,不使用大型科技公司的服务器。</string>
<string name="onb_point_encrypt">通过 DNS-over-HTTPS 加密每一次 DNS 查询</string>
<string name="onb_point_block">在所有应用中拦截广告和跟踪器</string>
<string name="onb_point_independent">只使用独立服务器,不用 Google 或 Cloudflare</string>
<string name="onb_key_title">获取访问密钥</string>
<string name="onb_key_text">SkySparkle 服务器使用个人密钥。完全免费:登录后,应用会自动获取密钥。</string>
<string name="onb_key_step1">点击“使用 Skysparkle 登录”——网站将在浏览器中打开</string>
<string name="onb_key_step2">登录或创建免费账户</string>
<string name="onb_key_step3">点击“Connect”——带着密钥回到这里</string>
<string name="onb_next">下一步</string>
<string name="onb_done">开始</string>
<string name="onb_skip">跳过,我选择其他服务器</string>
<string name="support_title">支持 SparkleDNS</string>
<string name="support_text">SparkleDNS 免费、开源且无广告。捐助用于支付 Skysparkle 服务器的费用,让应用持续发展。</string>
<string name="support_button">通过 Ko-fi 捐助</string>
</resources> </resources>
+46 -3
View File
@@ -97,14 +97,12 @@
<string name="period_24h">24 hours</string> <string name="period_24h">24 hours</string>
<string name="period_7d">7 days</string> <string name="period_7d">7 days</string>
<string name="home_lists_info">Lists on: %1$d · rules: %2$s</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="blocklist_title">DNS Blocklist</string>
<string name="tab_activity">Activity</string> <string name="tab_activity">Activity</string>
<string name="tab_settings">Settings</string> <string name="tab_settings">Settings</string>
<string name="companies_title">Company dominance</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_desc">Share of your requests that go to the biggest companies and other sites.</string>
<string name="companies_other">Other</string> <string name="companies_other">Other</string>
<string name="no_data">No data yet</string>
<string name="recent_title">Recent activity</string> <string name="recent_title">Recent activity</string>
<string name="filter">Filter</string> <string name="filter">Filter</string>
<string name="bl_search">Search lists</string> <string name="bl_search">Search lists</string>
@@ -127,4 +125,49 @@
<string name="settings_general">General</string> <string name="settings_general">General</string>
<string name="settings_apps">Apps without SparkleDNS</string> <string name="settings_apps">Apps without SparkleDNS</string>
<string name="settings_apps_desc">Picked apps use the regular DNS of the network</string> <string name="settings_apps_desc">Picked apps use the regular DNS of the network</string>
<string name="chart_empty">No data yet. Connect, and the chart fills in hour by hour.</string>
<string name="companies_wait">Collecting data: %1$d of %2$d requests</string>
<string name="blocklist_cta_lists">No lists are on. Turn on HaGeZi Pro to block ads and trackers.</string>
<string name="blocklist_cta_master">Blocking is off. Turn it on to filter ads and trackers.</string>
<string name="turn_on">Turn on</string>
<string name="downloading">Downloading…</string>
<string name="change_server">Change server</string>
<string name="alert_channel">Protection alerts</string>
<string name="alert_stopped_title">DNS protection stopped</string>
<string name="alert_stopped_text">The tunnel stopped working, so DNS is no longer encrypted. Open SparkleDNS to connect again.</string>
<string name="alert_bad_url_title">DNS protection not started</string>
<string name="alert_bad_url_text">The server address is not a valid HTTPS URL. Open SparkleDNS and check the server.</string>
<string name="alert_lockdown_title">DNS server unreachable</string>
<string name="alert_lockdown_text">\"Block connections without VPN\" is on, so SparkleDNS cannot reach the DNS server and lookups fail. Turn it off in Android VPN settings.</string>
<string name="sign_in">Sign in with Skysparkle</string>
<string name="sign_in_again">Sign in again</string>
<string name="sign_in_working">Signing in…</string>
<string name="key_status">Key added: %1$s…</string>
<string name="key_copy">Copy address</string>
<string name="key_copied">Address copied. Paste it in a browser or on another device.</string>
<string name="sign_in_done">Signed in. The key has been added.</string>
<string name="sign_in_failed">Sign-in failed. Please try again.</string>
<string name="sign_in_expired">The sign-in took too long. Please start again.</string>
<string name="sign_in_verify">Confirm your e-mail first, then sign in again.</string>
<string name="sign_in_suspended">This Skysparkle account is suspended.</string>
<string name="sign_in_network">No connection to skysparkle.cc. Check the internet and try again.</string>
<string name="key_needed">The SkySparkle server needs a personal access key. It is free: sign in with Skysparkle and the app gets the key by itself.</string>
<string name="key_add">Sign in</string>
<string name="alert_no_key_text">The SkySparkle server needs an access key. Open SparkleDNS and sign in with Skysparkle in Settings.</string>
<string name="onb_welcome_title">Welcome to SparkleDNS</string>
<string name="onb_welcome_text">Private DNS for your whole phone, without big-tech servers.</string>
<string name="onb_point_encrypt">Encrypts every DNS lookup with DNS-over-HTTPS</string>
<string name="onb_point_block">Blocks ads and trackers in all apps</string>
<string name="onb_point_independent">Uses only independent servers, never Google or Cloudflare</string>
<string name="onb_key_title">Get your access key</string>
<string name="onb_key_text">The SkySparkle server works with a personal key. It is free: sign in, and the app gets the key by itself.</string>
<string name="onb_key_step1">Tap “Sign in with Skysparkle” — the site opens in your browser</string>
<string name="onb_key_step2">Sign in or create a free account</string>
<string name="onb_key_step3">Tap “Connect” — you are back here with the key</string>
<string name="onb_next">Next</string>
<string name="onb_done">Start</string>
<string name="onb_skip">Skip, I\'ll choose another server</string>
<string name="support_title">Support SparkleDNS</string>
<string name="support_text">SparkleDNS is free, open source and has no ads. Donations pay for the Skysparkle server and keep the app going.</string>
<string name="support_button">Donate on Ko-fi</string>
</resources> </resources>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<exclude domain="root" />
<exclude domain="database" />
<exclude domain="sharedpref" />
<exclude domain="file" />
</cloud-backup>
<device-transfer>
<exclude domain="root" />
<exclude domain="database" />
<exclude domain="sharedpref" />
<exclude domain="file" />
</device-transfer>
</data-extraction-rules>
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
<locale android:name="en" />
<locale android:name="de" />
<locale android:name="ja" />
<locale android:name="lt" />
<locale android:name="ru" />
<locale android:name="zh" />
</locale-config>
@@ -5,14 +5,17 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
import java.nio.LongBuffer
class BlocklistMatchTest { class BlocklistMatchTest {
private fun set(vararg domains: String) = domains.map { DomainHash.of(it) }.sorted().toLongArray() private fun set(vararg domains: String) = domains.map { DomainHash.of(it) }.sorted().toLongArray()
private fun buf(vararg domains: String) = LongBuffer.wrap(set(*domains))
private fun buf(values: LongArray) = LongBuffer.wrap(values)
@Test @Test
fun blocksDomainsAndTheirSubdomains() { fun blocksDomainsAndTheirSubdomains() {
val lists = set("ads.example.com") val lists = buf("ads.example.com")
val custom = set("tracker.net") val custom = set("tracker.net")
assertTrue(isBlockedIn("ads.example.com", lists, custom)) assertTrue(isBlockedIn("ads.example.com", lists, custom))
@@ -21,7 +24,16 @@ class BlocklistMatchTest {
assertFalse(isBlockedIn("example.com", lists, custom)) assertFalse(isBlockedIn("example.com", lists, custom))
assertFalse(isBlockedIn("badads.example.com", lists, custom)) assertFalse(isBlockedIn("badads.example.com", lists, custom))
assertFalse(isBlockedIn("tracker.network", lists, custom)) assertFalse(isBlockedIn("tracker.network", lists, custom))
assertFalse(isBlockedIn("ads.example.com", LongArray(0), LongArray(0))) assertFalse(isBlockedIn("ads.example.com", EMPTY_SET, LongArray(0)))
}
@Test
fun skipsTrailingDots() {
val lists = buf("example.com")
assertTrue(isBlockedIn("www.example.com..", lists, LongArray(0)))
assertFalse(isBlockedIn("example.org.", lists, LongArray(0)))
assertFalse(isBlockedIn("...", lists, LongArray(0)))
} }
@Test @Test
@@ -42,8 +54,28 @@ class BlocklistMatchTest {
@Test @Test
fun countsEntriesInBothSetsOnce() { fun countsEntriesInBothSetsOnce() {
assertEquals(5, unionSize(longArrayOf(1, 2, 3, 4), longArrayOf(2, 5))) assertEquals(5, unionSize(buf(longArrayOf(1, 2, 3, 4)), longArrayOf(2, 5)))
assertEquals(2, unionSize(LongArray(0), longArrayOf(2, 5))) assertEquals(2, unionSize(EMPTY_SET, longArrayOf(2, 5)))
assertEquals(4, unionSize(longArrayOf(1, 2, 3, 4), LongArray(0))) assertEquals(4, unionSize(buf(longArrayOf(1, 2, 3, 4)), LongArray(0)))
}
@Test
fun streamsMergedValuesInOrderOnce() {
val out = ArrayList<Long>()
val count = mergeSortedInto(
listOf(buf(longArrayOf(-5, 1, 4, 9)), buf(longArrayOf(1, 2, 9, 12)), EMPTY_SET, buf(longArrayOf(12, 40)))
) { out.add(it) }
assertEquals(listOf(-5L, 1, 2, 4, 9, 12, 40), out)
assertEquals(7, count)
assertEquals(0, mergeSortedInto(emptyList()) { out.add(it) })
}
@Test
fun findsValuesInSortedBuffer() {
val values = buf(longArrayOf(Long.MIN_VALUE, -3, 0, 7, Long.MAX_VALUE))
listOf(Long.MIN_VALUE, -3L, 0L, 7L, Long.MAX_VALUE).forEach { assertTrue(values.containsSorted(it)) }
listOf(-4L, 1L, 8L).forEach { assertFalse(values.containsSorted(it)) }
assertFalse(EMPTY_SET.containsSorted(0))
} }
} }
@@ -1,5 +1,6 @@
package cc.skysparkle.sparkledns package cc.skysparkle.sparkledns
import okio.Buffer
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull import org.junit.Assert.assertNull
import org.junit.Test import org.junit.Test
@@ -49,5 +50,24 @@ class BlocklistParserTest {
val name = "a.b.example.com" val name = "a.b.example.com"
assertEquals(DomainHash.of("example.com"), DomainHash.of(name, name.indexOf("example"))) assertEquals(DomainHash.of("example.com"), DomainHash.of(name, name.indexOf("example")))
assertEquals(DomainHash.of(name), DomainHash.of(name, 0)) assertEquals(DomainHash.of(name), DomainHash.of(name, 0))
assertEquals(DomainHash.of("b.example"), DomainHash.of(name, 2, name.indexOf(".com")))
}
@Test
fun rulesWithAPathAreSkippedNotTurnedIntoTheWholeDomain() {
assertNull(BlocklistParser.parseLine("||example.com/ads/"))
assertNull(BlocklistParser.parseLine("|http://example.com/x|"))
assertNull(BlocklistParser.parseLine("https://example.com/banner.js"))
assertEquals("example.com", BlocklistParser.parseLine("||example.com/^"))
assertEquals("example.com", BlocklistParser.parseLine("https://example.com/"))
}
@Test
fun overlongLinesAreSkippedAndTheRestIsRead() {
val long = "x".repeat(BlocklistParser.MAX_LINE_BYTES.toInt() * 3)
val source = Buffer().writeUtf8("a.example\r\n$long\nb.example\nc.example")
val lines = mutableListOf<String>()
BlocklistParser.readLimitedLines(source) { lines += it.trim() }
assertEquals(listOf("a.example", "b.example", "c.example"), lines)
} }
} }
@@ -0,0 +1,43 @@
package cc.skysparkle.sparkledns
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class CompaniesTest {
@Test
fun matchesDomainsAndTheirSubdomains() {
assertEquals(Company.GOOGLE, Companies.of("youtube.com"))
assertEquals(Company.GOOGLE, Companies.of("r3---sn-abc.googlevideo.com"))
assertEquals(Company.META, Companies.of("scontent.cdninstagram.com"))
assertEquals(Company.X, Companies.of("t.co"))
assertEquals(Company.MICROSOFT, Companies.of("api.github.com"))
}
@Test
fun ignoresCaseAndTrailingDots() {
assertEquals(Company.APPLE, Companies.of("WWW.Apple.COM"))
assertEquals(Company.AMAZON, Companies.of("s3.amazonaws.com."))
assertEquals(Company.AMAZON, Companies.of("s3.amazonaws.com.."))
}
@Test
fun knowsGoogleCountrySites() {
assertEquals(Company.GOOGLE, Companies.of("google.de"))
assertEquals(Company.GOOGLE, Companies.of("www.google.co.uk"))
assertEquals(Company.GOOGLE, Companies.of("google.com.br"))
assertNull(Companies.of("google.example.org"))
assertNull(Companies.of("google."))
}
@Test
fun leavesOtherDomainsAlone() {
assertNull(Companies.of("example.com"))
assertNull(Companies.of("notyoutube.com"))
assertNull(Companies.of("youtube.com.example"))
assertNull(Companies.of("com"))
assertNull(Companies.of(""))
assertNull(Companies.of("."))
}
}
@@ -0,0 +1,126 @@
package cc.skysparkle.sparkledns
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
class HourlyCountersTest {
private val hours = HourlyCounters.HOURS
@Test
fun countsQueriesPerHour() {
val counters = HourlyCounters()
counters.record(QueryStatus.OK, 40, Company.GOOGLE, hour = 100)
counters.record(QueryStatus.OK, 20, null, hour = 100)
counters.record(QueryStatus.BLOCKED, 0, Company.META, hour = 100)
counters.record(QueryStatus.CACHED, 0, null, hour = 99)
counters.record(QueryStatus.FAILED, 5000, null, hour = 99)
val day = counters.summary(24, currentHour = 100)
assertEquals(5L, day.total)
assertEquals(1L, day.blocked)
assertEquals(1L, day.cached)
assertEquals(30, day.avgLatencyMs)
assertEquals(1L, day.companies[Company.GOOGLE.ordinal])
assertEquals(1L, day.companies[Company.META.ordinal])
assertEquals(3L, counters.summary(1, currentHour = 100).total)
val points = counters.hourly(3, currentHour = 100)
assertEquals(listOf(0L, 2L, 3L), points.map { it.total })
assertEquals(listOf(0L, 0L, 1L), points.map { it.blocked })
}
@Test
fun aSlotStartsOverAWeekLater() {
val counters = HourlyCounters()
counters.record(QueryStatus.OK, 10, null, hour = 5)
counters.record(QueryStatus.OK, 10, null, hour = 5L + hours)
assertEquals(1L, counters.summary(hours, currentHour = 5L + hours).total)
assertEquals(0L, counters.summary(1, currentHour = 5).total)
}
@Test
fun savedNumbersReadBackUnchanged() {
val counters = HourlyCounters()
counters.record(QueryStatus.BLOCKED, 0, Company.XIAOMI, hour = 1000)
counters.record(QueryStatus.OK, 12, Company.APPLE, hour = 1001)
val copy = requireNotNull(HourlyCounters.decode(counters.encode()))
assertArrayEquals(counters.hourIds, copy.hourIds)
for (index in 0 until hours) assertArrayEquals(counters.rows[index], copy.rows[index])
}
@Test
fun writesFormatOne() {
val bytes = HourlyCounters().encode()
val input = DataInputStream(ByteArrayInputStream(bytes))
assertEquals(1, input.readInt())
assertEquals(HourlyCounters.FIELDS, input.readInt())
assertEquals(hours, input.readInt())
assertEquals(-1L, input.readLong())
assertEquals(12 + hours * (HourlyCounters.FIELDS + 1) * 8, bytes.size)
}
@Test
fun readsFilesFromVersionsWithFewerCompanies() {
// A file from a version that knew two companies: field n of hour 7 holds n + 1
val fields = HourlyCounters.FIRST_COMPANY + 2
val bytes = ByteArrayOutputStream()
DataOutputStream(bytes).use { out ->
out.writeInt(1)
out.writeInt(fields)
out.writeInt(hours)
for (index in 0 until hours) {
out.writeLong(if (index == 7) 7L else -1L)
for (field in 0 until fields) out.writeLong(if (index == 7) field + 1L else 0L)
}
}
val summary = requireNotNull(HourlyCounters.decode(bytes.toByteArray())).summary(1, currentHour = 7)
assertEquals(1L, summary.total)
assertEquals(2L, summary.blocked)
assertEquals(3L, summary.cached)
assertEquals(0, summary.avgLatencyMs) // latency sum 4, count 5
assertArrayEquals(longArrayOf(6, 7) + LongArray(Company.entries.size - 2), summary.companies)
}
@Test
fun refusesOtherFormats() {
val bytes = HourlyCounters().encode()
bytes[3] = 2
assertNull(HourlyCounters.decode(bytes))
}
@Test
fun mergeKeepsWhatWasCountedBeforeTheFileWasRead() {
val saved = HourlyCounters()
saved.record(QueryStatus.OK, 10, null, hour = 50)
saved.record(QueryStatus.OK, 10, null, hour = 49)
val live = HourlyCounters()
live.record(QueryStatus.BLOCKED, 0, null, hour = 50)
live.merge(saved)
assertEquals(2L, live.summary(1, currentHour = 50).total)
assertEquals(1L, live.summary(1, currentHour = 50).blocked)
assertEquals(3L, live.summary(2, currentHour = 50).total)
// A slot already holding a newer hour keeps it
val later = HourlyCounters()
later.record(QueryStatus.OK, 10, null, hour = 50L + hours)
later.merge(saved)
assertEquals(1L, later.summary(1, currentHour = 50L + hours).total)
}
}
@@ -18,8 +18,8 @@ class PacketTest {
val parsed = requireNotNull(Packet.parseDnsQuery(packet, packet.size)) val parsed = requireNotNull(Packet.parseDnsQuery(packet, packet.size))
assertArrayEquals(query, parsed.payload) assertArrayEquals(query, parsed.payload)
assertArrayEquals(client, parsed.srcIp) assertEquals(i32(client, 0), parsed.srcIp)
assertArrayEquals(server, parsed.dstIp) assertEquals(i32(server, 0), parsed.dstIp)
assertEquals(40000, parsed.srcPort) assertEquals(40000, parsed.srcPort)
assertEquals(53, parsed.dstPort) assertEquals(53, parsed.dstPort)
} }
@@ -0,0 +1,43 @@
package cc.skysparkle.sparkledns
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Test
// The screens refresh once a second; a refresh that brings the same object has nothing to update
class RefreshTest {
@Test
fun logSnapshotIsReusedUntilTheLogChanges() {
QueryLog.clear()
val empty = QueryLog.snapshot()
assertSame(empty, QueryLog.snapshot())
QueryLog.add(DnsMessage.Question("example.com", 1), QueryStatus.OK, 10)
QueryLog.add(DnsMessage.Question("example.org", 28), QueryStatus.CACHED, 0)
val filled = QueryLog.snapshot()
assertNotSame(empty, filled)
assertEquals(listOf("example.org", "example.com"), filled.map { it.domain })
assertSame(filled, QueryLog.snapshot())
QueryLog.clear()
assertEquals(0, QueryLog.snapshot().size)
}
@Test
fun summaryIsReusedUntilSomethingChanges() {
val now = 1_000 * 3_600_000L
val first = StatsStore.summary(24, now)
assertSame(first, StatsStore.summary(24, now))
assertNotSame(first, StatsStore.summary(24 * 7, now))
StatsStore.record(QueryStatus.OK, 5, null, now)
val after = StatsStore.summary(24, now)
assertNotSame(first, after)
assertEquals(first.total + 1, after.total)
assertSame(after, StatsStore.summary(24, now))
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 342 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 504 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 584 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 575 KiB

After

Width:  |  Height:  |  Size: 667 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 513 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 391 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" rx="22" fill="#09090a"/><g transform="translate(7 7) scale(.86)" fill="#ededea"><path d="M51.70 6.81 L64.50 35.50 L93.19 48.30 L59.30 48.30 L51.70 40.70 Z"/><path transform="rotate(90 50 50)" d="M51.70 6.81 L64.50 35.50 L93.19 48.30 L59.30 48.30 L51.70 40.70 Z"/><path transform="rotate(180 50 50)" d="M51.70 6.81 L64.50 35.50 L93.19 48.30 L59.30 48.30 L51.70 40.70 Z"/><path transform="rotate(270 50 50)" d="M51.70 6.81 L64.50 35.50 L93.19 48.30 L59.30 48.30 L51.70 40.70 Z"/></g></svg>

After

Width:  |  Height:  |  Size: 581 B

+3 -3
View File
@@ -1,6 +1,6 @@
plugins { plugins {
id("com.android.application") version "9.2.1" apply false alias(libs.plugins.android.application) apply false
// Not applied to modules: only pins the Kotlin version used by AGP's built-in Kotlin // Not applied to modules: only pins the Kotlin version used by AGP's built-in Kotlin
id("org.jetbrains.kotlin.android") version "2.4.0" apply false alias(libs.plugins.kotlin.android) apply false
id("org.jetbrains.kotlin.plugin.compose") version "2.4.0" apply false alias(libs.plugins.kotlin.compose) apply false
} }
@@ -1,6 +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 • DNS läuft bei unerwarteten Paketen weiter; 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 • Anfragen erholen sich schneller nach einem WLAN-Mobilfunk-Wechsel und in langsamen Netzen
• Weniger Arbeit im Hintergrund: ausgeblendete Bildschirme werden nicht mehr aktualisiert • Weniger Hintergrundarbeit: ausgeblendete Bildschirme werden nicht mehr aktualisiert
• Blocklisten werden nur noch erneut geladen, wenn sie sich geändert haben • Blocklisten werden nur bei Änderungen neu geladen
• Schärfere App-Symbole, kleinere App • Schärfere App-Symbole, kleinere App
• Ein Doppeltipp auf „Verbinden“ verbindet nicht mehr doppelt; voller Speicher lässt die App nicht mehr abstürzen • Doppeltipp auf „Verbinden“ verbindet nicht doppelt; voller Speicher führt nicht mehr zum Absturz
@@ -1,2 +1,6 @@
• Neue gefüllte Symbole in der ganzen App (Material Symbols) • Neue gefüllte Symbole (Material Symbols)
• Symbole in Menüs, Einstellungen und auf Schaltflächen • Balkendiagramm für 24 Stunden oder 7 Tage, höher auf großen Bildschirmen
• Tablets: Inhalt mittig, auf breiten Bildschirmen zweispaltig
• Anteile der Konzerne erscheinen, sobald genug Daten da sind
• HaGeZi Pro direkt auf dem Startbildschirm einschalten
• Tippe auf den Server, um ihn zu wechseln
@@ -0,0 +1 @@
• Quad9 verbindet sich unter Android 14 und neuer jetzt über HTTP/3 (QUIC)
@@ -0,0 +1,2 @@
• Die letzte Aktivität zeigt eine Zeile pro Domain mit allen abgefragten Typen (A, AAAA, HTTPS) und der Anzahl der Anfragen
• Der Anteil der Konzerne nennt jetzt auch andere Websites, statt alle unter Andere zusammenzufassen
@@ -0,0 +1,6 @@
• Eine Benachrichtigung meldet, wenn der Schutz endet, die Serveradresse ungültig ist oder „Verbindungen ohne VPN blockieren“ den Server unerreichbar macht
• Bootstrap-Adressen funktionieren jetzt auch über HTTP/3
• Blocklistenregeln mit Pfad sperren nicht mehr ganze Websites
• Ausschalten über die Schnelleinstellung nur bei entsperrtem Handy
• App-Sprache in den Android-Einstellungen wählbar
• Aktualisierte Bibliotheken
@@ -0,0 +1 @@
• Der SkySparkle-Server nutzt jetzt die Adresse skysparkle.cc/dns-query
@@ -0,0 +1,2 @@
• Der SkySparkle-Server funktioniert jetzt mit einem persönlichen Schlüssel: Erstelle einen kostenlosen Schlüssel auf skysparkle.cc und gib ihn in den Einstellungen ein
• Neue Einführung beim ersten Start erklärt, wie du einen Schlüssel bekommst
@@ -1,2 +1,6 @@
• New filled icons throughout the app (Material Symbols) • New filled icons (Material Symbols)
• Icons in menus, Settings and on buttons • Bar chart for 24 hours or 7 days, taller on big screens
• Tablets: content stays centred, two columns on wide screens
• Company shares appear once there is enough data
• Turn on HaGeZi Pro right from Home
• Tap the server on Home to change it
@@ -0,0 +1 @@
• Quad9 now connects over HTTP/3 (QUIC) on Android 14 and newer
@@ -0,0 +1,2 @@
• Recent activity shows one row per domain with all requested types (A, AAAA, HTTPS) and the number of queries
• Company dominance names other sites instead of grouping them all as Other
@@ -0,0 +1,6 @@
• A notification tells you when protection stops, when the server address is invalid or when "Block connections without VPN" keeps the server unreachable
• Bootstrap addresses now also work over HTTP/3
• Blocklist rules with a path no longer block whole sites
• Turning protection off from the quick settings tile needs an unlocked phone
• App language can be set in Android settings
• Updated libraries
@@ -0,0 +1 @@
• The SkySparkle server now uses the address skysparkle.cc/dns-query
@@ -0,0 +1,2 @@
• The SkySparkle server now works with a personal key: create a free key at skysparkle.cc and enter it in Settings
• New first-launch guide that explains how to get a key
Binary file not shown.

Before

Width:  |  Height:  |  Size: 342 KiB

After

Width:  |  Height:  |  Size: 302 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 584 KiB

After

Width:  |  Height:  |  Size: 504 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 575 KiB

After

Width:  |  Height:  |  Size: 667 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 513 KiB

After

Width:  |  Height:  |  Size: 391 KiB

@@ -1,2 +1,6 @@
• アプリ全体のアイコンを塗りつぶしスタイルに一新(Material Symbols) • 塗りつぶしの新しいアイコン(Material Symbols)
• メニュー、設定、ボタンにアイコンを追加 • 24 時間/7 日間の棒グラフ。大きな画面では高く表示
• タブレット:コンテンツを中央に、広い画面では 2 列表示
• 企業の占有率はデータが十分に集まってから表示
• ホームから HaGeZi Pro をすぐにオン
• ホームのサーバーをタップして変更
@@ -0,0 +1 @@
• Android 14 以降では Quad9 に HTTP/3(QUIC)で接続
@@ -0,0 +1,2 @@
• 最近のアクティビティはドメインごとに 1 行で表示し、要求されたすべての種類(A、AAAA、HTTPS)とクエリ数を表示
• 企業の占有率で、その他のサイトもまとめずに名前で表示
@@ -0,0 +1,6 @@
• 保護が停止したとき、サーバーのアドレスが無効なとき、「VPN なしの接続をブロック」でサーバーに届かないときに通知
• Bootstrap アドレスが HTTP/3 でも使えるように
• パス付きのブロックリストのルールでサイト全体がブロックされなくなりました
• クイック設定タイルから保護をオフにするにはロック解除が必要に
• Android の設定でアプリの言語を選択可能に
• ライブラリを更新
@@ -0,0 +1 @@
• SkySparkle サーバーのアドレスが skysparkle.cc/dns-query に変わりました
@@ -0,0 +1,2 @@
• SkySparkle サーバーは個人キーで利用するようになりました。skysparkle.cc で無料のキーを作成し、設定に入力してください
• 初回起動時にキーの取得方法を説明するガイドを追加しました
@@ -1,2 +1,6 @@
• Naujos užpildytos piktogramos visoje programėlėje (Material Symbols) • Naujos užpildytos piktogramos (Material Symbols)
• Piktogramos meniu, nustatymuose ir mygtukuose • Stulpelinė 24 valandų arba 7 dienų diagrama, aukštesnė dideliuose ekranuose
• Planšetės: turinys centre, plačiuose ekranuose – du stulpeliai
• Įmonių dalys rodomos, kai surenkama pakankamai duomenų
• HaGeZi Pro įjungiamas tiesiai pradžios ekrane
• Bakstelėkite serverį pradžios ekrane, kad jį pakeistumėte
@@ -0,0 +1 @@
• Quad9 dabar jungiasi per HTTP/3 (QUIC) Android 14 ir naujesnėse versijose
@@ -0,0 +1,2 @@
• Naujausia veikla rodo vieną eilutę kiekvienam domenui su visais užklaustais tipais (A, AAAA, HTTPS) ir užklausų skaičiumi
• Įmonių dalyje kitos svetainės dabar rodomos pavadinimais, o ne sujungiamos į „Kitos“
@@ -0,0 +1,6 @@
• Pranešimas, kai apsauga išsijungia, serverio adresas netinkamas arba „Blokuoti ryšius be VPN“ neleidžia pasiekti serverio
• Bootstrap adresai dabar veikia ir per HTTP/3
• Blokavimo sąrašų taisyklės su keliu nebeblokuoja visų svetainių
• Išjungti apsaugą iš sparčiųjų nustatymų galima tik atrakinus telefoną
• Programėlės kalbą galima pasirinkti Android nustatymuose
• Atnaujintos bibliotekos
@@ -0,0 +1 @@
• SkySparkle serveris dabar naudoja adresą skysparkle.cc/dns-query
@@ -0,0 +1,2 @@
• SkySparkle serveris dabar veikia su asmeniniu raktu: susikurkite nemokamą raktą skysparkle.cc ir įveskite jį nustatymuose
• Naujas pirmojo paleidimo gidas paaiškina, kaip gauti raktą
@@ -1,2 +1,6 @@
• Новые залитые иконки во всём приложении (Material Symbols) • Новые залитые иконки (Material Symbols)
• Иконки в меню, настройках и на кнопках • Столбиковый график за 24 часа или 7 дней, выше на больших экранах
• Планшеты: контент по центру, на широких экранах две колонки
• Доли компаний появляются, когда данных достаточно
• HaGeZi Pro включается прямо с главной
• Нажмите на сервер на главной, чтобы сменить его
@@ -0,0 +1 @@
• Quad9 теперь подключается по HTTP/3 (QUIC) на Android 14 и новее
@@ -0,0 +1,2 @@
• Последняя активность показывает одну строку на домен со всеми запрошенными типами (A, AAAA, HTTPS) и числом запросов
• В «Доле компаний» остальные сайты показываются по названиям, а не объединяются в «Другие»
@@ -0,0 +1,6 @@
• Уведомление, если защита отключилась, адрес сервера неверный или «Блокировать соединения без VPN» не пускает к серверу
• Bootstrap-адреса теперь работают и по HTTP/3
• Правила блоклистов с путём больше не блокируют сайты целиком
• Выключить защиту с плитки можно только на разблокированном телефоне
• Язык приложения можно выбрать в настройках Android
• Обновлены библиотеки
@@ -0,0 +1 @@
• Сервер SkySparkle теперь работает по адресу skysparkle.cc/dns-query
@@ -0,0 +1,2 @@
• Сервер SkySparkle теперь работает по личному ключу: создайте бесплатный ключ на skysparkle.cc и введите его в настройках
• Новый гайд при первом запуске объясняет, как получить ключ
@@ -1,2 +1,6 @@
• 全应用采用新的填充图标(Material Symbols) • 全新填充图标(Material Symbols)
• 菜单、设置和按钮新增图标 • 24 小时或 7 天柱状图,大屏幕上更高
• 平板:内容居中,宽屏显示两栏
• 数据足够后才显示公司占比
• 在首页直接开启 HaGeZi Pro
• 点按首页上的服务器即可更换
@@ -0,0 +1 @@
• 在 Android 14 及更高版本上,Quad9 现通过 HTTP/3(QUIC)连接
@@ -0,0 +1,2 @@
• 最近活动按域名每行显示一条,包含所有请求类型(A、AAAA、HTTPS)及查询次数
• 公司占比中的其他网站现在按名称显示,不再全部归入“其他”

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