Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

Add-on: Ad Blocking

מקס חיים2b494772f5c1
diff --git a/addons/README.md b/addons/README.md
index c3f00031d..b2a834995 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -20,6 +20,7 @@ the core bigger or change how it behaves. You install an add-on only if you want
| [TV Static](tv-static/) | An off-the-air moment each time the screen turns on: the picture opens from a bright line, snow and hiss, colour bars or an old "no signal" screen for 3 to 10 s, then fades into what was on screen; the card sets style, sound and length | [@luyzfernando08](https://github.com/luyzfernando08) | Xiaomi Mi Box S (Android TV 9), Philco by Skyworth (Android TV 14) | foreground service (screen-on watcher), start at boot, display over other apps | <img src="tv-static/screenshot.jpg" width="240" alt="TV Static on a TV"> |
| [Brightness](brightness/) | Dims the picture below the TV's own minimum over every app (and the picture settings on Realtek TVs), with a warm night mode on a schedule and a one-press normal screen | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android 14) | overlay, foreground service, start at boot | <img src="brightness/screenshot.jpg" width="240" alt="Brightness on a TV"> |
| [Sleep Timer](sleep-timer/) | A sleep timer: 15 to 120 minutes, a one-minute countdown over what is playing with "15 more minutes", then standby; over HDMI-CEC the TV turns off with the box | [@luyzfernando08](https://github.com/luyzfernando08) | Xiaomi Mi Box S (Android TV 9) | accessibility (lock-screen action only), display over other apps, exact alarms | <img src="sleep-timer/screenshot.jpg" width="240" alt="Sleep Timer on a TV"> |
+| [Ad Blocking](ad-blocking/) | Your Pi-hole (6 or 5) or AdGuard Home on the TV: today's queries and blocked share, and one OK to pause blocking for five minutes | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android 14) | `INTERNET` (your blocker only) | <img src="ad-blocking/screenshot.jpg" width="240" alt="Ad Blocking on a TV"> |
A widget, an info tile, a storage or smart-home card: if it can live as its own small app, it can live
here. See the rules below.
diff --git a/addons/ad-blocking/.gitignore b/addons/ad-blocking/.gitignore
new file mode 100644
index 000000000..a7e04a21b
--- /dev/null
+++ b/addons/ad-blocking/.gitignore
@@ -0,0 +1,4 @@
+.gradle/
+build/
+app/build/
+local.properties
diff --git a/addons/ad-blocking/README.md b/addons/ad-blocking/README.md
new file mode 100644
index 000000000..f52170874
--- /dev/null
+++ b/addons/ad-blocking/README.md
@@ -0,0 +1,78 @@
+# Ad Blocking
+
+Your network's ad blocker on the TV: today's queries, how many were blocked and the share, from
+[Pi-hole](https://pi-hole.net) (version 6, or version 5) or [AdGuard Home](https://adguard.com/adguard-home/overview.html),
+and one OK to pause blocking for five minutes when a site or app won't work. A community add-on, not made by or
+affiliated with either project. For the [Clean Your TV](../../README.md) launcher it declares a
+[module card](../../docs/modules.md): once you answer **Show card** its tile reads "Ad Blocking" with a red glow.
+On any other Android TV home it is an ordinary app.
+
+![Ad Blocking on a TV, with demo data](screenshot.jpg)
+
+| Row | What it does |
+|---|---|
+| **Blocking** | On or Paused. OK pauses blocking for 5 minutes, or turns it back on. |
+| **Queries today**, **Blocked today**, **Blocked share** | The server's own counters. |
+| **Blocker** | Pi-hole or AdGuard Home; OK switches. |
+| **Address**, **Username** (AdGuard Home), **Password** | The connection. |
+
+It reads the server every 30 seconds while the screen is open, and nothing when it is closed.
+
+## How it talks to each server
+
+- **Pi-hole 6:** `POST /api/auth` with the password (or an app password, needed when two-factor login is on), then
+ `GET /api/stats/summary` and `GET /api/dns/blocking` with the session id, `POST /api/dns/blocking` to pause,
+ and `DELETE /api/auth` at the end of every round, so it never holds one of Pi-hole's limited sessions. A
+ Pi-hole without a password needs none.
+- **Pi-hole 5** (when `/api/auth` isn't there): `/admin/api.php?summaryRaw&auth=<API token>`, and `disable=300` or
+ `enable` to pause. The API token is under Settings, API in Pi-hole's web page.
+- **AdGuard Home:** `GET /control/stats` and `GET /control/status` with HTTP basic authentication, and
+ `POST /control/protection` to pause.
+
+## Setup
+
+Open the app and fill in the address and login with the TV's keyboard, or push them from a computer as a file so
+the password is never typed on the TV or put on a command line:
+
+```bash
+echo '{"kind": "pihole", "url": "http://192.168.1.2", "password": "..."}' > backup/ad-blocking.json
+# AdGuard Home: {"kind": "adguard", "url": "http://192.168.1.2:3000", "user": "admin", "password": "..."}
+TV_HOST=<tv ip> addons/ad-blocking/install.sh backup/ad-blocking.json
+```
+
+The app takes the file into its own storage and deletes it. Keep the file outside the repo (`backup/` is
+git-ignored).
+
+## Permissions
+
+| Permission | Why |
+|---|---|
+| `INTERNET` | Your Pi-hole or AdGuard Home, and nothing else: no telemetry, no update checks, no ads. |
+
+Plain `http://` is allowed for the home network (`res/xml/network.xml`). The password stays in the app's own
+storage (backups are off) and is sent only to the address you entered. `ConfigProvider` takes a pushed file and
+only the ADB shell can use it (it requires `WRITE_SECURE_SETTINGS`). No background service, accounts or libraries.
+
+## Build and install
+
+JDK 17 and Android SDK platform 34 with build-tools 34.0.0, as for the launcher:
+
+```bash
+TV_HOST=<tv ip> addons/ad-blocking/install.sh [config.json]
+```
+
+To build only: `cd addons/ad-blocking && ./gradlew assembleRelease`; the JVM tests run with
+`./gradlew testReleaseUnitTest`.
+
+## Limits
+
+- **Self-signed HTTPS** certificates are refused. Use `http://` on the home network.
+- **Today** is the server's own window: Pi-hole counts the last 24 hours, AdGuard Home its statistics period.
+
+## Tested on
+
+MOKA R8G (Android 14), on a home app that implements the module-card spec, against a stand-in Pi-hole 6 on the home network answering with the documented response shapes: the config pushed through `ConfigProvider`, login, the numbers, pause and resume, and the session closed after each round. **Not yet tried against a real Pi-hole or AdGuard Home:** the author has neither; reports are welcome. Pi-hole 5 and AdGuard Home are covered by JVM tests against their documented responses and local stand-ins. The screenshot shows that demo data, with the address blurred.
+
+## Maintainer
+
+[@maxhayim](https://github.com/maxhayim)
diff --git a/addons/ad-blocking/app/build.gradle b/addons/ad-blocking/app/build.gradle
new file mode 100644
index 000000000..1213ac6ea
--- /dev/null
+++ b/addons/ad-blocking/app/build.gradle
@@ -0,0 +1,41 @@
+plugins {
+ id 'com.android.application'
+}
+
+android {
+ namespace 'io.github.maxhayim.adblocking'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'io.github.maxhayim.adblocking'
+ minSdk 26
+ targetSdk 34
+ versionCode 1
+ versionName '0.1'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled true
+ shrinkResources true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ // Sideloaded over ADB, never published: signed with the debug key, like the launcher.
+ signingConfig signingConfigs.debug
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+
+ testOptions {
+ unitTests.returnDefaultValues = true
+ }
+}
+
+dependencies {
+ // No libraries in the APK. Test only: plain JVM tests in src/test; org.json because android.jar's copy is a stub there.
+ testImplementation 'junit:junit:4.13.2'
+ testImplementation 'org.json:json:20231013'
+}
diff --git a/addons/ad-blocking/app/proguard-rules.pro b/addons/ad-blocking/app/proguard-rules.pro
new file mode 100644
index 000000000..a4435d69a
--- /dev/null
+++ b/addons/ad-blocking/app/proguard-rules.pro
@@ -0,0 +1,2 @@
+# Keep class and method names: readable stack traces matter more than the last few KB in a sideloaded app.
+-dontobfuscate
diff --git a/addons/ad-blocking/app/src/main/AndroidManifest.xml b/addons/ad-blocking/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..cafceba8e
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/AndroidManifest.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-feature android:name="android.software.leanback" android:required="false" />
+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
+
+ <!-- Your Pi-hole or AdGuard Home, and nothing else. -->
+ <uses-permission android:name="android.permission.INTERNET" />
+
+ <application
+ android:allowBackup="false"
+ android:banner="@drawable/banner"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:networkSecurityConfig="@xml/network"
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar">
+
+ <activity
+ android:name=".MainActivity"
+ android:exported="true"
+ android:launchMode="singleTask"
+ android:windowSoftInputMode="adjustPan">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="com.gathin.tvhome.category.DOCK_CARD" />
+ </intent-filter>
+ <meta-data android:name="com.gathin.tvhome.card" android:resource="@xml/module_card" />
+ </activity>
+
+ <!-- install.sh writes the server address and password here with `content write`, so the password never sits on
+ a command line. Write-only, one file name, and only the ADB shell may call it. -->
+ <provider
+ android:name=".ConfigProvider"
+ android:authorities="${applicationId}.config"
+ android:exported="true"
+ android:permission="android.permission.WRITE_SECURE_SETTINGS" />
+ </application>
+</manifest>
diff --git a/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Blocker.java b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Blocker.java
new file mode 100644
index 000000000..504bb34fe
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Blocker.java
@@ -0,0 +1,146 @@
+package io.github.maxhayim.adblocking;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.Locale;
+
+/**
+ * The three APIs this app reads, with no Android types and no network, so the JVM tests cover them against the
+ * documented responses: Pi-hole v6 (https://docs.pi-hole.net/api/), Pi-hole v5 (/admin/api.php) and AdGuard Home
+ * (https://github.com/AdguardTeam/AdGuardHome/tree/master/openapi).
+ */
+final class Blocker {
+ /** How long Pause stops blocking, in seconds. */
+ static final int PAUSE_SECONDS = 300;
+
+ enum Kind { PIHOLE, ADGUARD }
+
+ /** Today's numbers and whether blocking is on. */
+ static final class Stats {
+ final long queries;
+ final long blocked;
+ final double percent;
+ final boolean enabled;
+
+ Stats(long queries, long blocked, double percent, boolean enabled) {
+ this.queries = queries;
+ this.blocked = blocked;
+ this.percent = percent;
+ this.enabled = enabled;
+ }
+ }
+
+ private Blocker() {
+ }
+
+ // ---------------------------------------------------------------- Pi-hole v6
+
+ static String piholeLoginBody(String password) {
+ return "{\"password\":" + JSONObject.quote(password == null ? "" : password) + "}";
+ }
+
+ /** The session id from POST /api/auth, "" when the Pi-hole has no password, null when refused. */
+ static String piholeSid(String json) throws JSONException {
+ JSONObject s = new JSONObject(json).optJSONObject("session");
+ if (s == null || !s.optBoolean("valid", false)) return null;
+ String sid = s.optString("sid", "");
+ return "null".equals(sid) ? "" : sid;
+ }
+
+ /** GET /api/stats/summary and GET /api/dns/blocking, together. */
+ static Stats pihole6(String summary, String blocking) throws JSONException {
+ JSONObject q = new JSONObject(summary).getJSONObject("queries");
+ long total = q.optLong("total", 0), blocked = q.optLong("blocked", 0);
+ double pct = q.has("percent_blocked") ? q.optDouble("percent_blocked", 0) : percent(blocked, total);
+ boolean on = "enabled".equals(new JSONObject(blocking).optString("blocking", ""));
+ return new Stats(total, blocked, pct, on);
+ }
+
+ static String piholePauseBody(boolean pause) {
+ return "{\"blocking\":" + !pause + ",\"timer\":" + (pause ? String.valueOf(PAUSE_SECONDS) : "null") + "}";
+ }
+
+ // ---------------------------------------------------------------- Pi-hole v5
+
+ static String pihole5Summary(String token) {
+ return "/admin/api.php?summaryRaw&auth=" + urlEncode(token);
+ }
+
+ static String pihole5Pause(boolean pause, String token) {
+ return "/admin/api.php?" + (pause ? "disable=" + PAUSE_SECONDS : "enable") + "&auth=" + urlEncode(token);
+ }
+
+ static Stats pihole5(String json) throws JSONException {
+ JSONObject o = new JSONObject(json);
+ if (!o.has("dns_queries_today")) throw new JSONException("not a Pi-hole v5 summary (wrong API token?)");
+ long total = o.optLong("dns_queries_today", 0), blocked = o.optLong("ads_blocked_today", 0);
+ return new Stats(total, blocked, o.optDouble("ads_percentage_today", percent(blocked, total)),
+ "enabled".equals(o.optString("status", "")));
+ }
+
+ // ---------------------------------------------------------------- AdGuard Home
+
+ static String basicAuth(String user, String password) {
+ String raw = (user == null ? "" : user) + ":" + (password == null ? "" : password);
+ return "Basic " + Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
+ }
+
+ /** GET /control/stats and GET /control/status, together. */
+ static Stats adguard(String stats, String status) throws JSONException {
+ JSONObject s = new JSONObject(stats);
+ long total = s.optLong("num_dns_queries", 0), blocked = s.optLong("num_blocked_filtering", 0);
+ return new Stats(total, blocked, percent(blocked, total), new JSONObject(status).optBoolean("protection_enabled", false));
+ }
+
+ static String adguardPauseBody(boolean pause) {
+ return "{\"enabled\":" + !pause + (pause ? ",\"duration\":" + PAUSE_SECONDS * 1000L : "") + "}";
+ }
+
+ // ---------------------------------------------------------------- wording
+
+ static double percent(long part, long total) {
+ return total <= 0 ? 0 : part * 100.0 / total;
+ }
+
+ static String count(long n) {
+ return String.format(Locale.US, "%,d", n);
+ }
+
+ static String pct(double p) {
+ return String.format(Locale.ROOT, "%.1f %%", p);
+ }
+
+ static String problem(int code, Kind kind) {
+ if (code == 401 || code == 403) return kind == Kind.ADGUARD ? "AdGuard Home refused the username or password."
+ : "Pi-hole refused the password (use an app password if two-factor login is on).";
+ if (code == 404) return "That address answers, but not as " + (kind == Kind.ADGUARD ? "AdGuard Home." : "Pi-hole.");
+ if (code <= 0) return "Can't reach the server at that address.";
+ return "The server answered with error " + code + ".";
+ }
+
+ /** "http://192.168.1.2" from what was typed: a scheme added when missing, trailing slashes and /admin dropped. */
+ static String normalizeUrl(String typed) {
+ if (typed == null) return "";
+ String u = typed.trim();
+ if (u.isEmpty()) return "";
+ if (!u.contains("://")) u = "http://" + u;
+ while (u.endsWith("/")) u = u.substring(0, u.length() - 1);
+ if (u.endsWith("/admin")) u = u.substring(0, u.length() - 6);
+ return u;
+ }
+
+ static boolean validUrl(String url) {
+ return url.matches("https?://[^\\s/?#]+(:[0-9]{1,5})?(/[^\\s?#]*)?");
+ }
+
+ private static String urlEncode(String s) {
+ try {
+ return java.net.URLEncoder.encode(s == null ? "" : s, "UTF-8");
+ } catch (java.io.UnsupportedEncodingException e) {
+ return "";
+ }
+ }
+}
diff --git a/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Config.java b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Config.java
new file mode 100644
index 000000000..afa447e4a
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Config.java
@@ -0,0 +1,75 @@
+package io.github.maxhayim.adblocking;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+
+import org.json.JSONObject;
+
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+
+/**
+ * Which blocker, its address and login, in the app's own storage (backups are off). They arrive typed on the TV,
+ * or as config.json pushed by install.sh, which is read once and deleted.
+ */
+final class Config {
+ static final String PUSHED = "config.json";
+
+ final Blocker.Kind kind;
+ final String url;
+ /** AdGuard Home only. */
+ final String user;
+ /** Pi-hole v6: the web or app password. Pi-hole v5: the API token. AdGuard Home: the password. */
+ final String password;
+
+ Config(Blocker.Kind kind, String url, String user, String password) {
+ this.kind = kind;
+ this.url = url;
+ this.user = user;
+ this.password = password;
+ }
+
+ /** A Pi-hole may have no password at all; AdGuard Home always has a login. */
+ boolean complete() {
+ return !url.isEmpty() && (kind == Blocker.Kind.PIHOLE || !user.isEmpty());
+ }
+
+ private static SharedPreferences prefs(Context c) {
+ return c.getSharedPreferences("server", Context.MODE_PRIVATE);
+ }
+
+ static Config load(Context c) {
+ SharedPreferences p = prefs(c);
+ Blocker.Kind k;
+ try {
+ k = Blocker.Kind.valueOf(p.getString("kind", "PIHOLE"));
+ } catch (IllegalArgumentException e) {
+ k = Blocker.Kind.PIHOLE;
+ }
+ return new Config(k, p.getString("url", ""), p.getString("user", ""), p.getString("password", ""));
+ }
+
+ static void save(Context c, String key, String value) {
+ if ("url".equals(key)) value = Blocker.normalizeUrl(value);
+ prefs(c).edit().putString(key, value == null ? "" : value.trim()).apply();
+ }
+
+ /** Takes a pushed config.json ({"kind": "pihole"|"adguard", "url", "user", "password"}), and deletes it. */
+ static boolean importPushed(Context c) {
+ File dir = c.getExternalFilesDir(null);
+ File f = dir == null ? null : new File(dir, PUSHED);
+ if (f == null || !f.isFile()) return false;
+ try {
+ JSONObject o = new JSONObject(new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8));
+ if (o.has("kind")) save(c, "kind", "adguard".equalsIgnoreCase(o.optString("kind")) ? "ADGUARD" : "PIHOLE");
+ for (String k : new String[]{"url", "user", "password"}) if (o.has(k)) save(c, k, o.optString(k));
+ return true;
+ } catch (Exception e) {
+ return false;
+ } finally {
+ //noinspection ResultOfMethodCallIgnored
+ f.delete();
+ }
+ }
+}
diff --git a/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/ConfigProvider.java b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/ConfigProvider.java
new file mode 100644
index 000000000..98a616333
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/ConfigProvider.java
@@ -0,0 +1,41 @@
+package io.github.maxhayim.adblocking;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.ParcelFileDescriptor;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+
+/**
+ * install.sh writes config.json here with `content write`, so the password travels as a file, never on a command
+ * line. Write-only, one file name, and only the ADB shell can call it (WRITE_SECURE_SETTINGS on the provider).
+ * The file is taken into the app's storage and deleted once it is closed.
+ */
+public class ConfigProvider extends ContentProvider {
+ @Override
+ public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
+ if (!mode.contains("w") || !Config.PUSHED.equals(uri.getLastPathSegment())) throw new FileNotFoundException(uri.toString());
+ File dir = getContext().getExternalFilesDir(null);
+ if (dir == null || (!dir.isDirectory() && !dir.mkdirs())) throw new FileNotFoundException("no files folder");
+ try {
+ return ParcelFileDescriptor.open(new File(dir, Config.PUSHED),
+ ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE,
+ new Handler(Looper.getMainLooper()),
+ e -> Config.importPushed(getContext()));
+ } catch (java.io.IOException e) {
+ throw new FileNotFoundException(e.getMessage());
+ }
+ }
+
+ @Override public boolean onCreate() { return true; }
+ @Override public String getType(Uri uri) { return null; }
+ @Override public Cursor query(Uri uri, String[] p, String s, String[] a, String o) { return null; }
+ @Override public Uri insert(Uri uri, ContentValues values) { return null; }
+ @Override public int update(Uri uri, ContentValues v, String s, String[] a) { return 0; }
+ @Override public int delete(Uri uri, String s, String[] a) { return 0; }
+}
diff --git a/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Http.java b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Http.java
new file mode 100644
index 000000000..6e8f9bfa3
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Http.java
@@ -0,0 +1,78 @@
+package io.github.maxhayim.adblocking;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+
+/** Plain HTTP to the blocker. Blocking: call it off the main thread. */
+final class Http {
+ static final class Reply {
+ /** 0 when the server couldn't be reached. */
+ final int code;
+ final String body;
+
+ Reply(int code, String body) {
+ this.code = code;
+ this.body = body;
+ }
+
+ boolean ok() {
+ return code >= 200 && code < 300;
+ }
+ }
+
+ private static final int TIMEOUT_MS = 6000;
+ private static final int MAX_BODY = 1024 * 1024;
+
+ private Http() {
+ }
+
+ /** header is "Name: value" or null. */
+ static Reply request(String method, String url, String body, String header) {
+ HttpURLConnection c = null;
+ try {
+ c = (HttpURLConnection) new URL(url).openConnection();
+ c.setRequestMethod(method);
+ c.setConnectTimeout(TIMEOUT_MS);
+ c.setReadTimeout(TIMEOUT_MS);
+ c.setInstanceFollowRedirects(false);
+ c.setRequestProperty("Accept", "application/json");
+ if (header != null) {
+ int colon = header.indexOf(':');
+ c.setRequestProperty(header.substring(0, colon).trim(), header.substring(colon + 1).trim());
+ }
+ if (body != null) {
+ c.setDoOutput(true);
+ c.setRequestProperty("Content-Type", "application/json");
+ byte[] b = body.getBytes(StandardCharsets.UTF_8);
+ c.setFixedLengthStreamingMode(b.length);
+ try (OutputStream out = c.getOutputStream()) {
+ out.write(b);
+ }
+ }
+ int code = c.getResponseCode();
+ InputStream in = code >= 400 ? c.getErrorStream() : c.getInputStream();
+ return new Reply(code, in == null ? "" : read(in));
+ } catch (IOException | RuntimeException e) {
+ return new Reply(0, String.valueOf(e.getMessage()));
+ } finally {
+ if (c != null) c.disconnect();
+ }
+ }
+
+ private static String read(InputStream in) throws IOException {
+ try (InputStream s = in) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buf = new byte[8192];
+ for (int n; (n = s.read(buf)) > 0; ) {
+ out.write(buf, 0, n);
+ if (out.size() > MAX_BODY) break;
+ }
+ return out.toString(StandardCharsets.UTF_8.name());
+ }
+ }
+}
diff --git a/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/MainActivity.java b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/MainActivity.java
new file mode 100644
index 000000000..3371b128b
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/MainActivity.java
@@ -0,0 +1,209 @@
+package io.github.maxhayim.adblocking;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.text.InputType;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * The tile and module card open this: today's queries and blocked share from your Pi-hole or AdGuard Home, and
+ * one OK to pause blocking for five minutes when a site won't work. It reads the server only while this screen
+ * is open.
+ */
+public class MainActivity extends Activity {
+ private static final long REFRESH_MS = 30_000;
+
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private final ExecutorService net = Executors.newSingleThreadExecutor();
+ private LinearLayout rows;
+ private TextView status;
+ private Config config;
+ private Server.Result last;
+ private final Runnable refresh = new Runnable() {
+ @Override
+ public void run() {
+ fetch(null);
+ main.postDelayed(this, REFRESH_MS);
+ }
+ };
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ LinearLayout page = new LinearLayout(this);
+ page.setOrientation(LinearLayout.VERTICAL);
+ page.setBackgroundColor(0xFF0D1117);
+ page.setPadding(px(48), px(32), px(48), px(24));
+ TextView title = new TextView(this);
+ title.setText(R.string.app_name);
+ title.setTextSize(28);
+ title.setTextColor(0xFFFFFFFF);
+ status = new TextView(this);
+ status.setTextSize(15);
+ status.setTextColor(0xFF8B949E);
+ status.setPadding(0, 0, 0, px(16));
+ page.addView(title);
+ page.addView(status);
+ ScrollView scroll = new ScrollView(this);
+ rows = new LinearLayout(this);
+ rows.setOrientation(LinearLayout.VERTICAL);
+ scroll.addView(rows);
+ page.addView(scroll, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
+ setContentView(page);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ Config.importPushed(this);
+ reload();
+ }
+
+ @Override
+ protected void onPause() {
+ main.removeCallbacks(refresh);
+ super.onPause();
+ }
+
+ @Override
+ protected void onDestroy() {
+ net.shutdownNow();
+ super.onDestroy();
+ }
+
+ /** Reads the numbers; pause non-null pauses (true) or resumes first. */
+ private void fetch(Boolean pause) {
+ Config c = config;
+ if (!c.complete()) return;
+ net.execute(() -> {
+ Server s = new Server(c);
+ Server.Result r = pause == null ? s.stats() : s.pause(pause);
+ main.post(() -> {
+ if (isFinishing()) return;
+ last = r;
+ build();
+ });
+ });
+ }
+
+ private void reload() {
+ config = Config.load(this);
+ last = null;
+ main.removeCallbacks(refresh);
+ build();
+ if (config.complete()) main.post(refresh);
+ }
+
+ /** Rebuilds the list; focus stays on the row it was on. */
+ private void build() {
+ int focused = rows.indexOfChild(rows.getFocusedChild());
+ rows.removeAllViews();
+ boolean adguard = config.kind == Blocker.Kind.ADGUARD;
+ String server = adguard ? "AdGuard Home" : "Pi-hole";
+ Row first = null;
+ if (!config.complete()) {
+ status.setText("Add your " + server + "'s address" + (adguard ? " and login." : " (and password, if it has one)."));
+ } else if (last == null) {
+ status.setText("Reading " + server + "…");
+ } else if (last.problem != null) {
+ status.setText(last.problem);
+ } else {
+ Blocker.Stats st = last.stats;
+ status.setText(server + (st.enabled ? ": blocking is on." : ": blocking is paused."));
+ first = add(new Row(this, "Blocking", st.enabled ? "OK pauses it for 5 minutes, for a site that won't work."
+ : "OK turns it back on now.", false, () -> fetch(st.enabled), null));
+ first.setValue(st.enabled ? "On" : "Paused");
+ add(new Row(this, "Queries today", null, false, null, null)).setValue(Blocker.count(st.queries));
+ add(new Row(this, "Blocked today", null, false, null, null)).setValue(Blocker.count(st.blocked));
+ Row share = add(new Row(this, "Blocked share", null, true, null, null));
+ share.setValue(Blocker.pct(st.percent));
+ share.setBar((float) Math.min(1, st.percent / 100));
+ }
+ heading("Connection");
+ Row kind = add(new Row(this, "Blocker", null, false, () -> {
+ Config.save(this, "kind", adguard ? "PIHOLE" : "ADGUARD");
+ reload();
+ }, null));
+ kind.setValue(server);
+ Row url = add(new Row(this, "Address", adguard ? "For example http://192.168.1.2:3000" : "For example http://192.168.1.2",
+ false, () -> edit("Address", config.url.isEmpty() ? "http://" : config.url,
+ InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI, v -> {
+ String u = Blocker.normalizeUrl(v);
+ if (!u.isEmpty() && !Blocker.validUrl(u)) {
+ status.setText("That doesn't look like an address: " + u);
+ return;
+ }
+ Config.save(this, "url", u);
+ reload();
+ }), null));
+ url.setValue(config.url.isEmpty() ? "Not set" : config.url);
+ if (adguard) {
+ Row user = add(new Row(this, "Username", null, false, () -> edit("Username", config.user,
+ InputType.TYPE_CLASS_TEXT, v -> {
+ Config.save(this, "user", v);
+ reload();
+ }), null));
+ user.setValue(config.user.isEmpty() ? "Not set" : config.user);
+ }
+ Row pw = add(new Row(this, adguard ? "Password" : "Password or API token",
+ adguard ? "Stored on this TV only." : "Pi-hole 6: the web or app password. Pi-hole 5: the API token. Stored on this TV only.",
+ false, () -> edit("Password", "", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD, v -> {
+ Config.save(this, "password", v);
+ reload();
+ }), null));
+ pw.setValue(config.password.isEmpty() ? "None" : "Set");
+
+ View keep = focused >= 0 && focused < rows.getChildCount() ? rows.getChildAt(focused) : null;
+ if (keep != null && keep.isFocusable()) keep.requestFocus();
+ else if (first != null) first.requestFocus();
+ else url.requestFocus();
+ }
+
+ private interface Done {
+ void done(String value);
+ }
+
+ private void edit(String title, String start, int type, Done done) {
+ EditText field = new EditText(this);
+ field.setInputType(type);
+ field.setSingleLine(true);
+ field.setText(start);
+ field.setSelection(start.length());
+ new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_Alert)
+ .setTitle(title)
+ .setView(field)
+ .setPositiveButton("Save", (d, w) -> done.done(field.getText().toString()))
+ .setNegativeButton("Cancel", null)
+ .show();
+ field.requestFocus();
+ }
+
+ private void heading(String text) {
+ TextView h = new TextView(this);
+ h.setText(text);
+ h.setTextSize(13);
+ h.setTextColor(0xFFE84855);
+ h.setPadding(px(16), px(18), 0, px(4));
+ rows.addView(h);
+ }
+
+ private Row add(Row r) {
+ rows.addView(r, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ return r;
+ }
+
+ private int px(int dp) {
+ return Math.round(dp * getResources().getDisplayMetrics().density);
+ }
+}
diff --git a/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Row.java b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Row.java
new file mode 100644
index 000000000..d282e1cc0
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Row.java
@@ -0,0 +1,103 @@
+package io.github.maxhayim.adblocking;
+
+import android.content.Context;
+import android.view.Gravity;
+import android.view.KeyEvent;
+import android.view.View;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+/**
+ * One settings row: a name with a line saying what it does on the left, its value on the right. OK runs onClick;
+ * Left and Right run onStep with -1 or +1, held keys repeat. A row with a bar draws its value as a slider.
+ */
+final class Row extends LinearLayout {
+ interface Step {
+ void step(int direction);
+ }
+
+ private final TextView value;
+ private final TextView desc;
+ private final View fill;
+ private final View rest;
+
+ Row(Context context, String name, String description, boolean bar, Runnable onClick, Step onStep) {
+ super(context);
+ float dp = context.getResources().getDisplayMetrics().density;
+ setOrientation(HORIZONTAL);
+ setGravity(Gravity.CENTER_VERTICAL);
+ int ph = Math.round(16 * dp), pv = Math.round(10 * dp);
+ setPadding(ph, pv, ph, pv);
+ setBackgroundResource(R.drawable.row_background);
+ boolean active = onClick != null || onStep != null;
+ setFocusable(active);
+ setClickable(onClick != null);
+ if (onClick != null) setOnClickListener(v -> onClick.run());
+ if (onStep != null) {
+ setOnKeyListener((v, code, e) -> {
+ if (code != KeyEvent.KEYCODE_DPAD_LEFT && code != KeyEvent.KEYCODE_DPAD_RIGHT) return false;
+ if (e.getAction() == KeyEvent.ACTION_DOWN) onStep.step(code == KeyEvent.KEYCODE_DPAD_LEFT ? -1 : 1);
+ return true;
+ });
+ }
+
+ LinearLayout text = new LinearLayout(context);
+ text.setOrientation(VERTICAL);
+ TextView label = new TextView(context);
+ label.setText(name);
+ label.setTextSize(17);
+ label.setTextColor(0xFFFFFFFF);
+ text.addView(label);
+ desc = new TextView(context);
+ desc.setTextSize(12);
+ desc.setTextColor(0xFF8B949E);
+ desc.setPadding(0, Math.round(2 * dp), Math.round(16 * dp), 0);
+ text.addView(desc);
+ setDetail(description);
+ addView(text, new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f));
+
+ if (bar) {
+ LinearLayout track = new LinearLayout(context);
+ track.setOrientation(HORIZONTAL);
+ track.setBackgroundColor(0x33FFFFFF);
+ fill = new View(context);
+ fill.setBackgroundColor(0xFFE84855);
+ rest = new View(context);
+ track.addView(fill, new LayoutParams(0, LayoutParams.MATCH_PARENT, 0f));
+ track.addView(rest, new LayoutParams(0, LayoutParams.MATCH_PARENT, 1f));
+ FrameLayout holder = new FrameLayout(context);
+ holder.addView(track, new FrameLayout.LayoutParams(Math.round(200 * dp), Math.round(6 * dp), Gravity.CENTER_VERTICAL));
+ LayoutParams hp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
+ hp.rightMargin = Math.round(16 * dp);
+ addView(holder, hp);
+ } else {
+ fill = rest = null;
+ }
+
+ value = new TextView(context);
+ value.setTextSize(17);
+ value.setTextColor(0xFFC9D1D9);
+ value.setGravity(Gravity.END);
+ value.setMinWidth(Math.round(90 * dp));
+ addView(value, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
+ }
+
+ void setDetail(String d) {
+ desc.setText(d == null ? "" : d);
+ desc.setVisibility(d == null || d.isEmpty() ? GONE : VISIBLE);
+ }
+
+ void setValue(String v) {
+ value.setText(v);
+ }
+
+ /** The slider's position, 0 to 1. */
+ void setBar(float fraction) {
+ if (fill == null) return;
+ float f = Math.max(0f, Math.min(1f, fraction));
+ ((LayoutParams) fill.getLayoutParams()).weight = f;
+ ((LayoutParams) rest.getLayoutParams()).weight = 1f - f;
+ fill.requestLayout();
+ }
+}
diff --git a/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Server.java b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Server.java
new file mode 100644
index 000000000..8f1b8306b
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/java/io/github/maxhayim/adblocking/Server.java
@@ -0,0 +1,99 @@
+package io.github.maxhayim.adblocking;
+
+import org.json.JSONException;
+
+/**
+ * One round with the blocker: today's numbers, or pausing and resuming. Pi-hole is tried as v6 first (a session
+ * that is closed again straight after, so it never holds one of Pi-hole's limited seats) and as v5 when the v6
+ * API isn't there. Blocking: call it off the main thread.
+ */
+final class Server {
+ /** Stats, or the problem to show. */
+ static final class Result {
+ final Blocker.Stats stats;
+ final String problem;
+
+ Result(Blocker.Stats stats, String problem) {
+ this.stats = stats;
+ this.problem = problem;
+ }
+ }
+
+ private final Config c;
+
+ Server(Config c) {
+ this.c = c;
+ }
+
+ Result stats() {
+ return c.kind == Blocker.Kind.ADGUARD ? adguard(null) : pihole(null);
+ }
+
+ /** Pauses (true) or resumes blocking, then reads the numbers again. */
+ Result pause(boolean pause) {
+ return c.kind == Blocker.Kind.ADGUARD ? adguard(pause) : pihole(pause);
+ }
+
+ private Result adguard(Boolean pause) {
+ String auth = "Authorization: " + Blocker.basicAuth(c.user, c.password);
+ if (pause != null) {
+ Http.Reply r = Http.request("POST", c.url + "/control/protection", Blocker.adguardPauseBody(pause), auth);
+ if (!r.ok()) return fail(r.code);
+ }
+ Http.Reply stats = Http.request("GET", c.url + "/control/stats", null, auth);
+ if (!stats.ok()) return fail(stats.code);
+ Http.Reply status = Http.request("GET", c.url + "/control/status", null, auth);
+ if (!status.ok()) return fail(status.code);
+ try {
+ return new Result(Blocker.adguard(stats.body, status.body), null);
+ } catch (JSONException e) {
+ return new Result(null, "That address answers, but not as AdGuard Home.");
+ }
+ }
+
+ private Result pihole(Boolean pause) {
+ Http.Reply login = Http.request("POST", c.url + "/api/auth", Blocker.piholeLoginBody(c.password), null);
+ if (login.code == 404) return pihole5(pause);
+ String sid;
+ try {
+ sid = login.code == 401 ? null : Blocker.piholeSid(login.body);
+ } catch (JSONException e) {
+ return pihole5(pause);
+ }
+ if (sid == null) return fail(login.code == 0 ? 0 : 401);
+ String header = sid.isEmpty() ? null : "X-FTL-SID: " + sid;
+ try {
+ if (pause != null) {
+ Http.Reply r = Http.request("POST", c.url + "/api/dns/blocking", Blocker.piholePauseBody(pause), header);
+ if (!r.ok()) return fail(r.code);
+ }
+ Http.Reply summary = Http.request("GET", c.url + "/api/stats/summary", null, header);
+ if (!summary.ok()) return fail(summary.code);
+ Http.Reply blocking = Http.request("GET", c.url + "/api/dns/blocking", null, header);
+ if (!blocking.ok()) return fail(blocking.code);
+ return new Result(Blocker.pihole6(summary.body, blocking.body), null);
+ } catch (JSONException e) {
+ return new Result(null, "That address answers, but not as Pi-hole.");
+ } finally {
+ if (header != null) Http.request("DELETE", c.url + "/api/auth", null, header);
+ }
+ }
+
+ private Result pihole5(Boolean pause) {
+ if (pause != null) {
+ Http.Reply r = Http.request("GET", c.url + Blocker.pihole5Pause(pause, c.password), null, null);
+ if (!r.ok()) return fail(r.code);
+ }
+ Http.Reply r = Http.request("GET", c.url + Blocker.pihole5Summary(c.password), null, null);
+ if (!r.ok()) return fail(r.code);
+ try {
+ return new Result(Blocker.pihole5(r.body), null);
+ } catch (JSONException e) {
+ return new Result(null, "Pi-hole refused the API token (Settings, API in Pi-hole's web page).");
+ }
+ }
+
+ private Result fail(int code) {
+ return new Result(null, Blocker.problem(code, c.kind));
+ }
+}
diff --git a/addons/ad-blocking/app/src/main/res/drawable/banner.xml b/addons/ad-blocking/app/src/main/res/drawable/banner.xml
new file mode 100644
index 000000000..f9fe172db
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/res/drawable/banner.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 16:9 banner: a shield with a bar chart beside it. Own art. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="320dp" android:height="180dp"
+ android:viewportWidth="320" android:viewportHeight="180">
+ <path android:fillColor="#101418" android:pathData="M0,0h320v180h-320z" />
+ <path android:fillColor="#E84855" android:pathData="M110,40l44,14v34c0,26 -20,42 -44,52c-24,-10 -44,-26 -44,-52v-34z" />
+ <path android:fillColor="#FFFFFF" android:pathData="M98,84h24v8h-24z" />
+ <path android:fillColor="#FFFFFF" android:pathData="M190,110h16v26h-16zM214,90h16v46h-16zM238,66h16v70h-16z" />
+</vector>
diff --git a/addons/ad-blocking/app/src/main/res/drawable/ic_foreground.xml b/addons/ad-blocking/app/src/main/res/drawable/ic_foreground.xml
new file mode 100644
index 000000000..4746e4ec4
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/res/drawable/ic_foreground.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A shield inside the adaptive icon's safe zone. Own art. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp" android:height="108dp"
+ android:viewportWidth="108" android:viewportHeight="108">
+ <path android:fillColor="#E84855" android:pathData="M54,36l16,5v12c0,10 -7,16 -16,20c-9,-4 -16,-10 -16,-20v-12z" />
+ <path android:fillColor="#FFFFFF" android:pathData="M47,53h14v4h-14z" />
+</vector>
diff --git a/addons/ad-blocking/app/src/main/res/drawable/row_background.xml b/addons/ad-blocking/app/src/main/res/drawable/row_background.xml
new file mode 100644
index 000000000..03ccab9f5
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/res/drawable/row_background.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A settings row: transparent until focused, then a glass highlight like the launcher's. -->
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_focused="true">
+ <shape android:shape="rectangle">
+ <solid android:color="#33FFFFFF" />
+ <stroke android:width="1dp" android:color="#55FFFFFF" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+ <item>
+ <shape android:shape="rectangle">
+ <solid android:color="#00000000" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+</selector>
diff --git a/addons/ad-blocking/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/addons/ad-blocking/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 000000000..0a99b20b1
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@android:color/black" />
+ <foreground android:drawable="@drawable/ic_foreground" />
+</adaptive-icon>
diff --git a/addons/ad-blocking/app/src/main/res/values/strings.xml b/addons/ad-blocking/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..4dc97db36
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Ad Blocking</string>
+</resources>
diff --git a/addons/ad-blocking/app/src/main/res/xml/module_card.xml b/addons/ad-blocking/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..d7305dc63
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<card spec="1" label="Ad Blocking" caption="Stats" accent="#E84855" />
diff --git a/addons/ad-blocking/app/src/main/res/xml/network.xml b/addons/ad-blocking/app/src/main/res/xml/network.xml
new file mode 100644
index 000000000..77a180e8f
--- /dev/null
+++ b/addons/ad-blocking/app/src/main/res/xml/network.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Pi-hole and AdGuard Home usually answer at http://<ip> on the home network, so plain HTTP is allowed. -->
+<network-security-config>
+ <base-config cleartextTrafficPermitted="true" />
+</network-security-config>
diff --git a/addons/ad-blocking/app/src/test/java/io/github/maxhayim/adblocking/BlockerTest.java b/addons/ad-blocking/app/src/test/java/io/github/maxhayim/adblocking/BlockerTest.java
new file mode 100644
index 000000000..a46aea4fb
--- /dev/null
+++ b/addons/ad-blocking/app/src/test/java/io/github/maxhayim/adblocking/BlockerTest.java
@@ -0,0 +1,94 @@
+package io.github.maxhayim.adblocking;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.json.JSONObject;
+import org.junit.Test;
+
+/** Against the response shapes the Pi-hole and AdGuard Home APIs document. */
+public class BlockerTest {
+ static final String PH6_AUTH = "{\"session\":{\"valid\":true,\"totp\":false,\"sid\":\"vFA+EP4MQ5JJvJg+3Q2Jnw=\",\"csrf\":\"Ux87YTIiMOf/GKCefVIOMw=\",\"validity\":300,\"message\":\"correct password\"},\"took\":0.003}";
+ static final String PH6_AUTH_NO_PASSWORD = "{\"session\":{\"valid\":true,\"totp\":false,\"sid\":null,\"validity\":-1,\"message\":\"no password set\"},\"took\":0.001}";
+ static final String PH6_AUTH_WRONG = "{\"session\":{\"valid\":false,\"totp\":false,\"sid\":null,\"validity\":-1,\"message\":\"password incorrect\"},\"took\":0.002}";
+ static final String PH6_SUMMARY = "{\"queries\":{\"total\":7497,\"blocked\":3465,\"percent_blocked\":34.5,\"unique_domains\":445,\"forwarded\":4574,\"cached\":9765},\"clients\":{\"active\":10,\"total\":22},\"gravity\":{\"domains_being_blocked\":104603,\"last_update\":1725194639},\"took\":0.003}";
+ static final String PH6_BLOCKING = "{\"blocking\":\"enabled\",\"timer\":null,\"took\":0.003}";
+ static final String PH5_SUMMARY = "{\"domains_being_blocked\":121860,\"dns_queries_today\":15329,\"ads_blocked_today\":2213,\"ads_percentage_today\":14.436,\"unique_domains\":1543,\"status\":\"enabled\"}";
+ static final String AGH_STATS = "{\"time_units\":\"hours\",\"num_dns_queries\":24000,\"num_blocked_filtering\":3000,\"num_replaced_safebrowsing\":0,\"avg_processing_time\":0.02}";
+ static final String AGH_STATUS = "{\"version\":\"v0.107.52\",\"dns_port\":53,\"http_port\":3000,\"protection_enabled\":true,\"running\":true}";
+
+ @Test
+ public void piholeSessions() throws Exception {
+ assertEquals("vFA+EP4MQ5JJvJg+3Q2Jnw=", Blocker.piholeSid(PH6_AUTH));
+ assertEquals("no password: no session id needed", "", Blocker.piholeSid(PH6_AUTH_NO_PASSWORD));
+ assertNull(Blocker.piholeSid(PH6_AUTH_WRONG));
+ assertEquals("secret", new JSONObject(Blocker.piholeLoginBody("secret")).getString("password"));
+ }
+
+ @Test
+ public void pihole6Numbers() throws Exception {
+ Blocker.Stats s = Blocker.pihole6(PH6_SUMMARY, PH6_BLOCKING);
+ assertEquals(7497, s.queries);
+ assertEquals(3465, s.blocked);
+ assertEquals(34.5, s.percent, 0.001);
+ assertTrue(s.enabled);
+ assertFalse(Blocker.pihole6(PH6_SUMMARY, "{\"blocking\":\"disabled\",\"timer\":120}").enabled);
+ }
+
+ @Test
+ public void pihole6Pause() throws Exception {
+ JSONObject p = new JSONObject(Blocker.piholePauseBody(true));
+ assertFalse(p.getBoolean("blocking"));
+ assertEquals(300, p.getInt("timer"));
+ assertTrue(new JSONObject(Blocker.piholePauseBody(false)).getBoolean("blocking"));
+ }
+
+ @Test
+ public void pihole5() throws Exception {
+ Blocker.Stats s = Blocker.pihole5(PH5_SUMMARY);
+ assertEquals(15329, s.queries);
+ assertEquals(2213, s.blocked);
+ assertTrue(s.enabled);
+ assertEquals("/admin/api.php?summaryRaw&auth=a%2Bb", Blocker.pihole5Summary("a+b"));
+ assertEquals("/admin/api.php?disable=300&auth=t", Blocker.pihole5Pause(true, "t"));
+ assertEquals("/admin/api.php?enable&auth=t", Blocker.pihole5Pause(false, "t"));
+ }
+
+ @Test(expected = org.json.JSONException.class)
+ public void pihole5WithoutTokenIsRefused() throws Exception {
+ Blocker.pihole5("{}");
+ }
+
+ @Test
+ public void adguard() throws Exception {
+ Blocker.Stats s = Blocker.adguard(AGH_STATS, AGH_STATUS);
+ assertEquals(24000, s.queries);
+ assertEquals(3000, s.blocked);
+ assertEquals(12.5, s.percent, 0.001);
+ assertTrue(s.enabled);
+ assertEquals("Basic YWRtaW46cGFzcw==", Blocker.basicAuth("admin", "pass"));
+ JSONObject p = new JSONObject(Blocker.adguardPauseBody(true));
+ assertFalse(p.getBoolean("enabled"));
+ assertEquals(300000, p.getLong("duration"));
+ assertFalse(new JSONObject(Blocker.adguardPauseBody(false)).has("duration"));
+ }
+
+ @Test
+ public void wording() {
+ assertEquals("12,345", Blocker.count(12345));
+ assertEquals("34.5 %", Blocker.pct(34.5));
+ assertEquals(0, Blocker.percent(5, 0), 0);
+ assertTrue(Blocker.problem(401, Blocker.Kind.PIHOLE).contains("password"));
+ assertTrue(Blocker.problem(0, Blocker.Kind.ADGUARD).contains("Can't reach"));
+ }
+
+ @Test
+ public void addresses() {
+ assertEquals("http://192.168.1.2", Blocker.normalizeUrl("192.168.1.2/admin/"));
+ assertEquals("http://pi.hole:8080", Blocker.normalizeUrl("http://pi.hole:8080"));
+ assertTrue(Blocker.validUrl("http://192.168.1.2:3000"));
+ assertFalse(Blocker.validUrl("http://"));
+ }
+}
diff --git a/addons/ad-blocking/app/src/test/java/io/github/maxhayim/adblocking/ServerTest.java b/addons/ad-blocking/app/src/test/java/io/github/maxhayim/adblocking/ServerTest.java
new file mode 100644
index 000000000..cc1108590
--- /dev/null
+++ b/addons/ad-blocking/app/src/test/java/io/github/maxhayim/adblocking/ServerTest.java
@@ -0,0 +1,81 @@
+package io.github.maxhayim.adblocking;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+/** Whole rounds against stand-in servers: the requests each API expects, in order, and the session closed after. */
+public class ServerTest {
+ private static TinyServer.Answer ok(String body) {
+ return new TinyServer.Answer(200, body);
+ }
+
+ @Test
+ public void pihole6RoundClosesItsSession() throws Exception {
+ try (TinyServer s = new TinyServer(r -> {
+ switch (r.line) {
+ case "POST /api/auth": return ok(BlockerTest.PH6_AUTH);
+ case "GET /api/stats/summary": return ok(BlockerTest.PH6_SUMMARY);
+ case "GET /api/dns/blocking": return ok(BlockerTest.PH6_BLOCKING);
+ default: return ok("{}");
+ }
+ })) {
+ Server.Result r = new Server(new Config(Blocker.Kind.PIHOLE, s.url(), "", "pw")).stats();
+ assertNull(r.problem);
+ assertEquals(7497, r.stats.queries);
+ assertEquals("pw", new org.json.JSONObject(s.seen.get(0).body).getString("password"));
+ assertEquals("vFA+EP4MQ5JJvJg+3Q2Jnw=", s.seen.get(1).headers.get("x-ftl-sid"));
+ assertEquals("DELETE /api/auth", s.seen.get(s.seen.size() - 1).line);
+ }
+ }
+
+ @Test
+ public void pihole6Pause() throws Exception {
+ try (TinyServer s = new TinyServer(r -> r.line.equals("POST /api/auth") ? ok(BlockerTest.PH6_AUTH)
+ : r.line.equals("GET /api/stats/summary") ? ok(BlockerTest.PH6_SUMMARY) : ok(BlockerTest.PH6_BLOCKING))) {
+ new Server(new Config(Blocker.Kind.PIHOLE, s.url(), "", "pw")).pause(true);
+ assertEquals("POST /api/dns/blocking", s.seen.get(1).line);
+ assertTrue(s.seen.get(1).body.contains("\"timer\":300"));
+ }
+ }
+
+ @Test
+ public void wrongPihole6Password() throws Exception {
+ try (TinyServer s = new TinyServer(r -> new TinyServer.Answer(401, BlockerTest.PH6_AUTH_WRONG))) {
+ Server.Result r = new Server(new Config(Blocker.Kind.PIHOLE, s.url(), "", "bad")).stats();
+ assertNull(r.stats);
+ assertTrue(r.problem.contains("password"));
+ }
+ }
+
+ @Test
+ public void pihole5WhenThereIsNoV6Api() throws Exception {
+ try (TinyServer s = new TinyServer(r -> r.line.startsWith("GET /admin/api.php?summaryRaw")
+ ? ok(BlockerTest.PH5_SUMMARY) : new TinyServer.Answer(404, "not found"))) {
+ Server.Result r = new Server(new Config(Blocker.Kind.PIHOLE, s.url(), "", "token")).stats();
+ assertNull(r.problem);
+ assertEquals(15329, r.stats.queries);
+ assertEquals("GET /admin/api.php?summaryRaw&auth=token", s.seen.get(1).line);
+ }
+ }
+
+ @Test
+ public void adguardWithBasicAuth() throws Exception {
+ try (TinyServer s = new TinyServer(r -> r.line.equals("GET /control/stats") ? ok(BlockerTest.AGH_STATS)
+ : r.line.equals("GET /control/status") ? ok(BlockerTest.AGH_STATUS) : ok("OK"))) {
+ Server.Result r = new Server(new Config(Blocker.Kind.ADGUARD, s.url(), "admin", "pass")).pause(true);
+ assertNull(r.problem);
+ assertEquals("POST /control/protection", s.seen.get(0).line);
+ assertEquals("Basic YWRtaW46cGFzcw==", s.seen.get(0).headers.get("authorization"));
+ assertEquals(3000, r.stats.blocked);
+ }
+ }
+
+ @Test
+ public void unreachable() {
+ Server.Result r = new Server(new Config(Blocker.Kind.ADGUARD, "http://127.0.0.1:1", "a", "b")).stats();
+ assertTrue(r.problem.contains("Can't reach"));
+ }
+}
diff --git a/addons/ad-blocking/app/src/test/java/io/github/maxhayim/adblocking/TinyServer.java b/addons/ad-blocking/app/src/test/java/io/github/maxhayim/adblocking/TinyServer.java
new file mode 100644
index 000000000..e624c814e
--- /dev/null
+++ b/addons/ad-blocking/app/src/test/java/io/github/maxhayim/adblocking/TinyServer.java
@@ -0,0 +1,87 @@
+package io.github.maxhayim.adblocking;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+
+/** A one-request-at-a-time HTTP/1.1 stand-in for a blocker: enough for HttpURLConnection, nothing more. */
+final class TinyServer implements AutoCloseable {
+ /** What arrived: "METHOD /path", the headers, the body. */
+ static final class Request {
+ final String line;
+ final Map<String, String> headers;
+ final String body;
+
+ Request(String line, Map<String, String> headers, String body) {
+ this.line = line;
+ this.headers = headers;
+ this.body = body;
+ }
+ }
+
+ /** Status code and body for a request. */
+ static final class Answer {
+ final int code;
+ final String body;
+
+ Answer(int code, String body) {
+ this.code = code;
+ this.body = body;
+ }
+ }
+
+ final List<Request> seen = Collections.synchronizedList(new ArrayList<>());
+ private final ServerSocket socket;
+ private final Thread loop;
+
+ TinyServer(Function<Request, Answer> handler) throws Exception {
+ socket = new ServerSocket(0, 5, InetAddress.getByName("127.0.0.1"));
+ loop = new Thread(() -> {
+ while (!socket.isClosed()) {
+ try (Socket s = socket.accept()) {
+ BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));
+ String[] first = in.readLine().split(" ");
+ Map<String, String> h = new java.util.HashMap<>();
+ for (String l; (l = in.readLine()) != null && !l.isEmpty(); ) {
+ int c = l.indexOf(':');
+ h.put(l.substring(0, c).trim().toLowerCase(), l.substring(c + 1).trim());
+ }
+ int length = Integer.parseInt(h.getOrDefault("content-length", "0"));
+ char[] b = new char[length];
+ for (int n = 0; n < length; ) n += in.read(b, n, length - n);
+ Request r = new Request(first[0] + " " + first[1], h, new String(b));
+ seen.add(r);
+ Answer a = handler.apply(r);
+ byte[] out = a.body.getBytes(StandardCharsets.UTF_8);
+ OutputStream o = s.getOutputStream();
+ o.write(("HTTP/1.1 " + a.code + " X\r\nContent-Type: application/json\r\nContent-Length: " + out.length
+ + "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.UTF_8));
+ o.write(out);
+ o.flush();
+ } catch (Exception ignored) {
+ // Closed, or a dropped connection.
+ }
+ }
+ });
+ loop.start();
+ }
+
+ String url() {
+ return "http://127.0.0.1:" + socket.getLocalPort();
+ }
+
+ @Override
+ public void close() throws Exception {
+ socket.close();
+ loop.join(2000);
+ }
+}
diff --git a/addons/ad-blocking/build.gradle b/addons/ad-blocking/build.gradle
new file mode 100644
index 000000000..48978475f
--- /dev/null
+++ b/addons/ad-blocking/build.gradle
@@ -0,0 +1,3 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+}
diff --git a/addons/ad-blocking/gradle.properties b/addons/ad-blocking/gradle.properties
new file mode 100644
index 000000000..18825f968
--- /dev/null
+++ b/addons/ad-blocking/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true
diff --git a/addons/ad-blocking/gradle/wrapper/gradle-wrapper.jar b/addons/ad-blocking/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..2c3521197
Binary files /dev/null and b/addons/ad-blocking/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/addons/ad-blocking/gradle/wrapper/gradle-wrapper.properties b/addons/ad-blocking/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..77f5d0ba6
--- /dev/null
+++ b/addons/ad-blocking/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,8 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
+distributionSha256Sum=d725d707bfabd4dfdc958c624003b3c80accc03f7037b5122c4b1d0ef15cecab
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/addons/ad-blocking/gradlew b/addons/ad-blocking/gradlew
new file mode 100755
index 000000000..f5feea6d6
--- /dev/null
+++ b/addons/ad-blocking/gradlew
@@ -0,0 +1,252 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/addons/ad-blocking/gradlew.bat b/addons/ad-blocking/gradlew.bat
new file mode 100644
index 000000000..9d21a2183
--- /dev/null
+++ b/addons/ad-blocking/gradlew.bat
@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/addons/ad-blocking/install.sh b/addons/ad-blocking/install.sh
new file mode 100755
index 000000000..2c5f8b15f
--- /dev/null
+++ b/addons/ad-blocking/install.sh
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+# Build Ad Blocking, install it on the TV and, optionally, push its Pi-hole or AdGuard Home login.
+# TV_HOST=<tv ip> addons/ad-blocking/install.sh [config.json] # {"kind": "pihole", "url": "http://192.168.1.2", "password": "..."}
+set -euo pipefail
+CONFIG="${1:-}"
+if [ -n "$CONFIG" ]; then
+ [ -f "$CONFIG" ] || { echo "no such file: $CONFIG" >&2; exit 1; }
+ CONFIG="$(cd "$(dirname "$CONFIG")" && pwd)/$(basename "$CONFIG")"
+ if command -v cygpath >/dev/null 2>&1; then CONFIG="$(cygpath -m "$CONFIG")"; fi
+fi
+: "${TV_HOST:?set TV_HOST to the TV IP address}"
+cd "$(dirname "$0")"
+TOOLS="$(cd ../../tools && pwd)"
+PY=$TOOLS/venv/bin/python
+[ -x "$PY" ] || PY=$TOOLS/venv/Scripts/python.exe
+export MSYS_NO_PATHCONV=1
+PKG=io.github.maxhayim.adblocking
+# Script paths stay relative: with MSYS_NO_PATHCONV, Git Bash would hand Windows Python a /c/... path.
+tv() { "$PY" -I ../../tools/tv.py "$@"; }
+
+[ -f local.properties ] || { [ -n "${ANDROID_HOME:-}" ] && echo "sdk.dir=$ANDROID_HOME" > local.properties; } || true
+if [ -n "${JAVA_HOME:-}" ]; then export PATH="$JAVA_HOME/bin:$PATH"; fi
+./gradlew assembleRelease -q --console=plain
+
+"$PY" -I ../../tools/b64push.py app/build/outputs/apk/release/app-release.apk /data/local/tmp/ad-blocking.apk
+OUT=$(tv 'pm install -r /data/local/tmp/ad-blocking.apk; rm -f /data/local/tmp/ad-blocking.apk')
+echo "$OUT"
+case "$OUT" in *Success*) ;; *) echo "ERROR: pm install failed" >&2; exit 1 ;; esac
+
+# The server and login go in as a file through the app's provider (only the ADB shell may write it), so the
+# password never sits on a command line on the TV. The app reads it once and deletes it.
+if [ -n "$CONFIG" ]; then
+ STAGE=/data/local/tmp/ad-blocking-config.json
+ tv --push "$CONFIG" "$STAGE" >/dev/null
+ tv "content write --uri content://$PKG.config/config.json < $STAGE; rm -f $STAGE; echo config pushed"
+fi
+tv "am start -n $PKG/.MainActivity >/dev/null; echo opened"
+echo "Installed. Ad Blocking is open on the TV; press Home and answer Show card for the card."
diff --git a/addons/ad-blocking/screenshot.jpg b/addons/ad-blocking/screenshot.jpg
new file mode 100644
index 000000000..423977407
Binary files /dev/null and b/addons/ad-blocking/screenshot.jpg differ
diff --git a/addons/ad-blocking/settings.gradle b/addons/ad-blocking/settings.gradle
new file mode 100644
index 000000000..942669998
--- /dev/null
+++ b/addons/ad-blocking/settings.gradle
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "ad-blocking"
+include ':app'