From 3dbd01969cbafcea2d92faf1868d796ee888d049 Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Fri, 23 Oct 2026 00:50:26 -0600 Subject: [PATCH 1/2] K2GO-427 feat(contentexchange): import content from a connected drive Add the import action, the receiver half of the disk round-trip, mirroring the merged export slice. The user picks a drive via SAF, the app reads the bundle (manifest.json, tolerating a missing one by scanning for .zim), the core validates per item (importable / already-have / newer / older / no-app), the user selects with a phone-disk preflight, and a foreground service stages each archive where the box (proot) can read it and calls the core to ingest it. - domain: ImportEntry/Manifest/Verdict/Scan/Preflight + ImportCarrier/ImportSource ports; reuse the generic ExportJob for the transfer state. - data: SafImportCarrier (DocumentsContract reader, no new permission/dependency), ImportManifestReader (parse + no-manifest scan), CxCoreImportSource (validate / import-item / delete), BoxImportStaging (box /library/.cx-staging <-> host path), CxCoreDataSource import/delete calls. - presentation: ImportReviewFragment + ViewModel/Adapter (grouped states, preflight), ContentImportService (specialUse foreground, per-item retry, grant release), ImportProgressFragment; "Import from drive" entry on the manager. - JVM tests for the scan, parse, verdict and preflight rules. Replace-older imports the newer version; auto-deleting the old copy is deferred (validate does not return the box's existing ref to delete, and it is per-app). Strings parked in strings_untranslated.xml; l10n at the feature closing PR. --- controller/app/src/main/AndroidManifest.xml | 9 + .../data/BoxImportStaging.java | 67 +++ .../data/CxCoreDataSource.java | 35 ++ .../data/CxCoreImportSource.java | 74 ++++ .../data/ImportManifestReader.java | 111 +++++ .../data/SafImportCarrier.java | 178 ++++++++ .../domain/ExportFilenames.java | 5 +- .../contentexchange/domain/ImportCarrier.java | 48 ++ .../contentexchange/domain/ImportEntry.java | 64 +++ .../domain/ImportManifest.java | 43 ++ .../domain/ImportPreflight.java | 27 ++ .../contentexchange/domain/ImportScan.java | 59 +++ .../contentexchange/domain/ImportSource.java | 33 ++ .../contentexchange/domain/ImportVerdict.java | 89 ++++ .../presentation/ContentImportService.java | 416 ++++++++++++++++++ .../presentation/ContentManagerFragment.java | 42 ++ .../presentation/ImportProgressFragment.java | 182 ++++++++ .../presentation/ImportReviewAdapter.java | 318 +++++++++++++ .../presentation/ImportReviewFragment.java | 272 ++++++++++++ .../presentation/ImportReviewItem.java | 38 ++ .../presentation/ImportReviewUiState.java | 45 ++ .../presentation/ImportReviewViewModel.java | 158 +++++++ .../ImportReviewViewModelFactory.java | 43 ++ .../presentation/ImportSelectionSummary.java | 24 + .../presentation/ImportSession.java | 230 ++++++++++ .../k2go/notifications/NotificationIds.java | 1 + .../layout/fragment_k2go_content_import.xml | 126 ++++++ .../layout/fragment_k2go_content_manager.xml | 12 + .../layout/fragment_k2go_import_review.xml | 90 ++++ .../main/res/values/strings_untranslated.xml | 24 + .../data/ImportManifestReaderTest.java | 89 ++++ .../domain/ImportPreflightTest.java | 32 ++ .../domain/ImportScanTest.java | 34 ++ .../domain/ImportVerdictTest.java | 60 +++ 34 files changed, 3076 insertions(+), 2 deletions(-) create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/BoxImportStaging.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreImportSource.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReader.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafImportCarrier.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportCarrier.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportEntry.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportManifest.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportPreflight.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportScan.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportSource.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportVerdict.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentImportService.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportProgressFragment.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewAdapter.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewFragment.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewItem.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewUiState.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModel.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModelFactory.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportSelectionSummary.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportSession.java create mode 100644 controller/app/src/main/res/layout/fragment_k2go_content_import.xml create mode 100644 controller/app/src/main/res/layout/fragment_k2go_import_review.xml create mode 100644 controller/app/src/test/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReaderTest.java create mode 100644 controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ImportPreflightTest.java create mode 100644 controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ImportScanTest.java create mode 100644 controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ImportVerdictTest.java diff --git a/controller/app/src/main/AndroidManifest.xml b/controller/app/src/main/AndroidManifest.xml index 284b027d1..58c4adeaf 100644 --- a/controller/app/src/main/AndroidManifest.xml +++ b/controller/app/src/main/AndroidManifest.xml @@ -230,6 +230,15 @@ android:value="Exports selected library content to a user-chosen drive through the co-located server REST engine." /> + + + + diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/BoxImportStaging.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/BoxImportStaging.java new file mode 100644 index 000000000..bdb492f72 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/BoxImportStaging.java @@ -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 and no separate bind for /library, so box /library maps + * to host /library (EnvironmentControl.rootfs = filesDir/rootfs/installed-rootfs/ + * iiab). This writes the staged archive under host /library/.cx-staging and + * reports the matching box path /library/.cx-staging/ 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(); + } + } +} 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 9d236a47a..06c18d92f 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 @@ -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:[]}} -> {@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 @@ -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 { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreImportSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreImportSource.java new file mode 100644 index 000000000..85fad674f --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreImportSource.java @@ -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 validate(List 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 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"))); + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReader.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReader.java new file mode 100644 index 000000000..6effdac0f --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReader.java @@ -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 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 parse(byte[] manifestBytes) throws Exception { + List 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 files) throws Exception { + List entries = new ArrayList<>(); + List 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()); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafImportCarrier.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafImportCarrier.java new file mode 100644 index 000000000..c6db6dd1e --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafImportCarrier.java @@ -0,0 +1,178 @@ +/* + * ============================================================================ + * Name : SafImportCarrier.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. SAF-backed import source: reads a bundle (manifest.json + one archive per + * item) from a user-picked drive/folder tree through the framework Storage Access + * Framework. The mirror of SafExportCarrier (the write side): DocumentsContract + + * ContentResolver directly (no androidx.documentfile), and 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. + * ============================================================================ + */ +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.ImportCarrier; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * One SAF document tree as an {@link ImportCarrier}. The tree Uri comes from + * {@code ACTION_OPEN_DOCUMENT_TREE} and must already carry a persisted permission. Children are listed + * once and indexed by display name, so the manifest read and each payload open resolve without a + * re-scan. + */ +public final class SafImportCarrier implements ImportCarrier { + + private static final String MANIFEST_NAME = "manifest.json"; + /** A manifest larger than this is treated as absent: the real index is a few KB. */ + private static final long MANIFEST_MAX_BYTES = 8L * 1024 * 1024; + + private final ContentResolver resolver; + private final Uri treeUri; + private final Uri treeDocUri; + + /** display name -> document id, built lazily from one children query. */ + private Map docIds; + private List files; + + public SafImportCarrier(Context context, Uri treeUri) { + this.resolver = context.getContentResolver(); + this.treeUri = treeUri; + this.treeDocUri = DocumentsContract.buildDocumentUriUsingTree( + treeUri, DocumentsContract.getTreeDocumentId(treeUri)); + } + + @Override + public String sourceLabel() { + String name = queryDisplayName(treeDocUri); + return name != null ? name : treeUri.getLastPathSegment(); + } + + @Override + public byte[] readManifest() throws IOException { + index(); + String id = docIds.get(MANIFEST_NAME); + if (id == null) { + // Case-insensitive fallback, for a drive that preserved odd casing. + for (Map.Entry e : docIds.entrySet()) { + if (MANIFEST_NAME.equalsIgnoreCase(e.getKey())) { + id = e.getValue(); + break; + } + } + } + if (id == null) { + return null; + } + Uri docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, id); + try (InputStream in = openStream(docUri)) { + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + byte[] chunk = new byte[8192]; + int n; + long total = 0L; + while ((n = in.read(chunk)) != -1) { + total += n; + if (total > MANIFEST_MAX_BYTES) { + return null; // too large to be the index: treat the bundle as manifest-less + } + buf.write(chunk, 0, n); + } + return buf.toByteArray(); + } + } + + @Override + public List listFiles() throws IOException { + index(); + return new ArrayList<>(files); + } + + @Override + public InputStream openPayload(String name) throws IOException { + index(); + String id = docIds.get(name); + if (id == null) { + throw new IOException("File not found on the drive: " + name); + } + return openStream(DocumentsContract.buildDocumentUriUsingTree(treeUri, id)); + } + + /** List the folder's direct children once (name + size + document id). */ + private void index() throws IOException { + if (docIds != null) { + return; + } + Map ids = new LinkedHashMap<>(); + List found = new ArrayList<>(); + Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( + treeUri, DocumentsContract.getTreeDocumentId(treeUri)); + String[] columns = { + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_SIZE, + DocumentsContract.Document.COLUMN_MIME_TYPE, + }; + try (Cursor c = resolver.query(childrenUri, columns, null, null, null)) { + if (c == null) { + throw new IOException("Could not read the selected folder"); + } + while (c.moveToNext()) { + String id = c.getString(0); + String name = c.getString(1); + long size = c.isNull(2) ? 0L : c.getLong(2); + String mime = c.getString(3); + if (name == null || DocumentsContract.Document.MIME_TYPE_DIR.equals(mime)) { + continue; // files only: sub-folders are not part of a flat bundle + } + ids.put(name, id); + found.add(new DriveFile(name, size)); + } + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException("Could not read the selected folder: " + e.getMessage(), e); + } + this.docIds = ids; + this.files = found; + } + + private InputStream openStream(Uri docUri) throws IOException { + try { + InputStream in = resolver.openInputStream(docUri); + if (in == null) { + throw new IOException("Could not open a file on the drive for reading"); + } + return in; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException("Could not open a file on the drive: " + 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/ExportFilenames.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportFilenames.java index c44b3654b..98f4d74ce 100644 --- 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 @@ -38,8 +38,9 @@ public static String resolve(String suggested, ItemRef ref, Set used) { return unique; } - /** Strip the path, drop illegal and control characters, trim. Returns null when nothing remains. */ - static String safeBaseName(String raw) { + /** Strip the path, drop illegal and control characters, trim. Returns null when nothing remains. + * Public so the import staging path reuses the one "safe FAT basename" rule. */ + public static String safeBaseName(String raw) { if (raw == null) { return null; } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportCarrier.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportCarrier.java new file mode 100644 index 000000000..558d6910b --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportCarrier.java @@ -0,0 +1,48 @@ +package org.appdevforall.k2go.contentexchange.domain; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +/** + * Domain port for the SOURCE of an import: where the bundle is read from. The mirror of + * {@link ExportCarrier} (the write side). One implementation is the SAF-backed drive reader; a future + * network carrier reuses the same port, so it is never hard-wired into the import sequence. + * + *

Only {@code java.io} crosses this boundary: no Android, no SAF type. The manifest is a few KB, so + * it is returned whole; payloads stream. + */ +public interface ImportCarrier { + + /** A short, human name of the chosen source (e.g. the folder name), for the UI. */ + String sourceLabel(); + + /** The top-level {@code manifest.json} bytes, or {@code null} when the bundle has none. */ + byte[] readManifest() throws IOException; + + /** The files directly in the chosen folder (name + size), for the no-manifest scan and lookups. */ + List listFiles() throws IOException; + + /** Open a readable stream for one payload file; the caller copies it, then closes it. */ + InputStream openPayload(String name) throws IOException; + + /** One file in the source folder: its display name and byte size. Immutable value. */ + final class DriveFile { + + private final String name; + private final long size; + + public DriveFile(String name, long size) { + this.name = name; + this.size = size; + } + + public String name() { + return name; + } + + public long size() { + return size; + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportEntry.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportEntry.java new file mode 100644 index 000000000..61b342fe2 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportEntry.java @@ -0,0 +1,64 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * One item read from a bundle's {@code manifest.json} (or recovered by scanning the drive when no + * manifest is present). The address and display fields the review UI needs, the archive file name on + * the drive to read, and the raw manifest-entry JSON text that is handed back verbatim to the core + * ({@code /v1/import/validate} and {@code /v1/import/item}). + * + *

Immutable value object. The JSON stays a {@link String} so this pure domain type carries no JSON + * framework; the data layer parses it and the core consumes it unchanged (identity, dedup, integrity, + * requires are preserved). + */ +public final class ImportEntry { + + private final String app; + private final String localRef; + private final String title; + private final long bytes; + private final String payloadName; + private final String entryJson; + + public ImportEntry(String app, String localRef, String title, long bytes, + String payloadName, String entryJson) { + this.app = app; + this.localRef = localRef; + this.title = title; + this.bytes = bytes; + this.payloadName = payloadName; + this.entryJson = entryJson; + } + + /** Adapter key: kiwix, kolibri, calibre. The grouping axis and the import target. */ + public String app() { + return app; + } + + /** The app's own handle to this item (from {@code identity.localRef}). */ + public String localRef() { + return localRef; + } + + public String title() { + return title; + } + + /** Declared size from the manifest; {@code <= 0} when unknown. Progress weight + preflight input. */ + public long bytes() { + return bytes; + } + + /** The archive file name to read from the drive ({@code payload} in the manifest entry). */ + public String payloadName() { + return payloadName; + } + + /** The raw manifest-entry JSON, passed to the core unchanged (it owns the shape). */ + public String entryJson() { + return entryJson; + } + + public ItemRef ref() { + return new ItemRef(app, localRef); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportManifest.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportManifest.java new file mode 100644 index 000000000..11b3a04ae --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportManifest.java @@ -0,0 +1,43 @@ +package org.appdevforall.k2go.contentexchange.domain; + +import java.util.Collections; +import java.util.List; + +/** + * The items read from a bundle on the drive: the parsed manifest entries, whether a real + * {@code manifest.json} was found (false means they were recovered by scanning the folder), and the + * names of files that could not be recognized without a manifest (reported, not fatal). + * + *

Immutable. Partial is first-class: an empty entry list with {@code hadManifest == false} means a + * folder with nothing recognizable in it. + */ +public final class ImportManifest { + + private final List entries; + private final boolean hadManifest; + private final List unrecognized; + + public ImportManifest(List entries, boolean hadManifest, List unrecognized) { + this.entries = Collections.unmodifiableList(entries); + this.hadManifest = hadManifest; + this.unrecognized = Collections.unmodifiableList(unrecognized); + } + + public List entries() { + return entries; + } + + /** True when a {@code manifest.json} was present; false when the items were scanned from the folder. */ + public boolean hadManifest() { + return hadManifest; + } + + /** Files in the folder that carry no app/identity without a manifest (e.g. a bare {@code .tar}). */ + public List unrecognized() { + return unrecognized; + } + + public boolean isEmpty() { + return entries.isEmpty(); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportPreflight.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportPreflight.java new file mode 100644 index 000000000..4580c1e54 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportPreflight.java @@ -0,0 +1,27 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * Pure phone-disk preflight for the import selection: the crux of the disparate-storage problem, where + * a small phone takes a subset of a big drive. The free figure is the phone's own {@code StatFs} view + * (authoritative on K2Go, where the box is a subtree of the phone disk), read by the presentation layer + * and passed in here. + * + *

The check is against the selected archive bytes. An extract-in-place app (Kiwix / Kolibri) needs + * more transient room while the core unpacks the staged archive; that is the core's own {@code 507} + * backstop, not modelled here, so this is a first-cut "will the copy fit" guard, not a guarantee. + */ +public final class ImportPreflight { + + private ImportPreflight() {} + + /** + * Whether the selected bytes fit in the phone's free space. Unknown free space ({@code null}) + * returns {@code false}: a destructive-cost decision does not guess. A zero selection fits. + */ + public static boolean fits(long selectedBytes, Long freeBytes) { + if (selectedBytes <= 0L) { + return true; + } + return freeBytes != null && selectedBytes <= freeBytes; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportScan.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportScan.java new file mode 100644 index 000000000..baa43ab94 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportScan.java @@ -0,0 +1,59 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * Pure rules for recovering items from a bundle that has no {@code manifest.json} (an export + * interrupted before it wrote the index). Only files whose app can be told from the name alone are + * recoverable: a Kiwix {@code .zim} carries its grouping keys in the filename convention + * {@code ___.zim}. A bare {@code .tar} (Kolibri / Calibre) gives no app + * or identity in its name, so it is left for a real manifest. + * + *

Mirrors the core's {@code parse_zim_filename} so a scanned item validates the same way a manifest + * item would. No UUID is read here (the scan has only names and sizes), so the synthesized dedup is + * advisory (soft): never a confident authoritative match on a missing id. Stateless, unit-testable. + */ +public final class ImportScan { + + public static final String APP_KIWIX = "kiwix"; + + private ImportScan() {} + + /** A date token like {@code 2023-10} or {@code 2023-10-01} at the tail of a Kiwix filename. */ + private static boolean isDate(String token) { + return token != null && token.matches("\\d{4}-\\d{2}(-\\d{2})?"); + } + + /** The app a drive file belongs to by its name alone, or {@code null} when it cannot be told. */ + public static String recognizeApp(String name) { + if (name == null) { + return null; + } + return name.toLowerCase(java.util.Locale.US).endsWith(".zim") ? APP_KIWIX : null; + } + + /** + * Decompose a Kiwix filename into {@code [creator, lang, flavour, date]}, matching the core. The + * flavour may span several underscore tokens; the date is the trailing dated token when present. + * A name off the convention still yields a stable creator (the stem) with empty lang/flavour/date. + */ + public static String[] parseZimFilename(String name) { + String n = name != null ? name : ""; + String stem = n.toLowerCase(java.util.Locale.US).endsWith(".zim") ? n.substring(0, n.length() - 4) : n; + String[] parts = stem.isEmpty() ? new String[0] : stem.split("_"); + int end = parts.length; + String date = ""; + if (end > 0 && isDate(parts[end - 1])) { + date = parts[end - 1]; + end--; + } + String creator = end > 0 ? parts[0] : stem; + String lang = end > 1 ? parts[1] : ""; + StringBuilder flavour = new StringBuilder(); + for (int i = 2; i < end; i++) { + if (flavour.length() > 0) { + flavour.append('_'); + } + flavour.append(parts[i]); + } + return new String[]{creator, lang, flavour.toString(), date}; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportSource.java new file mode 100644 index 000000000..16c865491 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportSource.java @@ -0,0 +1,33 @@ +package org.appdevforall.k2go.contentexchange.domain; + +import java.util.List; + +/** + * Domain port for the BOX side of an import: validate a bundle against this box, ingest one already + * staged item, and (for the manager's reclaim path) delete one item. 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. + * + *

All methods must be called off the main thread. + */ +public interface ImportSource { + + /** + * Validate the manifest items against this box: one verdict per entry, in the same order. Nothing + * is moved. An unknown app yields a {@code NO_APP} verdict (partial import is first-class). + */ + List validate(List entries) throws Exception; + + /** + * Ingest one item whose archive already sits at {@code payloadBoxPath}: a box-visible path inside + * the core's import area. The core delegates to the app's own import. Throws when the core rejects + * the item (bad path, no space, adapter failure). + */ + void importItem(String app, String entryJson, String payloadBoxPath) throws Exception; + + /** + * Delete one item from the box, delegating to the app's own delete. Available for the replace-older + * flow and the manager's reclaim action; the import sequence does not call it on its own. + */ + void delete(ItemRef ref) throws Exception; +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportVerdict.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportVerdict.java new file mode 100644 index 000000000..bcf02ccf0 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ImportVerdict.java @@ -0,0 +1,89 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * The receiver-side ruling on one bundle item, from {@code POST /v1/import/validate}: whether an app + * exists for it, and how what the box already has compares to the incoming item. + * + *

Verdict meaning is relative to the INCOMING item: {@code ABSENT} the box lacks it (a new import), + * {@code SAME_VERSION} the box has the same (skip), {@code OLDER_HERE} the box has an older one so the + * incoming is NEWER (an update), {@code NEWER_HERE} the box has a newer one so the incoming is OLDER + * (skip by default). A {@code SOFT} idKind (Calibre) makes the verdict advisory, not a hard fact. + * + *

Pure value object, unit-testable: the default-selection rule lives here so the UI and a test + * agree on it. + */ +public final class ImportVerdict { + + // Wire values from the core (status + verdict + idKind). + public static final String STATUS_IMPORTABLE = "importable"; + public static final String STATUS_NO_APP = "NO_APP"; + + public static final String ABSENT = "ABSENT"; + public static final String SAME_VERSION = "SAME_VERSION"; + public static final String OLDER_HERE = "OLDER_HERE"; + public static final String NEWER_HERE = "NEWER_HERE"; + + public static final String ID_SOFT = "SOFT"; + + private final String status; + private final String verdict; + private final String idKind; + + public ImportVerdict(String status, String verdict, String idKind) { + this.status = status != null ? status : STATUS_NO_APP; + this.verdict = verdict; + this.idKind = idKind; + } + + public String status() { + return status; + } + + public String verdict() { + return verdict; + } + + public String idKind() { + return idKind; + } + + public boolean hasApp() { + return STATUS_IMPORTABLE.equals(status); + } + + /** Advisory (Calibre soft key): the verdict is a hint, not a hard fact. */ + public boolean isAdvisory() { + return ID_SOFT.equalsIgnoreCase(idKind); + } + + public boolean isNew() { + return hasApp() && ABSENT.equals(verdict); + } + + /** The incoming item is newer than what the box has (an update). */ + public boolean isUpdate() { + return hasApp() && OLDER_HERE.equals(verdict); + } + + public boolean isSame() { + return hasApp() && SAME_VERSION.equals(verdict); + } + + /** The incoming item is older than what the box has. */ + public boolean isOlderIncoming() { + return hasApp() && NEWER_HERE.equals(verdict); + } + + /** May this item be imported at all (an app exists and it is not identical)? */ + public boolean isImportable() { + return hasApp() && !isSame(); + } + + /** + * Whether this item is selected by default: a genuinely new item, or an update to an older local + * copy. An item the box already has (same), an older incoming, or one with no app starts off. + */ + public boolean defaultSelected() { + return isNew() || isUpdate(); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentImportService.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentImportService.java new file mode 100644 index 000000000..0306a1b89 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentImportService.java @@ -0,0 +1,416 @@ +/* + * ============================================================================ + * Name : ContentImportService.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. Foreground service that drains the import queue: per selected item, SAF-read + * the archive from the user-picked drive, write it to the box-visible import-staging path + * the core reads, POST /v1/import/item so the core ingests it (delegating to the app's own + * import), then remove the staging copy. The mirror of ContentExportService (foreground + * specialUse + per-item queue + retry + notification + grant release), with the bytes + * flowing drive -> phone staging -> box. 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.BoxImportStaging; +import org.appdevforall.k2go.contentexchange.data.CxCoreDataSource; +import org.appdevforall.k2go.contentexchange.data.CxCoreImportSource; +import org.appdevforall.k2go.contentexchange.data.SafImportCarrier; +import org.appdevforall.k2go.contentexchange.domain.ExportJob; +import org.appdevforall.k2go.contentexchange.domain.ImportCarrier; +import org.appdevforall.k2go.contentexchange.domain.ImportSource; +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.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public final class ContentImportService extends Service { + + public static final String ACTION_START = "org.appdevforall.k2go.CONTENT_IMPORT_START"; + public static final String ACTION_RETRY = "org.appdevforall.k2go.CONTENT_IMPORT_RETRY"; + public static final String ACTION_CANCEL = "org.appdevforall.k2go.CONTENT_IMPORT_CANCEL"; + + public static final String EXTRA_TREE_URI = "treeUri"; + public static final String EXTRA_APPS = "apps"; + public static final String EXTRA_LOCAL_REFS = "localRefs"; + public static final String EXTRA_TITLES = "titles"; + public static final String EXTRA_ENTRIES = "entries"; + public static final String EXTRA_PAYLOADS = "payloads"; + public static final String EXTRA_BYTES = "bytes"; + + private static final String CHANNEL_ID = "content_import_channel"; + private static final int NOTIFICATION_ID = NotificationIds.CONTENT_IMPORT; + 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 ImportSession SESSION = new ImportSession(); + + static ImportSession session() { + return SESSION; + } + + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + + // ---- static control surface (the fragment calls these) ------------------------------------- + + /** Start an import of the selected items from the drive {@code treeUri}. */ + public static void start(Context ctx, Uri treeUri, ItemRef[] refs, String[] titles, + String[] entries, String[] payloads, long[] bytes) { + 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, ContentImportService.class).setAction(ACTION_START) + .putExtra(EXTRA_TREE_URI, treeUri.toString()) + .putExtra(EXTRA_APPS, apps) + .putExtra(EXTRA_LOCAL_REFS, locals) + .putExtra(EXTRA_TITLES, titles) + .putExtra(EXTRA_ENTRIES, entries) + .putExtra(EXTRA_PAYLOADS, payloads) + .putExtra(EXTRA_BYTES, bytes); + ContextCompat.startForegroundService(ctx, i); + } + + public static void retry(Context ctx) { + if (SESSION.canRetry()) { + ContextCompat.startForegroundService(ctx, + new Intent(ctx, ContentImportService.class).setAction(ACTION_RETRY)); + } + } + + public static void cancel(Context ctx) { + ContextCompat.startForegroundService(ctx, + new Intent(ctx, ContentImportService.class).setAction(ACTION_CANCEL)); + } + + /** Clear a settled session (the "Finish" button) and release its SAF grant. Safe when idle. */ + public static void finishSession(Context ctx) { + releaseGrant(ctx, SESSION.treeUri()); + SESSION.clear(); + } + + /** + * Release the persisted SAF grant for a finished import. Import is one-shot (pick a drive, read, + * done), so the grant is not needed afterwards; releasing it keeps the app's persisted-permission + * set from growing toward the system cap. Idempotent. + */ + 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: 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()) { + 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(); + SESSION.setRunning(true); + startForeground(NOTIFICATION_ID, buildNotification(null)); + worker.execute(this::drain); + 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); + String[] apps = intent.getStringArrayExtra(EXTRA_APPS); + String[] locals = intent.getStringArrayExtra(EXTRA_LOCAL_REFS); + String[] titles = intent.getStringArrayExtra(EXTRA_TITLES); + String[] entries = intent.getStringArrayExtra(EXTRA_ENTRIES); + String[] payloads = intent.getStringArrayExtra(EXTRA_PAYLOADS); + long[] bytes = intent.getLongArrayExtra(EXTRA_BYTES); + if (treeUri == null || apps == null || locals == null || apps.length == 0 + || apps.length != locals.length) { + stopSelf(); + return START_NOT_STICKY; + } + ItemRef[] refs = new ItemRef[apps.length]; + for (int i = 0; i < apps.length; i++) { + refs[i] = new ItemRef(apps[i], locals[i]); + } + SESSION.begin(refs, titles, entries, payloads, bytes, treeUri); + startForeground(NOTIFICATION_ID, buildNotification(null)); + worker.execute(this::drain); + return START_NOT_STICKY; + } + + // ---- the run ------------------------------------------------------------------------------- + + /** + * Drain the pending items: read each archive from the drive, stage it where the box can read it, + * ingest it, then clean up the staged copy. + * + *

v1 limitation (accepted): the run state is in-memory, so a process death mid-import loses it; + * v1 does within-run per-item retry only. Durable op-state and byte-resume are v1.x. + */ + private void drain() { + ImportSource source = new CxCoreImportSource(new CxCoreDataSource()); + BoxImportStaging staging = new BoxImportStaging(getApplicationContext()); + ImportCarrier carrier; + try { + carrier = new SafImportCarrier(getApplicationContext(), Uri.parse(SESSION.treeUri())); + } catch (Exception e) { + finishWithError("Could not open the drive: " + e.getMessage()); + return; + } + SESSION.setSource(carrier.sourceLabel()); + + ExportJob job = SESSION.job(); + 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(); + + String stored = BoxImportStaging.safeName(SESSION.payloadName(i)); + try { + copyToStaging(carrier, staging, SESSION.payloadName(i), stored, i, job, runStart); + source.importItem(ref.app(), SESSION.entryJson(i), BoxImportStaging.boxPath(stored)); + job.setDone(i); + } catch (Exception e) { + // The staging copy or the ingest failed: mark the item and keep its slot for a retry. + job.setFailed(i); + SESSION.publish(); + staging.remove(stored); + if (isNoSpace(e)) { + // No room on the shared phone/box disk: stop, leave the rest pending for a Retry. + finishWithError("Not enough space on the device."); + return; + } + continue; + } + staging.remove(stored); + + 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; + } + + if (SESSION.allDone()) { + // Fully imported: 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 archive from the drive to the box-visible staging path, updating per-item progress and + * honoring cancellation. Both streams close inside try-with-resources so a close-time failure + * (ENOSPC on the staging disk commonly surfaces at flush/close) propagates and the item is marked + * failed, never a silent partial written as done. + */ + private void copyToStaging(ImportCarrier carrier, BoxImportStaging staging, String payloadName, + String storedName, int i, ExportJob job, long runStart) + throws IOException { + byte[] buffer = new byte[COPY_BUFFER]; + long total = 0L; + long lastPublish = 0L; + try (InputStream in = carrier.openPayload(payloadName); + OutputStream out = staging.open(storedName)) { + int read; + while ((read = in.read(buffer)) != -1) { + if (SESSION.isCancelled()) { + throw new IOException("cancelled"); + } + out.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; + } + } + out.flush(); + } + } + + // ---- helpers ------------------------------------------------------------------------------- + + 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 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") + || lower.contains("insufficient 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, ContentImportService.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_import_notif_text); + return new NotificationCompat.Builder(this, CHANNEL_ID) + .setContentTitle(getString(R.string.k2go_cx_import_notif_title)) + .setContentText(text) + .setSmallIcon(android.R.drawable.stat_sys_download) + .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_import_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 e704cacd7..6e1bc7f9a 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 @@ -60,9 +60,12 @@ public class ContentManagerFragment extends Fragment { private View actionBar; private TextView selectionLabel; private Button exportButton; + private Button importButton; /** The folder picker; its result carries the drive/folder the user chose for the export. */ private ActivityResultLauncher openTree; + /** A separate folder picker for the import source (import starts from a drive, not a selection). */ + private ActivityResultLauncher openImportTree; @Nullable @Override @@ -73,10 +76,14 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c 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); + importButton = root.findViewById(R.id.k2go_cx_import); openTree = registerForActivityResult(new ActivityResultContracts.OpenDocumentTree(), this::onTreePicked); + openImportTree = registerForActivityResult( + new ActivityResultContracts.OpenDocumentTree(), this::onImportTreePicked); exportButton.setEnabled(true); exportButton.setOnClickListener(v -> onExportClicked()); + importButton.setOnClickListener(v -> onImportClicked()); TextView back = root.findViewById(R.id.k2go_cx_back); back.setText(getString(R.string.k2go_back_link)); @@ -212,6 +219,41 @@ private void onExportClicked() { openTree.launch(null); } + /** Import: if a run is already active, show it; otherwise pick the drive that holds the bundle. */ + private void onImportClicked() { + if (ContentImportService.session().hasSession()) { + showImportProgress(); + return; + } + // SAF folder picker: no storage permission is requested; the persisted grant is the authority. + openImportTree.launch(null); + } + + /** The import folder picker returned. Null means the user cancelled. */ + private void onImportTreePicked(@Nullable Uri treeUri) { + if (treeUri == null) { + return; + } + // Persist read so the review read and the foreground service keep access after this screen is gone. + int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION; + try { + requireContext().getContentResolver().takePersistableUriPermission(treeUri, flags); + } catch (SecurityException e) { + // Could not persist; proceed with the transient permission for this session. + } + requireActivity().getSupportFragmentManager().beginTransaction() + .replace(R.id.k2go_setup_host, ImportReviewFragment.newInstance(treeUri)) + .addToBackStack(null) + .commit(); + } + + private void showImportProgress() { + requireActivity().getSupportFragmentManager().beginTransaction() + .replace(R.id.k2go_setup_host, new ImportProgressFragment()) + .addToBackStack(null) + .commit(); + } + /** The folder picker returned. Null means the user cancelled. */ private void onTreePicked(@Nullable Uri treeUri) { if (treeUri == null || pendingExport == null || pendingExport.isEmpty()) { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportProgressFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportProgressFragment.java new file mode 100644 index 000000000..f924e1750 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportProgressFragment.java @@ -0,0 +1,182 @@ +/* + * ============================================================================ + * Name : ImportProgressFragment.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. Observes the ContentImportService session and renders the import 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. Mirror of ExportProgressFragment. + * ============================================================================ + */ +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.Locale; + +public class ImportProgressFragment extends Fragment { + + private TextView source; + private TextView overallLabel; + private LinearProgressIndicator overallBar; + private TextView overallDetail; + private TextView itemLabel; + private LinearProgressIndicator itemBar; + private TextView message; + private Button cancel; + private Button retry; + private Button finish; + + private final ImportSession session = ContentImportService.session(); + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle s) { + View root = inflater.inflate(R.layout.fragment_k2go_content_import, container, false); + source = root.findViewById(R.id.k2go_cxi_source); + overallLabel = root.findViewById(R.id.k2go_cxi_overall_label); + overallBar = root.findViewById(R.id.k2go_cxi_overall_bar); + overallDetail = root.findViewById(R.id.k2go_cxi_overall_detail); + itemLabel = root.findViewById(R.id.k2go_cxi_item_label); + itemBar = root.findViewById(R.id.k2go_cxi_item_bar); + message = root.findViewById(R.id.k2go_cxi_message); + cancel = root.findViewById(R.id.k2go_cxi_cancel); + retry = root.findViewById(R.id.k2go_cxi_retry); + finish = root.findViewById(R.id.k2go_cxi_finish); + + cancel.setOnClickListener(v -> ContentImportService.cancel(requireContext())); + retry.setOnClickListener(v -> ContentImportService.retry(requireContext())); + finish.setOnClickListener(v -> { + ContentImportService.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; + } + source.setText(getString(R.string.k2go_cx_import_source_fmt, session.sourceLabel())); + + boolean running = session.isRunning(); + String error = session.errorMessage(); + + overallBar.setIndeterminate(false); + overallBar.setProgressCompat(session.overallPercent(), true); + overallLabel.setText(getString(R.string.k2go_cx_export_overall_fmt, session.overallPercent())); + overallDetail.setText(overallDetail()); + + renderCurrentItem(running); + renderSettled(running, error); + + cancel.setVisibility(running ? View.VISIBLE : View.GONE); + boolean settled = !running; + retry.setVisibility(settled && session.canRetry() ? View.VISIBLE : View.GONE); + finish.setVisibility(settled ? View.VISIBLE : View.GONE); + } + + private void renderCurrentItem(boolean running) { + int i = session.index(); + if (running && 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, String error) { + if (running) { + message.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_import_done_fmt, done); + } else { + text = getString(R.string.k2go_cx_import_partial_fmt, done, total); + } + message.setText(text); + message.setVisibility(View.VISIBLE); + } + + 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/ImportReviewAdapter.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewAdapter.java new file mode 100644 index 000000000..e25bd6ab1 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewAdapter.java @@ -0,0 +1,318 @@ +package org.appdevforall.k2go.contentexchange.presentation; + +import android.content.Context; +import android.graphics.Typeface; +import android.view.Gravity; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.RecyclerView; + +import com.google.android.material.checkbox.MaterialCheckBox; + +import org.appdevforall.k2go.R; + +import java.util.ArrayList; +import java.util.List; + +/** + * Recycling adapter for the import review screen. A flat row list with four view types: one header + * block (source + a note when the bundle had no manifest), one header per app group, one row per + * bundle item (checkbox + title + size + a state badge), and a note row (unrecognized files). Only the + * item rows can be numerous, so recycling keeps a large bundle from inflating one view per item. + * + *

Selection lives in {@link ImportReviewViewModel}; the adapter reads and toggles it through + * {@link SelectionController} by item index, so a recycled row always reflects the current selection. + * A row the box cannot import (same version, older, no app) is shown disabled. + */ +final class ImportReviewAdapter extends RecyclerView.Adapter { + + interface SelectionController { + boolean isSelected(int index); + + void toggle(int index); + } + + static final int TYPE_HEADER = 0; + static final int TYPE_GROUP = 1; + static final int TYPE_ITEM = 2; + static final int TYPE_NOTE = 3; + + private final List rows = new ArrayList<>(); + private final SelectionController selection; + + ImportReviewAdapter(SelectionController selection) { + this.selection = selection; + } + + void submit(List newRows) { + rows.clear(); + rows.addAll(newRows); + notifyDataSetChanged(); + } + + @Override + public int getItemViewType(int position) { + return rows.get(position).type; + } + + @Override + public int getItemCount() { + return rows.size(); + } + + @NonNull + @Override + public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + Context ctx = parent.getContext(); + switch (viewType) { + case TYPE_HEADER: + return new HeaderVH(ctx); + case TYPE_GROUP: + return new GroupVH(ctx); + case TYPE_NOTE: + return new NoteVH(ctx); + default: + return new ItemVH(ctx, selection); + } + } + + @Override + public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { + Row row = rows.get(position); + switch (row.type) { + case TYPE_HEADER: + ((HeaderVH) holder).bind((HeaderRow) row); + break; + case TYPE_GROUP: + ((GroupVH) holder).bind((GroupRow) row); + break; + case TYPE_NOTE: + ((NoteVH) holder).bind((NoteRow) row); + break; + default: + ((ItemVH) holder).bind((ItemRow) row); + break; + } + } + + // --- Row model (strings resolved by the Fragment) --- + + abstract static class Row { + final int type; + + Row(int type) { + this.type = type; + } + } + + static final class HeaderRow extends Row { + final String title; + final String subtitle; + + HeaderRow(String title, String subtitle) { + super(TYPE_HEADER); + this.title = title; + this.subtitle = subtitle; + } + } + + static final class GroupRow extends Row { + final String name; + final String meta; + + GroupRow(String name, String meta) { + super(TYPE_GROUP); + this.name = name; + this.meta = meta; + } + } + + static final class ItemRow extends Row { + final int index; + final String title; + final String size; + final String state; + final boolean selectable; + + ItemRow(int index, String title, String size, String state, boolean selectable) { + super(TYPE_ITEM); + this.index = index; + this.title = title; + this.size = size; + this.state = state; + this.selectable = selectable; + } + } + + static final class NoteRow extends Row { + final String text; + + NoteRow(String text) { + super(TYPE_NOTE); + this.text = text; + } + } + + // --- View holders (built programmatically, mirroring the manager adapter) --- + + private static int px(Context ctx, int dp) { + return Math.round(dp * ctx.getResources().getDisplayMetrics().density); + } + + private static RecyclerView.LayoutParams fullWidth(int topMarginPx, int bottomMarginPx) { + RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams( + RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT); + lp.topMargin = topMarginPx; + lp.bottomMargin = bottomMarginPx; + return lp; + } + + private static TextView text(Context ctx, int appearance, int colorRes) { + TextView tv = new TextView(ctx); + tv.setTextAppearance(appearance); + tv.setTextColor(ContextCompat.getColor(ctx, colorRes)); + return tv; + } + + static final class HeaderVH extends RecyclerView.ViewHolder { + private final TextView title; + private final TextView subtitle; + + HeaderVH(Context ctx) { + super(new LinearLayout(ctx)); + LinearLayout root = (LinearLayout) itemView; + root.setOrientation(LinearLayout.VERTICAL); + root.setLayoutParams(fullWidth(px(ctx, 16), px(ctx, 4))); + + title = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_HeadlineMedium, R.color.k2go_ink); + root.addView(title); + + subtitle = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodyMedium, R.color.k2go_muted); + LinearLayout.LayoutParams subLp = new LinearLayout.LayoutParams(-1, -2); + subLp.topMargin = px(ctx, 4); + root.addView(subtitle, subLp); + } + + void bind(HeaderRow row) { + title.setText(row.title); + if (row.subtitle == null || row.subtitle.isEmpty()) { + subtitle.setVisibility(android.view.View.GONE); + } else { + subtitle.setVisibility(android.view.View.VISIBLE); + subtitle.setText(row.subtitle); + } + } + } + + static final class GroupVH extends RecyclerView.ViewHolder { + private final TextView name; + private final TextView meta; + + GroupVH(Context ctx) { + super(new LinearLayout(ctx)); + LinearLayout root = (LinearLayout) itemView; + root.setOrientation(LinearLayout.HORIZONTAL); + root.setGravity(Gravity.CENTER_VERTICAL); + root.setLayoutParams(fullWidth(px(ctx, 16), px(ctx, 8))); + + name = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_TitleMedium, R.color.k2go_ink); + name.setTypeface(name.getTypeface(), Typeface.BOLD); + root.addView(name, new LinearLayout.LayoutParams(0, -2, 1f)); + + meta = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodySmall, R.color.k2go_muted); + root.addView(meta); + } + + void bind(GroupRow row) { + name.setText(row.name); + meta.setText(row.meta); + } + } + + static final class ItemVH extends RecyclerView.ViewHolder { + private final MaterialCheckBox checkBox; + private final TextView title; + private final TextView size; + private final TextView state; + private final SelectionController selection; + private int boundIndex = -1; + + ItemVH(Context ctx, SelectionController selection) { + super(new LinearLayout(ctx)); + this.selection = selection; + LinearLayout row = (LinearLayout) itemView; + row.setOrientation(LinearLayout.HORIZONTAL); + row.setGravity(Gravity.CENTER_VERTICAL); + row.setBackgroundResource(R.drawable.k2go_card_bg); + row.setPadding(px(ctx, 16), px(ctx, 14), px(ctx, 16), px(ctx, 14)); + row.setLayoutParams(fullWidth(0, px(ctx, 12))); + + checkBox = new MaterialCheckBox(ctx); + FrameLayout slot = new FrameLayout(ctx); + FrameLayout.LayoutParams clp = new FrameLayout.LayoutParams(-2, -2); + clp.gravity = Gravity.CENTER; + slot.addView(checkBox, clp); + LinearLayout.LayoutParams slotLp = new LinearLayout.LayoutParams(px(ctx, 40), -2); + slotLp.rightMargin = px(ctx, 4); + row.addView(slot, slotLp); + + LinearLayout texts = new LinearLayout(ctx); + texts.setOrientation(LinearLayout.VERTICAL); + row.addView(texts, new LinearLayout.LayoutParams(0, -2, 1f)); + + title = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_TitleMedium, R.color.k2go_ink); + texts.addView(title); + state = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_LabelMedium, R.color.k2go_teal); + texts.addView(state); + + size = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodySmall, R.color.k2go_muted); + LinearLayout.LayoutParams szLp = new LinearLayout.LayoutParams(-2, -2); + szLp.leftMargin = px(ctx, 8); + row.addView(size, szLp); + + checkBox.setOnClickListener(v -> { + if (boundIndex >= 0) { + this.selection.toggle(boundIndex); + } + }); + row.setClickable(true); + row.setOnClickListener(v -> { + if (checkBox.isEnabled()) { + checkBox.performClick(); + } + }); + } + + void bind(ItemRow row) { + boundIndex = row.index; + title.setText(row.title); + size.setText(row.size); + state.setText(row.state); + int stateColor = row.selectable ? R.color.k2go_teal : R.color.k2go_muted; + state.setTextColor(ContextCompat.getColor(state.getContext(), stateColor)); + checkBox.setEnabled(row.selectable); + itemView.setEnabled(row.selectable); + itemView.setAlpha(row.selectable ? 1f : 0.6f); + checkBox.setChecked(row.selectable && selection.isSelected(row.index)); + } + } + + static final class NoteVH extends RecyclerView.ViewHolder { + private final TextView tv; + + NoteVH(Context ctx) { + super(text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodySmall, R.color.k2go_muted)); + tv = (TextView) itemView; + tv.setLayoutParams(fullWidth(0, px(ctx, 12))); + } + + void bind(NoteRow row) { + tv.setText(row.text); + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewFragment.java new file mode 100644 index 000000000..9448f50bf --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewFragment.java @@ -0,0 +1,272 @@ +/* + * ============================================================================ + * Name : ImportReviewFragment.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. The import review screen: reads a bundle from the picked drive, validates it + * against this box, and lists the items grouped by app with a state badge and a checkbox. + * The bottom bar shows the selected total against the device free space (the phone-disk + * preflight) and starts the import foreground service when the user confirms. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.presentation; + +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.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; +import androidx.lifecycle.ViewModelProvider; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import org.appdevforall.k2go.R; +import org.appdevforall.k2go.contentexchange.domain.ImportEntry; +import org.appdevforall.k2go.contentexchange.domain.ItemRef; +import org.appdevforall.k2go.util.ByteFormatter; + +import java.util.ArrayList; +import java.util.List; + +public class ImportReviewFragment extends Fragment { + + private static final String ARG_TREE_URI = "treeUri"; + + /** Create the review for a drive tree the manager already picked and persisted a grant for. */ + public static ImportReviewFragment newInstance(Uri treeUri) { + ImportReviewFragment f = new ImportReviewFragment(); + Bundle b = new Bundle(); + b.putString(ARG_TREE_URI, treeUri.toString()); + f.setArguments(b); + return f; + } + + private ImportReviewViewModel viewModel; + private ImportReviewAdapter adapter; + + private RecyclerView list; + private TextView status; + private View actionBar; + private TextView selectionLabel; + private TextView freeLabel; + private TextView warning; + private Button importButton; + + private boolean currentFits = false; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle s) { + View root = inflater.inflate(R.layout.fragment_k2go_import_review, container, false); + list = root.findViewById(R.id.k2go_cxr_list); + status = root.findViewById(R.id.k2go_cxr_status); + actionBar = root.findViewById(R.id.k2go_cxr_actionbar); + selectionLabel = root.findViewById(R.id.k2go_cxr_selection_label); + freeLabel = root.findViewById(R.id.k2go_cxr_free_label); + warning = root.findViewById(R.id.k2go_cxr_warning); + importButton = root.findViewById(R.id.k2go_cxr_import); + + TextView back = root.findViewById(R.id.k2go_cxr_back); + back.setText(getString(R.string.k2go_back_link)); + back.setOnClickListener(v -> requireActivity().getOnBackPressedDispatcher().onBackPressed()); + importButton.setOnClickListener(v -> onImportClicked()); + + Uri treeUri = Uri.parse(requireArguments().getString(ARG_TREE_URI)); + viewModel = new ViewModelProvider(this, new ImportReviewViewModelFactory(requireContext(), treeUri)) + .get(ImportReviewViewModel.class); + + adapter = new ImportReviewAdapter(new ImportReviewAdapter.SelectionController() { + @Override + public boolean isSelected(int index) { + return viewModel.isSelected(index); + } + + @Override + public void toggle(int index) { + viewModel.toggle(index); + } + }); + list.setLayoutManager(new LinearLayoutManager(requireContext())); + list.setAdapter(adapter); + + viewModel.state().observe(getViewLifecycleOwner(), this::render); + viewModel.selection().observe(getViewLifecycleOwner(), this::renderSelection); + + if (s == null) { + viewModel.load(); + } + return root; + } + + private void render(ImportReviewUiState st) { + if (st == null) { + return; + } + switch (st.status) { + case LOADING: + list.setVisibility(View.GONE); + showStatus(getString(R.string.k2go_cx_import_reading)); + return; + case ERROR: + list.setVisibility(View.GONE); + showStatus(getString(R.string.k2go_cx_import_read_error)); + return; + default: + break; + } + status.setVisibility(View.GONE); + list.setVisibility(View.VISIBLE); + adapter.submit(buildRows(st)); + } + + private void showStatus(String text) { + status.setText(text); + status.setVisibility(View.VISIBLE); + } + + /** Flatten the validated items into grouped rows (header, group headers, item rows, notes). */ + private List buildRows(ImportReviewUiState st) { + List rows = new ArrayList<>(); + String subtitle = st.hadManifest + ? getString(R.string.k2go_cx_import_subtitle) + : getString(R.string.k2go_cx_import_subtitle_scanned); + rows.add(new ImportReviewAdapter.HeaderRow(getString(R.string.k2go_cx_import_title), subtitle)); + + if (st.items.isEmpty()) { + rows.add(new ImportReviewAdapter.NoteRow(getString(R.string.k2go_cx_import_nothing))); + } else { + String currentApp = null; + int groupCount = 0; + long groupBytes = 0L; + int groupHeaderAt = -1; + for (ImportReviewItem item : st.items) { + String app = item.entry().app(); + if (currentApp == null || !currentApp.equals(app)) { + currentApp = app; + groupHeaderAt = rows.size(); + rows.add(new ImportReviewAdapter.GroupRow(appDisplayName(app), "")); + groupCount = 0; + groupBytes = 0L; + } + rows.add(itemRow(item)); + groupCount++; + groupBytes += Math.max(0L, item.entry().bytes()); + // Rewrite the group header meta as the running totals (header was added first). + rows.set(groupHeaderAt, new ImportReviewAdapter.GroupRow(appDisplayName(app), + getString(R.string.k2go_cx_group_meta_fmt, groupCount, + ByteFormatter.humanBytes(groupBytes)))); + } + } + + if (st.unrecognized != null && !st.unrecognized.isEmpty()) { + rows.add(new ImportReviewAdapter.NoteRow(getString(R.string.k2go_cx_import_unrecognized_fmt, + android.text.TextUtils.join(", ", st.unrecognized)))); + } + return rows; + } + + private ImportReviewAdapter.ItemRow itemRow(ImportReviewItem item) { + ImportEntry e = item.entry(); + String title = e.title() != null && !e.title().isEmpty() ? e.title() : e.localRef(); + String size = ByteFormatter.humanBytes(e.bytes()); + String state = stateLabel(item); + return new ImportReviewAdapter.ItemRow(item.index(), title, size, state, item.selectable()); + } + + private String stateLabel(ImportReviewItem item) { + String base; + if (!item.verdict().hasApp()) { + base = getString(R.string.k2go_cx_import_state_no_app); + } else if (item.verdict().isNew()) { + base = getString(R.string.k2go_cx_import_state_new); + } else if (item.verdict().isUpdate()) { + base = getString(R.string.k2go_cx_import_state_update); + } else if (item.verdict().isSame()) { + base = getString(R.string.k2go_cx_import_state_same); + } else if (item.verdict().isOlderIncoming()) { + base = getString(R.string.k2go_cx_import_state_older); + } else { + base = getString(R.string.k2go_cx_import_state_no_app); + } + // A soft (Calibre) verdict is advisory, not a hard fact: mark it so the user knows. + if (item.verdict().hasApp() && item.verdict().isAdvisory()) { + return getString(R.string.k2go_cx_import_state_advisory_fmt, base); + } + return base; + } + + private void renderSelection(ImportSelectionSummary sel) { + if (sel == null || sel.isEmpty()) { + actionBar.setVisibility(View.GONE); + currentFits = false; + return; + } + actionBar.setVisibility(View.VISIBLE); + selectionLabel.setText(getString(R.string.k2go_cx_selected_fmt, + sel.count, ByteFormatter.humanBytes(sel.bytes))); + freeLabel.setText(sel.freeBytes != null + ? getString(R.string.k2go_cx_free_fmt, ByteFormatter.humanBytes(sel.freeBytes)) + : getString(R.string.k2go_cx_free_unavailable)); + currentFits = sel.fits; + warning.setVisibility(sel.fits ? View.GONE : View.VISIBLE); + if (!sel.fits) { + warning.setText(getString(R.string.k2go_cx_import_wont_fit)); + } + importButton.setEnabled(sel.fits); + } + + private void onImportClicked() { + if (!currentFits) { + return; + } + List selected = viewModel.selectedEntries(); + if (selected.isEmpty()) { + return; + } + int n = selected.size(); + ItemRef[] refs = new ItemRef[n]; + String[] titles = new String[n]; + String[] entries = new String[n]; + String[] payloads = new String[n]; + long[] bytes = new long[n]; + for (int i = 0; i < n; i++) { + ImportEntry e = selected.get(i); + refs[i] = e.ref(); + titles[i] = e.title() != null && !e.title().isEmpty() ? e.title() : e.localRef(); + entries[i] = e.entryJson(); + payloads[i] = e.payloadName(); + bytes[i] = e.bytes(); + } + ContentImportService.start(requireContext(), viewModel.treeUri(), refs, titles, entries, payloads, bytes); + showProgress(); + } + + private void showProgress() { + requireActivity().getSupportFragmentManager().beginTransaction() + .replace(R.id.k2go_setup_host, new ImportProgressFragment()) + .addToBackStack(null) + .commit(); + } + + private String appDisplayName(String app) { + if (app == null) { + return ""; + } + switch (app) { + case "kiwix": + return getString(R.string.k2go_cx_app_kiwix); + case "kolibri": + return getString(R.string.k2go_cx_app_kolibri); + case "calibre": + return getString(R.string.k2go_cx_app_calibre); + default: + return app; + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewItem.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewItem.java new file mode 100644 index 000000000..35edf77ed --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewItem.java @@ -0,0 +1,38 @@ +package org.appdevforall.k2go.contentexchange.presentation; + +import org.appdevforall.k2go.contentexchange.domain.ImportEntry; +import org.appdevforall.k2go.contentexchange.domain.ImportVerdict; + +/** + * One bundle item paired with its receiver-side verdict, for the review screen. The {@code index} is + * the item's position in the validated list and the selection key. Immutable. + */ +final class ImportReviewItem { + + private final int index; + private final ImportEntry entry; + private final ImportVerdict verdict; + + ImportReviewItem(int index, ImportEntry entry, ImportVerdict verdict) { + this.index = index; + this.entry = entry; + this.verdict = verdict; + } + + int index() { + return index; + } + + ImportEntry entry() { + return entry; + } + + ImportVerdict verdict() { + return verdict; + } + + /** Only an importable item (an app exists and it is not identical) can be picked. */ + boolean selectable() { + return verdict.isImportable(); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewUiState.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewUiState.java new file mode 100644 index 000000000..a375f53e8 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewUiState.java @@ -0,0 +1,45 @@ +package org.appdevforall.k2go.contentexchange.presentation; + +import org.appdevforall.k2go.contentexchange.domain.ImportManifest; + +import java.util.Collections; +import java.util.List; + +/** + * The review-screen state: reading / ready / error, the validated items, whether a manifest was found, + * the names a scan could not recognize, and any read error. Immutable snapshot the fragment renders. + */ +final class ImportReviewUiState { + + enum Status { LOADING, READY, ERROR } + + final Status status; + final List items; + final boolean hadManifest; + final List unrecognized; + final String error; + + private ImportReviewUiState(Status status, List items, boolean hadManifest, + List unrecognized, String error) { + this.status = status; + this.items = items; + this.hadManifest = hadManifest; + this.unrecognized = unrecognized; + this.error = error; + } + + static ImportReviewUiState loading() { + return new ImportReviewUiState(Status.LOADING, Collections.emptyList(), true, + Collections.emptyList(), null); + } + + static ImportReviewUiState error(String message) { + return new ImportReviewUiState(Status.ERROR, Collections.emptyList(), true, + Collections.emptyList(), message); + } + + static ImportReviewUiState ready(List items, ImportManifest manifest) { + return new ImportReviewUiState(Status.READY, items, manifest.hadManifest(), + manifest.unrecognized(), null); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModel.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModel.java new file mode 100644 index 000000000..39281db2d --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModel.java @@ -0,0 +1,158 @@ +/* + * ============================================================================ + * Name : ImportReviewViewModel.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. Reads a bundle from the picked drive (manifest or folder scan), validates it + * against this box through the import source, and owns the review selection + the + * phone-disk preflight. Off-main-thread load; selection is encapsulated ViewModel state + * (indices into the validated list), not a static or a persisted wishlist. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.presentation; + +import android.content.Context; +import android.net.Uri; + +import androidx.lifecycle.LiveData; +import androidx.lifecycle.MutableLiveData; +import androidx.lifecycle.ViewModel; + +import org.appdevforall.k2go.contentexchange.data.ImportManifestReader; +import org.appdevforall.k2go.contentexchange.data.SafImportCarrier; +import org.appdevforall.k2go.contentexchange.domain.ImportEntry; +import org.appdevforall.k2go.contentexchange.domain.ImportManifest; +import org.appdevforall.k2go.contentexchange.domain.ImportPreflight; +import org.appdevforall.k2go.contentexchange.domain.ImportSource; +import org.appdevforall.k2go.contentexchange.domain.ImportVerdict; +import org.appdevforall.k2go.storage.StorageProbe; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class ImportReviewViewModel extends ViewModel { + + private final Context appContext; + private final Uri treeUri; + private final ImportManifestReader reader; + private final ImportSource source; + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + + private final MutableLiveData state = + new MutableLiveData<>(ImportReviewUiState.loading()); + private final MutableLiveData selection = + new MutableLiveData<>(new ImportSelectionSummary(0, 0L, null, true)); + + /** The validated items, in display order (grouped by app). Set on the loader thread. */ + private volatile List items = new ArrayList<>(); + private final Set selected = new HashSet<>(); + private volatile Long freeBytes; + + public ImportReviewViewModel(Context appContext, Uri treeUri, + ImportManifestReader reader, ImportSource source) { + this.appContext = appContext.getApplicationContext(); + this.treeUri = treeUri; + this.reader = reader; + this.source = source; + } + + public LiveData state() { + return state; + } + + public LiveData selection() { + return selection; + } + + public Uri treeUri() { + return treeUri; + } + + /** Read the bundle and validate it against the box, off the main thread. */ + public void load() { + state.postValue(ImportReviewUiState.loading()); + executor.execute(() -> { + try { + SafImportCarrier carrier = new SafImportCarrier(appContext, treeUri); + ImportManifest manifest = reader.read(carrier); + List entries = manifest.entries(); + List verdicts = source.validate(entries); + + List built = new ArrayList<>(); + selected.clear(); + for (int i = 0; i < entries.size(); i++) { + ImportVerdict v = i < verdicts.size() + ? verdicts.get(i) + : new ImportVerdict(ImportVerdict.STATUS_NO_APP, null, null); + built.add(new ImportReviewItem(i, entries.get(i), v)); + if (v.defaultSelected()) { + selected.add(i); + } + } + // Group by app for display (stable within a group by original order). + built.sort(Comparator.comparing((ImportReviewItem it) -> safe(it.entry().app()))); + + this.items = built; + this.freeBytes = StorageProbe.freeBytes(appContext); + state.postValue(ImportReviewUiState.ready(built, manifest)); + publishSelection(); + } catch (Exception e) { + state.postValue(ImportReviewUiState.error(e.getMessage())); + } + }); + } + + boolean isSelected(int index) { + return selected.contains(index); + } + + void toggle(int index) { + for (ImportReviewItem it : items) { + if (it.index() == index && it.selectable()) { + if (!selected.remove(index)) { + selected.add(index); + } + publishSelection(); + return; + } + } + } + + /** The entries the user picked, in display order, for the import service. */ + List selectedEntries() { + List out = new ArrayList<>(); + for (ImportReviewItem it : items) { + if (selected.contains(it.index())) { + out.add(it.entry()); + } + } + return out; + } + + private void publishSelection() { + long bytes = 0L; + int count = 0; + for (ImportReviewItem it : items) { + if (selected.contains(it.index())) { + count++; + bytes += Math.max(0L, it.entry().bytes()); + } + } + selection.postValue(new ImportSelectionSummary( + count, bytes, freeBytes, ImportPreflight.fits(bytes, freeBytes))); + } + + private static String safe(String s) { + return s != null ? s : ""; + } + + @Override + protected void onCleared() { + executor.shutdownNow(); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModelFactory.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModelFactory.java new file mode 100644 index 000000000..be0e3cdf8 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModelFactory.java @@ -0,0 +1,43 @@ +/* + * ============================================================================ + * Name : ImportReviewViewModelFactory.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. Hand-wires the import-review ViewModel (no DI framework): the manifest reader + * and the cx-core import source, plus the app context and the picked drive tree. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.presentation; + +import android.content.Context; +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.lifecycle.ViewModel; +import androidx.lifecycle.ViewModelProvider; + +import org.appdevforall.k2go.contentexchange.data.CxCoreDataSource; +import org.appdevforall.k2go.contentexchange.data.CxCoreImportSource; +import org.appdevforall.k2go.contentexchange.data.ImportManifestReader; + +public final class ImportReviewViewModelFactory implements ViewModelProvider.Factory { + + private final Context appContext; + private final Uri treeUri; + + public ImportReviewViewModelFactory(Context context, Uri treeUri) { + this.appContext = context.getApplicationContext(); + this.treeUri = treeUri; + } + + @NonNull + @Override + @SuppressWarnings("unchecked") + public T create(@NonNull Class modelClass) { + if (modelClass.isAssignableFrom(ImportReviewViewModel.class)) { + return (T) new ImportReviewViewModel(appContext, treeUri, + new ImportManifestReader(), new CxCoreImportSource(new CxCoreDataSource())); + } + throw new IllegalArgumentException("Unknown ViewModel class: " + modelClass.getName()); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportSelectionSummary.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportSelectionSummary.java new file mode 100644 index 000000000..17a181ab5 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportSelectionSummary.java @@ -0,0 +1,24 @@ +package org.appdevforall.k2go.contentexchange.presentation; + +/** + * The review-screen selection totals and the phone-disk verdict: how many items and bytes are picked, + * the device free space, and whether the selection fits. Immutable value the bottom bar reads. + */ +final class ImportSelectionSummary { + + final int count; + final long bytes; + final Long freeBytes; // null when the phone free space could not be read + final boolean fits; + + ImportSelectionSummary(int count, long bytes, Long freeBytes, boolean fits) { + this.count = count; + this.bytes = bytes; + this.freeBytes = freeBytes; + this.fits = fits; + } + + boolean isEmpty() { + return count == 0; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportSession.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportSession.java new file mode 100644 index 000000000..eba467b05 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportSession.java @@ -0,0 +1,230 @@ +/* + * ============================================================================ + * Name : ImportSession.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-427. The one import-run state the progress UI observes and the foreground service + * mutates. The mirror of ExportSession (encapsulated, not a static grab-bag). Holds the + * pure ExportJob (a generic per-item transfer state machine, reused for import) plus the + * selected items (address, title, manifest entry, archive name), the source drive and the + * derived speed/ETA. The sizes are known up front (from the manifest), so there is no + * separate planning phase. + * ============================================================================ + */ +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; + +final class ImportSession { + + /** 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 started = false; + private String errorMessage; + private String sourceLabel = ""; + /** The persisted SAF tree the run reads from; kept so a retry reaches the same drive. */ + private String treeUri; + + private ItemRef[] refs = new ItemRef[0]; + private String[] labels = new String[0]; + private String[] entryJson = new String[0]; + private String[] payloadNames = new String[0]; + + 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 over the selected items; sizes are known now, so the job begins immediately. */ + void begin(ItemRef[] request, String[] titles, String[] entries, String[] payloads, + long[] bytes, String treeUri) { + this.refs = request != null ? request : new ItemRef[0]; + this.labels = titles != null ? titles : new String[this.refs.length]; + this.entryJson = entries != null ? entries : new String[this.refs.length]; + this.payloadNames = payloads != null ? payloads : new String[this.refs.length]; + this.treeUri = treeUri; + this.sourceLabel = ""; + this.errorMessage = null; + this.started = true; + this.cancelled = false; + this.running = true; + this.speed = 0L; + this.etaSeconds = -1L; + job.begin(bytes != null ? bytes : new long[this.refs.length]); + publish(); + } + + void setSource(String label) { + this.sourceLabel = label != null ? label : ""; + publish(); + } + + void fail(String message) { + this.errorMessage = message; + this.running = false; + publish(); + } + + void setRate(long bytesPerSecond, long eta) { + this.speed = Math.max(0L, bytesPerSecond); + this.etaSeconds = eta; + } + + 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; + started = false; + errorMessage = null; + refs = new ItemRef[0]; + labels = new String[0]; + entryJson = new String[0]; + payloadNames = new String[0]; + treeUri = null; + 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; + } + + String entryJson(int i) { + return i >= 0 && i < entryJson.length ? entryJson[i] : null; + } + + 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; + } + + boolean isSettled() { + return started && !running && job.isSettled(); + } + + boolean allDone() { + return job.allDone(); + } + + boolean hasFailed() { + return job.hasFailed(); + } + + /** A settled run with work still left (failed items) for a retry. */ + boolean canRetry() { + return started && !running && itemCount() > 0 && !job.allDone(); + } + + String errorMessage() { + return errorMessage; + } + + String sourceLabel() { + return sourceLabel; + } + + 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 7d5de95e0..349a3ee39 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 @@ -38,6 +38,7 @@ private NotificationIds() {} 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) + public static final int CONTENT_IMPORT = 16; // ContentImportService (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_import.xml b/controller/app/src/main/res/layout/fragment_k2go_content_import.xml new file mode 100644 index 000000000..6b85a40f8 --- /dev/null +++ b/controller/app/src/main/res/layout/fragment_k2go_content_import.xml @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +