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
9 changes: 9 additions & 0 deletions controller/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,15 @@
android:value="Downloads offline library books through the co-located server REST engine." />
</service>

<service
android:name=".contentexchange.presentation.ContentExportService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Exports selected library content to a user-chosen drive through the co-located server REST engine." />
</service>

<!-- ADFA-5333: runs the LIVE dash-node update in the background (notification only) instead of
behind a blocking modal. Same shape as the download services above: not exported, and
specialUse because it drives the in-server blue-green rebuild rather than a stock transfer. -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* ============================================================================
* Name : CollectionManifest.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : K2GO-427. Assembles the top-level manifest.json of an export bundle from the
* per-item entries the plan returned, stamping each with the payload file name the
* carrier stored. The entry is used verbatim (identity, dedup, integrity) so the
* import side can pass items[] straight to the core; only payload is set here.
* Pure JSON assembly (no HTTP, no Android): unit-testable with org.json.
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.data;

import org.appdevforall.k2go.contentexchange.domain.ItemRef;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

public final class CollectionManifest {

/** The manifest format tag the import side keys on; bump when the shape changes. */
public static final String FORMAT = "k2go-content-manifest/1";

private CollectionManifest() {}

/**
* Build the manifest bytes for the given items, in order, stamping each entry's {@code payload}
* with the name from {@code payloadNames}. An entry without a captured source entry is skipped.
*/
public static byte[] build(Map<ItemRef, JSONObject> entries, List<ItemRef> order,
Map<ItemRef, String> payloadNames) throws JSONException {
JSONArray items = new JSONArray();
for (ItemRef ref : order) {
JSONObject captured = entries.get(ref);
if (captured == null) {
continue;
}
// Deep-copy via text so the captured entry stays clean for a retry, then stamp payload.
JSONObject entry = new JSONObject(captured.toString());
entry.put("payload", payloadNames.get(ref));
items.put(entry);
}
JSONObject manifest = new JSONObject();
manifest.put("format", FORMAT);
manifest.put("generated", nowIso8601());
manifest.put("source", new JSONObject().put("env", "k2go"));
manifest.put("items", items);
return manifest.toString(2).getBytes(StandardCharsets.UTF_8);
}

private static String nowIso8601() {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
return fmt.format(new Date());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
* 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.
* Description : K2GO-427. App-side client of the content-exchange core (cx-core)
* through dash-node's relay (/k2go-api/v1/*). Read side (list + storage)
* plus the export calls (plan + streaming item). Same HttpURLConnection
* shape as content/RestContentClient. The one place this feature touches
* HttpURLConnection.
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.data;
Expand All @@ -15,7 +16,9 @@
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -50,6 +53,65 @@ public JSONObject getStorage() throws Exception {
return getJson(V1 + "/storage");
}

/** {@code POST /v1/export/plan} with {@code {items:[{app,localRef}]}} -> the plan JSON. */
public JSONObject postExportPlan(JSONObject body) throws Exception {
return postJson(V1 + "/export/plan", body);
}

/**
* {@code GET /v1/export/item/{app}/{localRef}} -> the item's streaming archive. The core sends a
* chunked response with no Content-Length; the caller streams the body and closes the returned
* handle to release the connection. Path segments are percent-encoded (the core decodes them).
*/
public Stream openExportItem(String app, String localRef) throws Exception {
String url = V1 + "/export/item/" + encodeSegment(app) + "/" + encodeSegment(localRef);
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
try {
c.setUseCaches(false);
c.setConnectTimeout(CONNECT_TIMEOUT_MS);
c.setReadTimeout(READ_TIMEOUT_MS);
c.setRequestMethod("GET");
c.setRequestProperty("Accept", "application/octet-stream");
int code = c.getResponseCode();
if (code < 200 || code >= 400) {
String text = readAll(c.getErrorStream());
c.disconnect();
throw new Exception("HTTP " + code + ": " + text);
}
String filename = parseContentDispositionFilename(c.getHeaderField("Content-Disposition"));
return new Stream(c, c.getInputStream(), filename);
} catch (Exception e) {
c.disconnect();
throw e;
}
}

private static JSONObject postJson(String urlStr, JSONObject body) 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("POST");
c.setDoOutput(true);
c.setRequestProperty("Content-Type", "application/json");
c.setRequestProperty("Accept", "application/json");
byte[] payload = body.toString().getBytes(StandardCharsets.UTF_8);
try (OutputStream os = c.getOutputStream()) {
os.write(payload);
}
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 JSONObject getJson(String urlStr) throws Exception {
HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection();
try {
Expand Down Expand Up @@ -83,4 +145,65 @@ private static String readAll(InputStream is) throws Exception {
is.close();
return buf.toString(StandardCharsets.UTF_8.name());
}

/** Percent-encode one path segment (keep it a single segment; the core calls unquote). */
private static String encodeSegment(String s) throws Exception {
if (s == null) {
return "";
}
// URLEncoder is form encoding: a space becomes "+", which a path reads literally, so fix it.
return java.net.URLEncoder.encode(s, StandardCharsets.UTF_8.name()).replace("+", "%20");
}

/** Pull the {@code filename="..."} from a Content-Disposition header, or "" when absent. */
private static String parseContentDispositionFilename(String header) {
if (header == null) {
return "";
}
int at = header.toLowerCase(java.util.Locale.US).indexOf("filename=");
if (at < 0) {
return "";
}
String value = header.substring(at + "filename=".length()).trim();
if (value.startsWith("\"")) {
int end = value.indexOf('"', 1);
return end > 0 ? value.substring(1, end) : value.substring(1);
}
int semi = value.indexOf(';');
return semi >= 0 ? value.substring(0, semi).trim() : value;
}

/** A live streaming response: the body plus the server-suggested name. Close to release the socket. */
public static final class Stream implements Closeable {

private final HttpURLConnection connection;
private final InputStream body;
private final String filename;

Stream(HttpURLConnection connection, InputStream body, String filename) {
this.connection = connection;
this.body = body;
this.filename = filename;
}

public InputStream body() {
return body;
}

public String filename() {
return filename;
}

@Override
public void close() {
try {
if (body != null) {
body.close();
}
} catch (Exception ignored) {
// closing anyway
}
connection.disconnect();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* ============================================================================
* Name : CxCoreExportSource.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : K2GO-427. Data-layer implementation of the export source port against
* cx-core (through dash-node's /v1 relay): POST /v1/export/plan, the
* streaming GET /v1/export/item, and the collection-manifest assembly.
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.data;

import org.appdevforall.k2go.contentexchange.domain.ContentExportSource;
import org.appdevforall.k2go.contentexchange.domain.ExportItem;
import org.appdevforall.k2go.contentexchange.domain.ExportPlan;
import org.appdevforall.k2go.contentexchange.domain.ItemRef;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* Plans an export, streams one item, and builds the collection manifest.
*
* <p>The per-item entries the plan returns (identity + dedup + integrity) are captured here so the
* manifest can be assembled from the authoritative source rather than re-derived. That cache is this
* object's own copy of its own HTTP response, keyed by {@link ItemRef}: it is not a second source of
* truth for "what content exists" (the core owns that), only the plan this run already fetched.
*
* <p>Instances are single-run and used off the main thread; the capture is not shared.
*/
public final class CxCoreExportSource implements ContentExportSource {

private final CxCoreDataSource dataSource;

/** Captured plan entries for the manifest, by item, preserving request order. */
private final Map<ItemRef, JSONObject> entries = new LinkedHashMap<>();

public CxCoreExportSource(CxCoreDataSource dataSource) {
this.dataSource = dataSource;
}

@Override
public ExportPlan plan(List<ItemRef> refs) throws Exception {
JSONArray reqItems = new JSONArray();
for (ItemRef ref : refs) {
reqItems.put(new JSONObject().put("app", ref.app()).put("localRef", ref.localRef()));
}
JSONObject response = dataSource.postExportPlan(new JSONObject().put("items", reqItems));

entries.clear();
List<ExportItem> items = new ArrayList<>();
long total = 0L;
JSONArray found = response.optJSONArray("items");
if (found != null) {
for (int i = 0; i < found.length(); i++) {
JSONObject entry = found.optJSONObject(i);
if (entry == null) {
continue;
}
JSONObject identity = entry.optJSONObject("identity");
String app = entry.optString("app", "");
String localRef = identity != null ? identity.optString("localRef", "") : "";
if (app.isEmpty() || localRef.isEmpty()) {
continue;
}
ItemRef ref = new ItemRef(app, localRef);
long bytes = entry.optLong("bytes", 0L);
items.add(new ExportItem(ref, entry.optString("title", localRef), bytes));
entries.put(ref, entry);
total += bytes;
}
}

List<String> skipped = new ArrayList<>();
JSONArray missing = response.optJSONArray("missing");
if (missing != null) {
for (int i = 0; i < missing.length(); i++) {
JSONObject m = missing.optJSONObject(i);
if (m == null) {
continue;
}
skipped.add(m.optString("app", "?") + "/" + m.optString("localRef", "?")
+ " (" + m.optString("reason", "skipped") + ")");
}
}
// Prefer the server total; fall back to the summed item bytes.
long reported = response.optLong("totalBytes", total);
return new ExportPlan(items, skipped, reported);
}

@Override
public ItemPayload open(ItemRef ref) throws Exception {
CxCoreDataSource.Stream stream = dataSource.openExportItem(ref.app(), ref.localRef());
return new ItemPayload(stream.body(), stream.filename(), stream);
}

@Override
public byte[] buildManifest(List<ItemRef> order, Map<ItemRef, String> payloadNames) throws Exception {
return CollectionManifest.build(entries, order, payloadNames);
}
}
Loading
Loading