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/ExportJob.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportJob.java index cadf48aaa..2afb2c725 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportJob.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportJob.java @@ -30,12 +30,21 @@ public final class ExportJob { private int[] phase = new int[0]; private long[] staged = new long[0]; private int index = -1; + /** K2GO-376: import has no box-prepare phase (the sender already staged the item), so its per-item + * bar is a single download phase that fills 0..100 from copiedBytes, not the export two-phase bar. */ + private boolean singlePhase; /** * Start a run over {@code planned[i]} bytes per item (0 = unknown size). A negative planned * value marks an item the core could not plan: it starts {@link #FAILED}, not downloadable. */ public void begin(long[] plannedBytes) { + begin(plannedBytes, false); + } + + /** Single-phase variant (import): the active item's bar fills 0..100 straight from copiedBytes. */ + public void begin(long[] plannedBytes, boolean singlePhase) { + this.singlePhase = singlePhase; int n = plannedBytes != null ? plannedBytes.length : 0; status = new int[n]; planned = new long[n]; @@ -247,6 +256,9 @@ public int currentItemPercent() { if (i < 0 || i >= planned.length) { return 0; } + if (singlePhase) { + return pct(copied[i], planned[i]); // import: one download phase, 0..100 + } if (phase[i] == PHASE_PREPARE) { return half(staged[i], planned[i]); // 0..50 } @@ -260,4 +272,12 @@ private static int half(long done, long total) { } return (int) Math.min(50L, done * 50L / total); } + + /** {@code done/total} scaled into 0..100, or 0 when the total is unknown. */ + private static int pct(long done, long total) { + if (total <= 0) { + return 0; + } + return (int) Math.min(100L, done * 100L / total); + } } 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/ContentManagerAdapter.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java index 2e2ee5031..e050f9785 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java @@ -6,6 +6,7 @@ import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; +import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; @@ -21,7 +22,9 @@ import org.appdevforall.k2go.util.ByteFormatter; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; /** * Recycling adapter for the content manager. A single flat row list with four view @@ -54,7 +57,12 @@ public interface SelectionController { static final int TYPE_ITEM = 2; static final int TYPE_EMPTY = 3; + /** Every row (header, groups and their items). Stays complete across a collapse toggle. */ private final List rows = new ArrayList<>(); + /** The rows actually shown: {@link #rows} minus the items of collapsed groups. */ + private final List shown = new ArrayList<>(); + /** Apps whose items are hidden (collapsed). Default expanded = empty. Survives a reload. */ + private final Set collapsed = new HashSet<>(); private final SelectionController selection; public ContentManagerAdapter(SelectionController selection) { @@ -64,6 +72,7 @@ public ContentManagerAdapter(SelectionController selection) { public void submit(List newRows) { rows.clear(); rows.addAll(newRows); + rebuildShown(); notifyDataSetChanged(); } @@ -72,14 +81,48 @@ public void refreshSelectionStates() { notifyDataSetChanged(); } + /** Whether a group's items are hidden. Read by its header to pick the chevron direction. */ + boolean isCollapsed(String app) { + return collapsed.contains(app); + } + + /** Flips a group between expanded and collapsed and rebuilds the shown rows. */ + void toggleCollapse(String app) { + if (app == null) { + return; + } + if (!collapsed.remove(app)) { + collapsed.add(app); + } + rebuildShown(); + notifyDataSetChanged(); + } + + /** Recomputes {@link #shown}: a collapsed group keeps its header but drops its item/empty rows. */ + private void rebuildShown() { + shown.clear(); + boolean skip = false; // inside a collapsed group (set at its header, cleared at the next one) + for (Row row : rows) { + if (row.type == TYPE_GROUP) { + skip = collapsed.contains(((GroupRow) row).app); + shown.add(row); + } else if (skip && (row.type == TYPE_ITEM || row.type == TYPE_EMPTY)) { + // An item, or the "No items" note, under a collapsed group: hidden. The top-level + // empty-manager note has no preceding group, so skip is false and it still shows. + } else { + shown.add(row); + } + } + } + @Override public int getItemViewType(int position) { - return rows.get(position).type; + return shown.get(position).type; } @Override public int getItemCount() { - return rows.size(); + return shown.size(); } @NonNull @@ -90,7 +133,7 @@ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int case TYPE_HEADER: return new HeaderVH(ctx); case TYPE_GROUP: - return new GroupVH(ctx, selection); + return new GroupVH(ctx, selection, this); case TYPE_EMPTY: return new EmptyVH(ctx); default: @@ -100,7 +143,7 @@ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { - Row row = rows.get(position); + Row row = shown.get(position); switch (row.type) { case TYPE_HEADER: ((HeaderVH) holder).bind((HeaderRow) row); @@ -244,15 +287,22 @@ static final class GroupVH extends RecyclerView.ViewHolder { private final MaterialCheckBox checkBox; private final TextView name; private final TextView meta; + private final ImageView chevron; private final SelectionController selection; + private final ContentManagerAdapter adapter; // owns the collapse state (read + toggle) private String boundApp; - GroupVH(Context ctx, SelectionController selection) { + GroupVH(Context ctx, SelectionController selection, ContentManagerAdapter adapter) { super(new LinearLayout(ctx)); this.selection = selection; + this.adapter = adapter; LinearLayout root = (LinearLayout) itemView; root.setOrientation(LinearLayout.HORIZONTAL); root.setGravity(Gravity.CENTER_VERTICAL); + // A category header: a filled tonal band (distinct in hue from the cream item cards) with + // title-scale text, so the group reads as a header that dominates its items. M3 tonal. + root.setBackgroundResource(R.drawable.k2go_group_header_bg); + root.setPadding(px(ctx, 12), px(ctx, 12), px(ctx, 12), px(ctx, 12)); root.setLayoutParams(fullWidth(px(ctx, 16), px(ctx, 8))); checkBox = new MaterialCheckBox(ctx); @@ -266,20 +316,39 @@ static final class GroupVH extends RecyclerView.ViewHolder { slotLp.rightMargin = px(ctx, 4); root.addView(slot, slotLp); - name = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_TitleMedium, R.color.k2go_ink); + name = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_TitleLarge, R.color.k2go_ink); + // Bold so the category title keeps the highest visual weight: an accent color would read + // lighter than the near-white item titles in dark, which is the opposite of what we want. 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); - - // User taps only: setCheckedState() during bind does not fire this (no OnCheckedChange - // listener), so a recycled header never toggles the model by itself. + meta = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodyMedium, R.color.k2go_muted); + LinearLayout.LayoutParams metaLp = new LinearLayout.LayoutParams(-2, -2); + metaLp.leftMargin = px(ctx, 8); + root.addView(meta, metaLp); + + // Accordion affordance: a chevron showing whether the group is collapsed; the whole header + // toggles it (see the root click below). Muted so the title stays the dominant element. + chevron = new ImageView(ctx); + chevron.setContentDescription(ctx.getString(R.string.k2go_cx_toggle_group)); + chevron.setColorFilter(ContextCompat.getColor(ctx, R.color.k2go_muted)); + LinearLayout.LayoutParams chLp = new LinearLayout.LayoutParams(px(ctx, 24), px(ctx, 24)); + chLp.leftMargin = px(ctx, 8); + root.addView(chevron, chLp); + + // Checkbox tap selects the whole group; its own listener consumes the tap, so it never + // reaches the row. A tap anywhere else on the header expands or collapses the group. + // setCheckedState() during bind fires no listener, so a recycled header stays inert. checkBox.setOnClickListener(v -> { if (boundApp != null) { this.selection.toggleGroup(boundApp); } }); + root.setOnClickListener(v -> { + if (boundApp != null) { + this.adapter.toggleCollapse(boundApp); + } + }); } void bind(GroupRow row) { @@ -294,6 +363,9 @@ void bind(GroupRow row) { : state == GroupSelection.SOME ? MaterialCheckBox.STATE_INDETERMINATE : MaterialCheckBox.STATE_UNCHECKED); + // Collapsed -> down chevron (more below); expanded -> up chevron (tap to close). + chevron.setImageResource(adapter.isCollapsed(row.app) + ? R.drawable.ic_expand_more : R.drawable.ic_expand_less); } } 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..88e97b0e0 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,46 @@ 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; + } + // Tear our own hotspot down the moment Receive starts: the sender's AP IP (always 192.168.49.1) + // collides with our own hotspot IP if we are hosting, which traps the connection locally. + // Stopping here lets the interface release while the user scans; ContentReceiveFragment also + // waits for the release before it connects. K2GO-376. + LocalHotspotManager.get().stop(); + 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..ee6c6519a --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentReceiveFragment.java @@ -0,0 +1,290 @@ +/* + * ============================================================================ + * 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.util.Log; +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.fragment.app.FragmentManager; + +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.hotspot.LocalHotspotManager; +import org.appdevforall.k2go.storage.StorageProbe; +import org.appdevforall.k2go.util.ByteFormatter; + +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.util.Collections; +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 -> prepareThenFetch()); + + appContext = requireContext().getApplicationContext(); + host = requireArguments().getString(ARG_HOST); + port = requireArguments().getInt(ARG_PORT); + token = requireArguments().getString(ARG_TOKEN); + manifestUrl = requireArguments().getString(ARG_MANIFEST); + + prepareThenFetch(); // stop our own hotspot (its AP IP collides with the sender), then fetch + return root; + } + + /** + * The sender's LocalOnlyHotspot AP IP is always 192.168.49.1. If THIS device is also hosting a + * hotspot, its own 192.168.49.1 (the p2p0 interface) makes the sender address a LOCAL address, so + * the kernel traps the connection on loopback (the local route beats any per-Network binding) and + * the receiver reaches itself instead of the sender ("Could not reach the sender"). Tear our own + * hotspot down and wait until the sender address is no longer one of our interfaces, then fetch. + * The hotspot stays off; only Share starts it again. K2GO-376. + */ + private void prepareThenFetch() { + showConnecting(); + LocalHotspotManager.get().stop(); // no-op if we are not hosting + waitHostRemoteThenFetch(0); + } + + /** Poll off the main thread until the sender address is no longer a local interface address, then + * fetch. Gives up after ~12s and fetches anyway (the Try-again button remains). */ + private void waitHostRemoteThenFetch(int attempt) { + worker.execute(() -> { + boolean local = isLocalAddress(host); + main.post(() -> { + if (!isAdded() || getView() == null) { + return; + } + if (!local || attempt >= 24) { + fetchManifest(); + } else { + main.postDelayed(() -> { + if (isAdded()) { + waitHostRemoteThenFetch(attempt + 1); + } + }, 500); + } + }); + }); + } + + /** True when {@code ip} is assigned to one of this device's own interfaces. Uses + * {@link NetworkInterface} (not ConnectivityManager), so it also sees a p2p0 hotspot AP that + * ConnectivityManager does not expose as a Network. */ + private static boolean isLocalAddress(String ip) { + try { + InetAddress target = InetAddress.getByName(ip); + for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) { + for (InetAddress a : Collections.list(ni.getInetAddresses())) { + if (a.equals(target)) { + return true; + } + } + } + } catch (Exception ignored) { + // On error, treat as not-local: the fetch will surface any reachability problem itself. + } + return false; + } + + /** 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) { + Log.w("IIAB-CxReceive", "manifest fetch failed host=" + host + " port=" + port + + " manifestUrl=" + manifestUrl, 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. Drop this transient receive screen's own back-stack + * entry first (it must not be re-shown on Finish), then show progress over the manager on a fresh + * entry : so Finish pops cleanly back to the manager with no orphaned fragment left overlapping it + * (K2GO-376), and the network path ends up with the same single manager->progress entry as the SAF + * path. Runs from a button tap, not inside a FragmentManager transaction, so the immediate pop is + * safe. + */ + private void showProgress() { + FragmentManager fm = requireActivity().getSupportFragmentManager(); + fm.popBackStackImmediate(); + fm.beginTransaction() + .replace(R.id.k2go_setup_host, new ImportProgressFragment()) + .addToBackStack(null) + .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/ContentShareFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentShareFragment.java index 3e4141f81..76c099dc8 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentShareFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentShareFragment.java @@ -22,12 +22,16 @@ import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; +import com.google.android.material.button.MaterialButtonToggleGroup; + import org.appdevforall.k2go.R; import org.appdevforall.k2go.contentexchange.data.ShareHandshake; import org.appdevforall.k2go.contentexchange.domain.ShareTransport; import org.appdevforall.k2go.hotspot.HotspotPermissions; import org.appdevforall.k2go.hotspot.LocalHotspotManager; +import org.appdevforall.k2go.hotspot.data.ApAddressResolver; import org.appdevforall.k2go.redesign.QrSection; +import org.appdevforall.k2go.sync.transport.NetworkStateLiveData; public class ContentShareFragment extends Fragment { @@ -38,6 +42,8 @@ public class ContentShareFragment extends Fragment { private View receiveRoot; private QrSection secJoin; private QrSection secReceive; + private TextView transportLabel; + private MaterialButtonToggleGroup transportToggle; private Button done; private final ShareSession session = ContentShareService.session(); @@ -46,6 +52,11 @@ public class ContentShareFragment extends Fragment { /** One-shot guard so a re-entrant render() does not schedule the back-pop twice (K2GO-427). */ private boolean leaving; + /** K2GO-376 transport selector: which address the receive QR carries when both exist. false = + * the hotspot AP IP (the default, fast + direct); true = the station Wi-Fi IP (both phones on + * the same network). Ignored when only one address is available. */ + private boolean useWifiAddress; + @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle s) { @@ -66,6 +77,20 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c ((TextView) receiveRoot.findViewById(R.id.sec_badge)).setText("2"); ((TextView) receiveRoot.findViewById(R.id.sec_title)).setText(R.string.k2go_cx_share_step_receive); + transportLabel = root.findViewById(R.id.k2go_cxs_transport_label); + transportToggle = root.findViewById(R.id.k2go_cxs_transport); + transportToggle.addOnButtonCheckedListener((group, checkedId, isChecked) -> { + if (!isChecked) { + return; // react only to the newly selected button, not the one being cleared + } + boolean wifi = checkedId == R.id.k2go_cxs_transport_wifi; + if (wifi == useWifiAddress) { + return; // no change (also absorbs the programmatic sync in renderInvite, no re-render loop) + } + useWifiAddress = wifi; + renderInvite(); // re-encode the receive QR at the chosen address + }); + done.setOnClickListener(v -> { ContentShareService.cancel(requireContext()); goBack(); @@ -73,6 +98,10 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c // The AP IPv4 lands a beat after the hotspot reports ON; re-render when it (or the phase) changes // so the receive QR appears the moment every piece is ready. Observed once, tied to the view. hs.state().observe(getViewLifecycleOwner(), st -> render()); + // K2GO-376: also re-render on any network change (Wi-Fi off/on gives a new DHCP IP), so the + // Wi-Fi-transport QR never advertises a stale station address. Same reactive trigger Connect and + // Clone use (ADFA-5064); renderInvite() re-resolves the station IP and redraws the QR. + NetworkStateLiveData.get(requireContext()).observe(getViewLifecycleOwner(), t -> render()); return root; } @@ -156,13 +185,36 @@ private void renderInvite() { sec.subCaption.setText(""); sec.setFallback(requireContext(), null); } + transportLabel.setVisibility(View.GONE); + transportToggle.setVisibility(View.GONE); waiting.setVisibility(View.GONE); return; } String ssid = st != null && st.ssid != null ? st.ssid : ""; String pass = st != null && st.passphrase != null ? st.passphrase : ""; - String ip = st != null ? st.hotspotIp : null; + String hotspotIp = st != null ? st.hotspotIp : null; + String wifiIp = ApAddressResolver.resolveStationWifiIp(requireContext()); + + // Transport selector: a choice only when BOTH addresses exist and differ. With one, use it and + // hide the toggle (the common case). The hotspot is the default (fast, direct); Wi-Fi lets two + // phones already on the same network pull over it, avoiding the Wi-Fi Direct link. When Wi-Fi is + // chosen there is nothing to join, so the join-hotspot section is hidden too. + boolean both = hotspotIp != null && wifiIp != null && !hotspotIp.equals(wifiIp); + transportLabel.setVisibility(both ? View.VISIBLE : View.GONE); + transportToggle.setVisibility(both ? View.VISIBLE : View.GONE); + // The selection persists across a Wi-Fi blip: on Wi-Fi loss the toggle just hides and the QR + // falls back to whatever address is left; when Wi-Fi returns (a new DHCP IP), the choice is + // still Wi-Fi and the QR redraws at the fresh address, instead of silently reverting to hotspot. + if (both) { + int want = useWifiAddress ? R.id.k2go_cxs_transport_wifi : R.id.k2go_cxs_transport_hotspot; + if (transportToggle.getCheckedButtonId() != want) { + transportToggle.check(want); // sync UI to the field; the listener no-ops (state matches) + } + } + joinRoot.setVisibility(both && useWifiAddress ? View.GONE : View.VISIBLE); + String ip = both ? (useWifiAddress ? wifiIp : hotspotIp) + : (hotspotIp != null ? hotspotIp : wifiIp); // Section 1: join the hotspot (standard Wi-Fi auto-join QR + the credentials as fallback). secJoin.setQr(requireContext(), "WIFI:S:" + ssid + ";T:WPA;P:" + pass + ";;", null); @@ -197,6 +249,8 @@ private void showStatus(String text) { secReceive.stopPending(); joinRoot.setVisibility(View.GONE); receiveRoot.setVisibility(View.GONE); + transportLabel.setVisibility(View.GONE); + transportToggle.setVisibility(View.GONE); waiting.setVisibility(View.GONE); } 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..cbc0cf8b5 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; @@ -68,10 +81,23 @@ void begin(ItemRef[] request, String[] titles, String[] entries, String[] payloa this.running = true; this.speed = 0L; this.etaSeconds = -1L; - job.begin(bytes != null ? bytes : new long[this.refs.length]); + // Single-phase: the receiver has one download phase per item (no box-prepare), so the per-item + // bar fills 0..100 from the bytes pulled, not the export two-phase bar (K2GO-376). + job.begin(bytes != null ? bytes : new long[this.refs.length], true); 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 +137,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 +171,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/hotspot/data/ApAddressResolver.java b/controller/app/src/main/java/org/appdevforall/k2go/hotspot/data/ApAddressResolver.java index f1f6ac6bf..dc0519aac 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/hotspot/data/ApAddressResolver.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/hotspot/data/ApAddressResolver.java @@ -43,6 +43,18 @@ public static String resolveOnce(Context ctx, String ifaceHint) { return ApAddress.pick(candidates, ifaceHint, wifiIp); } + /** + * This device's station Wi-Fi IPv4 (the Wi-Fi it is a client on), or null when it is not on Wi-Fi. + * K2GO-376: the Share address selector offers this as the alternative to the hotspot AP IP, so two + * peers already on the same Wi-Fi pull over it instead of the finicky Wi-Fi Direct link. Same + * producer as resolveOnce (one interface scan plus the framework source), so both addresses agree. + */ + public static String resolveStationWifiIp(Context ctx) { + List candidates = new ArrayList<>(NetworkInterfaces.candidates()); + candidates.addAll(linkPropertyCandidates(ctx)); + return NetworkInterfaces.stationWifiIp(candidates); + } + /** ConnectivityManager/LinkProperties candidates. Best-effort: any failure yields an empty list. */ private static List linkPropertyCandidates(Context ctx) { List out = new ArrayList<>(); 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/drawable/k2go_group_header_bg.xml b/controller/app/src/main/res/drawable/k2go_group_header_bg.xml new file mode 100644 index 000000000..ae9f85aa2 --- /dev/null +++ b/controller/app/src/main/res/drawable/k2go_group_header_bg.xml @@ -0,0 +1,9 @@ + + + + + + + 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..8574eb06b 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 @@ -1,10 +1,12 @@ + header block (title + subtitle + storage summary) and the per-app category headers are row types + in the same list; a category header is a tonal band that dominates its items and toggles them + (accordion). The entry actions (Import, Receive) and the selection action bar (Export / Share / + Delete) are pinned below the list, never inside the scroll, so content rows never hide them. --> @@ -20,22 +22,13 @@ android:textAppearance="?attr/textAppearanceBodyMedium" android:textColor="@color/k2go_teal" /> - -