Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,28 +38,48 @@ 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())
.enqueueUniquePeriodicWork("catalog-refresh-" + name,
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())
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>The bundle is one JSON object per line, no header — each a <em>folder</em> 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.
*
* <p>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.
*
* <p>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<String, Row> byId;
private final Map<String, List<Row>> childrenByParent;

private BundledTreeIndex(Map<String, Row> byId, Map<String, List<Row>> childrenByParent) {
this.byId = byId;
this.childrenByParent = childrenByParent;
}

/** How many folders the index holds. */
public int size() {
return byId.size();
}

/**
* The node at {@code nodeId} with its direct child folders, or {@code null} when the
* bundle does not carry that node. Children are one level deep (no grandchildren).
*/
public TopicNode fetchOneLevel(String nodeId) {
String id = ChannelId.normalise(nodeId);
if (id == null) {
return null;
}
Row self = byId.get(id);
if (self == null) {
return null;
}
List<Row> childRows = childrenByParent.get(id);
List<TopicNode> kids = new ArrayList<>();
if (childRows != null) {
for (Row c : childRows) {
TopicNode child = TopicNode.fromBundle(
c.id, c.title, c.kind, c.bytes, c.count, c.dcount, c.dbytes, null);
if (child != null) {
kids.add(child);
}
}
}
return TopicNode.fromBundle(
self.id, self.title, self.kind, self.bytes, self.count, self.dcount, self.dbytes, kids);
}

public static Builder builder() {
return new Builder();
}

/** Accumulates rows line by line; see {@link #add}. */
public static final class Builder {
private final Map<String, Row> byId = new HashMap<>();
private final Map<String, List<Row>> childrenByParent = new LinkedHashMap<>();
private int skipped;

/**
* Feeds one JSONL line. Blank lines are ignored; a line that will not parse, carries
* no usable id, or repeats an id already seen is counted in {@link #skipped()} and
* dropped. Returns {@code this} for chaining.
*/
public Builder add(String line) {
if (line == null) {
return this;
}
String t = line.trim();
if (t.isEmpty()) {
return this;
}
try {
JSONObject o = new JSONObject(t);
String id = ChannelId.normalise(o.optString("id", ""));
if (id == null || byId.containsKey(id)) {
skipped++;
return this;
}
String parent = ChannelId.normalise(o.optString("parent", ""));
String parentKey = parent == null ? "" : parent; // roots have no parent
Row r = new Row(id,
o.optString("title", ""),
o.optString("kind", ""),
Math.max(0, o.optInt("count", 0)),
Math.max(0L, o.optLong("bytes", 0L)),
Math.max(0, o.optInt("dcount", 0)),
Math.max(0L, o.optLong("dbytes", 0L)));
byId.put(id, r);
List<Row> siblings = childrenByParent.get(parentKey);
if (siblings == null) {
siblings = new ArrayList<>();
childrenByParent.put(parentKey, siblings);
}
siblings.add(r);
} catch (Exception badLine) {
skipped++;
}
return this;
}

/** Lines dropped so far. */
public int skipped() {
return skipped;
}

public BundledTreeIndex build() {
return new BundledTreeIndex(
Collections.unmodifiableMap(byId),
Collections.unmodifiableMap(childrenByParent));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* ============================================================================
* Name : BundledTreeSource.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : Serves the Kolibri topic tree from the flat bundle shipped in
* the APK (kolibri_tree.jsonl), preferring a newer copy pulled
* from Cloudflare. The offline floor for tree browsing: it answers
* when neither the box nor Studio can (ADFA-5094).
* ============================================================================
*/
package org.iiab.controller.kolibri.data;

import android.content.Context;
import android.util.Log;

import org.iiab.controller.catalog.data.CatalogOverlay;
import org.iiab.controller.kolibri.domain.TopicNode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
* The topic tree bundled with the app, as a {@link TreeSource}.
*
* <p>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.
*
* <p>Unlike the box- and Studio-backed sources, this one is offline and holds the whole
* (topics-only) tree, so it is the <em>last</em> 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.
*
* <p>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;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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). */
Expand Down
Loading
Loading