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
@@ -0,0 +1,107 @@
package org.appdevforall.k2go.contentexchange.data;

import android.util.Log;

import org.appdevforall.k2go.contentexchange.domain.AppUsage;
import org.appdevforall.k2go.contentexchange.domain.ContentItem;
import org.appdevforall.k2go.contentexchange.domain.ContentRepository;
import org.appdevforall.k2go.contentexchange.domain.StorageStatus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
* Data-layer implementation of the domain {@link ContentRepository} port. Maps the
* cx-core JSON (via {@link CxCoreDataSource}) into domain entities.
*
* <p>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<String> fetchApps() throws Exception {
JSONObject json = dataSource.getApps();
JSONArray apps = json.optJSONArray("apps");
List<String> 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<ContentItem> fetchContent() throws Exception {
JSONObject json = dataSource.getContent();
JSONArray items = json.optJSONArray("items");
List<ContentItem> 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<AppUsage> 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();
}
}
}
Original file line number Diff line number Diff line change
@@ -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}.
*
* <p>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());
}
}
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>Immutable value object. Pure domain type.
*/
public final class ContentGroup {

private final String app;
private final List<ContentItem> items;
private final long totalBytes;

public ContentGroup(String app, List<ContentItem> 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<ContentItem> items() {
return items;
}

public boolean isEmpty() {
return items.isEmpty();
}

/** Sum of the items' sizes in bytes. */
public long totalBytes() {
return totalBytes;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package org.appdevforall.k2go.contentexchange.domain;

/**
* One managed content item on the box, as the manager UI lists it.
*
* <p>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.
*
* <p>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.
*
* <p>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 + '}';
}
}
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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.
*
* <p>Error contract:
* <ul>
* <li>{@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.</li>
* <li>{@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".</li>
* </ul>
*/
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<String> fetchApps() throws Exception;

/**
* Every content item on the box ({@code GET /v1/content}).
*
* @throws Exception when the box cannot be reached.
*/
List<ContentItem> 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();
}
Loading
Loading