From c5aab29ea40f16ff7431b0d37aebafab8df61b4d Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Sun, 25 Oct 2026 08:11:52 -0600 Subject: [PATCH 1/7] K2GO-376 feat(contentexchange): wireless Share receiver (network import carrier) Pull the sender-scoped items over the hotspot and import them through the existing flow. NetworkImportCarrier is the only sender-specific dependency (HTTP to the sender gate, token in the X-Share-Token header, 409-staging retry, per-connection Wi-Fi binding); stage and ingest are unchanged from the disk path. Add ShareUrls and ShareManifestReader (pure, unit-tested), ContentReceiveFragment (scan, fetch manifest, free-space preflight), ContentImportService.startNetwork, and ImportCarrier.onAllDelivered (POST /complete on a clean finish). Wi-Fi join uses the system invite QR (mirrors Clone); no new permission or dependency. --- .../data/NetworkImportCarrier.java | 267 ++++++++++++++++++ .../data/ShareManifestReader.java | 72 +++++ .../contentexchange/domain/ImportCarrier.java | 9 + .../contentexchange/domain/ShareUrls.java | 94 ++++++ .../presentation/ContentImportService.java | 67 ++++- .../presentation/ContentManagerFragment.java | 46 +++ .../presentation/ContentReceiveFragment.java | 218 ++++++++++++++ .../presentation/ImportSession.java | 49 ++++ .../sync/transport/WifiNetworkBinder.java | 41 ++- .../layout/fragment_k2go_content_manager.xml | 12 + .../layout/fragment_k2go_content_receive.xml | 89 ++++++ .../main/res/values/strings_untranslated.xml | 15 + .../data/ShareManifestReaderTest.java | 79 ++++++ .../contentexchange/domain/ShareUrlsTest.java | 87 ++++++ 14 files changed, 1125 insertions(+), 20 deletions(-) create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/NetworkImportCarrier.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ShareManifestReader.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ShareUrls.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentReceiveFragment.java create mode 100644 controller/app/src/main/res/layout/fragment_k2go_content_receive.xml create mode 100644 controller/app/src/test/java/org/appdevforall/k2go/contentexchange/data/ShareManifestReaderTest.java create mode 100644 controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ShareUrlsTest.java diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/NetworkImportCarrier.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/NetworkImportCarrier.java new file mode 100644 index 000000000..bd5a09fe2 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/NetworkImportCarrier.java @@ -0,0 +1,267 @@ +/* + * ============================================================================ + * Name : NetworkImportCarrier.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-376. The network ImportCarrier: the mirror of SafImportCarrier, but each item is + * read over HTTP from the sender's live cx-core gate on the shared hotspot, not from a + * SAF drive. readManifest() GETs the invite's manifest URL; openPayload(itemRef) GETs + * /v1/share//fetch/, retrying while the sender stages the item; the token + * rides the X-Share-Token header, never the URL. Everything downstream (stage to + * /library/.cx-staging, POST /v1/import/item) is unchanged from the disk path, so the + * carrier is the only sender-specific dependency of the import service. On a clean finish + * the carrier POSTs /complete so the gate releases the session (the receiver-driven close). + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.data; + +import android.content.Context; +import android.net.Network; +import android.util.Log; + +import org.appdevforall.k2go.contentexchange.domain.ImportCarrier; +import org.appdevforall.k2go.contentexchange.domain.ShareTransport; +import org.appdevforall.k2go.contentexchange.domain.ShareUrls; +import org.appdevforall.k2go.sync.transport.WifiNetworkBinder; +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.List; + +/** + * One Share session as an {@link ImportCarrier}, read over the hotspot from the sender's gate. The + * invite was validated at the scan boundary (ShareInviteValidator), so the host, port, token and + * manifest path are safe to compose into requests here; {@link ShareUrls} derives the per-item fetch + * and complete URLs from the one manifest path. + * + *

Because the sender's hotspot has no internet, the system may route a plain socket over cellular + * and never reach the peer. This pins only its own sockets to the Network whose subnet contains the + * sender (via {@link WifiNetworkBinder}), so the receiver's loopback ingest and the rest of the app + * keep normal networking. When no such Network is found (this device is the AP, or a direct route), it + * falls back to the default connection. + */ +public final class NetworkImportCarrier implements ImportCarrier { + + private static final String TAG = "IIAB-CxNetCarrier"; + + private static final int CONNECT_TIMEOUT_MS = 8000; + /** Small JSON reads (manifest, complete response). */ + private static final int READ_TIMEOUT_MS = 15000; + /** Per-read (inactivity) stall on the item stream, NOT a wall clock: a large item streams for + * minutes as long as bytes keep flowing; only a genuine stall trips it (mirrors the export fetch). */ + private static final int FETCH_STALL_TIMEOUT_MS = 60000; + /** A manifest larger than this is treated as an error: the index is a few KB. */ + private static final long MANIFEST_MAX_BYTES = 8L * 1024 * 1024; + + /** Wait between fetch retries while the sender stages the item (Kolibri export tar). */ + private static final long STAGING_RETRY_MS = 1500L; + /** Shorter wait when another stream holds the item (single-flight on the gate). */ + private static final long BUSY_RETRY_MS = 500L; + /** Upper bound on retrying one stalled item, so a wedged sender fails the item (retryable) rather + * than looping forever. Generous: staging a multi-GB channel is slow but finite. */ + private static final long FETCH_MAX_WAIT_MS = 30L * 60 * 1000; + + /** Lets the carrier abort its retry wait when the import run is cancelled (the service wires it). */ + public interface Cancellation { + boolean isCancelled(); + } + + private final Context appContext; + private final String host; + private final String baseUrl; + private final String token; + private final String manifestUrl; + private final Cancellation cancel; + + public NetworkImportCarrier(Context context, String host, int port, String token, + String manifestUrl, Cancellation cancel) { + this.appContext = context.getApplicationContext(); + this.host = host; + this.baseUrl = ShareTransport.SCHEME + "://" + host + ":" + port; + this.token = token; + this.manifestUrl = manifestUrl; + this.cancel = cancel != null ? cancel : () -> false; + } + + @Override + public String sourceLabel() { + return host; + } + + @Override + public byte[] readManifest() throws IOException { + HttpURLConnection c = open(ShareUrls.manifest(baseUrl, manifestUrl), "GET", READ_TIMEOUT_MS); + try { + int code = c.getResponseCode(); + if (code != 200) { + throw new IOException("Share manifest HTTP " + code + ": " + errorText(c)); + } + try (InputStream in = c.getInputStream()) { + return readCapped(in, MANIFEST_MAX_BYTES); + } + } finally { + c.disconnect(); + } + } + + @Override + public List listFiles() { + // Share always carries a manifest, so the no-manifest folder scan never runs over the network. + return Collections.emptyList(); + } + + @Override + public InputStream openPayload(String itemRef) throws IOException { + String url = ShareUrls.fetch(baseUrl, manifestUrl, itemRef); + long deadline = System.currentTimeMillis() + FETCH_MAX_WAIT_MS; + while (true) { + if (cancel.isCancelled()) { + throw new IOException("cancelled"); + } + HttpURLConnection c = open(url, "GET", FETCH_STALL_TIMEOUT_MS); + int code; + try { + code = c.getResponseCode(); + } catch (IOException e) { + c.disconnect(); + throw e; + } + if (code == 200) { + // The caller streams and closes this; closing disconnects the connection. + try { + return new ConnectionInputStream(c, c.getInputStream()); + } catch (IOException e) { + c.disconnect(); // never leak the socket if the body stream cannot be opened + throw e; + } + } + String state = stateOf(c); + c.disconnect(); + if (code == 409 && ("staging".equals(state) || "busy".equals(state))) { + if (System.currentTimeMillis() > deadline) { + throw new IOException("item did not become ready in time"); + } + sleep("staging".equals(state) ? STAGING_RETRY_MS : BUSY_RETRY_MS); + continue; // the sender is staging or the slot is busy: retry the same URL + } + throw new IOException("Share fetch HTTP " + code + + (state != null ? " (" + state + ")" : "")); + } + } + + @Override + public void onAllDelivered() { + // Best-effort clean-success close: the gate also self-bounds (safety cap) and the sender closes + // on its own teardown, so a failure here only delays the sender's release, never the import. + try { + HttpURLConnection c = open(ShareUrls.complete(baseUrl, manifestUrl), "POST", READ_TIMEOUT_MS); + try { + c.setDoOutput(true); + c.setRequestProperty("Content-Type", "application/json"); + try (OutputStream os = c.getOutputStream()) { + os.write("{}".getBytes(StandardCharsets.UTF_8)); + } + c.getResponseCode(); // drive the request; the body is not needed + } finally { + c.disconnect(); + } + } catch (Exception e) { + Log.i(TAG, "share complete failed (sender will self-bound): " + e.getMessage()); + } + } + + // ---- HTTP plumbing ------------------------------------------------------------------------- + + /** Open a connection to the sender, pinned to the Network that reaches its hotspot when one exists, + * with the share token in the header. The network is resolved per request, so a Wi-Fi reconnect to + * a new Network object is picked up on the next attempt. */ + private HttpURLConnection open(String urlStr, String method, int readTimeout) throws IOException { + URL url = new URL(urlStr); + Network net = WifiNetworkBinder.findHostNetwork(appContext, host); + URLConnection raw = net != null ? net.openConnection(url) : url.openConnection(); + HttpURLConnection c = (HttpURLConnection) raw; + c.setUseCaches(false); + c.setConnectTimeout(CONNECT_TIMEOUT_MS); + c.setReadTimeout(readTimeout); + c.setRequestMethod(method); + c.setRequestProperty("Accept", "application/json"); + c.setRequestProperty("X-Share-Token", token); // the only auth; never in the URL + return c; + } + + /** The {@code state} field of a 409/500 fetch body ("staging" / "busy" / "error"), or null. */ + private static String stateOf(HttpURLConnection c) { + String text = errorText(c); + if (text == null || text.isEmpty()) { + return null; + } + try { + return new JSONObject(text).optString("state", null); + } catch (Exception e) { + return null; + } + } + + private static String errorText(HttpURLConnection c) { + try (InputStream err = c.getErrorStream()) { + if (err == null) { + return ""; + } + return new String(readCapped(err, 64 * 1024), StandardCharsets.UTF_8); + } catch (Exception e) { + return ""; + } + } + + private static byte[] readCapped(InputStream in, long max) throws IOException { + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + byte[] chunk = new byte[8192]; + int n; + long total = 0L; + while ((n = in.read(chunk)) != -1) { + total += n; + if (total > max) { + throw new IOException("response exceeds " + max + " bytes"); + } + buf.write(chunk, 0, n); + } + return buf.toByteArray(); + } + + private void sleep(long ms) throws IOException { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("cancelled"); + } + } + + /** An item body that disconnects its HTTP connection when the caller closes the stream. */ + private static final class ConnectionInputStream extends FilterInputStream { + private final HttpURLConnection connection; + + ConnectionInputStream(HttpURLConnection connection, InputStream body) { + super(body); + this.connection = connection; + } + + @Override + public void close() throws IOException { + try { + super.close(); + } finally { + connection.disconnect(); + } + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ShareManifestReader.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ShareManifestReader.java new file mode 100644 index 000000000..9709c000b --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ShareManifestReader.java @@ -0,0 +1,72 @@ +/* + * ============================================================================ + * Name : ShareManifestReader.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-376. Parses the sender gate's Share manifest (GET /v1/share//manifest) into + * the same ImportEntry list the disk import consumes. Share is the network twin of + * Export, so a manifest item is the read-side item JSON (model.ManifestItem.to_json) + * with two share annotations added by the gate: itemRef (the fetch handle) and delivered + * (an advisory sender hint). This maps itemRef onto the ImportEntry payload handle and + * strips the annotations from the entry JSON handed to /v1/import/item, so downstream + * ingest is identical to the disk path. Pure org.json: no HTTP, no Android, unit-testable. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.data; + +import org.appdevforall.k2go.contentexchange.domain.ImportEntry; +import org.appdevforall.k2go.contentexchange.domain.ShareUrls; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +public final class ShareManifestReader { + + private ShareManifestReader() { + } + + /** + * Parse the Share manifest bytes into import entries. Each entry's payload handle is the item's + * {@code itemRef} (its index in the sender's scoped set, which the network carrier fetches by), and + * its entry JSON is the item JSON with the {@code itemRef} / {@code delivered} annotations removed, + * so it is the exact read-side item the import adapters already accept. Items the sender reported as + * missing (unknown app / not found) are not in {@code items}, so they never produce an entry. An + * item that cannot be addressed (no app, no localRef, or a non-numeric itemRef) is skipped. + */ + 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 item = items.optJSONObject(i); + if (item == null) { + continue; + } + String app = item.optString("app", ""); + JSONObject identity = item.optJSONObject("identity"); + String localRef = identity != null ? identity.optString("localRef", "") : ""; + String itemRef = item.optString("itemRef", ""); + if (app.isEmpty() || localRef.isEmpty() || !ShareUrls.isValidItemRef(itemRef)) { + continue; // not addressable or a drifted / hostile ref: skip, never fetch it + } + long bytes = item.optLong("bytes", 0L); + String title = item.optString("title", localRef); + // The entry handed to /v1/import/item is the pure read-side item (no share annotations), + // so network ingest matches the disk path exactly. itemRef is already captured above, so + // dropping it (and delivered) from this freshly parsed item is safe. + item.remove("itemRef"); + item.remove("delivered"); + out.add(new ImportEntry(app, localRef, title, bytes, itemRef, item.toString())); + } + return out; + } +} 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 index 558d6910b..97e9abc58 100644 --- 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 @@ -26,6 +26,15 @@ public interface ImportCarrier { /** Open a readable stream for one payload file; the caller copies it, then closes it. */ InputStream openPayload(String name) throws IOException; + /** + * Signal that the run finished with every requested item delivered (a clean success). The default + * is a no-op (a drive source has nothing to close); the network carrier uses it to tell the sender + * gate the receiver has everything, so the share session is released. Called at most once, only on + * a fully-complete run. + */ + default void onAllDelivered() throws IOException { + } + /** One file in the source folder: its display name and byte size. Immutable value. */ final class DriveFile { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ShareUrls.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ShareUrls.java new file mode 100644 index 000000000..08855386d --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ShareUrls.java @@ -0,0 +1,94 @@ +/* + * ============================================================================ + * Name : ShareUrls.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-376. Pure composition of the receiver's Share URLs from the scanned invite: the + * manifest, per-item fetch, and complete endpoints on the sender's gate. The invite's + * base origin and manifest path are already validated (ShareInviteValidator); this + * derives the sibling paths from the one manifest path, so there is a single source for + * the share-session path prefix. No android.*, no java.net, no JSON: unit-testable. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * Builds the receiver-side Share URLs from a validated invite. The invite carries the sender's origin + * ({@code http://host:port}) and the manifest path ({@code /v1/share//manifest}); the fetch and + * complete endpoints are siblings of the manifest ({@code .../fetch/}, {@code .../complete}), + * so they are derived from the one manifest path rather than re-composed from a separately parsed + * session id (one source for the prefix). + * + *

The token is never part of any URL: it travels in the {@code X-Share-Token} header. The + * {@code itemRef} is the item's index in the sender's scoped set, always decimal digits (validated by + * {@link #isValidItemRef}), so it needs no percent-encoding to be a safe single path segment. + */ +public final class ShareUrls { + + private static final String MANIFEST_SUFFIX = "/manifest"; + + private ShareUrls() { + } + + /** The manifest URL: {@code baseUrl + manifestPath}. */ + public static String manifest(String baseUrl, String manifestPath) { + requireOrigin(baseUrl); + return baseUrl + requireManifestPath(manifestPath); + } + + /** The per-item fetch URL: the share-session prefix + {@code /fetch/}. */ + public static String fetch(String baseUrl, String manifestPath, String itemRef) { + requireOrigin(baseUrl); + if (!isValidItemRef(itemRef)) { + throw new IllegalArgumentException("itemRef must be decimal digits"); + } + return baseUrl + sessionPrefix(manifestPath) + "/fetch/" + itemRef; + } + + /** The clean-success close URL: the share-session prefix + {@code /complete}. */ + public static String complete(String baseUrl, String manifestPath) { + requireOrigin(baseUrl); + return baseUrl + sessionPrefix(manifestPath) + "/complete"; + } + + /** + * The share-session path prefix, the manifest path with its trailing {@code /manifest} removed + * ({@code /v1/share//manifest} -> {@code /v1/share/}). Fails closed when the path is not a + * manifest path, so a drifted invite can never compose a sibling URL off a wrong base. + */ + public static String sessionPrefix(String manifestPath) { + String path = requireManifestPath(manifestPath); + return path.substring(0, path.length() - MANIFEST_SUFFIX.length()); + } + + /** True when {@code itemRef} is a non-empty run of decimal digits (the gate's {@code str(index)}). */ + public static boolean isValidItemRef(String itemRef) { + if (itemRef == null || itemRef.isEmpty() || itemRef.length() > 9) { + return false; // a 9-digit cap is far above any real item count and blocks absurd input + } + for (int i = 0; i < itemRef.length(); i++) { + char c = itemRef.charAt(i); + if (c < '0' || c > '9') { + return false; + } + } + return true; + } + + private static void requireOrigin(String baseUrl) { + // A bare origin only: no trailing slash and no path, so the composed path is exactly ours. + if (baseUrl == null || !(baseUrl.startsWith("http://") || baseUrl.startsWith("https://")) + || baseUrl.endsWith("/") || baseUrl.indexOf('/', baseUrl.indexOf("//") + 2) >= 0) { + throw new IllegalArgumentException("baseUrl must be a bare http(s) origin"); + } + } + + private static String requireManifestPath(String manifestPath) { + if (manifestPath == null || manifestPath.length() <= MANIFEST_SUFFIX.length() + || manifestPath.charAt(0) != '/' || !manifestPath.endsWith(MANIFEST_SUFFIX) + || manifestPath.contains("..") || manifestPath.contains("://")) { + throw new IllegalArgumentException("not a /.../manifest path"); + } + return manifestPath; + } +} 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 index 0c8f91df7..2b6c545fb 100644 --- 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 @@ -34,6 +34,7 @@ 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.NetworkImportCarrier; import org.appdevforall.k2go.contentexchange.data.SafImportCarrier; import org.appdevforall.k2go.contentexchange.domain.ExportJob; import org.appdevforall.k2go.contentexchange.domain.ImportCarrier; @@ -55,6 +56,12 @@ public final class ContentImportService extends Service { public static final String ACTION_CANCEL = "org.appdevforall.k2go.CONTENT_IMPORT_CANCEL"; public static final String EXTRA_TREE_URI = "treeUri"; + /** Network (Share) source: the sender's hotspot address, token and manifest path (K2GO-376). A + * START intent carries either {@link #EXTRA_TREE_URI} (drive) or these (network), never both. */ + public static final String EXTRA_NET_HOST = "netHost"; + public static final String EXTRA_NET_PORT = "netPort"; + public static final String EXTRA_SHARE_TOKEN = "shareToken"; + public static final String EXTRA_MANIFEST_URL = "manifestUrl"; public static final String EXTRA_APPS = "apps"; public static final String EXTRA_LOCAL_REFS = "localRefs"; public static final String EXTRA_TITLES = "titles"; @@ -99,6 +106,33 @@ public static void start(Context ctx, Uri treeUri, ItemRef[] refs, String[] titl ContextCompat.startForegroundService(ctx, i); } + /** + * Start a network import: pull the sender-scoped items from its gate over the hotspot (K2GO-376). + * Same per-item queue / staging / ingest as the drive path; only the carrier (the source) differs. + */ + public static void startNetwork(Context ctx, String host, int port, String token, String manifestUrl, + 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_NET_HOST, host) + .putExtra(EXTRA_NET_PORT, port) + .putExtra(EXTRA_SHARE_TOKEN, token) + .putExtra(EXTRA_MANIFEST_URL, manifestUrl) + .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, @@ -190,13 +224,15 @@ public int onStartCommand(Intent intent, int flags, int startId) { return START_NOT_STICKY; } String treeUri = intent.getStringExtra(EXTRA_TREE_URI); + String netHost = intent.getStringExtra(EXTRA_NET_HOST); 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 + boolean network = netHost != null; + if ((treeUri == null && !network) || apps == null || locals == null || apps.length == 0 || apps.length != locals.length) { stopSelf(); return START_NOT_STICKY; @@ -205,7 +241,13 @@ public int onStartCommand(Intent intent, int flags, int startId) { for (int i = 0; i < apps.length; i++) { refs[i] = new ItemRef(apps[i], locals[i]); } - SESSION.begin(refs, titles, entries, payloads, bytes, treeUri); + if (network) { + SESSION.beginNetwork(refs, titles, entries, payloads, bytes, netHost, + intent.getIntExtra(EXTRA_NET_PORT, 0), + intent.getStringExtra(EXTRA_SHARE_TOKEN), intent.getStringExtra(EXTRA_MANIFEST_URL)); + } else { + SESSION.begin(refs, titles, entries, payloads, bytes, treeUri); + } startForeground(NOTIFICATION_ID, buildNotification(null)); worker.execute(this::drain); return START_NOT_STICKY; @@ -225,9 +267,17 @@ private void drain() { BoxImportStaging staging = new BoxImportStaging(getApplicationContext()); ImportCarrier carrier; try { - carrier = new SafImportCarrier(getApplicationContext(), Uri.parse(SESSION.treeUri())); + // The carrier is the only sender-specific dependency: a drive (SAF) source or a paired + // sender over the hotspot (network). Everything after it (stage + ingest) is identical. + if (SESSION.isNetwork()) { + carrier = new NetworkImportCarrier(getApplicationContext(), SESSION.shareHost(), + SESSION.sharePort(), SESSION.shareToken(), SESSION.shareManifestUrl(), + SESSION::isCancelled); + } else { + carrier = new SafImportCarrier(getApplicationContext(), Uri.parse(SESSION.treeUri())); + } } catch (Exception e) { - finishWithError("Could not open the drive: " + e.getMessage()); + finishWithError("Could not open the source: " + e.getMessage()); return; } SESSION.setSource(carrier.sourceLabel()); @@ -283,7 +333,14 @@ private void drain() { if (SESSION.allDone()) { // Fully imported: one-shot done, so free the grant now (a partial run keeps it for Retry). - releaseGrant(getApplicationContext(), SESSION.treeUri()); + releaseGrant(getApplicationContext(), SESSION.treeUri()); // null treeUri (network) is a no-op + try { + // Clean success: tell a network sender the receiver has everything, so its gate + // releases the session (best effort; the sender also self-bounds). + carrier.onAllDelivered(); + } catch (Exception ignored) { + // the sender's safety cap backstops a failed signal + } } SESSION.setRunning(false); SESSION.setRate(0L, -1L); 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 84e4b0b1e..1c77612b0 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 @@ -33,7 +33,11 @@ import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; +import com.journeyapps.barcodescanner.ScanContract; +import com.journeyapps.barcodescanner.ScanOptions; + import org.appdevforall.k2go.R; +import org.appdevforall.k2go.contentexchange.data.ShareHandshake; import org.appdevforall.k2go.contentexchange.domain.ContentGroup; import org.appdevforall.k2go.contentexchange.domain.ContentItem; import org.appdevforall.k2go.contentexchange.domain.ItemRef; @@ -68,9 +72,13 @@ public class ContentManagerFragment extends Fragment { private TextView selectionLabel; private Button exportButton; private Button importButton; + private Button receiveButton; private Button deleteButton; private Button shareButton; + /** The invite-QR scanner for the receive flow (same ZXing contract Clone uses). */ + private ActivityResultLauncher inviteScan; + /** The selection captured when Share was tapped, held across the hotspot-permission round-trip. */ private List pendingShare; /** Runtime hotspot permission (NEARBY_WIFI_DEVICES / ACCESS_FINE_LOCATION), requested before the @@ -96,6 +104,7 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c 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); + receiveButton = root.findViewById(R.id.k2go_cx_receive); deleteButton = root.findViewById(R.id.k2go_cx_delete); shareButton = root.findViewById(R.id.k2go_cx_share); @@ -104,9 +113,11 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c new ActivityResultContracts.OpenDocumentTree(), this::onImportTreePicked); hotspotPerm = registerForActivityResult( new ActivityResultContracts.RequestMultiplePermissions(), result -> onHotspotPermissionResult()); + inviteScan = registerForActivityResult(new ScanContract(), r -> onInviteScanned(r.getContents())); exportButton.setEnabled(true); exportButton.setOnClickListener(v -> onExportClicked()); importButton.setOnClickListener(v -> onImportClicked()); + receiveButton.setOnClickListener(v -> onReceiveClicked()); deleteButton.setEnabled(true); deleteButton.setOnClickListener(v -> onDeleteClicked()); shareButton.setEnabled(true); @@ -317,6 +328,41 @@ private void showImportProgress() { .commit(); } + // ---- receive (wireless Share, K2GO-376) ---------------------------------------------------- + + /** Receive: if an import run is still active, show it; otherwise scan the sender's invite QR. The + * user joins the sender hotspot first (the invite's companion Wi-Fi QR, handled by the system). */ + private void onReceiveClicked() { + if (ContentImportService.session().isRunning()) { + showImportProgress(); + return; + } + ScanOptions o = new ScanOptions(); + o.setDesiredBarcodeFormats(ScanOptions.QR_CODE); + o.setPrompt(getString(R.string.k2go_cx_receive_scan_prompt)); + o.setBeepEnabled(false); + o.setBarcodeImageEnabled(false); + o.setOrientationLocked(false); + inviteScan.launch(o); + } + + /** The scanner returned. Null means the user cancelled; a non-invite or invalid QR is rejected. */ + private void onInviteScanned(@Nullable String contents) { + if (!isAdded() || contents == null) { + return; + } + ShareHandshake.ShareInvite invite = ShareHandshake.decode(contents); + if (invite == null) { + String msg = getString(R.string.k2go_cx_receive_invalid); + Snackbar.make(requireView(), msg, SnackbarDuration.millisForText(msg)).show(); + return; + } + requireActivity().getSupportFragmentManager().beginTransaction() + .replace(R.id.k2go_setup_host, ContentReceiveFragment.newInstance(invite)) + .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/ContentReceiveFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentReceiveFragment.java new file mode 100644 index 000000000..d4149c20d --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentReceiveFragment.java @@ -0,0 +1,218 @@ +/* + * ============================================================================ + * Name : ContentReceiveFragment.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-376. The receive step of wireless Share: after the user joins the sender hotspot + * and scans the invite QR, this fetches the sender's manifest over the hotspot, runs the + * receiver-side free-space preflight, and starts the network import (then the shared + * import progress screen). The sender already scoped what is shared, so there is no + * per-item selection here: the receiver pulls the scoped set. The manifest fetch is a + * short, idempotent GET on a worker; a flaky hotspot shows an error with a retry. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.presentation; + +import android.content.Context; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +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 org.appdevforall.k2go.R; +import org.appdevforall.k2go.contentexchange.data.NetworkImportCarrier; +import org.appdevforall.k2go.contentexchange.data.ShareHandshake; +import org.appdevforall.k2go.contentexchange.data.ShareManifestReader; +import org.appdevforall.k2go.contentexchange.domain.ImportEntry; +import org.appdevforall.k2go.contentexchange.domain.ImportPreflight; +import org.appdevforall.k2go.contentexchange.domain.ItemRef; +import org.appdevforall.k2go.storage.StorageProbe; +import org.appdevforall.k2go.util.ByteFormatter; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class ContentReceiveFragment extends Fragment { + + private static final String ARG_HOST = "host"; + private static final String ARG_PORT = "port"; + private static final String ARG_TOKEN = "token"; + private static final String ARG_MANIFEST = "manifestUrl"; + + /** Create the receive screen for a validated invite the manager just scanned. */ + public static ContentReceiveFragment newInstance(ShareHandshake.ShareInvite invite) { + ContentReceiveFragment f = new ContentReceiveFragment(); + Bundle b = new Bundle(); + b.putString(ARG_HOST, invite.host); + b.putInt(ARG_PORT, invite.port); + b.putString(ARG_TOKEN, invite.token); + b.putString(ARG_MANIFEST, invite.manifestUrl); + f.setArguments(b); + return f; + } + + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + private final Handler main = new Handler(Looper.getMainLooper()); + + private TextView status; + private TextView freeLabel; + private TextView warning; + private Button receiveButton; + private Button retryButton; + + private Context appContext; + private String host; + private int port; + private String token; + private String manifestUrl; + + /** The parsed, scoped items once the manifest is read; the Receive button hands them to the service. */ + private List entries; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle s) { + View root = inflater.inflate(R.layout.fragment_k2go_content_receive, container, false); + status = root.findViewById(R.id.k2go_cxrv_status); + freeLabel = root.findViewById(R.id.k2go_cxrv_free_label); + warning = root.findViewById(R.id.k2go_cxrv_warning); + receiveButton = root.findViewById(R.id.k2go_cxrv_receive); + retryButton = root.findViewById(R.id.k2go_cxrv_retry); + + TextView back = root.findViewById(R.id.k2go_cxrv_back); + back.setText(getString(R.string.k2go_back_link)); + back.setOnClickListener(v -> requireActivity().getOnBackPressedDispatcher().onBackPressed()); + receiveButton.setOnClickListener(v -> onReceiveClicked()); + retryButton.setOnClickListener(v -> fetchManifest()); + + appContext = requireContext().getApplicationContext(); + host = requireArguments().getString(ARG_HOST); + port = requireArguments().getInt(ARG_PORT); + token = requireArguments().getString(ARG_TOKEN); + manifestUrl = requireArguments().getString(ARG_MANIFEST); + + fetchManifest(); // idempotent GET; safe to re-run on a recreate or a Try-again tap + return root; + } + + /** Fetch and parse the sender's manifest on a worker, then render the summary or an error. */ + private void fetchManifest() { + entries = null; + showConnecting(); + worker.execute(() -> { + List parsed; + try { + NetworkImportCarrier carrier = new NetworkImportCarrier( + appContext, host, port, token, manifestUrl, () -> false); + parsed = ShareManifestReader.parse(carrier.readManifest()); + } catch (Exception e) { + post(() -> showError()); + return; + } + post(() -> showManifest(parsed)); + }); + } + + private void showConnecting() { + status.setText(getString(R.string.k2go_cx_receive_connecting)); + freeLabel.setVisibility(View.GONE); + warning.setVisibility(View.GONE); + receiveButton.setVisibility(View.GONE); + retryButton.setVisibility(View.GONE); + } + + private void showError() { + status.setText(getString(R.string.k2go_cx_receive_error)); + freeLabel.setVisibility(View.GONE); + warning.setVisibility(View.GONE); + receiveButton.setVisibility(View.GONE); + retryButton.setVisibility(View.VISIBLE); + } + + private void showManifest(List parsed) { + this.entries = parsed; + retryButton.setVisibility(View.GONE); + if (parsed.isEmpty()) { + status.setText(getString(R.string.k2go_cx_receive_nothing)); + freeLabel.setVisibility(View.GONE); + warning.setVisibility(View.GONE); + receiveButton.setVisibility(View.GONE); + return; + } + long total = 0L; + for (ImportEntry e : parsed) { + total += Math.max(0L, e.bytes()); + } + status.setText(getString(R.string.k2go_cx_receive_ready_fmt, + parsed.size(), ByteFormatter.humanBytes(total))); + + Long free = StorageProbe.freeBytes(appContext); + freeLabel.setText(free != null + ? getString(R.string.k2go_cx_free_fmt, ByteFormatter.humanBytes(free)) + : getString(R.string.k2go_cx_free_unavailable)); + freeLabel.setVisibility(View.VISIBLE); + + // The whole scoped set may not fit; warn, but still allow it (partial is first-class and the + // receiver cannot deselect items the sender scoped). The service stops cleanly on ENOSPC. + boolean fits = ImportPreflight.fits(total, free); + warning.setVisibility(fits ? View.GONE : View.VISIBLE); + if (!fits) { + warning.setText(getString(R.string.k2go_cx_receive_wont_fit)); + } + receiveButton.setVisibility(View.VISIBLE); + } + + private void onReceiveClicked() { + if (entries == null || entries.isEmpty()) { + return; + } + int n = entries.size(); + ItemRef[] refs = new ItemRef[n]; + String[] titles = new String[n]; + String[] entryJson = new String[n]; + String[] payloads = new String[n]; + long[] bytes = new long[n]; + for (int i = 0; i < n; i++) { + ImportEntry e = entries.get(i); + refs[i] = e.ref(); + titles[i] = e.title() != null && !e.title().isEmpty() ? e.title() : e.localRef(); + entryJson[i] = e.entryJson(); + payloads[i] = e.payloadName(); + bytes[i] = e.bytes(); + } + ContentImportService.startNetwork(requireContext(), host, port, token, manifestUrl, + refs, titles, entryJson, payloads, bytes); + showProgress(); + } + + /** Swap to the shared import progress screen. Not added to the back stack, so Finish there pops + * straight back to the manager (this transient connect screen is not re-shown). */ + private void showProgress() { + requireActivity().getSupportFragmentManager().beginTransaction() + .replace(R.id.k2go_setup_host, new ImportProgressFragment()) + .commit(); + } + + private void post(Runnable r) { + main.post(() -> { + if (isAdded() && getView() != null) { + r.run(); + } + }); + } + + @Override + public void onDestroy() { + worker.shutdownNow(); + super.onDestroy(); + } +} 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 index eba467b05..f3a3ad533 100644 --- 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 @@ -39,6 +39,15 @@ interface Listener { /** The persisted SAF tree the run reads from; kept so a retry reaches the same drive. */ private String treeUri; + // Network (Share) source, when the run pulls from a paired sender instead of a drive (K2GO-376). + // shareHost == null means the SAF (drive) path; non-null means the network path, and these carry + // the sender address + token + manifest path so the service rebuilds the carrier (and a retry + // reaches the same sender). + private String shareHost; + private int sharePort; + private String shareToken; + private String shareManifestUrl; + private ItemRef[] refs = new ItemRef[0]; private String[] labels = new String[0]; private String[] entryJson = new String[0]; @@ -61,6 +70,10 @@ void begin(ItemRef[] request, String[] titles, String[] entries, String[] payloa this.entryJson = entries != null ? entries : new String[this.refs.length]; this.payloadNames = payloads != null ? payloads : new String[this.refs.length]; this.treeUri = treeUri; + this.shareHost = null; // SAF path by default; beginNetwork sets the network coordinates + this.sharePort = 0; + this.shareToken = null; + this.shareManifestUrl = null; this.sourceLabel = ""; this.errorMessage = null; this.started = true; @@ -72,6 +85,17 @@ void begin(ItemRef[] request, String[] titles, String[] entries, String[] payloa publish(); } + /** Start a network (Share) run: the same per-item state as {@link #begin}, plus the sender address, + * token and manifest path the carrier pulls from. No SAF tree (the source is the hotspot). */ + void beginNetwork(ItemRef[] request, String[] titles, String[] entries, String[] payloads, + long[] bytes, String host, int port, String token, String manifestUrl) { + begin(request, titles, entries, payloads, bytes, null); + this.shareHost = host; + this.sharePort = port; + this.shareToken = token; + this.shareManifestUrl = manifestUrl; + } + void setSource(String label) { this.sourceLabel = label != null ? label : ""; publish(); @@ -111,6 +135,10 @@ void clear() { entryJson = new String[0]; payloadNames = new String[0]; treeUri = null; + shareHost = null; + sharePort = 0; + shareToken = null; + shareManifestUrl = null; job.begin(new long[0]); speed = 0L; etaSeconds = -1L; @@ -141,6 +169,27 @@ String treeUri() { return treeUri; } + /** True when this run pulls from a paired sender over the network, not from a SAF drive. */ + boolean isNetwork() { + return shareHost != null; + } + + String shareHost() { + return shareHost; + } + + int sharePort() { + return sharePort; + } + + String shareToken() { + return shareToken; + } + + String shareManifestUrl() { + return shareManifestUrl; + } + boolean isCancelled() { return cancelled; } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/sync/transport/WifiNetworkBinder.java b/controller/app/src/main/java/org/appdevforall/k2go/sync/transport/WifiNetworkBinder.java index e3e50d788..b16865bff 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/sync/transport/WifiNetworkBinder.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/sync/transport/WifiNetworkBinder.java @@ -43,20 +43,40 @@ private WifiNetworkBinder() { /** Bind the process to the local Network whose subnet contains hostIp. Returns true if bound. */ public static boolean bindToHostNetwork(Context ctx, String hostIp) { - if (ctx == null || hostIp == null) return false; + Network match = findHostNetwork(ctx, hostIp); // handles null ctx / hostIp / cm + if (match == null) { + Log.i(TAG, "No local network matches host " + hostIp + "; not binding (direct/local route)"); + return false; + } ConnectivityManager cm = (ConnectivityManager) ctx.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; + boolean ok = cm.bindProcessToNetwork(match); + Log.i(TAG, "Bound process to " + match + " to reach host " + hostIp + " -> " + ok); + return ok; + } + + /** + * The local {@link Network} whose link subnet contains {@code hostIp}, or {@code null} when none + * matches (this device is itself the AP, or the host is reached by the default route). Caller can + * open a connection on the returned Network to pin ONLY that socket to the peer's Wi-Fi / hotspot, + * instead of {@link #bindToHostNetwork} which pins the whole process (needed only for a native + * child such as rsync). The subnet match is the single source for "which Network reaches the host". + */ + public static Network findHostNetwork(Context ctx, String hostIp) { + if (ctx == null || hostIp == null) return null; + ConnectivityManager cm = (ConnectivityManager) + ctx.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); + if (cm == null) return null; InetAddress host; try { host = InetAddress.getByName(hostIp); } catch (Exception e) { - return false; + return null; } - if (!(host instanceof Inet4Address)) return false; + if (!(host instanceof Inet4Address)) return null; - Network match = null; try { for (Network net : cm.getAllNetworks()) { LinkProperties lp = cm.getLinkProperties(net); @@ -64,23 +84,14 @@ public static boolean bindToHostNetwork(Context ctx, String hostIp) { for (LinkAddress la : lp.getLinkAddresses()) { InetAddress local = la.getAddress(); if (local instanceof Inet4Address && sameSubnet(local, host, la.getPrefixLength())) { - match = net; - break; + return net; } } - if (match != null) break; } } catch (Exception e) { Log.w(TAG, "Network enumeration failed", e); } - - if (match == null) { - Log.i(TAG, "No local network matches host " + hostIp + "; not binding (direct/local route)"); - return false; - } - boolean ok = cm.bindProcessToNetwork(match); - Log.i(TAG, "Bound process to " + match + " to reach host " + hostIp + " -> " + ok); - return ok; + return null; } /** Release any process-level network binding (back to the system default). */ diff --git a/controller/app/src/main/res/layout/fragment_k2go_content_manager.xml b/controller/app/src/main/res/layout/fragment_k2go_content_manager.xml index 54464ac3e..b8c367e36 100644 --- a/controller/app/src/main/res/layout/fragment_k2go_content_manager.xml +++ b/controller/app/src/main/res/layout/fragment_k2go_content_manager.xml @@ -32,6 +32,18 @@ android:layout_marginTop="4dp" android:text="@string/k2go_cx_import_from_drive" /> + +