diff --git a/controller/app/src/main/AndroidManifest.xml b/controller/app/src/main/AndroidManifest.xml index 86d033ac9..284b027d1 100644 --- a/controller/app/src/main/AndroidManifest.xml +++ b/controller/app/src/main/AndroidManifest.xml @@ -221,6 +221,15 @@ android:value="Downloads offline library books through the co-located server REST engine." /> + + + + diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CollectionManifest.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CollectionManifest.java new file mode 100644 index 000000000..2a2911112 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CollectionManifest.java @@ -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 entries, List order, + Map 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()); + } +} 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 index 3ce36f9e2..9d236a47a 100644 --- 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 @@ -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; @@ -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; @@ -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 { @@ -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(); + } + } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreExportSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreExportSource.java new file mode 100644 index 000000000..629c9f546 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreExportSource.java @@ -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. + * + *

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. + * + *

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 entries = new LinkedHashMap<>(); + + public CxCoreExportSource(CxCoreDataSource dataSource) { + this.dataSource = dataSource; + } + + @Override + public ExportPlan plan(List 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 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 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 order, Map payloadNames) throws Exception { + return CollectionManifest.build(entries, order, payloadNames); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafExportCarrier.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafExportCarrier.java new file mode 100644 index 000000000..5e1535c3d --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafExportCarrier.java @@ -0,0 +1,103 @@ +/* + * ============================================================================ + * Name : SafExportCarrier.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. SAF-backed export destination: writes the bundle to a user-picked + * drive/folder tree (USB-OTG or SD) through the framework Storage Access + * Framework. Uses DocumentsContract + ContentResolver directly (no + * androidx.documentfile dependency) and adds NO storage permission: the + * persisted tree grant from the picker is the only authority. Reaches a USB-OTG + * volume and an SD card uniformly and stays valid on the Play flavor, which + * drops MANAGE_EXTERNAL_STORAGE. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.data; + +import android.content.ContentResolver; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.provider.DocumentsContract; + +import org.appdevforall.k2go.contentexchange.domain.ExportCarrier; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * One SAF document tree as an {@link ExportCarrier}. The tree Uri comes from + * {@code ACTION_OPEN_DOCUMENT_TREE} and must already carry a persisted permission. + */ +public final class SafExportCarrier implements ExportCarrier { + + private static final String MANIFEST_NAME = "manifest.json"; + private static final String MIME_JSON = "application/json"; + private static final String MIME_BINARY = "application/octet-stream"; + + private final ContentResolver resolver; + private final Uri treeDocUri; + + public SafExportCarrier(Context context, Uri treeUri) { + this.resolver = context.getContentResolver(); + this.treeDocUri = DocumentsContract.buildDocumentUriUsingTree( + treeUri, DocumentsContract.getTreeDocumentId(treeUri)); + } + + @Override + public String destinationLabel() { + String name = queryDisplayName(treeDocUri); + return name != null ? name : treeDocUri.getLastPathSegment(); + } + + @Override + public PayloadSink openPayload(String desiredName) throws IOException { + Uri file = createDocument(MIME_BINARY, desiredName); + OutputStream out = openOutput(file); + // SAF may rename on a collision; record the name actually stored so the manifest matches. + String actual = queryDisplayName(file); + return new PayloadSink(out, actual != null ? actual : desiredName); + } + + @Override + public OutputStream openManifest() throws IOException { + return openOutput(createDocument(MIME_JSON, MANIFEST_NAME)); + } + + private Uri createDocument(String mime, String name) throws IOException { + try { + Uri uri = DocumentsContract.createDocument(resolver, treeDocUri, mime, name); + if (uri == null) { + throw new IOException("Could not create " + name + " on the destination"); + } + return uri; + } catch (Exception e) { + // Includes a SecurityException if the grant was revoked, or a provider failure. + throw new IOException("Could not create " + name + ": " + e.getMessage(), e); + } + } + + private OutputStream openOutput(Uri file) throws IOException { + try { + OutputStream out = resolver.openOutputStream(file); + if (out == null) { + throw new IOException("Destination refused a write stream"); + } + return out; + } catch (Exception e) { + throw new IOException("Could not open the destination for writing: " + e.getMessage(), e); + } + } + + private String queryDisplayName(Uri docUri) { + try (Cursor c = resolver.query(docUri, + new String[]{DocumentsContract.Document.COLUMN_DISPLAY_NAME}, null, null, null)) { + if (c != null && c.moveToFirst() && !c.isNull(0)) { + return c.getString(0); + } + } catch (Exception ignored) { + // fall through to null + } + return null; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentExportSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentExportSource.java new file mode 100644 index 000000000..d1e2fd198 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentExportSource.java @@ -0,0 +1,75 @@ +package org.appdevforall.k2go.contentexchange.domain; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +/** + * Domain port for the BOX side of an export: plan the items, stream one item's archive, and + * build the collection manifest. The Data layer implements it against the core REST API + * (through dash-node's {@code /v1/*} relay); the domain never learns the transport or the + * JSON shape. + * + *

The manifest is built here rather than in the carrier because the source holds the + * authoritative per-item entries the plan returned (identity, dedup, integrity); the carrier + * only supplies where each payload landed. Keeping JSON out of the domain is why + * {@link #buildManifest} returns ready bytes. + * + *

All methods must be called off the main thread. + */ +public interface ContentExportSource { + + /** Plan the given items: exact sizes + skip list, moving no payload. */ + ExportPlan plan(List refs) throws Exception; + + /** Open the streaming archive for one item. The caller copies the stream, then closes it. */ + ItemPayload open(ItemRef ref) throws Exception; + + /** + * Build the top-level {@code manifest.json} over the items that were written, in the given + * order, stamping each entry's {@code payload} with the name the carrier actually stored. + * Returns the UTF-8 bytes of the collection manifest. + */ + byte[] buildManifest(List order, Map payloadNames) throws Exception; + + /** + * One item's archive as a byte stream plus the server-suggested file name + * (from {@code Content-Disposition}). {@link #close()} releases the underlying connection. + */ + final class ItemPayload implements Closeable { + + private final InputStream stream; + private final String filename; + private final Closeable connection; + + public ItemPayload(InputStream stream, String filename, Closeable connection) { + this.stream = stream; + this.filename = filename; + this.connection = connection; + } + + public InputStream stream() { + return stream; + } + + /** The server-suggested name (may be empty; the caller derives a safe name from it). */ + public String filename() { + return filename; + } + + @Override + public void close() throws IOException { + try { + if (stream != null) { + stream.close(); + } + } finally { + if (connection != null) { + connection.close(); + } + } + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportCarrier.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportCarrier.java new file mode 100644 index 000000000..d7d79f695 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportCarrier.java @@ -0,0 +1,45 @@ +package org.appdevforall.k2go.contentexchange.domain; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * Domain port for the DESTINATION of an export: where the bytes land. One implementation is the + * SAF-backed drive writer; the import flow and a future network carrier reuse the same port, so + * the carrier is never hard-wired into the export sequence. + * + *

Only {@code java.io} crosses this boundary: no Android, no SAF type. The carrier chooses the + * final name for a payload (a destination may rename on a collision), so {@link #openPayload} + * reports the name actually used, which the manifest then records. + */ +public interface ExportCarrier { + + /** A short, human name of the chosen destination (e.g. the folder name), for the UI. */ + String destinationLabel(); + + /** Open a writable stream for one payload file; reports the name the destination stored. */ + PayloadSink openPayload(String desiredName) throws IOException; + + /** Open a writable stream for the top-level {@code manifest.json}. */ + OutputStream openManifest() throws IOException; + + /** An open payload stream plus the name the destination actually stored it under. */ + final class PayloadSink { + + private final OutputStream stream; + private final String name; + + public PayloadSink(OutputStream stream, String name) { + this.stream = stream; + this.name = name; + } + + public OutputStream stream() { + return stream; + } + + public String name() { + return name; + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportFilenames.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportFilenames.java new file mode 100644 index 000000000..c44b3654b --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportFilenames.java @@ -0,0 +1,89 @@ +package org.appdevforall.k2go.contentexchange.domain; + +import java.util.Set; + +/** + * Pure rules for the name each item's archive is written under in the bundle. + * + *

The server suggests a name through {@code Content-Disposition}, but it arrives over the + * wire, so it is sanitized to a safe basename (no path separators, no characters a FAT / exFAT + * drive rejects, no control characters) before it touches the destination. An empty or unusable + * suggestion falls back to a name built from the item address. Names are de-duplicated so two + * items can never collide on one file. + * + *

Stateless except for the {@code used} set the caller threads through, so it is unit-testable + * on a plain JVM. + */ +public final class ExportFilenames { + + private ExportFilenames() {} + + /** Characters not allowed in a FAT / exFAT file name, plus the path separators. */ + private static final String ILLEGAL = "\\/:*?\"<>|"; + + /** + * Resolve the name to store this item under, and record it in {@code used}. + * + * @param suggested the server-suggested name ({@code Content-Disposition}); may be null/empty + * @param ref the item address, used to build a fallback name + * @param used names already taken in this bundle; the returned name is added to it + */ + public static String resolve(String suggested, ItemRef ref, Set used) { + String base = safeBaseName(suggested); + if (base == null) { + base = fallback(ref); + } + String unique = deduplicate(base, used); + used.add(unique); + return unique; + } + + /** Strip the path, drop illegal and control characters, trim. Returns null when nothing remains. */ + static String safeBaseName(String raw) { + if (raw == null) { + return null; + } + String name = raw; + int slash = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')); + if (slash >= 0) { + name = name.substring(slash + 1); + } + StringBuilder out = new StringBuilder(name.length()); + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + if (c < 0x20 || ILLEGAL.indexOf(c) >= 0) { + continue; + } + out.append(c); + } + // Leading dots hide the file on unix-like viewers and "." / ".." are not real names. + String trimmed = out.toString().trim(); + while (trimmed.startsWith(".")) { + trimmed = trimmed.substring(1); + } + return trimmed.isEmpty() ? null : trimmed; + } + + private static String fallback(ItemRef ref) { + String app = safeBaseName(ref != null ? ref.app() : null); + String local = safeBaseName(ref != null ? ref.localRef() : null); + String base = (app != null ? app : "item") + "_" + (local != null ? local : "payload"); + return base + ".bin"; + } + + /** Append {@code _2}, {@code _3}, ... before the extension until the name is unused. */ + private static String deduplicate(String name, Set used) { + if (!used.contains(name)) { + return name; + } + int dot = name.lastIndexOf('.'); + String stem = dot > 0 ? name.substring(0, dot) : name; + String ext = dot > 0 ? name.substring(dot) : ""; + for (int n = 2; ; n++) { + String candidate = stem + "_" + n + ext; + if (!used.contains(candidate)) { + return candidate; + } + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportItem.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportItem.java new file mode 100644 index 000000000..c541dea85 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportItem.java @@ -0,0 +1,32 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * One item the core planned for export: its address, a display title, and the exact byte + * size the plan returned. The size is the progress weight (the export stream is chunked, so + * there is no Content-Length to measure against). Immutable. Pure domain type. + */ +public final class ExportItem { + + private final ItemRef ref; + private final String title; + private final long bytes; + + public ExportItem(ItemRef ref, String title, long bytes) { + this.ref = ref; + this.title = title; + this.bytes = bytes; + } + + public ItemRef ref() { + return ref; + } + + public String title() { + return title; + } + + /** Exact size from the plan; {@code 0} when the core could not size it. */ + public long bytes() { + return bytes; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportJob.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportJob.java new file mode 100644 index 000000000..028cac4cc --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportJob.java @@ -0,0 +1,210 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * The pure state of one export run: a per-item status plus how many bytes of each item have been + * written, and the derived progress. The service mutates it as it drains the queue; the UI reads + * the derived figures. No Android, no IO: unit-testable on a plain JVM. + * + *

The item is the unit of resume (ADR "Resilience"): a failed item is re-queued and re-done on + * its own; the rest are untouched. The arrays are indexed by the original request order and set to + * one length in {@link #begin}, so the UI can never read a length mismatch. + */ +public final class ExportJob { + + public static final int PENDING = 0; + public static final int ACTIVE = 1; + public static final int DONE = 2; + public static final int FAILED = 3; + + private int[] status = new int[0]; + private long[] planned = new long[0]; + private long[] copied = new long[0]; + private int index = -1; + + /** + * Start a run over {@code planned[i]} bytes per item (0 = unknown size). A negative planned + * value marks an item the core could not plan: it starts {@link #FAILED}, not downloadable. + */ + public void begin(long[] plannedBytes) { + int n = plannedBytes != null ? plannedBytes.length : 0; + status = new int[n]; + planned = new long[n]; + copied = new long[n]; + index = -1; + for (int i = 0; i < n; i++) { + if (plannedBytes[i] < 0) { + status[i] = FAILED; + } else { + planned[i] = plannedBytes[i]; + } + } + } + + public int size() { + return status.length; + } + + public int status(int i) { + return i >= 0 && i < status.length ? status[i] : FAILED; + } + + public long planned(int i) { + return i >= 0 && i < planned.length ? planned[i] : 0L; + } + + public long copied(int i) { + return i >= 0 && i < copied.length ? copied[i] : 0L; + } + + /** The item currently being written, or -1 when none is active. */ + public int index() { + return index; + } + + /** The first item still waiting, or -1 when the queue is drained. */ + public int firstPending() { + for (int i = 0; i < status.length; i++) { + if (status[i] == PENDING) { + return i; + } + } + return -1; + } + + public void setActive(int i) { + if (i >= 0 && i < status.length) { + status[i] = ACTIVE; + copied[i] = 0L; + index = i; + } + } + + /** Record the absolute bytes written so far for item {@code i}. */ + public void setCopied(int i, long bytes) { + if (i >= 0 && i < copied.length) { + copied[i] = Math.max(0L, bytes); + } + } + + public void setDone(int i) { + if (i >= 0 && i < status.length) { + status[i] = DONE; + // A chunked archive can run slightly over the planned size (tar headers); clamp so the + // per-item and overall bars read a clean 100 percent. + if (planned[i] > 0 && copied[i] < planned[i]) { + copied[i] = planned[i]; + } + } + } + + public void setFailed(int i) { + if (i >= 0 && i < status.length) { + status[i] = FAILED; + } + } + + /** Re-queue every failed item (reset its progress) for a retry. Returns how many changed. */ + public int requeueFailed() { + int changed = 0; + for (int i = 0; i < status.length; i++) { + if (status[i] == FAILED) { + status[i] = PENDING; + copied[i] = 0L; + changed++; + } + } + return changed; + } + + public boolean hasFailed() { + for (int st : status) { + if (st == FAILED) { + return true; + } + } + return false; + } + + public int doneCount() { + return count(DONE); + } + + public int failedCount() { + return count(FAILED); + } + + private int count(int target) { + int c = 0; + for (int st : status) { + if (st == target) { + c++; + } + } + return c; + } + + /** No item is still pending or active (the run has settled; some may have failed). */ + public boolean isSettled() { + if (status.length == 0) { + return false; + } + for (int st : status) { + if (st == PENDING || st == ACTIVE) { + return false; + } + } + return true; + } + + /** Every item finished successfully. */ + public boolean allDone() { + return status.length > 0 && doneCount() == status.length; + } + + public long plannedTotal() { + long t = 0L; + for (long p : planned) { + t += p; + } + return t; + } + + public long copiedTotal() { + long t = 0L; + for (int i = 0; i < copied.length; i++) { + t += Math.min(copied[i], planned[i] > 0 ? planned[i] : copied[i]); + } + return t; + } + + /** Overall percent, weighted by planned bytes; falls back to item count when sizes are unknown. */ + public int overallPercent() { + long total = plannedTotal(); + if (total > 0) { + long done = 0L; + for (int i = 0; i < status.length; i++) { + if (status[i] == DONE) { + done += planned[i]; + } else if (status[i] == ACTIVE) { + done += Math.min(copied[i], planned[i]); + } + } + return (int) Math.min(100L, done * 100L / total); + } + int n = status.length; + if (n == 0) { + return 0; + } + int settled = doneCount() + failedCount(); + return (int) Math.min(100L, (long) settled * 100L / n); + } + + /** Percent of the active item written so far (0 when its size is unknown). */ + public int currentItemPercent() { + int i = index; + if (i < 0 || i >= planned.length || planned[i] <= 0) { + return 0; + } + return (int) Math.min(100L, copied[i] * 100L / planned[i]); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportPlan.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportPlan.java new file mode 100644 index 000000000..87ea39a3c --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportPlan.java @@ -0,0 +1,38 @@ +package org.appdevforall.k2go.contentexchange.domain; + +import java.util.Collections; +import java.util.List; + +/** + * The result of {@code POST /v1/export/plan}: the items the core can export (with exact + * sizes), the ones it skipped (unknown app / not found), and the total bytes. Moving no + * payload, so the front shows the total and the skip list before any byte moves. + * + *

Partial is first-class (ADR): a skipped item is reported, never fatal. Immutable. + */ +public final class ExportPlan { + + private final List items; + private final List skipped; + private final long totalBytes; + + public ExportPlan(List items, List skipped, long totalBytes) { + this.items = Collections.unmodifiableList(items); + this.skipped = Collections.unmodifiableList(skipped); + this.totalBytes = totalBytes; + } + + /** The items the core can export, in the order requested. */ + public List items() { + return items; + } + + /** Human-readable reasons for each item the core could not plan (may be empty). */ + public List skipped() { + return skipped; + } + + public long totalBytes() { + return totalBytes; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ItemRef.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ItemRef.java new file mode 100644 index 000000000..62494db24 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ItemRef.java @@ -0,0 +1,54 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * The address of one content item on the box: the adapter key plus the app's own local + * handle. This is what every action slice (export / import / delete) names an item by, and + * it matches the core contract {@code {app, localRef}}. + * + *

Immutable value object with value equality, so it is a safe map key (the export flow + * keys the manifest payload names and the captured plan entries by it). Pure domain type. + */ +public final class ItemRef { + + private final String app; + private final String localRef; + + public ItemRef(String app, String localRef) { + this.app = app; + this.localRef = localRef; + } + + public String app() { + return app; + } + + public String localRef() { + return localRef; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof ItemRef)) { + return false; + } + ItemRef other = (ItemRef) o; + return eq(app, other.app) && eq(localRef, other.localRef); + } + + private static boolean eq(String a, String b) { + return a == null ? b == null : a.equals(b); + } + + @Override + public int hashCode() { + return 31 * (app == null ? 0 : app.hashCode()) + (localRef == null ? 0 : localRef.hashCode()); + } + + @Override + public String toString() { + return app + "/" + localRef; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java new file mode 100644 index 000000000..8f27a54d8 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java @@ -0,0 +1,499 @@ +/* + * ============================================================================ + * Name : ContentExportService.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. Foreground service that drains the export queue: plan the selected + * items, then per item pull the streaming archive from cx-core and write it to the + * SAF destination, writing the collection manifest last over the items that landed. + * Reuses the download-service pattern (foreground specialUse + per-item queue + + * retry + notification), but the bytes flow phone <- box -> drive here, so it is a + * plain stream copy, not the server-owned POST/poll engine. The item is the unit of + * resume (per-item retry); pause/resume and within-item byte-resume are later work. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.presentation; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Build; +import android.os.IBinder; +import android.os.SystemClock; + +import androidx.annotation.Nullable; +import androidx.core.app.NotificationCompat; +import androidx.core.content.ContextCompat; + +import org.appdevforall.k2go.R; +import org.appdevforall.k2go.contentexchange.data.CxCoreDataSource; +import org.appdevforall.k2go.contentexchange.data.CxCoreExportSource; +import org.appdevforall.k2go.contentexchange.data.SafExportCarrier; +import org.appdevforall.k2go.contentexchange.domain.ContentExportSource; +import org.appdevforall.k2go.contentexchange.domain.ExportCarrier; +import org.appdevforall.k2go.contentexchange.domain.ExportFilenames; +import org.appdevforall.k2go.contentexchange.domain.ExportJob; +import org.appdevforall.k2go.contentexchange.domain.ExportPlan; +import org.appdevforall.k2go.contentexchange.domain.ItemRef; +import org.appdevforall.k2go.notifications.NotificationIds; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public final class ContentExportService extends Service { + + public static final String ACTION_START = "org.appdevforall.k2go.CONTENT_EXPORT_START"; + public static final String ACTION_RETRY = "org.appdevforall.k2go.CONTENT_EXPORT_RETRY"; + public static final String ACTION_CANCEL = "org.appdevforall.k2go.CONTENT_EXPORT_CANCEL"; + + public static final String EXTRA_TREE_URI = "treeUri"; + public static final String EXTRA_APPS = "apps"; + public static final String EXTRA_LOCAL_REFS = "localRefs"; + + private static final String CHANNEL_ID = "content_export_channel"; + private static final int NOTIFICATION_ID = NotificationIds.CONTENT_EXPORT; + private static final int COPY_BUFFER = 64 * 1024; + private static final long PUBLISH_INTERVAL_MS = 250L; + private static final long NOTIFY_INTERVAL_MS = 1000L; + + /** The single run state the progress fragment observes. */ + private static final ExportSession SESSION = new ExportSession(); + + static ExportSession session() { + return SESSION; + } + + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + + // ---- static control surface (the fragment calls these) ------------------------------------- + + public static void start(Context ctx, Uri treeUri, ItemRef[] refs) { + String[] apps = new String[refs.length]; + String[] locals = new String[refs.length]; + for (int i = 0; i < refs.length; i++) { + apps[i] = refs[i].app(); + locals[i] = refs[i].localRef(); + } + Intent i = new Intent(ctx, ContentExportService.class).setAction(ACTION_START) + .putExtra(EXTRA_TREE_URI, treeUri.toString()) + .putExtra(EXTRA_APPS, apps) + .putExtra(EXTRA_LOCAL_REFS, locals); + ContextCompat.startForegroundService(ctx, i); + } + + public static void retry(Context ctx) { + if (SESSION.canRetry()) { + ContextCompat.startForegroundService(ctx, + new Intent(ctx, ContentExportService.class).setAction(ACTION_RETRY)); + } + } + + public static void cancel(Context ctx) { + ContextCompat.startForegroundService(ctx, + new Intent(ctx, ContentExportService.class).setAction(ACTION_CANCEL)); + } + + /** Clear a settled session (the "Finish" button) and release its one-shot SAF grant. Safe to + * call when nothing is running. */ + public static void finishSession(Context ctx) { + releaseGrant(ctx, SESSION.treeUri()); + SESSION.clear(); + } + + /** + * Release the persisted SAF grant for a finished export. Export is one-shot (pick a drive, write, + * done), so the grant is not needed afterwards; releasing it keeps the app's persisted-permission + * set from growing toward the system cap. Idempotent: releasing a grant not held is a no-op. + */ + static void releaseGrant(Context ctx, String treeUri) { + if (treeUri == null) { + return; + } + try { + ctx.getContentResolver().releasePersistableUriPermission(Uri.parse(treeUri), + Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); + } catch (Exception ignored) { + // already released, or never persisted (transient grant): nothing to free + } + } + + @Override + public void onCreate() { + super.onCreate(); + createChannel(); + } + + @Nullable + @Override + public IBinder onBind(Intent intent) { + return null; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + String action = intent != null ? intent.getAction() : null; + + if (ACTION_CANCEL.equals(action)) { + releaseGrant(getApplicationContext(), SESSION.treeUri()); + SESSION.markCancelled(); + SESSION.clear(); + stopForeground(true); + stopSelf(); + return START_NOT_STICKY; + } + + if (SESSION.isRunning() && !ACTION_CANCEL.equals(action)) { + return START_NOT_STICKY; // a duplicate start while draining: ignore + } + + if (ACTION_RETRY.equals(action)) { + if (!SESSION.canRetry()) { + stopSelf(); + return START_NOT_STICKY; + } + SESSION.requeueFailed(); // flip failed items back to pending; leftover pending stay + SESSION.setRunning(true); + startForeground(NOTIFICATION_ID, buildNotification(null)); + worker.execute(() -> drain(/* fresh= */ false)); + return START_NOT_STICKY; + } + + // START: a fresh run from the intent. + if (intent == null) { + stopSelf(); + return START_NOT_STICKY; + } + String treeUri = intent.getStringExtra(EXTRA_TREE_URI); + final ItemRef[] refs = readRefs(intent); + if (refs.length == 0 || treeUri == null) { + stopSelf(); + return START_NOT_STICKY; + } + SESSION.beginPlanning(refs, initialLabels(refs), treeUri); + startForeground(NOTIFICATION_ID, buildNotification(null)); + worker.execute(() -> drain(/* fresh= */ true)); + return START_NOT_STICKY; + } + + // ---- the run ------------------------------------------------------------------------------- + + /** + * Plan (fresh only), then drain the pending items and write the manifest over what landed. + * + *

v1 limitation (accepted): the run state is in-memory, so a process death mid-export loses it + * (no cross-process-death resume), and because the manifest is written last, an interrupted run + * leaves payloads on the drive with no manifest. v1 does within-run per-item retry only; durable + * op-state and the manifest-interrupt hardening are v1.x (the import side also validates and skips). + */ + private void drain(boolean fresh) { + ExportCarrier carrier; + ContentExportSource source = new CxCoreExportSource(new CxCoreDataSource()); + try { + carrier = new SafExportCarrier(getApplicationContext(), Uri.parse(SESSION.treeUri())); + } catch (Exception e) { + finishWithError("Could not open the destination: " + e.getMessage()); + return; + } + SESSION.setDestination(carrier.destinationLabel()); + + try { + ExportPlan plan = source.plan(refsList()); + if (fresh) { + applyPlan(plan); + } + } catch (Exception e) { + // The box is unreachable: fail the run (keep any items a prior run finished). + finishWithError("Could not reach the box: " + e.getMessage()); + return; + } + + ExportJob job = SESSION.job(); + Set used = seedUsedNames(); + long runStart = SystemClock.elapsedRealtime(); + long lastSampleAt = runStart; + long lastSampleBytes = job.copiedTotal(); + + for (int i = job.firstPending(); i >= 0; i = job.firstPending()) { + if (SESSION.isCancelled()) { + break; + } + ItemRef ref = SESSION.refAt(i); + job.setActive(i); + SESSION.publish(); + notifyNow(); + + try (ContentExportSource.ItemPayload payload = source.open(ref)) { + String name = ExportFilenames.resolve(payload.filename(), ref, used); + ExportCarrier.PayloadSink sink = carrier.openPayload(name); + SESSION.setPayloadName(i, sink.name()); + copy(payload.stream(), sink.stream(), i, job, runStart); + job.setDone(i); + } catch (IOException e) { + job.setFailed(i); + SESSION.publish(); + if (isNoSpace(e)) { + // The drive is full: stop and leave the rest pending for a Retry after space is freed. + finishWithError("The drive is out of space."); + return; + } + continue; // a per-item failure: skip it, keep going + } catch (Exception e) { + job.setFailed(i); + SESSION.publish(); + continue; + } + + long now = SystemClock.elapsedRealtime(); + if (now - lastSampleAt >= 500L) { + sampleRate(job, now - lastSampleAt, job.copiedTotal() - lastSampleBytes); + lastSampleAt = now; + lastSampleBytes = job.copiedTotal(); + } + SESSION.publish(); + } + + if (SESSION.isCancelled()) { + SESSION.clear(); + stopForeground(true); + stopSelf(); + return; + } + + writeManifest(source, carrier, job); + if (SESSION.allDone()) { + // Fully exported: one-shot done, so free the grant now (a partial run keeps it for Retry). + releaseGrant(getApplicationContext(), SESSION.treeUri()); + } + SESSION.setRunning(false); + SESSION.setRate(0L, -1L); + SESSION.publish(); + stopForeground(true); + stopSelf(); + } + + /** + * Copy one stream to the destination, updating per-item progress and honoring cancellation. The + * output is closed here inside try-with-resources so a close-time failure (ENOSPC on a drive + * commonly surfaces at flush/close, not write) propagates and the item is marked failed, never + * a silent partial written as done. + */ + private void copy(InputStream in, OutputStream out, int i, ExportJob job, long runStart) + throws IOException { + byte[] buffer = new byte[COPY_BUFFER]; + long total = 0L; + long lastPublish = 0L; + try (OutputStream sink = out) { + int read; + while ((read = in.read(buffer)) != -1) { + if (SESSION.isCancelled()) { + throw new IOException("cancelled"); + } + sink.write(buffer, 0, read); + total += read; + job.setCopied(i, total); + long now = SystemClock.elapsedRealtime(); + if (now - lastPublish >= PUBLISH_INTERVAL_MS) { + long elapsed = now - runStart; + if (elapsed > 0) { + long speed = job.copiedTotal() * 1000L / elapsed; + long remaining = job.plannedTotal() - job.copiedTotal(); + long eta = speed > 0 ? Math.max(0L, remaining / speed) : -1L; + SESSION.setRate(speed, eta); + } + SESSION.publish(); + maybeNotify(now); + lastPublish = now; + } + } + sink.flush(); + } + } + + private void writeManifest(ContentExportSource source, ExportCarrier carrier, ExportJob job) { + List order = new ArrayList<>(); + Map names = new HashMap<>(); + for (int i = 0; i < job.size(); i++) { + if (job.status(i) == ExportJob.DONE) { + ItemRef ref = SESSION.refAt(i); + order.add(ref); + names.put(ref, SESSION.payloadName(i)); + } + } + if (order.isEmpty()) { + return; // nothing landed: no manifest to write + } + try (OutputStream out = carrier.openManifest()) { + out.write(source.buildManifest(order, names)); + out.flush(); + } catch (Exception e) { + // Rare (the manifest is tiny): the payloads are on the drive but the index is missing. + SESSION.fail("Items were written but the manifest could not be saved. Re-export to rewrite it."); + } + } + + // ---- helpers ------------------------------------------------------------------------------- + + private void applyPlan(ExportPlan plan) { + // Align the plan to the fixed request order; an item the core could not plan gets -1 + // (ExportJob marks it FAILED) so the queue never blocks waiting for it. + ItemRef[] refs = SESSION.refs(); + Map sized = new HashMap<>(); + Map titles = new HashMap<>(); + for (int k = 0; k < plan.items().size(); k++) { + sized.put(plan.items().get(k).ref(), plan.items().get(k).bytes()); + titles.put(plan.items().get(k).ref(), plan.items().get(k).title()); + } + long[] planned = new long[refs.length]; + String[] labels = new String[refs.length]; + for (int i = 0; i < refs.length; i++) { + Long b = sized.get(refs[i]); + planned[i] = b != null ? b : -1L; + String t = titles.get(refs[i]); + labels[i] = t != null && !t.isEmpty() ? t : refs[i].localRef(); + } + SESSION.applyPlan(labels, planned, plan.skipped()); + } + + private Set seedUsedNames() { + Set used = new HashSet<>(); + for (int i = 0; i < SESSION.itemCount(); i++) { + String name = SESSION.payloadName(i); + if (name != null) { + used.add(name); + } + } + return used; + } + + private void sampleRate(ExportJob job, long dtMs, long dBytes) { + if (dtMs <= 0) { + return; + } + long speed = Math.max(0L, dBytes * 1000L / dtMs); + long remaining = job.plannedTotal() - job.copiedTotal(); + long eta = speed > 0 ? Math.max(0L, remaining / speed) : -1L; + SESSION.setRate(speed, eta); + } + + private void finishWithError(String message) { + SESSION.fail(message); + stopForeground(true); + stopSelf(); + } + + private static ItemRef[] readRefs(Intent intent) { + String[] apps = intent.getStringArrayExtra(EXTRA_APPS); + String[] locals = intent.getStringArrayExtra(EXTRA_LOCAL_REFS); + if (apps == null || locals == null || apps.length != locals.length) { + return new ItemRef[0]; + } + ItemRef[] refs = new ItemRef[apps.length]; + for (int i = 0; i < apps.length; i++) { + refs[i] = new ItemRef(apps[i], locals[i]); + } + return refs; + } + + private static String[] initialLabels(ItemRef[] refs) { + String[] labels = new String[refs.length]; + for (int i = 0; i < refs.length; i++) { + labels[i] = refs[i].localRef(); + } + return labels; + } + + private List refsList() { + List list = new ArrayList<>(); + ItemRef[] refs = SESSION.refs(); + for (ItemRef ref : refs) { + list.add(ref); + } + return list; + } + + private static boolean isNoSpace(Throwable e) { + for (Throwable t = e; t != null; t = t.getCause()) { + String msg = t.getMessage(); + if (msg != null) { + String lower = msg.toLowerCase(java.util.Locale.US); + if (lower.contains("enospc") || lower.contains("no space")) { + return true; + } + } + } + return false; + } + + // ---- notification -------------------------------------------------------------------------- + + private long lastNotifyAt = 0L; + + private void notifyNow() { + lastNotifyAt = SystemClock.elapsedRealtime(); + NotificationManager m = getSystemService(NotificationManager.class); + if (m != null) { + m.notify(NOTIFICATION_ID, buildNotification(currentLabel())); + } + } + + private void maybeNotify(long now) { + if (now - lastNotifyAt >= NOTIFY_INTERVAL_MS) { + notifyNow(); + } + } + + @Nullable + private String currentLabel() { + int i = SESSION.index(); + return i >= 0 ? SESSION.label(i) : null; + } + + private Notification buildNotification(@Nullable String contentText) { + Intent cancel = new Intent(this, ContentExportService.class).setAction(ACTION_CANCEL); + PendingIntent cancelIntent = PendingIntent.getService(this, 1, cancel, + PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); + String text = contentText != null && !contentText.isEmpty() + ? contentText : getString(R.string.k2go_cx_export_notif_text); + return new NotificationCompat.Builder(this, CHANNEL_ID) + .setContentTitle(getString(R.string.k2go_cx_export_notif_title)) + .setContentText(text) + .setSmallIcon(android.R.drawable.stat_sys_upload) + .setOngoing(true) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setOnlyAlertOnce(true) + .addAction(0, getString(R.string.k2go_dash_cancel), cancelIntent) + .build(); + } + + private void createChannel() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationChannel channel = new NotificationChannel( + CHANNEL_ID, getString(R.string.k2go_cx_export_channel_name), + NotificationManager.IMPORTANCE_LOW); + NotificationManager manager = getSystemService(NotificationManager.class); + if (manager != null) { + manager.createNotificationChannel(channel); + } + } + } + + @Override + public void onDestroy() { + worker.shutdownNow(); + super.onDestroy(); + } +} 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 index c58337e42..e704cacd7 100644 --- 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 @@ -5,19 +5,24 @@ * 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. + * free disk, with per-item multi-select. The EXPORT action is wired + * (pick a drive via SAF, then write the open-format bundle through the + * foreground service); Share / Delete are later slices and stay disabled. * ============================================================================ */ package org.appdevforall.k2go.contentexchange.presentation; +import android.content.Intent; +import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.widget.Button; import android.widget.TextView; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; @@ -25,9 +30,12 @@ import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; +import com.google.android.material.dialog.MaterialAlertDialogBuilder; + 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.ItemRef; import org.appdevforall.k2go.contentexchange.domain.ManagedContent; import org.appdevforall.k2go.contentexchange.domain.StorageStatus; import org.appdevforall.k2go.storage.StorageProbe; @@ -51,6 +59,10 @@ public class ContentManagerFragment extends Fragment { private TextView status; private View actionBar; private TextView selectionLabel; + private Button exportButton; + + /** The folder picker; its result carries the drive/folder the user chose for the export. */ + private ActivityResultLauncher openTree; @Nullable @Override @@ -60,6 +72,11 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c 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); + exportButton = root.findViewById(R.id.k2go_cx_export); + + openTree = registerForActivityResult(new ActivityResultContracts.OpenDocumentTree(), this::onTreePicked); + exportButton.setEnabled(true); + exportButton.setOnClickListener(v -> onExportClicked()); TextView back = root.findViewById(R.id.k2go_cx_back); back.setText(getString(R.string.k2go_back_link)); @@ -177,6 +194,84 @@ private void renderSelection(SelectionSummary sel) { actionBar.setVisibility(View.VISIBLE); } + /** The selection captured when Export was tapped, held across the folder picker round-trip. */ + private List pendingExport; + + /** Export: if a run is already active, just show it; otherwise capture the selection and pick a drive. */ + private void onExportClicked() { + if (ContentExportService.session().hasSession()) { + showProgress(); + return; + } + List selected = viewModel.selectedItems(); + if (selected.isEmpty()) { + return; + } + pendingExport = selected; + // SAF folder picker: no storage permission is requested; the persisted grant is the authority. + openTree.launch(null); + } + + /** The folder picker returned. Null means the user cancelled. */ + private void onTreePicked(@Nullable Uri treeUri) { + if (treeUri == null || pendingExport == null || pendingExport.isEmpty()) { + return; + } + // Persist read+write so the foreground service keeps access after this screen is gone. + int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION; + android.content.ContentResolver resolver = requireContext().getContentResolver(); + try { + resolver.takePersistableUriPermission(treeUri, flags); + } catch (SecurityException e) { + // The grant could not be persisted; proceed with the transient permission for this session. + } + // Safety net against unbounded growth: the run releases its own grant when it finishes, but an + // export abandoned before "Finish" (e.g. the process is killed) would leave a stale grant. Export + // is the app's only persisted-grant user, so drop every persisted tree except the one just taken. + for (android.content.UriPermission p : resolver.getPersistedUriPermissions()) { + if (!p.getUri().equals(treeUri)) { + try { + resolver.releasePersistableUriPermission(p.getUri(), flags); + } catch (Exception ignored) { + // best-effort prune + } + } + } + confirmAndStart(treeUri, pendingExport); + } + + private void confirmAndStart(Uri treeUri, List selected) { + long total = 0L; + for (ContentItem item : selected) { + total += Math.max(0L, item.bytes()); + } + String message = getString(R.string.k2go_cx_export_confirm_fmt, + selected.size(), ByteFormatter.humanBytes(total)); + new MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.k2go_cx_action_export) + .setMessage(message) + .setNegativeButton(R.string.k2go_dash_cancel, null) + .setPositiveButton(R.string.k2go_cx_action_export, (d, w) -> startExport(treeUri, selected)) + .show(); + } + + private void startExport(Uri treeUri, List selected) { + ItemRef[] refs = new ItemRef[selected.size()]; + for (int i = 0; i < selected.size(); i++) { + refs[i] = new ItemRef(selected.get(i).app(), selected.get(i).localRef()); + } + ContentExportService.start(requireContext(), treeUri, refs); + viewModel.clearSelection(); + showProgress(); + } + + private void showProgress() { + requireActivity().getSupportFragmentManager().beginTransaction() + .replace(R.id.k2go_setup_host, new ExportProgressFragment()) + .addToBackStack(null) + .commit(); + } + /** Friendly app label; falls back to the raw adapter key for an unknown app. */ private String appDisplayName(String app) { if (app == null) { 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 index e7d89bc6f..c3410e51d 100644 --- 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 @@ -11,8 +11,10 @@ import org.appdevforall.k2go.contentexchange.domain.ManagedContent; import org.appdevforall.k2go.contentexchange.domain.StorageStatus; +import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; @@ -44,6 +46,9 @@ public class ContentManagerViewModel extends ViewModel { private final Set selectedIds = new HashSet<>(); /** selectionId -> item bytes, rebuilt on each successful load, for the selection total. */ private final Map bytesById = new HashMap<>(); + /** The last loaded content, so the action slices can resolve the selected items. Volatile: set on + * the loader thread, read on the main thread after the SUCCESS state is observed. */ + private volatile ManagedContent lastContent; public ContentManagerViewModel(ListManagedContentUseCase listContent, GetStorageStatusUseCase getStorage) { this.listContent = listContent; @@ -65,6 +70,7 @@ public void load() { try { ManagedContent content = listContent.execute(); StorageStatus storage = getStorage.execute(); + lastContent = content; indexBytes(content); state.postValue(ContentManagerUiState.success(content, storage)); } catch (Exception e) { @@ -77,6 +83,23 @@ public boolean isSelected(String selectionId) { return selectedIds.contains(selectionId); } + /** The currently selected items (for an action slice: export / delete). Empty if nothing loaded. */ + public List selectedItems() { + List out = new ArrayList<>(); + ManagedContent content = lastContent; + if (content == null) { + return out; + } + for (ContentGroup group : content.groups()) { + for (ContentItem item : group.items()) { + if (selectedIds.contains(item.selectionId())) { + out.add(item); + } + } + } + return out; + } + /** Toggles one item's selection and republishes the summary. */ public void toggle(String selectionId) { if (!selectedIds.remove(selectionId)) { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java new file mode 100644 index 000000000..e264fc410 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java @@ -0,0 +1,200 @@ +/* + * ============================================================================ + * Name : ExportProgressFragment.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. Observes the ContentExportService session and renders the export progress + * (overall + current item: bar / percent / bytes / speed / ETA), then the settled + * state (done or partial) with Retry / Finish. Reads state only; all work is the + * foreground service's. + * ============================================================================ + */ +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.Button; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; + +import com.google.android.material.progressindicator.LinearProgressIndicator; + +import org.appdevforall.k2go.R; +import org.appdevforall.k2go.contentexchange.domain.ExportJob; +import org.appdevforall.k2go.util.ByteFormatter; + +import java.util.List; +import java.util.Locale; + +public class ExportProgressFragment extends Fragment { + + private TextView destination; + private TextView overallLabel; + private LinearProgressIndicator overallBar; + private TextView overallDetail; + private TextView itemLabel; + private LinearProgressIndicator itemBar; + private TextView message; + private TextView skipped; + private Button cancel; + private Button retry; + private Button finish; + + private final ExportSession session = ContentExportService.session(); + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle s) { + View root = inflater.inflate(R.layout.fragment_k2go_content_export, container, false); + destination = root.findViewById(R.id.k2go_cxx_destination); + overallLabel = root.findViewById(R.id.k2go_cxx_overall_label); + overallBar = root.findViewById(R.id.k2go_cxx_overall_bar); + overallDetail = root.findViewById(R.id.k2go_cxx_overall_detail); + itemLabel = root.findViewById(R.id.k2go_cxx_item_label); + itemBar = root.findViewById(R.id.k2go_cxx_item_bar); + message = root.findViewById(R.id.k2go_cxx_message); + skipped = root.findViewById(R.id.k2go_cxx_skipped); + cancel = root.findViewById(R.id.k2go_cxx_cancel); + retry = root.findViewById(R.id.k2go_cxx_retry); + finish = root.findViewById(R.id.k2go_cxx_finish); + + cancel.setOnClickListener(v -> ContentExportService.cancel(requireContext())); + retry.setOnClickListener(v -> ContentExportService.retry(requireContext())); + finish.setOnClickListener(v -> { + ContentExportService.finishSession(requireContext()); + goBack(); + }); + return root; + } + + @Override + public void onResume() { + super.onResume(); + session.setListener(() -> { + if (isAdded()) { + render(); + } + }); + render(); + } + + @Override + public void onPause() { + super.onPause(); + session.setListener(null); + } + + private void render() { + // A cleared / absent session means the run finished and was dismissed: leave this screen. + if (!session.hasSession()) { + goBack(); + return; + } + destination.setText(getString(R.string.k2go_cx_export_destination_fmt, session.destinationLabel())); + + boolean running = session.isRunning(); + boolean preparing = session.isPreparing(); + String error = session.errorMessage(); + + overallBar.setIndeterminate(preparing); + if (!preparing) { + overallBar.setProgressCompat(session.overallPercent(), true); + } + overallLabel.setText(preparing + ? getString(R.string.k2go_cx_export_preparing) + : getString(R.string.k2go_cx_export_overall_fmt, session.overallPercent())); + overallDetail.setText(preparing ? "" : overallDetail()); + + renderCurrentItem(running, preparing); + renderSettled(running, preparing, error); + + cancel.setVisibility(running ? View.VISIBLE : View.GONE); + boolean settled = !running; + retry.setVisibility(settled && session.canRetry() ? View.VISIBLE : View.GONE); + finish.setVisibility(settled && !preparing ? View.VISIBLE : View.GONE); + } + + private void renderCurrentItem(boolean running, boolean preparing) { + int i = session.index(); + if (running && !preparing && i >= 0) { + itemLabel.setVisibility(View.VISIBLE); + itemBar.setVisibility(View.VISIBLE); + itemLabel.setText(session.label(i)); + itemBar.setProgressCompat(session.currentItemPercent(), true); + } else { + itemLabel.setVisibility(View.GONE); + itemBar.setVisibility(View.GONE); + } + } + + private void renderSettled(boolean running, boolean preparing, String error) { + if (running || preparing) { + message.setVisibility(View.GONE); + skipped.setVisibility(View.GONE); + return; + } + int done = countDone(); + int total = session.itemCount(); + String text; + if (error != null) { + text = error; + } else if (session.allDone()) { + text = getString(R.string.k2go_cx_export_done_fmt, done); + } else { + text = getString(R.string.k2go_cx_export_partial_fmt, done, total); + } + message.setText(text); + message.setVisibility(View.VISIBLE); + + List skippedItems = session.skipped(); + if (skippedItems != null && !skippedItems.isEmpty()) { + skipped.setText(getString(R.string.k2go_cx_export_skipped_fmt, + android.text.TextUtils.join("\n", skippedItems))); + skipped.setVisibility(View.VISIBLE); + } else { + skipped.setVisibility(View.GONE); + } + } + + private int countDone() { + int c = 0; + for (int i = 0; i < session.itemCount(); i++) { + if (session.status(i) == ExportJob.DONE) { + c++; + } + } + return c; + } + + private String overallDetail() { + String bytes = ByteFormatter.humanBytes(session.copiedTotal()) + + " / " + ByteFormatter.humanBytes(session.plannedTotal()); + long speed = session.speed(); + long eta = session.etaSeconds(); + StringBuilder sb = new StringBuilder(bytes); + if (speed > 0) { + sb.append(" : ").append(ByteFormatter.humanBytes(speed)).append("/s"); + } + if (eta >= 0) { + sb.append(" : ").append(getString(R.string.k2go_cx_export_eta_fmt, formatEta(eta))); + } + return sb.toString(); + } + + private static String formatEta(long seconds) { + long m = seconds / 60; + long s = seconds % 60; + return String.format(Locale.US, "%d:%02d", m, s); + } + + private void goBack() { + if (isAdded()) { + requireActivity().getOnBackPressedDispatcher().onBackPressed(); + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java new file mode 100644 index 000000000..37106a7b3 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java @@ -0,0 +1,256 @@ +/* + * ============================================================================ + * Name : ExportSession.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. The one export-run state the progress UI observes and the foreground + * service mutates. Encapsulated (no public mutable fields, not a static grab-bag): + * the service owns the single instance and the fragment reads it through getters, + * mirroring the Clone / download session pattern. Holds the pure ExportJob plus the + * request, labels, destination and the derived speed/ETA. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.presentation; + +import android.os.Handler; +import android.os.Looper; + +import org.appdevforall.k2go.contentexchange.domain.ExportJob; +import org.appdevforall.k2go.contentexchange.domain.ItemRef; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +final class ExportSession { + + /** Pinged on the main thread whenever the run state changes. */ + interface Listener { + void onUpdate(); + } + + private final Handler main = new Handler(Looper.getMainLooper()); + private final ExportJob job = new ExportJob(); + + private Listener listener; + + private volatile boolean running = false; + private volatile boolean cancelled = false; + private boolean planned = false; + private String errorMessage; + private String destinationLabel = ""; + /** The persisted SAF tree the run writes to; kept here so a retry (possibly a new service + * process) reaches the same destination without the Intent carrying it again. */ + private String treeUri; + + private ItemRef[] refs = new ItemRef[0]; + private String[] labels = new String[0]; + /** The bundle file name each item was stored under, by request index. Survives a retry so the + * manifest can list items completed in an earlier run (whose files are already on the drive). */ + private String[] payloadNames = new String[0]; + private List skipped = Collections.emptyList(); + + private long speed = 0L; // bytes/sec, smoothed + private long etaSeconds = -1L; // whole-run seconds remaining, -1 unknown + + void setListener(Listener l) { + this.listener = l; + } + + // ---- service-side mutation ----------------------------------------------------------------- + + /** Start a run: the request and destination are fixed now; sizes/labels arrive with the plan. */ + void beginPlanning(ItemRef[] request, String[] initialLabels, String treeUri) { + this.refs = request != null ? request : new ItemRef[0]; + this.labels = initialLabels != null ? initialLabels : new String[this.refs.length]; + this.payloadNames = new String[this.refs.length]; + this.treeUri = treeUri; + this.destinationLabel = ""; + this.skipped = Collections.emptyList(); + this.errorMessage = null; + this.planned = false; + this.cancelled = false; + this.running = true; + this.speed = 0L; + this.etaSeconds = -1L; + publish(); + } + + void setDestination(String label) { + this.destinationLabel = label != null ? label : ""; + publish(); + } + + /** Apply the plan: begin the job over the sized items, upgrade labels to titles. */ + void applyPlan(String[] titleLabels, long[] plannedBytes, List skippedReasons) { + if (titleLabels != null && titleLabels.length == refs.length) { + this.labels = titleLabels; + } + this.skipped = skippedReasons != null ? new ArrayList<>(skippedReasons) : Collections.emptyList(); + job.begin(plannedBytes); + this.planned = true; + publish(); + } + + void fail(String message) { + this.errorMessage = message; + this.running = false; + publish(); + } + + void setRate(long bytesPerSecond, long etaSeconds) { + this.speed = Math.max(0L, bytesPerSecond); + this.etaSeconds = etaSeconds; + } + + void setRunning(boolean value) { + this.running = value; + } + + void markCancelled() { + this.cancelled = true; + this.running = false; + } + + int requeueFailed() { + return job.requeueFailed(); + } + + void clear() { + running = false; + cancelled = false; + planned = false; + errorMessage = null; + refs = new ItemRef[0]; + labels = new String[0]; + payloadNames = new String[0]; + treeUri = null; + skipped = Collections.emptyList(); + job.begin(new long[0]); + speed = 0L; + etaSeconds = -1L; + publish(); + } + + ExportJob job() { + return job; + } + + ItemRef refAt(int i) { + return i >= 0 && i < refs.length ? refs[i] : null; + } + + void setPayloadName(int i, String name) { + if (i >= 0 && i < payloadNames.length) { + payloadNames[i] = name; + } + } + + String payloadName(int i) { + return i >= 0 && i < payloadNames.length ? payloadNames[i] : null; + } + + ItemRef[] refs() { + return refs; + } + + String treeUri() { + return treeUri; + } + + boolean isCancelled() { + return cancelled; + } + + void publish() { + main.post(() -> { + if (listener != null) { + listener.onUpdate(); + } + }); + } + + // ---- UI-side reads ------------------------------------------------------------------------- + + boolean isRunning() { + return running; + } + + boolean hasSession() { + return refs.length > 0; + } + + /** A run exists, is active, but the plan has not landed yet. */ + boolean isPreparing() { + return running && !planned; + } + + boolean isSettled() { + return planned && !running && job.isSettled(); + } + + boolean allDone() { + return job.allDone(); + } + + boolean hasFailed() { + return job.hasFailed(); + } + + /** A settled run with work still left (failed items, or items re-queued by a failed re-plan). */ + boolean canRetry() { + return planned && !running && itemCount() > 0 && !job.allDone(); + } + + String errorMessage() { + return errorMessage; + } + + String destinationLabel() { + return destinationLabel; + } + + List skipped() { + return skipped; + } + + int itemCount() { + return job.size(); + } + + int index() { + return job.index(); + } + + String label(int i) { + return i >= 0 && i < labels.length ? labels[i] : ""; + } + + int status(int i) { + return job.status(i); + } + + int overallPercent() { + return job.overallPercent(); + } + + int currentItemPercent() { + return job.currentItemPercent(); + } + + long copiedTotal() { + return job.copiedTotal(); + } + + long plannedTotal() { + return job.plannedTotal(); + } + + long speed() { + return speed; + } + + long etaSeconds() { + return etaSeconds; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/notifications/NotificationIds.java b/controller/app/src/main/java/org/appdevforall/k2go/notifications/NotificationIds.java index aec49bd17..7d5de95e0 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/notifications/NotificationIds.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/notifications/NotificationIds.java @@ -37,6 +37,7 @@ private NotificationIds() {} public static final int DEEPOP = 12; // DeepOpService public static final int INSTALL_MODULE_FAILURE = 13; // InstallNotifications (dismissible "install failed") public static final int FORGEJO_SEED = 14; // ForgejoSeedService + public static final int CONTENT_EXPORT = 15; // ContentExportService (K2GO-427) // High range: single-purpose notifications that re-alert in place (they replace, never stack), // kept well away from the low range. Listed here too so the one source stays complete. diff --git a/controller/app/src/main/res/layout/fragment_k2go_content_export.xml b/controller/app/src/main/res/layout/fragment_k2go_content_export.xml new file mode 100644 index 000000000..a446d00d8 --- /dev/null +++ b/controller/app/src/main/res/layout/fragment_k2go_content_export.xml @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +