Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
addons/game-day: publish each team's next game for the launcher, and a shell-only door for setup
Justin Newman261ed5aa7711
diff --git a/addons/game-day/app/src/main/AndroidManifest.xml b/addons/game-day/app/src/main/AndroidManifest.xmlindex f63a4f009..a6c22f6a8 100644--- a/addons/game-day/app/src/main/AndroidManifest.xml+++ b/addons/game-day/app/src/main/AndroidManifest.xml@@ -10,5 +10,22 @@<applicationandroid:allowBackup="false"android:label="@string/app_name"- android:supportsRtl="false" />+ android:supportsRtl="false">++ <!-- Clean Your TV launcher, game_day (docs/modules.md): where Home reads each team's next game. -->+ <meta-data android:name="com.gathin.tvhome.games" android:value="io.github.justinnewman.gameday.games" />++ <!-- Read-only and holding no links: what Home shows anyway. -->+ <provider+ android:name=".GamesProvider"+ android:authorities="io.github.justinnewman.gameday.games"+ android:exported="true" />++ <!-- The setup script's door. WRITE_SECURE_SETTINGS is held by the ADB shell only, so no app can use it. -->+ <provider+ android:name=".FilesProvider"+ android:authorities="io.github.justinnewman.gameday.files"+ android:exported="true"+ android:permission="android.permission.WRITE_SECURE_SETTINGS" />+ </application></manifest>diff --git a/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Background.java b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Background.javanew file mode 100644index 000000000..7640dfb95--- /dev/null+++ b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Background.java@@ -0,0 +1,67 @@+package io.github.justinnewman.gameday;++import android.content.Context;++import java.io.File;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.time.ZoneId;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.atomic.AtomicBoolean;++/**+ * The one thread Game Day fetches on. Nothing is scheduled: a fetch runs only when something asks for the games+ * (the launcher, the settings screen) and a calendar's copy is over a day old, so nothing runs while Home is not+ * on screen and the TV is never woken.+ */+final class Background {+ private static final ExecutorService ONE = Executors.newSingleThreadExecutor();+ private static final AtomicBoolean REFRESHING = new AtomicBoolean();++ private Background() {+ }++ static void execute(Runnable r) {+ ONE.execute(r);+ }++ /** Fetch the calendars that are due; tell the launcher when one came in. */+ static void refresh(Context ctx, long nowMs) {+ Context app = ctx.getApplicationContext();+ if (!REFRESHING.compareAndSet(false, true)) return;+ ONE.execute(() -> {+ try {+ Repository repo = new Repository(app);+ Fetcher fetcher = new Fetcher();+ boolean changed = false;+ for (Calendar c : repo.due(nowMs)) changed |= repo.fetch(fetcher, c, nowMs).error == null;+ if (changed) GamesProvider.changed(app);+ } finally {+ REFRESHING.set(false);+ }+ });+ }++ /** The setup script's file: apply it, fetch everything, leave the report in result.txt. */+ static void applySetup(Context ctx, File received) {+ Context app = ctx.getApplicationContext();+ ONE.execute(() -> {+ Repository repo = new Repository(app);+ String text;+ try {+ text = new String(Files.readAllBytes(received.toPath()), StandardCharsets.UTF_8);+ } catch (IOException e) {+ text = null;+ } finally {+ //noinspection ResultOfMethodCallIgnored+ received.delete();+ }+ String result = text == null ? "error|0|the file did not arrive\ndone\n"+ : repo.applySetupFile(text, System.currentTimeMillis(), new Fetcher(), ZoneId.systemDefault());+ Repository.write(new File(repo.dir(), FilesProvider.RESULT), result);+ GamesProvider.changed(app);+ });+ }+}diff --git a/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/FilesProvider.java b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/FilesProvider.javanew file mode 100644index 000000000..433e4b02e--- /dev/null+++ b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/FilesProvider.java@@ -0,0 +1,81 @@+package io.github.justinnewman.gameday;++import android.content.ContentProvider;+import android.content.ContentValues;+import android.content.Context;+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;+import java.io.IOException;++/**+ * The setup script's way in (setup.sh / setup.ps1, over ADB). It requires WRITE_SECURE_SETTINGS, which only the+ * ADB shell holds, so no app on the TV can read or change the calendar links through it.+ * <ul>+ * <li>write {@code calendars.txt}: the new list ({@code sport | name | link}); applied when the file is closed.</li>+ * <li>read {@code result.txt}: the report, one line per calendar, ending with {@code done}. Never a link.</li>+ * </ul>+ */+public final class FilesProvider extends ContentProvider {+ static final String CALENDARS = "calendars.txt";+ static final String RESULT = "result.txt";++ @Override+ public boolean onCreate() {+ return true;+ }++ @Override+ public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {+ Context ctx = getContext();+ String name = uri.getLastPathSegment();+ if (ctx == null || name == null) throw new FileNotFoundException();+ File result = new File(ctx.getFilesDir(), RESULT);+ if (name.equals(CALENDARS) && mode.contains("w")) {+ // The script waits for "done": a report from an earlier run must not answer for this one.+ Repository.write(result, "working\n");+ File received = new File(ctx.getCacheDir(), "setup.txt");+ try {+ return ParcelFileDescriptor.open(received, ParcelFileDescriptor.MODE_WRITE_ONLY+ | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE,+ new Handler(Looper.getMainLooper()), e -> Background.applySetup(ctx, received));+ } catch (IOException e) {+ throw new FileNotFoundException(e.getMessage());+ }+ }+ if (name.equals(RESULT) && !mode.contains("w")) {+ return ParcelFileDescriptor.open(result, ParcelFileDescriptor.MODE_READ_ONLY);+ }+ throw new FileNotFoundException(name);+ }++ @Override+ public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {+ return null;+ }++ @Override+ public String getType(Uri uri) {+ return "text/plain";+ }++ @Override+ public Uri insert(Uri uri, ContentValues values) {+ throw new UnsupportedOperationException();+ }++ @Override+ public int delete(Uri uri, String selection, String[] selectionArgs) {+ throw new UnsupportedOperationException();+ }++ @Override+ public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {+ throw new UnsupportedOperationException();+ }+}diff --git a/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/GamesProvider.java b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/GamesProvider.javanew file mode 100644index 000000000..d411855d0--- /dev/null+++ b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/GamesProvider.java@@ -0,0 +1,65 @@+package io.github.justinnewman.gameday;++import android.content.ContentProvider;+import android.content.ContentValues;+import android.content.Context;+import android.database.Cursor;+import android.database.MatrixCursor;+import android.net.Uri;++/**+ * Each team's next game, for the Clean Your TV launcher's game_day panel (docs/modules.md). Read-only and+ * exported without a permission: it holds only what Home shows anyway (who plays, when, the colour), never a link.+ * One row per calendar, sorted by start; an empty cursor means nothing within a week.+ */+public final class GamesProvider extends ContentProvider {+ static final String AUTHORITY = "io.github.justinnewman.gameday.games";+ static final Uri TURNS = Uri.parse("content://" + AUTHORITY + "/turns");+ static final String[] COLUMNS = {"top_line", "word", "start_ms", "end_ms", "colour", "calendar", "turn_seconds"};++ static void changed(Context ctx) {+ ctx.getContentResolver().notifyChange(TURNS, null);+ }++ @Override+ public boolean onCreate() {+ return true;+ }++ @Override+ public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {+ if (!"turns".equals(uri.getLastPathSegment())) return null;+ Context ctx = getContext();+ if (ctx == null) return null;+ Repository repo = new Repository(ctx);+ long now = System.currentTimeMillis();+ int seconds = repo.turnSeconds();+ MatrixCursor c = new MatrixCursor(COLUMNS);+ for (Schedule.Turn t : repo.turns(now)) {+ c.addRow(new Object[] {t.topLine, t.word, t.startMs, t.endMs, t.colour, t.calendar, seconds});+ }+ c.setNotificationUri(ctx.getContentResolver(), TURNS);+ Background.refresh(ctx, now);+ return c;+ }++ @Override+ public String getType(Uri uri) {+ return "vnd.android.cursor.dir/vnd." + AUTHORITY + ".turn";+ }++ @Override+ public Uri insert(Uri uri, ContentValues values) {+ throw new UnsupportedOperationException("read-only");+ }++ @Override+ public int delete(Uri uri, String selection, String[] selectionArgs) {+ throw new UnsupportedOperationException("read-only");+ }++ @Override+ public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {+ throw new UnsupportedOperationException("read-only");+ }+}diff --git a/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Repository.java b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Repository.javanew file mode 100644index 000000000..a54eda4cf--- /dev/null+++ b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Repository.java@@ -0,0 +1,199 @@+package io.github.justinnewman.gameday;++import android.content.Context;++import java.io.File;+import java.io.IOException;+import java.io.Reader;+import java.nio.charset.StandardCharsets;+import java.nio.file.AtomicMoveNotSupportedException;+import java.nio.file.Files;+import java.nio.file.StandardCopyOption;+import java.time.Duration;+import java.time.Instant;+import java.time.ZoneId;+import java.time.format.DateTimeFormatter;+import java.util.ArrayList;+import java.util.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Set;++import org.json.JSONException;+import org.json.JSONObject;++/**+ * Everything Game Day keeps, in the app's own files (never backed up): the calendar list with its links,+ * each calendar's last good copy and fetch status, and the seconds per turn.+ */+final class Repository {+ static final int TURN_DEFAULT = 30;+ static final int TURN_MIN = 10;+ static final int TURN_MAX = 120;+ static final String NOTHING = "nothing in the next 7 days";++ private static final Duration READ_AHEAD = Duration.ofDays(8);+ private static final DateTimeFormatter NEXT = DateTimeFormatter.ofPattern("EEE h:mm a", Locale.US);++ private final File dir;++ Repository(Context ctx) {+ this(ctx.getFilesDir());+ }++ Repository(File dir) {+ this.dir = dir;+ }++ File dir() {+ return dir;+ }++ List<Calendar> calendars() {+ String json = read(new File(dir, "calendars.json"));+ return json == null ? new ArrayList<>() : CalendarStore.fromJson(json);+ }++ /** Saves the list and forgets the copies and statuses of calendars no longer on it. */+ void save(List<Calendar> calendars) {+ write(new File(dir, "calendars.json"), CalendarStore.toJson(calendars));+ Set<String> keep = new HashSet<>();+ for (Calendar c : calendars) keep.add(c.id);+ File[] files = dir.listFiles();+ if (files == null) return;+ for (File f : files) {+ String n = f.getName();+ String id = n.startsWith("cal-") && n.endsWith(".ics") ? n.substring(4, n.length() - 4)+ : n.startsWith("status-") && n.endsWith(".json") ? n.substring(7, n.length() - 5) : null;+ //noinspection ResultOfMethodCallIgnored+ if (id != null && !keep.contains(id)) f.delete();+ }+ }++ int turnSeconds() {+ String json = read(new File(dir, "settings.json"));+ if (json == null) return TURN_DEFAULT;+ try {+ return clampTurn(new JSONObject(json).optInt("turn_seconds", TURN_DEFAULT));+ } catch (JSONException unreadable) {+ return TURN_DEFAULT;+ }+ }++ /** 10 to 120 seconds, in steps of 5. */+ void setTurnSeconds(int seconds) {+ try {+ write(new File(dir, "settings.json"), new JSONObject().put("turn_seconds", clampTurn(seconds)).toString());+ } catch (JSONException impossible) {+ throw new IllegalStateException(impossible);+ }+ }++ private static int clampTurn(int s) {+ int stepped = Math.round(s / 5f) * 5;+ return Math.max(TURN_MIN, Math.min(TURN_MAX, stepped));+ }++ FetchStatus status(String id) {+ String json = read(new File(dir, "status-" + id + ".json"));+ return json == null ? null : FetchStatus.fromJson(json);+ }++ void saveStatus(String id, FetchStatus s) {+ write(new File(dir, "status-" + id + ".json"), s.toJson());+ }++ /** Calendars whose copy is over a day old and that did not fail in the last hour. */+ List<Calendar> due(long nowMs) {+ List<Calendar> out = new ArrayList<>();+ for (Calendar c : calendars()) {+ if (Fetcher.due(status(c.id), nowMs)) out.add(c);+ }+ return out;+ }++ FetchStatus fetch(Fetcher fetcher, Calendar c, long nowMs) {+ FetchStatus s = fetcher.fetch(c, dir, status(c.id), nowMs);+ saveStatus(c.id, s);+ return s;+ }++ List<Schedule.Turn> turns(long nowMs) {+ return turns(nowMs, ZoneId.systemDefault());+ }++ List<Schedule.Turn> turns(long nowMs, ZoneId zone) {+ return turns(calendars(), nowMs, zone);+ }++ /** "Sat 1:00 AM", or "nothing in the next 7 days". */+ String nextLine(Calendar c, long nowMs, ZoneId zone) {+ List<Schedule.Turn> t = turns(Collections.singletonList(c), nowMs, zone);+ return t.isEmpty() ? NOTHING : NEXT.format(Instant.ofEpochMilli(t.get(0).startMs).atZone(zone));+ }++ private List<Schedule.Turn> turns(List<Calendar> calendars, long nowMs, ZoneId zone) {+ Instant now = Instant.ofEpochMilli(nowMs);+ Map<String, List<Ics.Event>> events = new HashMap<>();+ for (Calendar c : calendars) {+ File f = Fetcher.cacheFile(dir, c.id);+ if (!f.exists()) continue;+ try (Reader r = Files.newBufferedReader(f.toPath(), StandardCharsets.UTF_8)) {+ events.put(c.id, Ics.parse(r, zone, now, now.plus(READ_AHEAD)));+ } catch (IOException | Ics.NotACalendar unreadable) {+ // A copy only lands here after it parsed once; skip it if the file went bad.+ }+ }+ return Schedule.turns(calendars, events, now, zone);+ }++ /**+ * The setup script's file: replaces the list, fetches every calendar, and returns the report the script prints.+ * One line per calendar, {@code ok|name|sport|entries|next} or {@code fail|name|sport|error}; for a file it cannot+ * use, {@code error|line|message} and the list stays as it was. Always ends with {@code done}. Never a link.+ */+ String applySetupFile(String text, long nowMs, Fetcher fetcher, ZoneId zone) {+ List<Calendar> list;+ try {+ list = CalendarStore.parseSetupFile(text);+ } catch (CalendarStore.BadLine bad) {+ return "error|" + bad.line + "|" + bad.getMessage() + "\ndone\n";+ }+ save(list);+ StringBuilder b = new StringBuilder();+ for (Calendar c : list) {+ FetchStatus s = fetch(fetcher, c, nowMs);+ String head = c.name + "|" + c.sport.label() + "|";+ if (s.error == null) b.append("ok|").append(head).append(s.entries).append('|').append(nextLine(c, nowMs, zone));+ else b.append("fail|").append(head).append(s.error);+ b.append('\n');+ }+ return b.append("done\n").toString();+ }++ private static String read(File f) {+ try {+ return f.exists() ? new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8) : null;+ } catch (IOException e) {+ return null;+ }+ }++ /** Write to a temporary file, then move it into place, so a reader never sees half a file. */+ static void write(File f, String text) {+ File tmp = new File(f.getParentFile(), f.getName() + ".tmp");+ try {+ Files.write(tmp.toPath(), text.getBytes(StandardCharsets.UTF_8));+ try {+ Files.move(tmp.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);+ } catch (AtomicMoveNotSupportedException notAtomic) {+ Files.move(tmp.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);+ }+ } catch (IOException e) {+ throw new IllegalStateException("could not save " + f.getName(), e);+ }+ }+}diff --git a/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/RepositoryTest.java b/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/RepositoryTest.javanew file mode 100644index 000000000..6aa20f5a1--- /dev/null+++ b/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/RepositoryTest.java@@ -0,0 +1,126 @@+package io.github.justinnewman.gameday;++import static org.junit.Assert.assertEquals;+import static org.junit.Assert.assertFalse;+import static org.junit.Assert.assertTrue;++import java.io.File;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.time.Instant;+import java.time.ZoneId;+import java.time.ZoneOffset;+import java.util.Arrays;+import java.util.List;++import org.junit.Before;+import org.junit.Rule;+import org.junit.Test;+import org.junit.rules.TemporaryFolder;++public class RepositoryTest {+ private static final Instant NOW = Instant.parse("2027-04-02T12:00:00Z");+ private static final ZoneId UTC = ZoneOffset.UTC;++ @Rule public TemporaryFolder tmp = new TemporaryFolder();+ private File dir;+ private Repository repo;++ @Before public void setUp() throws Exception {+ dir = tmp.newFolder();+ repo = new Repository(dir);+ }++ private static Calendar cal(String name, String sport, int colour) {+ String link = "https://h.example/" + name.replace(' ', '-');+ return new Calendar(Links.id(link), name, link, Sport.byLabel(sport), colour);+ }++ private void cache(Calendar c, String summary, String start) throws Exception {+ String ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:" + start + "\r\nSUMMARY:" + summary + "\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";+ Files.write(Fetcher.cacheFile(dir, c.id).toPath(), ics.getBytes(StandardCharsets.UTF_8));+ }++ @Test public void turnSecondsClampAndStep() {+ assertEquals(30, repo.turnSeconds());+ repo.setTurnSeconds(7);+ assertEquals(10, repo.turnSeconds());+ repo.setTurnSeconds(31);+ assertEquals(30, repo.turnSeconds());+ repo.setTurnSeconds(33);+ assertEquals(35, repo.turnSeconds());+ repo.setTurnSeconds(500);+ assertEquals(120, new Repository(dir).turnSeconds());+ }++ @Test public void calendarsAreSavedAndRead() {+ assertTrue(repo.calendars().isEmpty());+ List<Calendar> list = Arrays.asList(cal("Minnesota Wild", "Hockey", 16), cal("Utah Royals", "Soccer", 14));+ repo.save(list);+ List<Calendar> back = new Repository(dir).calendars();+ assertEquals(2, back.size());+ assertEquals("Utah Royals", back.get(1).name);+ }++ @Test public void turnsComeFromCachedFiles() throws Exception {+ Calendar wild = cal("Minnesota Wild", "Hockey", 16);+ Calendar royals = cal("Utah Royals", "Soccer", 14);+ repo.save(Arrays.asList(wild, royals));+ cache(wild, "π Minnesota Wild @ Dallas Stars", "20270403T000000Z");+ cache(royals, "β½ Utah Royals vs Portland Thorns", "20270402T200000Z");+ List<Schedule.Turn> t = repo.turns(NOW.toEpochMilli(), UTC);+ assertEquals(2, t.size());+ assertEquals("Portland Thorns at Utah Royals", t.get(0).topLine);+ assertEquals(Palette.colour(14), t.get(0).colour);+ assertEquals(Palette.colour(16), t.get(1).colour);+ }++ @Test public void nextLineDescribesTheNextEntry() throws Exception {+ Calendar wild = cal("Minnesota Wild", "Hockey", 16);+ cache(wild, "π Minnesota Wild @ Dallas Stars", "20270403T010000Z");+ assertEquals("Sat 1:00 AM", repo.nextLine(wild, NOW.toEpochMilli(), UTC));+ assertEquals("nothing in the next 7 days", repo.nextLine(cal("Nobody", "Hockey", 3), NOW.toEpochMilli(), UTC));+ }++ @Test public void resultFileNeverHasALink() {+ String result = repo.applySetupFile("Hockey|Minnesota Wild|http://127.0.0.1:1/secret-token.ics\n"+ + "Soccer|Utah Royals|https://127.0.0.1:1/other-secret.ics", NOW.toEpochMilli(), new Fetcher(300, 300), UTC);+ assertTrue(result, result.contains("fail|Minnesota Wild|Hockey|No answer"));+ assertTrue(result, result.endsWith("done\n"));+ assertFalse(result, result.contains("http"));+ assertFalse(result, result.contains("secret"));+ assertEquals(2, repo.calendars().size());+ }++ @Test public void badSetupFileLeavesTheListAlone() {+ repo.save(Arrays.asList(cal("Minnesota Wild", "Hockey", 16)));+ String result = repo.applySetupFile("Basketbal|Jazz|https://h.example/j.ics", NOW.toEpochMilli(), new Fetcher(300, 300), UTC);+ assertTrue(result, result.startsWith("error|1|Line 1: unknown sport"));+ assertTrue(result.endsWith("done\n"));+ assertEquals(1, repo.calendars().size());+ assertEquals("Minnesota Wild", repo.calendars().get(0).name);+ }++ @Test public void removedCalendarsLoseTheirCache() throws Exception {+ Calendar wild = cal("Minnesota Wild", "Hockey", 16);+ Calendar royals = cal("Utah Royals", "Soccer", 14);+ repo.save(Arrays.asList(wild, royals));+ cache(wild, "A @ B", "20270403T000000Z");+ cache(royals, "C @ D", "20270403T000000Z");+ repo.saveStatus(royals.id, new FetchStatus(1, 0, null, 1));+ repo.save(Arrays.asList(wild));+ assertTrue(Fetcher.cacheFile(dir, wild.id).exists());+ assertFalse(Fetcher.cacheFile(dir, royals.id).exists());+ assertEquals(null, repo.status(royals.id));+ }++ @Test public void dueCalendars() {+ Calendar wild = cal("Minnesota Wild", "Hockey", 16);+ Calendar royals = cal("Utah Royals", "Soccer", 14);+ repo.save(Arrays.asList(wild, royals));+ repo.saveStatus(wild.id, new FetchStatus(NOW.toEpochMilli() - 3_600_000L, 0, null, 3));+ List<Calendar> due = repo.due(NOW.toEpochMilli());+ assertEquals(1, due.size());+ assertEquals("Utah Royals", due.get(0).name);+ }+}