diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/data/CatalogRepositoryImpl.java b/controller/app/src/main/java/org/iiab/controller/kolibri/data/CatalogRepositoryImpl.java index d83770023..6f4d1403d 100644 --- a/controller/app/src/main/java/org/iiab/controller/kolibri/data/CatalogRepositoryImpl.java +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/data/CatalogRepositoryImpl.java @@ -3,8 +3,8 @@ * Name : CatalogRepositoryImpl.java * Author : AppDevForAll * Copyright : Copyright (c) 2026 AppDevForAll - * Description : Wires the bundled catalog and the live Studio tree behind the - * domain port (ADFA-4954). + * Description : Wires the bundled catalog and the topic tree (box-served first, + * Studio as fallback) behind the domain port (ADFA-4954, -5094). * ============================================================================ */ package org.iiab.controller.kolibri.data; @@ -38,10 +38,13 @@ public final class CatalogRepositoryImpl implements CatalogRepository { private static final String BASENAME = BundledCatalogSource.ASSET; private final BundledCatalogSource bundled; - private final StudioTreeSource studio; + private final TreeSource tree; public CatalogRepositoryImpl(Context context) { - this(new BundledCatalogSource(context), new StudioTreeSource()); + // ADFA-5094: prefer the box-served topic tree (offline, whole tree once the channel's + // metadata is imported) and fall back to Studio when the box cannot answer. + this(new BundledCatalogSource(context), + new FallbackTreeSource(new LocalTreeSource(), new StudioTreeSource())); // Keep the bundled catalog current: a weekly refresh plus an opportunistic (TTL-gated) // check now. Only the Context constructor schedules — the test constructor below does not. org.iiab.controller.catalog.data.CatalogRefreshScheduler.scheduleWeekly( @@ -50,10 +53,10 @@ public CatalogRepositoryImpl(Context context) { context, CATALOG, MANIFEST_URL, BASENAME); } - /** For tests and for pointing the tree source at a mirror. */ - public CatalogRepositoryImpl(BundledCatalogSource bundled, StudioTreeSource studio) { + /** For tests and for pointing the tree source elsewhere (e.g. a local-first composite). */ + public CatalogRepositoryImpl(BundledCatalogSource bundled, TreeSource tree) { this.bundled = bundled; - this.studio = studio; + this.tree = tree; } @Override @@ -68,6 +71,6 @@ public String catalogGeneratedOn() { @Override public TopicNode fetchTree(String nodeId) { - return studio.fetchTree(nodeId); + return tree.fetchTree(nodeId); } } diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/data/FallbackTreeSource.java b/controller/app/src/main/java/org/iiab/controller/kolibri/data/FallbackTreeSource.java new file mode 100644 index 000000000..8b7bfb0d0 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/data/FallbackTreeSource.java @@ -0,0 +1,46 @@ +/* + * ============================================================================ + * Name : FallbackTreeSource.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : Tries one tree source, then another. Lets the repository prefer + * the box-served tree and fall back to Studio (ADFA-5094). + * ============================================================================ + */ +package org.iiab.controller.kolibri.data; + +import org.iiab.controller.kolibri.domain.TopicNode; + +/** + * A {@link TreeSource} that asks {@code primary} first and {@code secondary} + * only when the first has nothing. + * + *
The one place the local-first policy lives: prefer the box (offline, + * instant, whole tree once imported), fall to Studio when the box cannot answer + * — box down, channel not imported, or PR3 not yet shipped, in which case the + * primary always misses and behaviour is exactly what it was before ADFA-5094. + * + *
Deliberately pure — no network, no Android — so this routing is unit-tested + * on a plain JVM while the sources it composes are integration concerns. + * {@code secondary} is not consulted when {@code primary} answers, so a hit + * costs no extra call. + */ +public final class FallbackTreeSource implements TreeSource { + + private final TreeSource primary; + private final TreeSource secondary; + + public FallbackTreeSource(TreeSource primary, TreeSource secondary) { + if (primary == null || secondary == null) { + throw new IllegalArgumentException("both sources are required"); + } + this.primary = primary; + this.secondary = secondary; + } + + @Override + public TopicNode fetchTree(String nodeId) { + TopicNode fromPrimary = primary.fetchTree(nodeId); + return fromPrimary != null ? fromPrimary : secondary.fetchTree(nodeId); + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/data/LocalTreeSource.java b/controller/app/src/main/java/org/iiab/controller/kolibri/data/LocalTreeSource.java new file mode 100644 index 000000000..6d82b9143 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/data/LocalTreeSource.java @@ -0,0 +1,140 @@ +/* + * ============================================================================ + * Name : LocalTreeSource.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : Reads a channel's topic tree from the box on localhost, when the + * channel's metadata has been imported there. Offline path for + * topic browsing (ADFA-5094). + * ============================================================================ + */ +package org.iiab.controller.kolibri.data; + +import android.util.Log; + +import org.iiab.controller.config.BoxEndpoints; +import org.iiab.controller.kolibri.domain.ChannelId; +import org.iiab.controller.kolibri.domain.TopicNode; +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +/** + * Reads topic trees from the box's Kolibri REST core, not the internet. + * + *
The offline counterpart to {@link StudioTreeSource}. Once a channel has been + * metadata-imported on the box (its tree DB present, the content not necessarily + * downloaded — ADFA-5094 PR3), the box can answer the same shape Studio does, so + * the picker browses the whole tree with no connectivity. Until that import + * exists the endpoint returns 404 and this source returns {@code null}, which is + * the signal for {@link FallbackTreeSource} to try Studio instead. + * + *
The response is deliberately the same JSON as Studio's + * {@code contentnode_tree}, so {@link StudioCatalogMapper#tree(JSONObject)} + * parses both with no branching. The box owns that translation (PR3); the device + * side stays a thin read. + * + *
Talks to localhost, so timeouts are tight — a slow box is a bug, not the
+ * poor long-haul link {@link StudioTreeSource} plans for. Blocking by design;
+ * never throws, per the {@link TreeSource} contract.
+ */
+public final class LocalTreeSource implements TreeSource {
+
+ private static final String TAG = "K2Go-Kolibri";
+
+ /** Endpoint under the box API base: {@code /k2go-api/kolibri/tree/ Blocking by design, so the caller controls threading. Never throws: a
* failure is a {@code null} return, per the {@code CatalogRepository} contract.
*/
-public final class StudioTreeSource {
+public final class StudioTreeSource implements TreeSource {
private static final String TAG = "K2Go-Kolibri";
@@ -66,6 +66,7 @@ public StudioTreeSource(String baseUrl) {
* @return the subtree, or null when the request failed or the body was not
* a usable node
*/
+ @Override
public TopicNode fetchTree(String nodeId) {
// Validate before the id reaches a URL path, not after. Every caller
// today passes an already-normalised Channel.rootNodeId(), but this
diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/data/TreeSource.java b/controller/app/src/main/java/org/iiab/controller/kolibri/data/TreeSource.java
new file mode 100644
index 000000000..bd2695f97
--- /dev/null
+++ b/controller/app/src/main/java/org/iiab/controller/kolibri/data/TreeSource.java
@@ -0,0 +1,36 @@
+/*
+ * ============================================================================
+ * Name : TreeSource.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : One seam for reading a channel's topic tree, so the repository
+ * can prefer a box-served tree and fall back to Studio without
+ * knowing which is which (ADFA-5094).
+ * ============================================================================
+ */
+package org.iiab.controller.kolibri.data;
+
+import org.iiab.controller.kolibri.domain.TopicNode;
+
+/**
+ * A source of one level of a channel's topic tree.
+ *
+ * Introduced so the two implementations — {@link StudioTreeSource} over the
+ * internet and {@link LocalTreeSource} over the box on localhost — are
+ * interchangeable behind {@link FallbackTreeSource}. Before ADFA-5094 the
+ * repository held a {@code StudioTreeSource} directly; the tree was Studio's or
+ * nothing.
+ *
+ * Same contract as {@code CatalogRepository.fetchTree}: never throws.
+ * A failure — no network, box not running, channel not imported, a malformed
+ * body — is a {@code null} return, so a fallback source can be tried in turn.
+ */
+public interface TreeSource {
+
+ /**
+ * One level of the tree rooted at {@code nodeId}, with its direct children.
+ *
+ * @return the subtree, or {@code null} when this source could not serve it
+ */
+ TopicNode fetchTree(String nodeId);
+}
diff --git a/controller/app/src/test/java/org/iiab/controller/kolibri/data/FallbackTreeSourceTest.java b/controller/app/src/test/java/org/iiab/controller/kolibri/data/FallbackTreeSourceTest.java
new file mode 100644
index 000000000..500596e3f
--- /dev/null
+++ b/controller/app/src/test/java/org/iiab/controller/kolibri/data/FallbackTreeSourceTest.java
@@ -0,0 +1,93 @@
+/*
+ * ============================================================================
+ * Name : FallbackTreeSourceTest.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : Unit tests for the local-first tree routing. Pure JVM (ADFA-5094).
+ * ============================================================================
+ */
+package org.iiab.controller.kolibri.data;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+
+import org.iiab.controller.kolibri.domain.TopicNode;
+import org.junit.Test;
+
+/**
+ * The routing that lets the box-served tree win and Studio cover the miss.
+ *
+ * Three behaviours matter: a primary hit is returned without touching the
+ * secondary, a primary miss falls through with the same node id, and two misses
+ * are a miss — the null the {@code CatalogRepository} contract expects.
+ */
+public class FallbackTreeSourceTest {
+
+ private static final String ID = "c150ea1d69495d37b5b0ac6f017e9bfb";
+
+ /** Answers with whatever it was handed; records how it was used. */
+ private static final class FakeSource implements TreeSource {
+ final TopicNode answer;
+ int calls;
+ String asked;
+
+ FakeSource(TopicNode answer) {
+ this.answer = answer;
+ }
+
+ @Override
+ public TopicNode fetchTree(String nodeId) {
+ calls++;
+ asked = nodeId;
+ return answer;
+ }
+ }
+
+ private static TopicNode node(String title) {
+ return TopicNode.of(ID, title, "topic", false, 0L, 0, null);
+ }
+
+ @Test
+ public void primaryHit_returnsPrimary_andSkipsSecondary() {
+ TopicNode local = node("local");
+ FakeSource primary = new FakeSource(local);
+ FakeSource secondary = new FakeSource(node("studio"));
+
+ TopicNode got = new FallbackTreeSource(primary, secondary).fetchTree(ID);
+
+ assertSame("a primary hit must be returned as-is", local, got);
+ assertEquals(1, primary.calls);
+ assertEquals("secondary must not be consulted on a hit", 0, secondary.calls);
+ }
+
+ @Test
+ public void primaryMiss_fallsToSecondary_withSameId() {
+ FakeSource primary = new FakeSource(null);
+ TopicNode studio = node("studio");
+ FakeSource secondary = new FakeSource(studio);
+
+ TopicNode got = new FallbackTreeSource(primary, secondary).fetchTree(ID);
+
+ assertSame(studio, got);
+ assertEquals(1, primary.calls);
+ assertEquals(1, secondary.calls);
+ assertEquals("the fallback must ask for the same node", ID, secondary.asked);
+ }
+
+ @Test
+ public void bothMiss_returnsNull() {
+ FallbackTreeSource fb = new FallbackTreeSource(new FakeSource(null), new FakeSource(null));
+ assertNull(fb.fetchTree(ID));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void nullPrimary_rejected() {
+ new FallbackTreeSource(null, new FakeSource(null));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void nullSecondary_rejected() {
+ new FallbackTreeSource(new FakeSource(null), null);
+ }
+}
diff --git a/controller/app/src/test/java/org/iiab/controller/kolibri/data/LocalTreeSourceTest.java b/controller/app/src/test/java/org/iiab/controller/kolibri/data/LocalTreeSourceTest.java
new file mode 100644
index 000000000..cc1ac4ea5
--- /dev/null
+++ b/controller/app/src/test/java/org/iiab/controller/kolibri/data/LocalTreeSourceTest.java
@@ -0,0 +1,130 @@
+/*
+ * ============================================================================
+ * Name : LocalTreeSourceTest.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : Unit tests for LocalTreeSource against a MockWebServer, mirroring
+ * StudioTreeSourceTest. Verifies the box path and that a miss is a
+ * null the fallback can act on (ADFA-5094).
+ * ============================================================================
+ */
+package org.iiab.controller.kolibri.data;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import java.util.Arrays;
+
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import okhttp3.mockwebserver.RecordedRequest;
+
+import org.iiab.controller.kolibri.domain.TopicNode;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Unit tests for {@link LocalTreeSource} against a local {@link MockWebServer},
+ * the same treatment {@link StudioTreeSourceTest} gives the internet source.
+ *
+ * Two things are specific to the local source and worth pinning: it addresses
+ * the box's {@code /k2go-api/kolibri/tree/} path, and a 404 — the ordinary case
+ * where a channel's metadata is not on the box — comes back as {@code null} so
+ * {@link FallbackTreeSource} moves on to Studio, rather than as an error. The
+ * JSON parsing itself is Studio's mapper and is exercised there; here the focus
+ * is the transport and the miss behaviour.
+ *
+ * Runs on a plain JVM: {@code android.util.Log} is stubbed by the module's
+ * {@code testOptions.unitTests.returnDefaultValues}.
+ */
+public class LocalTreeSourceTest {
+
+ private static final String CH = "c150ea1d69495d37b5b0ac6f017e9bfb";
+ private static final String NODE = "23a7dc9c73635cd2abbd3e8aab13c3ca";
+
+ private MockWebServer server;
+ private LocalTreeSource source;
+
+ @Before
+ public void setUp() throws Exception {
+ server = new MockWebServer();
+ server.start();
+ // Trailing slash on purpose: the constructor has to strip it, or every URL
+ // it builds carries a double slash.
+ source = new LocalTreeSource(server.url("/k2go-api/").toString());
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ server.shutdown();
+ }
+
+ private static MockResponse json(String body) {
+ return new MockResponse().setResponseCode(200)
+ .setHeader("Content-Type", "application/json").setBody(body);
+ }
+
+ private static String treeJson() {
+ return "{\"id\":\"" + CH + "\",\"title\":\"3asafeer\",\"kind\":\"topic\","
+ + "\"is_leaf\":false,\"lft\":1,\"rght\":360,\"children\":{\"more\":null,"
+ + "\"results\":[{\"id\":\"" + NODE + "\",\"title\":\"Beginner\","
+ + "\"kind\":\"video\",\"is_leaf\":true,"
+ + "\"files\":[{\"file_size\":800,\"preset\":\"high_res_video\"}]}]}}";
+ }
+
+ @Test
+ public void readsATreeAndHitsTheBoxPath() throws Exception {
+ server.enqueue(json(treeJson()));
+
+ TopicNode t = source.fetchTree(CH);
+ assertEquals(CH, t.id());
+ assertEquals(1, t.children().size());
+ assertEquals(800L, t.subtreeBytes());
+
+ RecordedRequest req = server.takeRequest();
+ assertEquals("/k2go-api/kolibri/tree/" + CH, req.getPath());
+ assertEquals("GET", req.getMethod());
+ assertEquals("application/json", req.getHeader("Accept"));
+ }
+
+ @Test
+ public void aChannelNotImportedIsNullRatherThanAnException() throws Exception {
+ // 404 is ordinary here — the channel's metadata simply is not on the box —
+ // and must be a null so FallbackTreeSource tries Studio instead.
+ server.enqueue(new MockResponse().setResponseCode(404).setBody("{\"detail\":\"nope\"}"));
+ assertNull(source.fetchTree(CH));
+ }
+
+ @Test
+ public void aServerErrorIsNull() throws Exception {
+ server.enqueue(new MockResponse().setResponseCode(500));
+ assertNull(source.fetchTree(CH));
+ }
+
+ @Test
+ public void anIdThatIsNotANodeIdNeverBecomesARequest() throws Exception {
+ // Validate before the id reaches the URL path: a value with a slash or a
+ // query string would address something else on the box.
+ for (String bad : Arrays.asList("../../admin", "abc?x=1", "bisan-sukod",
+ "", " ", null)) {
+ assertNull("expected null for " + bad, source.fetchTree(bad));
+ }
+ assertEquals("no request should have been made", 0, server.getRequestCount());
+ }
+
+ @Test
+ public void aBodyThatIsNotJsonIsNull() throws Exception {
+ server.enqueue(json("nope"));
+ assertNull(source.fetchTree(CH));
+ }
+
+ @Test
+ public void aBaseUrlWithoutATrailingSlashWorksToo() throws Exception {
+ String noSlash = server.url("/k2go-api").toString();
+ server.enqueue(json(treeJson()));
+ assertNotNull(new LocalTreeSource(noSlash).fetchTree(CH));
+ assertEquals("/k2go-api/kolibri/tree/" + CH, server.takeRequest().getPath());
+ }
+}
diff --git a/controller/docs/ADR-5094-offline-tree-depth.md b/controller/docs/ADR-5094-offline-tree-depth.md
new file mode 100644
index 000000000..c54ccac8d
--- /dev/null
+++ b/controller/docs/ADR-5094-offline-tree-depth.md
@@ -0,0 +1,63 @@
+# ADR — Offline topic-tree depth: box-served tree, local-first with Studio fallback
+
+Status: **Draft, for discussion.** Ticket ADFA-5094 (parent ADFA-1028). Sibling of
+ADR-5094 (catalog service, the *freshness* half); this is the *depth* half. Builds on
+ADR-4954 (Kolibri content selection) and **amends one consequence of it** — that topic
+selection needs connectivity — while leaving the layering intact.
+
+## Context
+
+Channel selection is offline: the channel list is a bundled asset (ADR-4954 D1). Topic
+selection is not. `CatalogRepository.fetchTree(nodeId)` is served by `StudioTreeSource`,
+which reads `studio.learningequality.org/api/public/v2/contentnode_tree/