Per the port contract: {@link #fetchApps()} / {@link #fetchContent()} throw on
+ * a real failure (box unreachable); {@link #fetchStorage()} never throws and returns
+ * {@link StorageStatus#unavailable()} when the endpoint is missing or fails, so the
+ * manager degrades gracefully.
+ */
+public final class ContentRepositoryImpl implements ContentRepository {
+
+ private static final String TAG = "CxContentRepository";
+
+ private final CxCoreDataSource dataSource;
+
+ public ContentRepositoryImpl(CxCoreDataSource dataSource) {
+ this.dataSource = dataSource;
+ }
+
+ @Override
+ public List fetchApps() throws Exception {
+ JSONObject json = dataSource.getApps();
+ JSONArray apps = json.optJSONArray("apps");
+ List out = new ArrayList<>();
+ if (apps != null) {
+ for (int i = 0; i < apps.length(); i++) {
+ String app = apps.optString(i, "");
+ if (!app.isEmpty()) {
+ out.add(app);
+ }
+ }
+ }
+ return out;
+ }
+
+ @Override
+ public List fetchContent() throws Exception {
+ JSONObject json = dataSource.getContent();
+ JSONArray items = json.optJSONArray("items");
+ List out = new ArrayList<>();
+ if (items != null) {
+ for (int i = 0; i < items.length(); i++) {
+ JSONObject o = items.optJSONObject(i);
+ if (o == null) {
+ continue;
+ }
+ String app = o.optString("app", "");
+ String kind = o.optString("kind", "");
+ String title = o.optString("title", "");
+ long bytes = o.optLong("bytes", 0L);
+ // identity.localRef is the app's own handle to this item (export / delete).
+ JSONObject identity = o.optJSONObject("identity");
+ String localRef = identity != null ? identity.optString("localRef", "") : "";
+ if (app.isEmpty() || localRef.isEmpty()) {
+ // No stable selection identity: skip rather than list an unactionable row.
+ continue;
+ }
+ out.add(new ContentItem(app, kind, title, bytes, localRef));
+ }
+ }
+ return out;
+ }
+
+ @Override
+ public StorageStatus fetchStorage() {
+ try {
+ JSONObject json = dataSource.getStorage();
+ String volume = json.optString("volume", "");
+ long total = json.optLong("totalBytes", 0L);
+ long free = json.optLong("freeBytes", 0L);
+ long usedByContent = json.optLong("usedByContentBytes", 0L);
+ List perApp = new ArrayList<>();
+ JSONArray arr = json.optJSONArray("perApp");
+ if (arr != null) {
+ for (int i = 0; i < arr.length(); i++) {
+ JSONObject o = arr.optJSONObject(i);
+ if (o == null) {
+ continue;
+ }
+ String app = o.optString("app", "");
+ if (!app.isEmpty()) {
+ perApp.add(new AppUsage(app, o.optLong("bytes", 0L)));
+ }
+ }
+ }
+ return StorageStatus.of(volume, total, free, usedByContent, perApp);
+ } catch (Exception e) {
+ // Optional endpoint (added by a parallel core change): degrade, do not fail.
+ Log.i(TAG, "Storage summary unavailable: " + e.getMessage());
+ return StorageStatus.unavailable();
+ }
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java
new file mode 100644
index 000000000..3ce36f9e2
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java
@@ -0,0 +1,86 @@
+/*
+ * ============================================================================
+ * Name : CxCoreDataSource.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-427. App-side reader of the content-exchange core (cx-core)
+ * through dash-node's relay (/k2go-api/v1/*). Read side only
+ * (list + storage); the export / import / delete calls are later
+ * slices. Same HttpURLConnection shape as content/RestContentClient.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.contentexchange.data;
+
+import org.appdevforall.k2go.config.BoxEndpoints;
+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;
+
+/**
+ * The one place in this feature that touches {@link HttpURLConnection}. It issues
+ * GETs to the cx-core read endpoints and returns the parsed JSON object; mapping
+ * to domain entities lives in {@link ContentRepositoryImpl}.
+ *
+ *
Must be called off the main thread.
+ */
+public final class CxCoreDataSource {
+
+ /** cx-core API root behind dash-node's relay: {@code http://localhost:8085/k2go-api/v1}. */
+ private static final String V1 = BoxEndpoints.API + "/v1";
+
+ private static final int CONNECT_TIMEOUT_MS = 5000;
+ private static final int READ_TIMEOUT_MS = 20000;
+
+ /** {@code GET /v1/apps} -> {@code {"apps": [...]}}. */
+ public JSONObject getApps() throws Exception {
+ return getJson(V1 + "/apps");
+ }
+
+ /** {@code GET /v1/content} -> {@code {"items": [...]}} (all apps). */
+ public JSONObject getContent() throws Exception {
+ return getJson(V1 + "/content");
+ }
+
+ /** {@code GET /v1/storage} -> the storage summary. May 404 until the core adds it. */
+ public JSONObject getStorage() throws Exception {
+ return getJson(V1 + "/storage");
+ }
+
+ private static JSONObject getJson(String urlStr) throws Exception {
+ HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection();
+ try {
+ c.setUseCaches(false);
+ c.setConnectTimeout(CONNECT_TIMEOUT_MS);
+ c.setReadTimeout(READ_TIMEOUT_MS);
+ c.setRequestMethod("GET");
+ c.setRequestProperty("Accept", "application/json");
+ int code = c.getResponseCode();
+ boolean ok = code >= 200 && code < 400;
+ String text = readAll(ok ? c.getInputStream() : c.getErrorStream());
+ if (!ok) {
+ throw new Exception("HTTP " + code + ": " + text);
+ }
+ return new JSONObject(text.isEmpty() ? "{}" : text);
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ private static String readAll(InputStream is) throws Exception {
+ if (is == null) {
+ return "";
+ }
+ ByteArrayOutputStream buf = new ByteArrayOutputStream();
+ byte[] chunk = new byte[4096];
+ int n;
+ while ((n = is.read(chunk)) != -1) {
+ buf.write(chunk, 0, n);
+ }
+ is.close();
+ return buf.toString(StandardCharsets.UTF_8.name());
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/AppUsage.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/AppUsage.java
new file mode 100644
index 000000000..63103d845
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/AppUsage.java
@@ -0,0 +1,24 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+/**
+ * Bytes used by one app's content, as reported by the core {@code GET /v1/storage}
+ * {@code perApp} list. Immutable value object. Pure domain type.
+ */
+public final class AppUsage {
+
+ private final String app;
+ private final long bytes;
+
+ public AppUsage(String app, long bytes) {
+ this.app = app;
+ this.bytes = bytes;
+ }
+
+ public String app() {
+ return app;
+ }
+
+ public long bytes() {
+ return bytes;
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentGroup.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentGroup.java
new file mode 100644
index 000000000..7f88983bd
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentGroup.java
@@ -0,0 +1,43 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * One app's content as the manager renders it: the app key, its items, and the
+ * sum of their sizes. An installed app with no content is a valid empty group
+ * (so the manager can show "Kiwix: no items"), which is why {@code app} comes
+ * from the installed-apps list, not only from the items.
+ *
+ *
Immutable value object. Pure domain type.
+ */
+public final class ContentGroup {
+
+ private final String app;
+ private final List items;
+ private final long totalBytes;
+
+ public ContentGroup(String app, List items, long totalBytes) {
+ this.app = app;
+ this.items = Collections.unmodifiableList(items);
+ this.totalBytes = totalBytes;
+ }
+
+ public String app() {
+ return app;
+ }
+
+ /** The app's items (never null; may be empty for an installed-but-empty app). */
+ public List items() {
+ return items;
+ }
+
+ public boolean isEmpty() {
+ return items.isEmpty();
+ }
+
+ /** Sum of the items' sizes in bytes. */
+ public long totalBytes() {
+ return totalBytes;
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentItem.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentItem.java
new file mode 100644
index 000000000..3d03a12ff
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentItem.java
@@ -0,0 +1,69 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+/**
+ * One managed content item on the box, as the manager UI lists it.
+ *
+ *
Immutable value object. Maps one entry of the core {@code GET /v1/content}
+ * manifest (ADR "granular content exchange", Pillar 1 read side). This slice needs
+ * only the display and selection fields: {@code app} (adapter key, the grouping
+ * axis), {@code kind} (the app content type), {@code title}, {@code bytes}, and
+ * {@code localRef} (the app's own authoritative-local handle to this exact item).
+ * The pair {@code (app, localRef)} is the selection identity the later action
+ * slices (export / delete) address an item by.
+ *
+ *
The cross-box {@code dedup} envelope the manifest also carries is NOT modeled
+ * here: no code in this read/select slice reads it. The import / share slices that
+ * need it extend this entity and its mapper.
+ *
+ *
Pure domain type: no Android and no networking dependencies.
+ */
+public final class ContentItem {
+
+ private final String app;
+ private final String kind;
+ private final String title;
+ private final long bytes;
+ private final String localRef;
+
+ public ContentItem(String app, String kind, String title, long bytes, String localRef) {
+ this.app = app;
+ this.kind = kind;
+ this.title = title;
+ this.bytes = bytes;
+ this.localRef = localRef;
+ }
+
+ /** Adapter key: kiwix, kolibri, calibre, ... . The grouping axis. */
+ public String app() {
+ return app;
+ }
+
+ /** App content type (free-form, app-defined). */
+ public String kind() {
+ return kind;
+ }
+
+ public String title() {
+ return title;
+ }
+
+ /** Available size in bytes; a value {@code <= 0} means "unknown". */
+ public long bytes() {
+ return bytes;
+ }
+
+ /** The app's own handle to this item on this box (export / delete address). */
+ public String localRef() {
+ return localRef;
+ }
+
+ /** Stable selection key for multi-select: {@code app + "/" + localRef}. */
+ public String selectionId() {
+ return app + "/" + localRef;
+ }
+
+ @Override
+ public String toString() {
+ return "ContentItem{" + app + ", " + localRef + ", bytes=" + bytes + '}';
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentRepository.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentRepository.java
new file mode 100644
index 000000000..b40a77c11
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentRepository.java
@@ -0,0 +1,44 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+import java.util.List;
+
+/**
+ * Domain port for reading managed content and storage from the box.
+ *
+ *
The abstraction the domain owns; the Data layer implements it against the
+ * core REST API (reached through dash-node: {@code /k2go-api/v1/*}). The domain
+ * never learns HOW the data is fetched.
+ *
+ *
Error contract:
+ *
+ *
{@link #fetchApps()} and {@link #fetchContent()} back the manager's
+ * essential data; they throw on a real failure (box unreachable), which the
+ * use case / ViewModel turns into an error state.
+ *
{@link #fetchStorage()} is optional (the endpoint may not exist yet); it
+ * never throws and returns {@link StorageStatus#unavailable()} on any
+ * failure, so the manager degrades gracefully to "no free-disk figure".
+ *
+ */
+public interface ContentRepository {
+
+ /**
+ * Installed apps that have a loaded adapter on the box ({@code GET /v1/apps}).
+ * Drives the group set and ordering, so an installed-but-empty app still shows.
+ *
+ * @throws Exception when the box cannot be reached.
+ */
+ List fetchApps() throws Exception;
+
+ /**
+ * Every content item on the box ({@code GET /v1/content}).
+ *
+ * @throws Exception when the box cannot be reached.
+ */
+ List fetchContent() throws Exception;
+
+ /**
+ * The box storage summary ({@code GET /v1/storage}). Never throws; returns
+ * {@link StorageStatus#unavailable()} when the endpoint is missing or fails.
+ */
+ StorageStatus fetchStorage();
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/GetStorageStatusUseCase.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/GetStorageStatusUseCase.java
new file mode 100644
index 000000000..a7285b2bf
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/GetStorageStatusUseCase.java
@@ -0,0 +1,24 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+/**
+ * Gets the box storage summary for the manager's "total used / free disk" row.
+ *
+ *
Thin by design: the degrade rule ("could not read /v1/storage") lives in the
+ * repository contract, which returns {@link StorageStatus#unavailable()} instead
+ * of throwing. This use case never throws, so a missing storage endpoint never
+ * fails the manager: the content still lists, only the free-disk figure is hidden.
+ */
+public final class GetStorageStatusUseCase {
+
+ private final ContentRepository repository;
+
+ public GetStorageStatusUseCase(ContentRepository repository) {
+ this.repository = repository;
+ }
+
+ /** Never null; {@link StorageStatus#available()} is {@code false} when unreachable. */
+ public StorageStatus execute() {
+ StorageStatus status = repository.fetchStorage();
+ return status != null ? status : StorageStatus.unavailable();
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ListManagedContentUseCase.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ListManagedContentUseCase.java
new file mode 100644
index 000000000..05d52d216
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ListManagedContentUseCase.java
@@ -0,0 +1,116 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Lists managed content grouped by app, with per-group and grand totals.
+ *
+ *
This is the business rule the manager renders. The grouping, ordering and
+ * totalling live here (not in the UI or the data source), so it is a pure,
+ * JVM-unit-testable function of (installed apps, content items).
+ *
+ *
Rules:
+ *
+ *
One group per installed app, so an installed-but-empty app still shows.
+ *
Items whose app is not in the installed list are not dropped: a trailing
+ * group is created for each such app (defensive against a lagging
+ * {@code /v1/apps}).
+ *
Group order: a preferred order ({@code kiwix, kolibri, calibre}) first,
+ * then any other apps alphabetically.
+ *
Items within a group are ordered by title (case-insensitive), then by
+ * {@code localRef} as a stable tiebreak.
+ *
A group total is the sum of its items' bytes; the grand total is the sum
+ * across all groups.
+ *
+ */
+public final class ListManagedContentUseCase {
+
+ /** Apps shown first, in this order; any other app follows alphabetically. */
+ static final List PREFERRED_ORDER = Arrays.asList("kiwix", "kolibri", "calibre");
+
+ private final ContentRepository repository;
+
+ public ListManagedContentUseCase(ContentRepository repository) {
+ this.repository = repository;
+ }
+
+ /** Fetches installed apps + content from the box, then groups them. */
+ public ManagedContent execute() throws Exception {
+ return group(repository.fetchApps(), repository.fetchContent());
+ }
+
+ /**
+ * Pure grouping: installed apps + items -> grouped content with totals.
+ * Static and side-effect-free so tests drive it directly.
+ */
+ static ManagedContent group(List installedApps, List items) {
+ // Preserve one slot per installed app (empty groups included), in a map that
+ // keeps insertion order; orphan-app items append new slots after.
+ Map> byApp = new LinkedHashMap<>();
+ if (installedApps != null) {
+ for (String app : installedApps) {
+ if (app != null && !byApp.containsKey(app)) {
+ byApp.put(app, new ArrayList<>());
+ }
+ }
+ }
+ if (items != null) {
+ for (ContentItem item : items) {
+ if (item == null) {
+ continue;
+ }
+ byApp.computeIfAbsent(item.app(), k -> new ArrayList<>()).add(item);
+ }
+ }
+
+ List appOrder = new ArrayList<>(byApp.keySet());
+ appOrder.sort(ListManagedContentUseCase::compareApps);
+
+ List groups = new ArrayList<>(appOrder.size());
+ long grandTotal = 0L;
+ for (String app : appOrder) {
+ List groupItems = byApp.get(app);
+ groupItems.sort(ITEM_ORDER);
+ long groupTotal = 0L;
+ for (ContentItem item : groupItems) {
+ groupTotal += Math.max(0L, item.bytes());
+ }
+ grandTotal += groupTotal;
+ groups.add(new ContentGroup(app, groupItems, groupTotal));
+ }
+ return new ManagedContent(groups, grandTotal);
+ }
+
+ /** Preferred apps first in their fixed order, then the rest alphabetically. */
+ static int compareApps(String a, String b) {
+ int ra = PREFERRED_ORDER.indexOf(a);
+ int rb = PREFERRED_ORDER.indexOf(b);
+ if (ra >= 0 || rb >= 0) {
+ if (ra < 0) {
+ return 1;
+ }
+ if (rb < 0) {
+ return -1;
+ }
+ return Integer.compare(ra, rb);
+ }
+ return a.compareToIgnoreCase(b);
+ }
+
+ private static final Comparator ITEM_ORDER = (x, y) -> {
+ int byTitle = safe(x.title()).compareToIgnoreCase(safe(y.title()));
+ if (byTitle != 0) {
+ return byTitle;
+ }
+ return safe(x.localRef()).compareTo(safe(y.localRef()));
+ };
+
+ private static String safe(String s) {
+ return s == null ? "" : s;
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ManagedContent.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ManagedContent.java
new file mode 100644
index 000000000..f04d96d14
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ManagedContent.java
@@ -0,0 +1,41 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * All managed content on the box, grouped by app, with the grand total of every
+ * item's size. This is what {@link ListManagedContentUseCase} produces and the
+ * manager screen renders (groups + per-item sizes + total used).
+ *
+ *
Immutable value object. Pure domain type.
+ */
+public final class ManagedContent {
+
+ private final List groups;
+ private final long totalBytes;
+
+ public ManagedContent(List groups, long totalBytes) {
+ this.groups = Collections.unmodifiableList(groups);
+ this.totalBytes = totalBytes;
+ }
+
+ /** Per-app groups, in display order (never null; may be empty). */
+ public List groups() {
+ return groups;
+ }
+
+ /** Sum of every item's size across all groups: the "total used by content". */
+ public long totalBytes() {
+ return totalBytes;
+ }
+
+ public boolean isEmpty() {
+ for (ContentGroup g : groups) {
+ if (!g.isEmpty()) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/StorageStatus.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/StorageStatus.java
new file mode 100644
index 000000000..594dbd084
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/StorageStatus.java
@@ -0,0 +1,79 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * The box content volume's storage summary, mapped from the core
+ * {@code GET /v1/storage} ({volume, totalBytes, freeBytes, usedByContentBytes,
+ * perApp:[{app, bytes}]}).
+ *
+ *
{@code /v1/storage} is added by a parallel core change and may not be
+ * reachable yet; {@link #available()} is {@code false} then, and the manager
+ * degrades to showing content without the free-disk figure (never an error). An
+ * {@link #unavailable()} instance carries this state.
+ *
+ *
Note: {@code freeBytes} / {@code totalBytes} describe the BOX volume as the core
+ * sees it. On K2Go that is a fiction (the box writes into a subtree of the phone
+ * storage), so the manager takes only the CONTENT totals ({@code usedByContentBytes},
+ * {@code perApp}) from here and reads the real free disk phone-side via
+ * {@code storage.StorageProbe}. The box figures are kept for the box-side IIAB Console.
+ *
+ *
Immutable value object. Pure domain type.
+ */
+public final class StorageStatus {
+
+ private final boolean available;
+ private final String volume;
+ private final long totalBytes;
+ private final long freeBytes;
+ private final long usedByContentBytes;
+ private final List perApp;
+
+ private StorageStatus(boolean available, String volume, long totalBytes, long freeBytes,
+ long usedByContentBytes, List perApp) {
+ this.available = available;
+ this.volume = volume;
+ this.totalBytes = totalBytes;
+ this.freeBytes = freeBytes;
+ this.usedByContentBytes = usedByContentBytes;
+ this.perApp = Collections.unmodifiableList(perApp);
+ }
+
+ public static StorageStatus of(String volume, long totalBytes, long freeBytes,
+ long usedByContentBytes, List perApp) {
+ return new StorageStatus(true, volume, totalBytes, freeBytes, usedByContentBytes, perApp);
+ }
+
+ /** The "could not read /v1/storage" state: no figures, {@code available == false}. */
+ public static StorageStatus unavailable() {
+ return new StorageStatus(false, null, 0L, 0L, 0L, Collections.emptyList());
+ }
+
+ /** {@code true} when the core returned a storage summary; {@code false} when it was unreachable. */
+ public boolean available() {
+ return available;
+ }
+
+ public String volume() {
+ return volume;
+ }
+
+ public long totalBytes() {
+ return totalBytes;
+ }
+
+ /** Free bytes on the box content volume; meaningful only when {@link #available()}. */
+ public long freeBytes() {
+ return freeBytes;
+ }
+
+ public long usedByContentBytes() {
+ return usedByContentBytes;
+ }
+
+ /** Per-app byte usage (never null; empty when unavailable). */
+ public List perApp() {
+ return perApp;
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java
new file mode 100644
index 000000000..f69758115
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java
@@ -0,0 +1,320 @@
+package org.appdevforall.k2go.contentexchange.presentation;
+
+import android.content.Context;
+import android.graphics.Typeface;
+import android.view.Gravity;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.core.content.ContextCompat;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.google.android.material.checkbox.MaterialCheckBox;
+
+import org.appdevforall.k2go.R;
+import org.appdevforall.k2go.contentexchange.domain.ContentItem;
+import org.appdevforall.k2go.util.ByteFormatter;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Recycling adapter for the content manager. A single flat row list with four view
+ * types: one header block (title + subtitle + storage summary), one header per app
+ * group, one row per content item, and an empty-state note. Only the item rows can
+ * be numerous: recycling keeps a large library (hundreds of books / many ZIMs) from
+ * inflating one view per item at once, which janks and can OOM weak 32-bit devices.
+ *
+ *
Selection state is NOT held here: it lives in {@link ContentManagerViewModel};
+ * the adapter reads and toggles it through {@link SelectionController}, so a rebound
+ * (recycled) row always reflects the current selection.
+ */
+public final class ContentManagerAdapter extends RecyclerView.Adapter {
+
+ /** The adapter's window into the ViewModel-owned selection. */
+ public interface SelectionController {
+ boolean isSelected(String selectionId);
+
+ void toggle(String selectionId);
+ }
+
+ static final int TYPE_HEADER = 0;
+ static final int TYPE_GROUP = 1;
+ static final int TYPE_ITEM = 2;
+ static final int TYPE_EMPTY = 3;
+
+ private final List rows = new ArrayList<>();
+ private final SelectionController selection;
+
+ public ContentManagerAdapter(SelectionController selection) {
+ this.selection = selection;
+ }
+
+ public void submit(List newRows) {
+ rows.clear();
+ rows.addAll(newRows);
+ notifyDataSetChanged();
+ }
+
+ @Override
+ public int getItemViewType(int position) {
+ return rows.get(position).type;
+ }
+
+ @Override
+ public int getItemCount() {
+ return rows.size();
+ }
+
+ @NonNull
+ @Override
+ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ Context ctx = parent.getContext();
+ switch (viewType) {
+ case TYPE_HEADER:
+ return new HeaderVH(ctx);
+ case TYPE_GROUP:
+ return new GroupVH(ctx);
+ case TYPE_EMPTY:
+ return new EmptyVH(ctx);
+ default:
+ return new ItemVH(ctx, selection);
+ }
+ }
+
+ @Override
+ public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
+ Row row = rows.get(position);
+ switch (row.type) {
+ case TYPE_HEADER:
+ ((HeaderVH) holder).bind((HeaderRow) row);
+ break;
+ case TYPE_GROUP:
+ ((GroupVH) holder).bind((GroupRow) row);
+ break;
+ case TYPE_EMPTY:
+ ((EmptyVH) holder).bind((EmptyRow) row);
+ break;
+ default:
+ ((ItemVH) holder).bind((ItemRow) row);
+ break;
+ }
+ }
+
+ // --- Row model (all strings resolved by the Fragment, which owns Context/resources) ---
+
+ public abstract static class Row {
+ final int type;
+
+ Row(int type) {
+ this.type = type;
+ }
+ }
+
+ public static final class HeaderRow extends Row {
+ final String title;
+ final String subtitle;
+ final String usedLine;
+ final String freeLine;
+
+ public HeaderRow(String title, String subtitle, String usedLine, String freeLine) {
+ super(TYPE_HEADER);
+ this.title = title;
+ this.subtitle = subtitle;
+ this.usedLine = usedLine;
+ this.freeLine = freeLine;
+ }
+ }
+
+ public static final class GroupRow extends Row {
+ final String name;
+ final String meta;
+
+ public GroupRow(String name, String meta) {
+ super(TYPE_GROUP);
+ this.name = name;
+ this.meta = meta;
+ }
+ }
+
+ public static final class ItemRow extends Row {
+ final ContentItem item;
+
+ public ItemRow(ContentItem item) {
+ super(TYPE_ITEM);
+ this.item = item;
+ }
+ }
+
+ public static final class EmptyRow extends Row {
+ final String text;
+
+ public EmptyRow(String text) {
+ super(TYPE_EMPTY);
+ this.text = text;
+ }
+ }
+
+ // --- View holders (views built programmatically, like the redesign's card rows) ---
+
+ private static int px(Context ctx, int dp) {
+ return Math.round(dp * ctx.getResources().getDisplayMetrics().density);
+ }
+
+ private static RecyclerView.LayoutParams fullWidth(int topMarginPx, int bottomMarginPx) {
+ RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(
+ RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT);
+ lp.topMargin = topMarginPx;
+ lp.bottomMargin = bottomMarginPx;
+ return lp;
+ }
+
+ private static TextView text(Context ctx, int appearance, int colorRes) {
+ TextView tv = new TextView(ctx);
+ tv.setTextAppearance(appearance);
+ tv.setTextColor(ContextCompat.getColor(ctx, colorRes));
+ return tv;
+ }
+
+ static final class HeaderVH extends RecyclerView.ViewHolder {
+ private final TextView title;
+ private final TextView subtitle;
+ private final TextView used;
+ private final TextView free;
+
+ HeaderVH(Context ctx) {
+ super(new LinearLayout(ctx));
+ LinearLayout root = (LinearLayout) itemView;
+ root.setOrientation(LinearLayout.VERTICAL);
+ root.setLayoutParams(fullWidth(px(ctx, 16), px(ctx, 4)));
+
+ title = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_HeadlineMedium, R.color.k2go_ink);
+ root.addView(title);
+
+ subtitle = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodyLarge, R.color.k2go_muted);
+ LinearLayout.LayoutParams subLp = new LinearLayout.LayoutParams(-1, -2);
+ subLp.topMargin = px(ctx, 4);
+ root.addView(subtitle, subLp);
+
+ LinearLayout card = new LinearLayout(ctx);
+ card.setOrientation(LinearLayout.VERTICAL);
+ card.setBackgroundResource(R.drawable.k2go_card_bg);
+ card.setPadding(px(ctx, 16), px(ctx, 14), px(ctx, 16), px(ctx, 14));
+ LinearLayout.LayoutParams cardLp = new LinearLayout.LayoutParams(-1, -2);
+ cardLp.topMargin = px(ctx, 16);
+ root.addView(card, cardLp);
+
+ used = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_TitleMedium, R.color.k2go_ink);
+ card.addView(used);
+ free = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodyMedium, R.color.k2go_muted);
+ LinearLayout.LayoutParams freeLp = new LinearLayout.LayoutParams(-1, -2);
+ freeLp.topMargin = px(ctx, 2);
+ card.addView(free, freeLp);
+ }
+
+ void bind(HeaderRow row) {
+ title.setText(row.title);
+ subtitle.setText(row.subtitle);
+ used.setText(row.usedLine);
+ free.setText(row.freeLine);
+ }
+ }
+
+ static final class GroupVH extends RecyclerView.ViewHolder {
+ private final TextView name;
+ private final TextView meta;
+
+ GroupVH(Context ctx) {
+ super(new LinearLayout(ctx));
+ LinearLayout root = (LinearLayout) itemView;
+ root.setOrientation(LinearLayout.HORIZONTAL);
+ root.setGravity(Gravity.CENTER_VERTICAL);
+ root.setLayoutParams(fullWidth(px(ctx, 16), px(ctx, 8)));
+
+ name = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_TitleMedium, R.color.k2go_ink);
+ name.setTypeface(name.getTypeface(), Typeface.BOLD);
+ root.addView(name, new LinearLayout.LayoutParams(0, -2, 1f));
+
+ meta = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodySmall, R.color.k2go_muted);
+ root.addView(meta);
+ }
+
+ void bind(GroupRow row) {
+ name.setText(row.name);
+ meta.setText(row.meta);
+ }
+ }
+
+ static final class ItemVH extends RecyclerView.ViewHolder {
+ private final MaterialCheckBox checkBox;
+ private final TextView title;
+ private final TextView size;
+ private final SelectionController selection;
+ private String boundId;
+
+ ItemVH(Context ctx, SelectionController selection) {
+ super(new LinearLayout(ctx));
+ this.selection = selection;
+ LinearLayout row = (LinearLayout) itemView;
+ row.setOrientation(LinearLayout.HORIZONTAL);
+ row.setGravity(Gravity.CENTER_VERTICAL);
+ row.setBackgroundResource(R.drawable.k2go_card_bg);
+ row.setPadding(px(ctx, 16), px(ctx, 14), px(ctx, 16), px(ctx, 14));
+ row.setLayoutParams(fullWidth(0, px(ctx, 12)));
+
+ checkBox = new MaterialCheckBox(ctx);
+ // Fixed-width leading slot so every row shares one indentation (K2GO-426 convention).
+ FrameLayout slot = new FrameLayout(ctx);
+ FrameLayout.LayoutParams clp = new FrameLayout.LayoutParams(-2, -2);
+ clp.gravity = Gravity.CENTER;
+ slot.addView(checkBox, clp);
+ LinearLayout.LayoutParams slotLp = new LinearLayout.LayoutParams(px(ctx, 40), -2);
+ slotLp.rightMargin = px(ctx, 4);
+ row.addView(slot, slotLp);
+
+ title = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_TitleMedium, R.color.k2go_ink);
+ row.addView(title, new LinearLayout.LayoutParams(0, -2, 1f));
+
+ size = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodySmall, R.color.k2go_muted);
+ LinearLayout.LayoutParams szLp = new LinearLayout.LayoutParams(-2, -2);
+ szLp.leftMargin = px(ctx, 8);
+ row.addView(size, szLp);
+
+ // User taps only: setChecked() during bind does not fire OnClickListener, so a recycled
+ // row never toggles the model by itself. A row tap performs the checkbox click (bigger target).
+ checkBox.setOnClickListener(v -> {
+ if (boundId != null) {
+ this.selection.toggle(boundId);
+ }
+ });
+ row.setClickable(true);
+ row.setOnClickListener(v -> checkBox.performClick());
+ }
+
+ void bind(ItemRow row) {
+ ContentItem item = row.item;
+ boundId = item.selectionId();
+ title.setText(item.title().isEmpty() ? item.localRef() : item.title());
+ size.setText(ByteFormatter.humanBytes(item.bytes()));
+ checkBox.setChecked(selection.isSelected(boundId));
+ }
+ }
+
+ static final class EmptyVH extends RecyclerView.ViewHolder {
+ private final TextView tv;
+
+ EmptyVH(Context ctx) {
+ super(text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodySmall, R.color.k2go_muted));
+ tv = (TextView) itemView;
+ tv.setLayoutParams(fullWidth(0, px(ctx, 12)));
+ }
+
+ void bind(EmptyRow row) {
+ tv.setText(row.text);
+ }
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java
new file mode 100644
index 000000000..c58337e42
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java
@@ -0,0 +1,196 @@
+/*
+ * ============================================================================
+ * Name : ContentManagerFragment.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-427. The content manager (gestor): lists managed content
+ * grouped by app, each item with its size, plus total used and the
+ * free disk, with per-item multi-select. SLICE 1 (foundation): the
+ * bottom action bar (Export / Share / Delete) is present but
+ * disabled; those actions are later slices.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.contentexchange.presentation;
+
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.fragment.app.Fragment;
+import androidx.lifecycle.ViewModelProvider;
+import androidx.recyclerview.widget.LinearLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
+
+import org.appdevforall.k2go.R;
+import org.appdevforall.k2go.contentexchange.domain.ContentGroup;
+import org.appdevforall.k2go.contentexchange.domain.ContentItem;
+import org.appdevforall.k2go.contentexchange.domain.ManagedContent;
+import org.appdevforall.k2go.contentexchange.domain.StorageStatus;
+import org.appdevforall.k2go.storage.StorageProbe;
+import org.appdevforall.k2go.util.ByteFormatter;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Reads the box content through {@link ContentManagerViewModel} and renders it in a
+ * {@link RecyclerView} (recycled item rows, so a large library does not inflate one
+ * view per item). The storage summary and the per-app group headers are row types in
+ * the same list. Selection lives in the ViewModel; the bottom bar reflects it.
+ */
+public class ContentManagerFragment extends Fragment {
+
+ private ContentManagerViewModel viewModel;
+ private ContentManagerAdapter adapter;
+
+ private RecyclerView list;
+ private TextView status;
+ private View actionBar;
+ private TextView selectionLabel;
+
+ @Nullable
+ @Override
+ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle s) {
+ View root = inflater.inflate(R.layout.fragment_k2go_content_manager, container, false);
+ list = root.findViewById(R.id.k2go_cx_list);
+ status = root.findViewById(R.id.k2go_cx_status);
+ actionBar = root.findViewById(R.id.k2go_cx_actionbar);
+ selectionLabel = root.findViewById(R.id.k2go_cx_selection_label);
+
+ TextView back = root.findViewById(R.id.k2go_cx_back);
+ back.setText(getString(R.string.k2go_back_link));
+ back.setOnClickListener(v -> requireActivity().getOnBackPressedDispatcher().onBackPressed());
+
+ viewModel = new ViewModelProvider(this, new ContentManagerViewModelFactory())
+ .get(ContentManagerViewModel.class);
+
+ adapter = new ContentManagerAdapter(new ContentManagerAdapter.SelectionController() {
+ @Override
+ public boolean isSelected(String selectionId) {
+ return viewModel.isSelected(selectionId);
+ }
+
+ @Override
+ public void toggle(String selectionId) {
+ viewModel.toggle(selectionId);
+ }
+ });
+ list.setLayoutManager(new LinearLayoutManager(requireContext()));
+ list.setAdapter(adapter);
+
+ viewModel.state().observe(getViewLifecycleOwner(), this::render);
+ viewModel.selection().observe(getViewLifecycleOwner(), this::renderSelection);
+
+ if (s == null) {
+ viewModel.load();
+ }
+ return root;
+ }
+
+ private void render(ContentManagerUiState st) {
+ if (st == null) {
+ return;
+ }
+ switch (st.status) {
+ case LOADING:
+ list.setVisibility(View.GONE);
+ showStatus(getString(R.string.k2go_cx_loading));
+ return;
+ case ERROR:
+ list.setVisibility(View.GONE);
+ showStatus(getString(R.string.k2go_cx_error));
+ return;
+ default:
+ break;
+ }
+ status.setVisibility(View.GONE);
+ list.setVisibility(View.VISIBLE);
+ adapter.submit(buildRows(st.content, st.storage));
+ }
+
+ private void showStatus(String text) {
+ status.setText(text);
+ status.setVisibility(View.VISIBLE);
+ }
+
+ /** Flattens the grouped content into the adapter's row list (header, groups, items, empty). */
+ private List buildRows(ManagedContent content, StorageStatus storage) {
+ List rows = new ArrayList<>();
+ rows.add(new ContentManagerAdapter.HeaderRow(
+ getString(R.string.k2go_cx_title),
+ getString(R.string.k2go_cx_subtitle),
+ usedLine(content, storage),
+ freeLine()));
+ if (content.isEmpty()) {
+ rows.add(new ContentManagerAdapter.EmptyRow(getString(R.string.k2go_cx_empty)));
+ return rows;
+ }
+ for (ContentGroup group : content.groups()) {
+ rows.add(new ContentManagerAdapter.GroupRow(
+ appDisplayName(group.app()),
+ getString(R.string.k2go_cx_group_meta_fmt,
+ group.items().size(), ByteFormatter.humanBytes(group.totalBytes()))));
+ if (group.isEmpty()) {
+ rows.add(new ContentManagerAdapter.EmptyRow(getString(R.string.k2go_cx_group_empty)));
+ } else {
+ for (ContentItem item : group.items()) {
+ rows.add(new ContentManagerAdapter.ItemRow(item));
+ }
+ }
+ }
+ return rows;
+ }
+
+ /**
+ * "Used by content" from the core: {@code usedByContentBytes} when {@code /v1/storage} is
+ * available (dedup-aware), else the item sum from {@code /v1/content}.
+ */
+ private String usedLine(ManagedContent content, StorageStatus storage) {
+ long used = (storage != null && storage.available())
+ ? storage.usedByContentBytes() : content.totalBytes();
+ return getString(R.string.k2go_cx_used_fmt, ByteFormatter.humanBytes(used));
+ }
+
+ /**
+ * Free disk from the shared {@link StorageProbe} (StatFs): on K2Go the app owns the phone-disk
+ * truth, not the core's {@code /v1/storage} box-volume figure (a fiction on the phone).
+ */
+ private String freeLine() {
+ Long freeBytes = StorageProbe.freeBytes(requireContext());
+ return freeBytes != null
+ ? getString(R.string.k2go_cx_free_fmt, ByteFormatter.humanBytes(freeBytes))
+ : getString(R.string.k2go_cx_free_unavailable);
+ }
+
+ /** Updates the bottom action bar from the selection. Buttons stay disabled (slice 1). */
+ private void renderSelection(SelectionSummary sel) {
+ if (sel == null || sel.isEmpty()) {
+ actionBar.setVisibility(View.GONE);
+ return;
+ }
+ selectionLabel.setText(getString(R.string.k2go_cx_selected_fmt,
+ sel.count, ByteFormatter.humanBytes(sel.bytes)));
+ actionBar.setVisibility(View.VISIBLE);
+ }
+
+ /** Friendly app label; falls back to the raw adapter key for an unknown app. */
+ private String appDisplayName(String app) {
+ if (app == null) {
+ return "";
+ }
+ switch (app) {
+ case "kiwix":
+ return getString(R.string.k2go_cx_app_kiwix);
+ case "kolibri":
+ return getString(R.string.k2go_cx_app_kolibri);
+ case "calibre":
+ return getString(R.string.k2go_cx_app_calibre);
+ default:
+ return app;
+ }
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerUiState.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerUiState.java
new file mode 100644
index 000000000..b23aabac2
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerUiState.java
@@ -0,0 +1,42 @@
+package org.appdevforall.k2go.contentexchange.presentation;
+
+import org.appdevforall.k2go.contentexchange.domain.ManagedContent;
+import org.appdevforall.k2go.contentexchange.domain.StorageStatus;
+
+/**
+ * Immutable UI state for the content manager, exposed by {@link ContentManagerViewModel}.
+ *
+ *
Presentation-layer type. Carries the loaded content (grouped) and the box
+ * storage summary. {@code storage.available()} is {@code false} when the core has
+ * no {@code /v1/storage} yet; the screen then hides the free-disk figure (it does
+ * not go to {@link Status#ERROR} for that). {@link Status#ERROR} is only a real
+ * content-load failure (box unreachable).
+ */
+public final class ContentManagerUiState {
+
+ public enum Status {LOADING, SUCCESS, ERROR}
+
+ public final Status status;
+ public final ManagedContent content;
+ public final StorageStatus storage;
+ public final String error;
+
+ private ContentManagerUiState(Status status, ManagedContent content, StorageStatus storage, String error) {
+ this.status = status;
+ this.content = content;
+ this.storage = storage;
+ this.error = error;
+ }
+
+ public static ContentManagerUiState loading() {
+ return new ContentManagerUiState(Status.LOADING, null, null, null);
+ }
+
+ public static ContentManagerUiState success(ManagedContent content, StorageStatus storage) {
+ return new ContentManagerUiState(Status.SUCCESS, content, storage, null);
+ }
+
+ public static ContentManagerUiState error(String message) {
+ return new ContentManagerUiState(Status.ERROR, null, null, message);
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModel.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModel.java
new file mode 100644
index 000000000..e7d89bc6f
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModel.java
@@ -0,0 +1,122 @@
+package org.appdevforall.k2go.contentexchange.presentation;
+
+import androidx.lifecycle.LiveData;
+import androidx.lifecycle.MutableLiveData;
+import androidx.lifecycle.ViewModel;
+
+import org.appdevforall.k2go.contentexchange.domain.ContentGroup;
+import org.appdevforall.k2go.contentexchange.domain.ContentItem;
+import org.appdevforall.k2go.contentexchange.domain.GetStorageStatusUseCase;
+import org.appdevforall.k2go.contentexchange.domain.ListManagedContentUseCase;
+import org.appdevforall.k2go.contentexchange.domain.ManagedContent;
+import org.appdevforall.k2go.contentexchange.domain.StorageStatus;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * Presentation-layer ViewModel for the content manager.
+ *
+ *
Loads the grouped content and the storage summary off the main thread (one
+ * posts LOADING then SUCCESS/ERROR), and owns the transient multi-selection. The
+ * selection is a plain {@link Set} of {@link ContentItem#selectionId()} values held
+ * here (encapsulated ViewModel state, not persisted and not a static), so it
+ * survives a config change but not a process death, which is correct for an
+ * ephemeral pick.
+ *
+ *
Depends only on Domain use cases, never on the Data layer directly.
+ */
+public class ContentManagerViewModel extends ViewModel {
+
+ private final ListManagedContentUseCase listContent;
+ private final GetStorageStatusUseCase getStorage;
+ private final ExecutorService executor = Executors.newSingleThreadExecutor();
+
+ private final MutableLiveData state =
+ new MutableLiveData<>(ContentManagerUiState.loading());
+ private final MutableLiveData selection =
+ new MutableLiveData<>(SelectionSummary.empty());
+
+ private final Set selectedIds = new HashSet<>();
+ /** selectionId -> item bytes, rebuilt on each successful load, for the selection total. */
+ private final Map bytesById = new HashMap<>();
+
+ public ContentManagerViewModel(ListManagedContentUseCase listContent, GetStorageStatusUseCase getStorage) {
+ this.listContent = listContent;
+ this.getStorage = getStorage;
+ }
+
+ public LiveData state() {
+ return state;
+ }
+
+ public LiveData selection() {
+ return selection;
+ }
+
+ /** Loads content + storage. Content failure -> ERROR; storage failure only hides the free figure. */
+ public void load() {
+ state.postValue(ContentManagerUiState.loading());
+ executor.execute(() -> {
+ try {
+ ManagedContent content = listContent.execute();
+ StorageStatus storage = getStorage.execute();
+ indexBytes(content);
+ state.postValue(ContentManagerUiState.success(content, storage));
+ } catch (Exception e) {
+ state.postValue(ContentManagerUiState.error(e.getMessage()));
+ }
+ });
+ }
+
+ public boolean isSelected(String selectionId) {
+ return selectedIds.contains(selectionId);
+ }
+
+ /** Toggles one item's selection and republishes the summary. */
+ public void toggle(String selectionId) {
+ if (!selectedIds.remove(selectionId)) {
+ selectedIds.add(selectionId);
+ }
+ publishSelection();
+ }
+
+ public void clearSelection() {
+ if (!selectedIds.isEmpty()) {
+ selectedIds.clear();
+ publishSelection();
+ }
+ }
+
+ /** Rebuilds the id->bytes index and drops any selected id that no longer exists. */
+ private void indexBytes(ManagedContent content) {
+ bytesById.clear();
+ for (ContentGroup group : content.groups()) {
+ for (ContentItem item : group.items()) {
+ bytesById.put(item.selectionId(), Math.max(0L, item.bytes()));
+ }
+ }
+ selectedIds.retainAll(bytesById.keySet());
+ publishSelection();
+ }
+
+ private void publishSelection() {
+ long total = 0L;
+ for (String id : selectedIds) {
+ Long b = bytesById.get(id);
+ if (b != null) {
+ total += b;
+ }
+ }
+ selection.postValue(new SelectionSummary(selectedIds.size(), total));
+ }
+
+ @Override
+ protected void onCleared() {
+ executor.shutdownNow();
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModelFactory.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModelFactory.java
new file mode 100644
index 000000000..a6be4cbf6
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModelFactory.java
@@ -0,0 +1,31 @@
+package org.appdevforall.k2go.contentexchange.presentation;
+
+import androidx.annotation.NonNull;
+import androidx.lifecycle.ViewModel;
+import androidx.lifecycle.ViewModelProvider;
+
+import org.appdevforall.k2go.contentexchange.data.ContentRepositoryImpl;
+import org.appdevforall.k2go.contentexchange.data.CxCoreDataSource;
+import org.appdevforall.k2go.contentexchange.domain.ContentRepository;
+import org.appdevforall.k2go.contentexchange.domain.GetStorageStatusUseCase;
+import org.appdevforall.k2go.contentexchange.domain.ListManagedContentUseCase;
+
+/**
+ * Manual dependency wiring for {@link ContentManagerViewModel}: composes
+ * Data -> Domain -> Presentation by hand (no DI framework, per the feature rules).
+ */
+public class ContentManagerViewModelFactory implements ViewModelProvider.Factory {
+
+ @NonNull
+ @Override
+ @SuppressWarnings("unchecked")
+ public T create(@NonNull Class modelClass) {
+ if (modelClass.isAssignableFrom(ContentManagerViewModel.class)) {
+ ContentRepository repository = new ContentRepositoryImpl(new CxCoreDataSource());
+ return (T) new ContentManagerViewModel(
+ new ListManagedContentUseCase(repository),
+ new GetStorageStatusUseCase(repository));
+ }
+ throw new IllegalArgumentException("Unknown ViewModel class: " + modelClass.getName());
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/SelectionSummary.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/SelectionSummary.java
new file mode 100644
index 000000000..d9a8fe066
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/SelectionSummary.java
@@ -0,0 +1,26 @@
+package org.appdevforall.k2go.contentexchange.presentation;
+
+/**
+ * The current multi-select summary the bottom action bar reads: how many items are
+ * selected and their combined size. Immutable. Selection itself lives in the
+ * {@link ContentManagerViewModel} (transient UI state, not persisted and not static,
+ * per the "no new shared mutable static state" rule).
+ */
+public final class SelectionSummary {
+
+ public final int count;
+ public final long bytes;
+
+ public SelectionSummary(int count, long bytes) {
+ this.count = count;
+ this.bytes = bytes;
+ }
+
+ public boolean isEmpty() {
+ return count == 0;
+ }
+
+ public static SelectionSummary empty() {
+ return new SelectionSummary(0, 0L);
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/SettingsFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/SettingsFragment.java
index 0baa2e5f0..4666cf75b 100644
--- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/SettingsFragment.java
+++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/SettingsFragment.java
@@ -45,6 +45,12 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
i.putExtra(SetupLibraryActivity.EXTRA_MODULE_MGMT, true);
ctx.startActivity(i);
});
+ // K2GO-427: content manager (gestor) : list content by app, sizes, free disk, multi-select.
+ SettingsUi.row(ctx, list, getString(R.string.k2go_settings_content_mgr), getString(R.string.k2go_settings_content_mgr_sub), null, v -> {
+ android.content.Intent i = new android.content.Intent(ctx, SetupLibraryActivity.class);
+ i.putExtra(SetupLibraryActivity.EXTRA_CONTENT_MANAGER, true);
+ ctx.startActivity(i);
+ });
// ADFA-5169: always-visible entry to the queued content orders (finding 6). Shows a count, or
// "None" when empty. Opens as a settings sub-screen (bottom nav stays), like Language/About.
pendingRow = SettingsUi.row(ctx, list, getString(R.string.k2go_settings_pending), null, pendingValue(ctx), v -> {
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/SetupLibraryActivity.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/SetupLibraryActivity.java
index 715256c78..4371f6cb9 100644
--- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/SetupLibraryActivity.java
+++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/SetupLibraryActivity.java
@@ -42,6 +42,8 @@ public class SetupLibraryActivity extends AppCompatActivity implements org.appde
public static final String EXTRA_ZIM_SETUP = "zimSetup";
/** ADFA-4952: open Backup & restore directly (Settings → Advanced). */
public static final String EXTRA_BACKUP_RESTORE = "backupRestore";
+ /** K2GO-427: open the content manager (gestor) directly, from Settings. */
+ public static final String EXTRA_CONTENT_MANAGER = "contentManager";
/**
* ADFA-5150: the one way into recovery — restore a backup, install over the internet, or clone from
@@ -135,6 +137,7 @@ protected void onCreate(Bundle savedInstanceState) {
&& !launchIntent.getBooleanExtra(EXTRA_DASHBOARD_DETAIL, false)
&& !launchIntent.getBooleanExtra(EXTRA_MAPS_SETUP, false)
&& !launchIntent.getBooleanExtra(EXTRA_ZIM_SETUP, false)
+ && !launchIntent.getBooleanExtra(EXTRA_CONTENT_MANAGER, false)
&& !launchIntent.getBooleanExtra(EXTRA_CONTENT_ONLY, false);
if (wizardSetup) {
// Fence the FAB off the top-right help icon (72dp), the same as the wizard activity.
@@ -163,6 +166,8 @@ protected void onCreate(Bundle savedInstanceState) {
} else if (moduleMgmt || moduleDetail != null || dashboardDetail) {
selectedTier = readInstalledTier(); // ADFA-4842: module management hub (proot apps)
first = new ModuleHubFragment();
+ } else if (getIntent().getBooleanExtra(EXTRA_CONTENT_MANAGER, false)) {
+ first = new org.appdevforall.k2go.contentexchange.presentation.ContentManagerFragment(); // K2GO-427
} else if (mapsSetup) {
selectedTier = readInstalledTier(); // ADFA-4958: maps content selector, entered from Home
first = new MapsChooseFragment();
diff --git a/controller/app/src/main/res/layout/fragment_k2go_content_manager.xml b/controller/app/src/main/res/layout/fragment_k2go_content_manager.xml
new file mode 100644
index 000000000..b5f7d6337
--- /dev/null
+++ b/controller/app/src/main/res/layout/fragment_k2go_content_manager.xml
@@ -0,0 +1,111 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/controller/app/src/main/res/values/strings_untranslated.xml b/controller/app/src/main/res/values/strings_untranslated.xml
index 75d7b9e57..584e615fb 100644
--- a/controller/app/src/main/res/values/strings_untranslated.xml
+++ b/controller/app/src/main/res/values/strings_untranslated.xml
@@ -10,4 +10,27 @@
strings.xml.
-->
+
+ Content manager
+ Content on this box, grouped by app. Select items to manage them.
+ Loading content...
+ Could not reach the box. Try again.
+ No content on this box yet.
+ Used by content: %1$s
+ Free on device: %1$s
+ Free space: unavailable
+ %1$d items : %2$s
+ No items
+ %1$d selected : %2$s
+ Export
+ Share
+ Delete
+ Export, share and delete are not available yet.
+ Wikipedia & ZIM
+ Courses
+ Books
+ Content manager
+ Manage, export and remove content
diff --git a/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/GetStorageStatusUseCaseTest.java b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/GetStorageStatusUseCaseTest.java
new file mode 100644
index 000000000..1e0b30709
--- /dev/null
+++ b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/GetStorageStatusUseCaseTest.java
@@ -0,0 +1,64 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Pure-JVM unit tests for the storage use case. The degrade rule ("could not read
+ * /v1/storage") must never surface as an error: the use case returns an unavailable
+ * status so the manager still lists content.
+ */
+public class GetStorageStatusUseCaseTest {
+
+ @Test
+ public void returnsTheRepositoryStatusWhenAvailable() {
+ StorageStatus status = StorageStatus.of("/library", 1000L, 400L, 600L, Collections.emptyList());
+ StorageStatus out = new GetStorageStatusUseCase(new FakeRepository(status)).execute();
+
+ assertTrue(out.available());
+ assertEquals(400L, out.freeBytes());
+ assertEquals(600L, out.usedByContentBytes());
+ }
+
+ @Test
+ public void passesThroughUnavailableWithoutError() {
+ StorageStatus out = new GetStorageStatusUseCase(
+ new FakeRepository(StorageStatus.unavailable())).execute();
+ assertFalse(out.available());
+ }
+
+ @Test
+ public void nullFromRepositoryBecomesUnavailable() {
+ StorageStatus out = new GetStorageStatusUseCase(new FakeRepository(null)).execute();
+ assertFalse(out.available());
+ }
+
+ private static final class FakeRepository implements ContentRepository {
+ private final StorageStatus storage;
+
+ FakeRepository(StorageStatus storage) {
+ this.storage = storage;
+ }
+
+ @Override
+ public List fetchApps() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public List fetchContent() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public StorageStatus fetchStorage() {
+ return storage;
+ }
+ }
+}
diff --git a/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ListManagedContentUseCaseTest.java b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ListManagedContentUseCaseTest.java
new file mode 100644
index 000000000..ff83bfe05
--- /dev/null
+++ b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ListManagedContentUseCaseTest.java
@@ -0,0 +1,159 @@
+package org.appdevforall.k2go.contentexchange.domain;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Pure-JVM unit tests for the grouping / ordering / totalling rule. No Android, no
+ * network: the pure static {@code group(...)} is driven directly, and {@code execute()}
+ * uses a hand-written fake repository (no mocking framework needed).
+ */
+public class ListManagedContentUseCaseTest {
+
+ private static ContentItem item(String app, String title, long bytes, String localRef) {
+ return new ContentItem(app, "", title, bytes, localRef);
+ }
+
+ private static ContentGroup groupOf(ManagedContent mc, String app) {
+ for (ContentGroup g : mc.groups()) {
+ if (g.app().equals(app)) {
+ return g;
+ }
+ }
+ throw new AssertionError("no group for " + app);
+ }
+
+ @Test
+ public void groupsItemsByAppWithPerGroupAndGrandTotals() {
+ List items = Arrays.asList(
+ item("kiwix", "Wikipedia", 100L, "a"),
+ item("kiwix", "Wiktionary", 50L, "b"),
+ item("calibre", "A Book", 10L, "u1"));
+ ManagedContent mc = ListManagedContentUseCase.group(
+ Arrays.asList("kiwix", "calibre"), items);
+
+ assertEquals(150L, groupOf(mc, "kiwix").totalBytes());
+ assertEquals(2, groupOf(mc, "kiwix").items().size());
+ assertEquals(10L, groupOf(mc, "calibre").totalBytes());
+ assertEquals(160L, mc.totalBytes());
+ assertFalse(mc.isEmpty());
+ }
+
+ @Test
+ public void installedAppWithNoContentIsAnEmptyGroup() {
+ ManagedContent mc = ListManagedContentUseCase.group(
+ Arrays.asList("kiwix", "kolibri"),
+ Collections.singletonList(item("kiwix", "Wikipedia", 100L, "a")));
+
+ assertTrue(groupOf(mc, "kolibri").isEmpty());
+ assertEquals(0L, groupOf(mc, "kolibri").totalBytes());
+ assertEquals(100L, mc.totalBytes());
+ }
+
+ @Test
+ public void itemFromAnUninstalledAppIsStillKept() {
+ // /v1/apps lags behind /v1/content: the item must not be silently dropped.
+ ManagedContent mc = ListManagedContentUseCase.group(
+ Collections.singletonList("kiwix"),
+ Collections.singletonList(item("calibre", "A Book", 10L, "u1")));
+
+ assertEquals(10L, groupOf(mc, "calibre").totalBytes());
+ assertEquals(10L, mc.totalBytes());
+ }
+
+ @Test
+ public void preferredAppsOrderFirstThenOthersAlphabetically() {
+ List apps = Arrays.asList("zebra", "calibre", "ark", "kiwix", "kolibri");
+ ManagedContent mc = ListManagedContentUseCase.group(apps, Collections.emptyList());
+
+ List order = new ArrayList<>();
+ for (ContentGroup g : mc.groups()) {
+ order.add(g.app());
+ }
+ assertEquals(Arrays.asList("kiwix", "kolibri", "calibre", "ark", "zebra"), order);
+ }
+
+ @Test
+ public void itemsWithinAGroupAreOrderedByTitle() {
+ List items = Arrays.asList(
+ item("kiwix", "Zebra", 1L, "z"),
+ item("kiwix", "apple", 1L, "a"),
+ item("kiwix", "Mango", 1L, "m"));
+ ManagedContent mc = ListManagedContentUseCase.group(
+ Collections.singletonList("kiwix"), items);
+
+ List titles = new ArrayList<>();
+ for (ContentItem it : groupOf(mc, "kiwix").items()) {
+ titles.add(it.title());
+ }
+ assertEquals(Arrays.asList("apple", "Mango", "Zebra"), titles);
+ }
+
+ @Test
+ public void negativeOrZeroBytesDoNotReduceTotals() {
+ List items = Arrays.asList(
+ item("kiwix", "Good", 100L, "a"),
+ item("kiwix", "Unknown", -1L, "b"),
+ item("kiwix", "Zero", 0L, "c"));
+ ManagedContent mc = ListManagedContentUseCase.group(
+ Collections.singletonList("kiwix"), items);
+
+ assertEquals(100L, groupOf(mc, "kiwix").totalBytes());
+ assertEquals(100L, mc.totalBytes());
+ }
+
+ @Test
+ public void emptyEverythingIsAnEmptyResult() {
+ ManagedContent mc = ListManagedContentUseCase.group(
+ Collections.emptyList(), Collections.emptyList());
+ assertTrue(mc.isEmpty());
+ assertEquals(0L, mc.totalBytes());
+ assertTrue(mc.groups().isEmpty());
+ }
+
+ @Test
+ public void executeFetchesAppsAndContentFromTheRepository() throws Exception {
+ FakeRepository repo = new FakeRepository();
+ repo.apps = Arrays.asList("kiwix");
+ repo.content = Collections.singletonList(item("kiwix", "Wikipedia", 100L, "a"));
+
+ ManagedContent mc = new ListManagedContentUseCase(repo).execute();
+
+ assertTrue(repo.fetchAppsCalled);
+ assertTrue(repo.fetchContentCalled);
+ assertEquals(100L, mc.totalBytes());
+ }
+
+ /** Minimal fake of the domain port; storage is not exercised here. */
+ private static final class FakeRepository implements ContentRepository {
+ List apps = Collections.emptyList();
+ List content = Collections.emptyList();
+ boolean fetchAppsCalled = false;
+ boolean fetchContentCalled = false;
+
+ @Override
+ public List fetchApps() {
+ fetchAppsCalled = true;
+ return apps;
+ }
+
+ @Override
+ public List fetchContent() {
+ fetchContentCalled = true;
+ return content;
+ }
+
+ @Override
+ public StorageStatus fetchStorage() {
+ return StorageStatus.unavailable();
+ }
+ }
+}