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 @@ -230,6 +230,15 @@
android:value="Exports selected library content to a user-chosen drive through the co-located server REST engine." />
</service>

<service
android:name=".contentexchange.presentation.ContentImportService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Imports selected library content from 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,67 @@
/*
* ============================================================================
* Name : BoxImportStaging.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : K2GO-427. Bridges one SAF-read archive to a box-visible path the core can ingest.
* proot runs with -r <rootfs> and no separate bind for /library, so box /library maps
* to host <rootfs>/library (EnvironmentControl.rootfs = filesDir/rootfs/installed-rootfs/
* iiab). This writes the staged archive under host <rootfs>/library/.cx-staging and
* reports the matching box path /library/.cx-staging/<name> for POST /v1/import/item.
* The core default CX_STAGING_DIR is /library/.cx-staging (its is_within_dir guard).
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.data;

import android.content.Context;

import org.appdevforall.k2go.contentexchange.domain.ExportFilenames;
import org.appdevforall.k2go.env.EnvironmentControl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public final class BoxImportStaging {

/** The box-side import area, matching the core's default {@code CX_STAGING_DIR}. */
private static final String BOX_STAGING_DIR = "/library/.cx-staging";
private static final String HOST_STAGING_SUBPATH = "library/.cx-staging";

private final File hostDir;

public BoxImportStaging(Context context) {
this.hostDir = new File(EnvironmentControl.rootfs(context), HOST_STAGING_SUBPATH);
}

/** The box-visible path for a staged file, as POST /v1/import/item expects it. */
public static String boxPath(String storedName) {
return BOX_STAGING_DIR + "/" + storedName;
}

/** A FAT-safe single-segment name for an untrusted drive filename (reuses the export rule). */
public static String safeName(String name) {
String safe = ExportFilenames.safeBaseName(name);
return safe != null ? safe : "payload.bin";
}

/** Open the host staging file for writing, creating the staging directory if needed. */
public OutputStream open(String storedName) throws IOException {
if (!hostDir.exists() && !hostDir.mkdirs()) {
throw new IOException("Could not create the import staging folder");
}
return new FileOutputStream(new File(hostDir, storedName));
}

/** Remove a staged file after the core has ingested it (best effort). */
public void remove(String storedName) {
File f = new File(hostDir, storedName);
if (f.exists()) {
// The core moves/extracts from this path; a leftover copy only wastes space, so ignore a
// failed delete rather than fail the import.
//noinspection ResultOfMethodCallIgnored
f.delete();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ public JSONObject postExportPlan(JSONObject body) throws Exception {
return postJson(V1 + "/export/plan", body);
}

/** {@code POST /v1/import/validate} with {@code {items:[<entry>]}} -> {@code {results:[...]}}. */
public JSONObject postImportValidate(JSONObject body) throws Exception {
return postJson(V1 + "/import/validate", body);
}

/** {@code POST /v1/import/item} with {@code {app, entry, payloadPath}} -> the ingest result. */
public JSONObject postImportItem(JSONObject body) throws Exception {
return postJson(V1 + "/import/item", body);
}

/** {@code DELETE /v1/content/{app}/{localRef}} -> {@code {ok, freedBytes}}. */
public JSONObject deleteContent(String app, String localRef) throws Exception {
return deleteJson(V1 + "/content/" + encodeSegment(app) + "/" + encodeSegment(localRef));
}

/**
* {@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
Expand Down Expand Up @@ -112,6 +127,26 @@ private static JSONObject postJson(String urlStr, JSONObject body) throws Except
}
}

private static JSONObject deleteJson(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("DELETE");
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 JSONObject getJson(String urlStr) throws Exception {
HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection();
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* ============================================================================
* Name : CxCoreImportSource.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : K2GO-427. Data-layer implementation of the import source port against cx-core
* (through dash-node's /v1 relay): POST /v1/import/validate (per-item verdict),
* POST /v1/import/item (ingest one staged item), and DELETE /v1/content (reclaim).
* The manifest entries are passed to the core unchanged; the core owns the shape.
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.data;

import org.appdevforall.k2go.contentexchange.domain.ImportEntry;
import org.appdevforall.k2go.contentexchange.domain.ImportSource;
import org.appdevforall.k2go.contentexchange.domain.ImportVerdict;
import org.appdevforall.k2go.contentexchange.domain.ItemRef;
import org.json.JSONArray;
import org.json.JSONObject;

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

public final class CxCoreImportSource implements ImportSource {

private final CxCoreDataSource dataSource;

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

@Override
public List<ImportVerdict> validate(List<ImportEntry> entries) throws Exception {
JSONArray items = new JSONArray();
for (ImportEntry e : entries) {
items.put(new JSONObject(e.entryJson()));
}
JSONObject response = dataSource.postImportValidate(new JSONObject().put("items", items));
JSONArray results = response.optJSONArray("results");
List<ImportVerdict> verdicts = new ArrayList<>();
for (int i = 0; i < entries.size(); i++) {
JSONObject r = results != null ? results.optJSONObject(i) : null;
if (r == null) {
verdicts.add(new ImportVerdict(ImportVerdict.STATUS_NO_APP, null, null));
continue;
}
verdicts.add(new ImportVerdict(
r.optString("status", ImportVerdict.STATUS_NO_APP),
r.isNull("verdict") ? null : r.optString("verdict", null),
r.isNull("idKind") ? null : r.optString("idKind", null)));
}
return verdicts;
}

@Override
public void importItem(String app, String entryJson, String payloadBoxPath) throws Exception {
JSONObject body = new JSONObject()
.put("app", app)
.put("entry", new JSONObject(entryJson))
.put("payloadPath", payloadBoxPath);
JSONObject result = dataSource.postImportItem(body);
if (!result.optBoolean("ok", false)) {
throw new Exception(result.optString("reason", result.optString("error", "import failed")));
}
}

@Override
public void delete(ItemRef ref) throws Exception {
JSONObject result = dataSource.deleteContent(ref.app(), ref.localRef());
if (!result.optBoolean("ok", false)) {
throw new Exception(result.optString("reason", result.optString("error", "delete failed")));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* ============================================================================
* Name : ImportManifestReader.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : K2GO-427. Reads a bundle's items from the drive: parse the top-level manifest.json
* into ImportEntry objects, keeping each raw entry verbatim for the core; and, when no
* manifest is present (an export interrupted before it wrote the index), scan the folder
* for recognizable files (a Kiwix .zim) and synthesize entries from the filename. Pure
* JSON (org.json), no HTTP and no Android: the parse / scan are unit-testable on a JVM.
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.data;

import org.appdevforall.k2go.contentexchange.domain.ImportCarrier;
import org.appdevforall.k2go.contentexchange.domain.ImportEntry;
import org.appdevforall.k2go.contentexchange.domain.ImportManifest;
import org.appdevforall.k2go.contentexchange.domain.ImportScan;
import org.json.JSONArray;
import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public final class ImportManifestReader {

private static final String MANIFEST_NAME = "manifest.json";

/** Read a bundle through the carrier: a real manifest when present, else a folder scan. */
public ImportManifest read(ImportCarrier carrier) throws Exception {
byte[] manifest = carrier.readManifest();
if (manifest != null && manifest.length > 0) {
List<ImportEntry> entries = parse(manifest);
if (!entries.isEmpty()) {
return new ImportManifest(entries, true, new ArrayList<>());
}
// A manifest that parsed to nothing usable: fall through to a scan rather than show empty.
}
return scan(carrier.listFiles());
}

/** Parse {@code manifest.json} bytes into entries, keeping each raw entry for the core. */
public static List<ImportEntry> parse(byte[] manifestBytes) throws Exception {
List<ImportEntry> out = new ArrayList<>();
if (manifestBytes == null || manifestBytes.length == 0) {
return out;
}
JSONObject root = new JSONObject(new String(manifestBytes, StandardCharsets.UTF_8));
JSONArray items = root.optJSONArray("items");
if (items == null) {
return out;
}
for (int i = 0; i < items.length(); i++) {
JSONObject entry = items.optJSONObject(i);
if (entry == null) {
continue;
}
String app = entry.optString("app", "");
JSONObject identity = entry.optJSONObject("identity");
String localRef = identity != null ? identity.optString("localRef", "") : "";
String payload = entry.optString("payload", "");
// An item we cannot address or whose archive the manifest does not name is not importable.
if (app.isEmpty() || localRef.isEmpty() || payload.isEmpty()) {
continue;
}
out.add(new ImportEntry(app, localRef, entry.optString("title", localRef),
entry.optLong("bytes", 0L), payload, entry.toString()));
}
return out;
}

/** Scan a manifest-less folder: recognize what each file belongs to by its name alone. */
public static ImportManifest scan(List<ImportCarrier.DriveFile> files) throws Exception {
List<ImportEntry> entries = new ArrayList<>();
List<String> unrecognized = new ArrayList<>();
if (files != null) {
for (ImportCarrier.DriveFile file : files) {
String name = file.name();
if (name == null || MANIFEST_NAME.equalsIgnoreCase(name)) {
continue;
}
String app = ImportScan.recognizeApp(name);
if (ImportScan.APP_KIWIX.equals(app)) {
entries.add(kiwixEntry(name, file.size()));
} else {
unrecognized.add(name);
}
}
}
return new ImportManifest(entries, false, unrecognized);
}

/** Synthesize a Kiwix entry from a .zim filename: dedup keys from the name, no UUID (soft). */
private static ImportEntry kiwixEntry(String name, long size) throws Exception {
String[] p = ImportScan.parseZimFilename(name);
String stem = name.toLowerCase(java.util.Locale.US).endsWith(".zim")
? name.substring(0, name.length() - 4) : name;
JSONObject line = new JSONObject()
.put("creator", p[0]).put("lang", p[1]).put("flavour", p[2]);
JSONObject dedup = new JSONObject()
.put("line", line).put("build", JSONObject.NULL)
.put("version", p[3]).put("idKind", "SOFT");
JSONObject identity = new JSONObject().put("localRef", name).put("dedup", dedup);
JSONObject entry = new JSONObject()
.put("app", ImportScan.APP_KIWIX).put("kind", "zim")
.put("title", stem).put("bytes", size)
.put("identity", identity).put("payload", name);
return new ImportEntry(ImportScan.APP_KIWIX, name, stem, size, name, entry.toString());
}
}
Loading
Loading