Skip to content

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

addons/game-day: fetch a calendar at most daily, keep the last good copy

Justin Newmana216b74ec1c3
diff --git a/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/FetchStatus.java b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/FetchStatus.java
new file mode 100644
index 000000000..a5946c314
--- /dev/null
+++ b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/FetchStatus.java
@@ -0,0 +1,41 @@
+package io.github.justinnewman.gameday;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/** How a calendar's last fetches went, kept beside its cached copy. */
+final class FetchStatus {
+ final long lastSuccessMs;
+ final long lastFailureMs;
+ /** "Not a calendar link", "Link refused (403)", "No answer", "Over 5 MB"; null after a success. */
+ final String error;
+ /** Events in the last good copy. */
+ final int entries;
+
+ FetchStatus(long lastSuccessMs, long lastFailureMs, String error, int entries) {
+ this.lastSuccessMs = lastSuccessMs;
+ this.lastFailureMs = lastFailureMs;
+ this.error = error;
+ this.entries = entries;
+ }
+
+ String toJson() {
+ try {
+ JSONObject o = new JSONObject().put("success", lastSuccessMs).put("failure", lastFailureMs).put("entries", entries);
+ if (error != null) o.put("error", error);
+ return o.toString();
+ } catch (JSONException impossible) {
+ throw new IllegalStateException(impossible);
+ }
+ }
+
+ static FetchStatus fromJson(String json) {
+ try {
+ JSONObject o = new JSONObject(json);
+ return new FetchStatus(o.optLong("success"), o.optLong("failure"),
+ o.has("error") ? o.optString("error") : null, o.optInt("entries"));
+ } catch (JSONException unreadable) {
+ return null;
+ }
+ }
+}
diff --git a/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Fetcher.java b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Fetcher.java
new file mode 100644
index 000000000..a37308b1a
--- /dev/null
+++ b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Fetcher.java
@@ -0,0 +1,106 @@
+package io.github.justinnewman.gameday;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.StandardCopyOption;
+import java.time.Instant;
+import java.time.ZoneOffset;
+
+/**
+ * Fetches a calendar at most once a day and keeps the last good copy: a fetch that fails, or that brings back
+ * something that is not a calendar, leaves the cached file as it was, so Home never loses its games because
+ * Wi-Fi blinked or a server had a bad hour. The link is never logged.
+ */
+final class Fetcher {
+ static final int MAX_BYTES = 5 * 1024 * 1024;
+ static final long STALE_MS = 24 * 3_600_000L;
+ static final long RETRY_MS = 3_600_000L;
+
+ private static final Instant ALL_FROM = Instant.EPOCH;
+ private static final Instant ALL_TO = Instant.parse("2200-01-01T00:00:00Z");
+
+ private final int connectMs;
+ private final int readMs;
+
+ Fetcher() {
+ this(15_000, 30_000);
+ }
+
+ Fetcher(int connectMs, int readMs) {
+ this.connectMs = connectMs;
+ this.readMs = readMs;
+ }
+
+ /** Fetch when the last good copy is over a day old and the last failure is over an hour old. */
+ static boolean due(FetchStatus s, long nowMs) {
+ if (s == null) return true;
+ return nowMs - s.lastSuccessMs >= STALE_MS && nowMs - s.lastFailureMs >= RETRY_MS;
+ }
+
+ static File cacheFile(File dir, String id) {
+ return new File(dir, "cal-" + id + ".ics");
+ }
+
+ FetchStatus fetch(Calendar c, File dir, FetchStatus previous, long nowMs) {
+ File part = new File(dir, "cal-" + c.id + ".part");
+ try {
+ String error = download(c.link, part);
+ if (error != null) return failed(previous, nowMs, error);
+ int entries;
+ try (Reader r = new InputStreamReader(Files.newInputStream(part.toPath()), StandardCharsets.UTF_8)) {
+ entries = Ics.parse(r, ZoneOffset.UTC, ALL_FROM, ALL_TO).size();
+ } catch (Ics.NotACalendar notCalendar) {
+ return failed(previous, nowMs, notCalendar.getMessage());
+ }
+ Files.move(part.toPath(), cacheFile(dir, c.id).toPath(), StandardCopyOption.REPLACE_EXISTING);
+ return new FetchStatus(nowMs, previous == null ? 0 : previous.lastFailureMs, null, entries);
+ } catch (IOException e) {
+ return failed(previous, nowMs, "No answer");
+ } finally {
+ //noinspection ResultOfMethodCallIgnored
+ part.delete();
+ }
+ }
+
+ /** Writes the body to {@code to}; returns an error to show, or null. */
+ private String download(String link, File to) throws IOException {
+ HttpURLConnection conn = (HttpURLConnection) new URL(link).openConnection();
+ try {
+ conn.setConnectTimeout(connectMs);
+ conn.setReadTimeout(readMs);
+ conn.setInstanceFollowRedirects(true);
+ conn.setRequestProperty("User-Agent", "GameDay/1 (Android TV)");
+ int code = conn.getResponseCode();
+ if (code != HttpURLConnection.HTTP_OK) return "Link refused (" + code + ")";
+ long length = conn.getContentLengthLong();
+ if (length > MAX_BYTES) return "Over 5 MB";
+ try (InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(to)) {
+ byte[] buf = new byte[16 * 1024];
+ long total = 0;
+ for (int n = in.read(buf); n >= 0; n = in.read(buf)) {
+ total += n;
+ if (total > MAX_BYTES) return "Over 5 MB";
+ out.write(buf, 0, n);
+ }
+ }
+ return null;
+ } finally {
+ conn.disconnect();
+ }
+ }
+
+ private static FetchStatus failed(FetchStatus previous, long nowMs, String error) {
+ return previous == null
+ ? new FetchStatus(0, nowMs, error, 0)
+ : new FetchStatus(previous.lastSuccessMs, nowMs, error, previous.entries);
+ }
+}
diff --git a/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/FetcherTest.java b/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/FetcherTest.java
new file mode 100644
index 000000000..0ad07715e
--- /dev/null
+++ b/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/FetcherTest.java
@@ -0,0 +1,138 @@
+package io.github.justinnewman.gameday;
+
+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 java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+public class FetcherTest {
+ private static final long HOUR = 3_600_000L;
+ private static final long NOW = 1_800_000_000_000L;
+ private static final String ICS = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20270403T000000Z\r\nSUMMARY:🏒 A @ B\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
+
+ @Rule public TemporaryFolder tmp = new TemporaryFolder();
+
+ /** A one-route HTTP/1.0 server on a plain socket: the JDK's HttpServer is not on Android's test classpath. */
+ private ServerSocket server;
+ private Thread serving;
+ private volatile int status = 200;
+ private volatile String type = "text/calendar";
+ private volatile byte[] body = ICS.getBytes(StandardCharsets.UTF_8);
+
+ @Before public void start() throws IOException {
+ server = new ServerSocket(0);
+ serving = new Thread(() -> {
+ while (!server.isClosed()) {
+ try (Socket s = server.accept()) {
+ BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.ISO_8859_1));
+ for (String line = in.readLine(); line != null && !line.isEmpty(); line = in.readLine()) {
+ // request line and headers: not needed
+ }
+ OutputStream o = s.getOutputStream();
+ o.write(("HTTP/1.0 " + status + " X\r\nContent-Type: " + type + "\r\nContent-Length: " + body.length
+ + "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.ISO_8859_1));
+ o.write(body);
+ o.flush();
+ } catch (IOException closed) {
+ return;
+ }
+ }
+ });
+ serving.start();
+ }
+
+ @After public void stop() throws Exception {
+ server.close();
+ serving.join(2000);
+ }
+
+ private Calendar calendar() {
+ String link = "http://127.0.0.1:" + server.getLocalPort() + "/cal.ics";
+ return new Calendar(Links.id(link), "Wild", link, Sport.byLabel("Hockey"), 12);
+ }
+
+ @Test public void dueRules() {
+ assertTrue(Fetcher.due(null, NOW));
+ assertFalse(Fetcher.due(new FetchStatus(NOW - 23 * HOUR, 0, null, 5), NOW));
+ assertTrue(Fetcher.due(new FetchStatus(NOW - 25 * HOUR, 0, null, 5), NOW));
+ assertFalse(Fetcher.due(new FetchStatus(0, NOW - HOUR / 2, "No answer", 0), NOW));
+ assertTrue(Fetcher.due(new FetchStatus(0, NOW - 2 * HOUR, "No answer", 0), NOW));
+ }
+
+ @Test public void goodFetchIsCached() throws Exception {
+ File dir = tmp.newFolder();
+ FetchStatus s = new Fetcher().fetch(calendar(), dir, null, NOW);
+ assertNull(s.error);
+ assertEquals(1, s.entries);
+ assertEquals(NOW, s.lastSuccessMs);
+ assertEquals(ICS, new String(Files.readAllBytes(Fetcher.cacheFile(dir, calendar().id).toPath()), StandardCharsets.UTF_8));
+ }
+
+ @Test public void htmlBodyIsReportedAsNotACalendar() throws Exception {
+ type = "text/html";
+ body = "<!DOCTYPE html><html>Sign in</html>".getBytes(StandardCharsets.UTF_8);
+ File dir = tmp.newFolder();
+ FetchStatus s = new Fetcher().fetch(calendar(), dir, null, NOW);
+ assertEquals("Not a calendar link", s.error);
+ assertEquals(NOW, s.lastFailureMs);
+ assertFalse(Fetcher.cacheFile(dir, calendar().id).exists());
+ }
+
+ @Test public void failureKeepsLastGoodCopy() throws Exception {
+ File dir = tmp.newFolder();
+ Fetcher f = new Fetcher();
+ FetchStatus good = f.fetch(calendar(), dir, null, NOW);
+ status = 403;
+ body = "nope".getBytes(StandardCharsets.UTF_8);
+ FetchStatus bad = f.fetch(calendar(), dir, good, NOW + 25 * HOUR);
+ assertEquals("Link refused (403)", bad.error);
+ assertEquals(NOW, bad.lastSuccessMs);
+ assertEquals(NOW + 25 * HOUR, bad.lastFailureMs);
+ assertEquals(1, bad.entries);
+ assertEquals(ICS, new String(Files.readAllBytes(Fetcher.cacheFile(dir, calendar().id).toPath()), StandardCharsets.UTF_8));
+ }
+
+ @Test public void oversizeIsRefused() throws Exception {
+ byte[] big = new byte[Fetcher.MAX_BYTES + 1024 * 1024];
+ byte[] head = ICS.getBytes(StandardCharsets.UTF_8);
+ System.arraycopy(head, 0, big, 0, head.length);
+ body = big;
+ FetchStatus s = new Fetcher().fetch(calendar(), tmp.newFolder(), null, NOW);
+ assertEquals("Over 5 MB", s.error);
+ }
+
+ @Test public void noAnswerIsReported() throws Exception {
+ try (ServerSocket silent = new ServerSocket(0)) {
+ String link = "http://127.0.0.1:" + silent.getLocalPort() + "/cal.ics";
+ Calendar c = new Calendar(Links.id(link), "Wild", link, Sport.byLabel("Hockey"), 12);
+ FetchStatus s = new Fetcher(500, 500).fetch(c, tmp.newFolder(), null, NOW);
+ assertEquals("No answer", s.error);
+ }
+ }
+
+ @Test public void statusRoundTrip() {
+ FetchStatus s = new FetchStatus(NOW, NOW + 1, "Link refused (403)", 214);
+ FetchStatus back = FetchStatus.fromJson(s.toJson());
+ assertEquals(NOW, back.lastSuccessMs);
+ assertEquals(NOW + 1, back.lastFailureMs);
+ assertEquals("Link refused (403)", back.error);
+ assertEquals(214, back.entries);
+ assertNull(FetchStatus.fromJson("garbage"));
+ }
+}