diff --git a/controller/app/src/main/java/org/iiab/controller/catalog/data/CatalogRefreshScheduler.java b/controller/app/src/main/java/org/iiab/controller/catalog/data/CatalogRefreshScheduler.java index 81e1e4b7a..ca83296aa 100644 --- a/controller/app/src/main/java/org/iiab/controller/catalog/data/CatalogRefreshScheduler.java +++ b/controller/app/src/main/java/org/iiab/controller/catalog/data/CatalogRefreshScheduler.java @@ -38,17 +38,27 @@ private static Data input(String name, String manifestUrl, String basename) { .build(); } - private static Constraints connected() { + private static Constraints constraints(NetworkType netType) { return new Constraints.Builder() - .setRequiredNetworkType(NetworkType.CONNECTED) + .setRequiredNetworkType(netType) .build(); } - /** Weekly periodic refresh, enqueued once per catalog (KEEP). Safe to call on every launch. */ + /** Weekly periodic refresh over any connection. Safe to call on every launch. */ public static void scheduleWeekly(Context ctx, String name, String manifestUrl, String basename) { + scheduleWeekly(ctx, name, manifestUrl, basename, NetworkType.CONNECTED); + } + + /** + * Weekly periodic refresh, enqueued once per catalog (KEEP). Safe to call on every launch. + * {@code netType} lets a large asset ask for {@link NetworkType#UNMETERED} so it refreshes only + * on Wi-Fi and never spends the user's mobile data (ADFA-5094: the tree bundle is ~16 MB). + */ + public static void scheduleWeekly(Context ctx, String name, String manifestUrl, String basename, + NetworkType netType) { PeriodicWorkRequest req = new PeriodicWorkRequest.Builder( CatalogRefreshWorker.class, 7, TimeUnit.DAYS) - .setConstraints(connected()) + .setConstraints(constraints(netType)) .setInputData(input(name, manifestUrl, basename)) .build(); WorkManager.getInstance(ctx.getApplicationContext()) @@ -56,10 +66,20 @@ public static void scheduleWeekly(Context ctx, String name, String manifestUrl, ExistingPeriodicWorkPolicy.KEEP, req); } - /** Opportunistic one-shot; the worker's TTL gate no-ops it when still fresh. */ + /** Opportunistic one-shot over any connection; the worker's TTL gate no-ops it when fresh. */ public static void refreshNow(Context ctx, String name, String manifestUrl, String basename) { + refreshNow(ctx, name, manifestUrl, basename, NetworkType.CONNECTED); + } + + /** + * Opportunistic one-shot; the worker's TTL gate no-ops it when still fresh. {@code netType} + * constrains which connection may trigger it — {@link NetworkType#UNMETERED} keeps a large + * asset off mobile data (ADFA-5094). + */ + public static void refreshNow(Context ctx, String name, String manifestUrl, String basename, + NetworkType netType) { OneTimeWorkRequest req = new OneTimeWorkRequest.Builder(CatalogRefreshWorker.class) - .setConstraints(connected()) + .setConstraints(constraints(netType)) .setInputData(input(name, manifestUrl, basename)) .build(); WorkManager.getInstance(ctx.getApplicationContext()) diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/data/BundledTreeIndex.java b/controller/app/src/main/java/org/iiab/controller/kolibri/data/BundledTreeIndex.java new file mode 100644 index 000000000..1fbcc5a7c --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/data/BundledTreeIndex.java @@ -0,0 +1,170 @@ +/* + * ============================================================================ + * Name : BundledTreeIndex.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : Pure, in-memory index over the flat offline topic-tree bundle + * (kolibri_tree.jsonl, "topics" variant). Serves one level at a + * time, the shape TreeSource wants, without Android or I/O so it + * is unit-testable on a plain JVM (ADFA-5094). + * ============================================================================ + */ +package org.iiab.controller.kolibri.data; + +import org.iiab.controller.kolibri.domain.ChannelId; +import org.iiab.controller.kolibri.domain.TopicNode; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The offline topic tree, flattened. + * + *
The bundle is one JSON object per line, no header — each a folder with the + * aggregates the generator measured over the whole published content DB: {@code count} + * (subtree resource count), {@code bytes} (subtree bytes), and {@code dcount}/{@code dbytes} + * (the folder's direct loose-resource leaves, folded so the bundle need not carry them). A + * row names its {@code parent}; the channel roots carry an empty parent. + * + *
Built once via {@link Builder} (fed line by line, so the ~MB file never lands in a + * single list) and then queried by node id. {@link #fetchOneLevel} returns that node with + * its direct child folders — one level, matching {@link TreeSource#fetchTree} — each child + * carrying its own aggregates so the picker shows sizes before drilling. Individual leaf + * resources are not in the bundle; the live source fills them when online. + * + *
Never throws: a malformed, duplicate, or unidentifiable line is skipped, and an
+ * unknown node id is a {@code null} return.
+ */
+public final class BundledTreeIndex {
+
+ /** A folder row, ids already normalised. */
+ private static final class Row {
+ final String id;
+ final String title;
+ final String kind;
+ final int count;
+ final long bytes;
+ final int dcount;
+ final long dbytes;
+
+ Row(String id, String title, String kind, int count, long bytes, int dcount, long dbytes) {
+ this.id = id;
+ this.title = title;
+ this.kind = kind;
+ this.count = count;
+ this.bytes = bytes;
+ this.dcount = dcount;
+ this.dbytes = dbytes;
+ }
+ }
+
+ private final Map Mirrors {@link BundledCatalogSource}: JSON Lines, one folder per line (no header),
+ * parsed once into a {@link BundledTreeIndex} and cached for the process — the file does
+ * not change while the app runs, and a pulled Cloudflare overlay is preferred over the APK
+ * asset, picked up by the same mtime check.
+ *
+ * Unlike the box- and Studio-backed sources, this one is offline and holds the whole
+ * (topics-only) tree, so it is the last fallback: when the box has not imported a
+ * channel and there is no internet, this still lets the user browse what a channel contains.
+ * Individual leaf resources are not in the bundle — a mixed level shows the folder's loose
+ * aggregate, and the live source fills the leaves when online.
+ *
+ * Blocking; call from an IO thread. Never throws (the {@link TreeSource} contract): a
+ * missing asset or unknown node id is a {@code null} return, so a caller can move on.
+ */
+public final class BundledTreeSource implements TreeSource {
+
+ private static final String TAG = "K2Go-Kolibri";
+ // ADFA-5094: also the overlay basename — CatalogRepositoryImpl points the tree refresh worker
+ // at this same name, so the worker writes the overlay exactly where this source looks for it.
+ static final String ASSET = "kolibri_tree.jsonl";
+
+ private static volatile BundledTreeIndex cachedIndex;
+ // -1 = not loaded, 0 = APK asset, >0 = the pulled overlay's lastModified.
+ private static volatile long cachedOverlayMtime = -1L;
+
+ private final Context appContext;
+
+ public BundledTreeSource(Context context) {
+ this.appContext = context.getApplicationContext();
+ }
+
+ @Override
+ public TopicNode fetchTree(String nodeId) {
+ reloadIfOverlayChanged();
+ BundledTreeIndex idx = load();
+ return idx == null ? null : idx.fetchOneLevel(nodeId);
+ }
+
+ /** Drops the cache. For tests and for the in-place tree refresh (ADFA-5094). */
+ public static void invalidate() {
+ cachedIndex = null;
+ cachedOverlayMtime = -1L;
+ }
+
+ /**
+ * Pick up a freshly pulled overlay (or its removal) without an explicit callback: if the
+ * overlay file's mtime differs from what the cache was loaded from, drop the cache so the
+ * next {@link #load()} reads the current source.
+ */
+ private void reloadIfOverlayChanged() {
+ if (cachedIndex == null) {
+ return; // not loaded yet; load() picks the source
+ }
+ File overlay = CatalogOverlay.file(appContext, ASSET);
+ long mtime = overlay.exists() ? overlay.lastModified() : 0L;
+ if (mtime != cachedOverlayMtime) {
+ invalidate();
+ }
+ }
+
+ private BundledTreeIndex load() {
+ if (cachedIndex != null) {
+ return cachedIndex;
+ }
+ synchronized (BundledTreeSource.class) {
+ if (cachedIndex != null) {
+ return cachedIndex;
+ }
+ BundledTreeIndex.Builder builder = BundledTreeIndex.builder();
+
+ // Prefer the pulled overlay over the APK asset when it is present.
+ File overlay = CatalogOverlay.file(appContext, ASSET);
+ boolean useOverlay = overlay.exists();
+ long mtime = useOverlay ? overlay.lastModified() : 0L;
+
+ try (InputStream is = useOverlay
+ ? new FileInputStream(overlay) : appContext.getAssets().open(ASSET);
+ BufferedReader r = new BufferedReader(
+ new InputStreamReader(is, StandardCharsets.UTF_8))) {
+ String line;
+ while ((line = r.readLine()) != null) {
+ builder.add(line);
+ }
+ } catch (Exception e) {
+ // A missing asset is a build problem, not a runtime one, but it must not take
+ // the app down: log and serve an empty tree, so the caller falls through.
+ Log.w(TAG, "bundled tree unavailable: " + e.getMessage());
+ }
+
+ if (builder.skipped() > 0) {
+ Log.w(TAG, "bundled tree: skipped " + builder.skipped() + " unusable line(s)");
+ }
+ cachedIndex = builder.build();
+ cachedOverlayMtime = mtime;
+ return cachedIndex;
+ }
+ }
+}
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 6f4d1403d..3174a9b79 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
@@ -37,20 +37,39 @@ public final class CatalogRepositoryImpl implements CatalogRepository {
// from, so the worker writes it exactly where the source looks (they must never drift).
private static final String BASENAME = BundledCatalogSource.ASSET;
+ // ADFA-5094: the offline topic-tree bundle is refreshed the same way, from its own manifest,
+ // overlaying its own APK asset. A separate name so the two refreshes never collide.
+ private static final String TREE_CATALOG = "kolibri-tree";
+ private static final String TREE_MANIFEST_URL =
+ "https://k2go-download.appdevforall.org/catalogs/kolibri-tree.manifest.json";
+ private static final String TREE_BASENAME = BundledTreeSource.ASSET;
+
private final BundledCatalogSource bundled;
private final TreeSource tree;
public CatalogRepositoryImpl(Context context) {
// 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.
+ // metadata is imported), then Studio when online, and finally the bundled tree — the
+ // offline floor that lets the user browse a channel even with the box unimported and no
+ // internet. Live sources win when they can answer, so the bundle is consulted last.
this(new BundledCatalogSource(context),
- new FallbackTreeSource(new LocalTreeSource(), new StudioTreeSource()));
+ new FallbackTreeSource(new LocalTreeSource(),
+ new FallbackTreeSource(new StudioTreeSource(), new BundledTreeSource(context))));
// 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(
context, CATALOG, MANIFEST_URL, BASENAME);
org.iiab.controller.catalog.data.CatalogRefreshScheduler.refreshNow(
context, CATALOG, MANIFEST_URL, BASENAME);
+ // The tree bundle refreshes on the same cadence, but only on Wi-Fi (UNMETERED): it is ~16 MB
+ // against the catalog's ~83 KB, and the APK asset is a working floor, so a metered pull is
+ // not worth the user's mobile data.
+ org.iiab.controller.catalog.data.CatalogRefreshScheduler.scheduleWeekly(
+ context, TREE_CATALOG, TREE_MANIFEST_URL, TREE_BASENAME,
+ androidx.work.NetworkType.UNMETERED);
+ org.iiab.controller.catalog.data.CatalogRefreshScheduler.refreshNow(
+ context, TREE_CATALOG, TREE_MANIFEST_URL, TREE_BASENAME,
+ androidx.work.NetworkType.UNMETERED);
}
/** For tests and for pointing the tree source elsewhere (e.g. a local-first composite). */
diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/domain/TopicNode.java b/controller/app/src/main/java/org/iiab/controller/kolibri/domain/TopicNode.java
index ad24a8db9..eb9bc48fd 100644
--- a/controller/app/src/main/java/org/iiab/controller/kolibri/domain/TopicNode.java
+++ b/controller/app/src/main/java/org/iiab/controller/kolibri/domain/TopicNode.java
@@ -49,11 +49,14 @@ public final class TopicNode {
private final long subtreeBytes;
private final boolean subtreeSizeKnown;
private final int descendantCount;
+ private final int looseResourceCount;
+ private final long looseResourceBytes;
private final List Unlike {@link #of}, the subtree size and count are given, not summed
+ * from children: the offline bundle is flat and served one level at a time, and the
+ * aggregates were computed by the generator over the whole published content DB, so
+ * a folder can report its true size before any child is fetched. {@code subtreeBytes}
+ * is therefore always {@link #hasSubtreeSize() known}.
+ *
+ * The bundle keeps only folders; a folder's direct loose leaf resources
+ * are folded into {@code looseResourceCount}/{@code looseResourceBytes}, so a mixed
+ * level can show "N resources here" without carrying leaves the bundle omits. The live
+ * source (Studio / box) fills those individual leaves when online.
+ *
+ * @param descendantCount the subtree resource count the generator measured
+ * @return the node, or {@code null} when {@code rawId} is not a valid node id
+ */
+ public static TopicNode fromBundle(String rawId, String title, String kind,
+ long subtreeBytes, int descendantCount,
+ int looseResourceCount, long looseResourceBytes,
+ List