diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java index e621c7ea1..6b50b6dab 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreDataSource.java @@ -3,11 +3,11 @@ * Name : CxCoreDataSource.java * Author : AppDevForAll * Copyright : Copyright (c) 2026 AppDevForAll - * Description : K2GO-427. App-side client of the content-exchange core (cx-core) + * Description : K2GO-427 / K2GO-507. App-side client of the content-exchange core (cx-core) * through dash-node's relay (/k2go-api/v1/*). Read side (list + storage) - * plus the export calls (plan + streaming item). Same HttpURLConnection - * shape as content/RestContentClient. The one place this feature touches - * HttpURLConnection. + * plus the export long operation (prepare / status / fetch / abort) and the + * import calls. Same HttpURLConnection shape as content/RestContentClient. The + * one place this feature touches HttpURLConnection. * ============================================================================ */ package org.appdevforall.k2go.contentexchange.data; @@ -40,6 +40,12 @@ public final class CxCoreDataSource { /** Delete blocks on the box's own delete (Kolibri deletechannel, Kiwix reindex), which can run * well past the read-side timeout, so it waits longer than a plain read. */ private static final int DELETE_READ_TIMEOUT_MS = 120000; + /** K2GO-507: the export fetch read timeout is a per-read (inactivity) gap, NOT a total wall + * clock. {@link HttpURLConnection#setReadTimeout} fires only when a single read blocks this + * long with no bytes, and it resets on every read, so a multi-GB staged tar can stream for + * minutes as long as bytes keep flowing; only a genuine stall trips it. The op is already + * staged when we fetch, so the response head returns fast. */ + private static final int FETCH_STALL_TIMEOUT_MS = 60000; /** {@code GET /v1/apps} -> {@code {"apps": [...]}}. */ public JSONObject getApps() throws Exception { @@ -81,24 +87,43 @@ public JSONObject deleteContent(String app, String localRef) throws Exception { } /** - * {@code GET /v1/export/item/{app}/{localRef}} -> the item's streaming archive. The core sends a - * chunked response with no Content-Length; the caller streams the body and closes the returned - * handle to release the connection. Path segments are percent-encoded (the core decodes them). + * {@code POST /v1/export/prepare} with {@code {app, localRef}} -> {@code {opId, state, totalBytes}}. + * Starts (or finds nothing to stage for) the export operation; returns fast. K2GO-507. */ - public Stream openExportItem(String app, String localRef) throws Exception { - String url = V1 + "/export/item/" + encodeSegment(app) + "/" + encodeSegment(localRef); + public JSONObject postExportPrepare(String app, String localRef) throws Exception { + JSONObject body = new JSONObject().put("app", app).put("localRef", localRef); + return postJson(V1 + "/export/prepare", body); + } + + /** + * {@code GET /v1/export/status/{opId}} -> {@code {state, stagedBytes, totalBytes, error?}}. A 404 + * means the op was swept; it surfaces as {@link CxHttpException} with {@code code() == 404} so the + * caller can re-prepare rather than keep polling a dead id. K2GO-507. + */ + public JSONObject getExportStatus(String opId) throws Exception { + return getJson(V1 + "/export/status/" + encodeSegment(opId)); + } + + /** + * {@code GET /v1/export/fetch/{opId}} -> the staged archive as a chunked stream. The op is already + * staged, so the response head returns fast; the body uses a per-read STALL timeout (see + * {@link #FETCH_STALL_TIMEOUT_MS}), not a wall clock. The caller streams the body and closes the + * returned handle to release the connection (the core clears the op on close). K2GO-507. + */ + public Stream openExportFetch(String opId) throws Exception { + String url = V1 + "/export/fetch/" + encodeSegment(opId); HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection(); try { c.setUseCaches(false); c.setConnectTimeout(CONNECT_TIMEOUT_MS); - c.setReadTimeout(READ_TIMEOUT_MS); + c.setReadTimeout(FETCH_STALL_TIMEOUT_MS); c.setRequestMethod("GET"); c.setRequestProperty("Accept", "application/octet-stream"); int code = c.getResponseCode(); if (code < 200 || code >= 400) { String text = readAll(c.getErrorStream()); c.disconnect(); - throw new Exception("HTTP " + code + ": " + text); + throw new CxHttpException(code, text); } String filename = parseContentDispositionFilename(c.getHeaderField("Content-Disposition")); return new Stream(c, c.getInputStream(), filename); @@ -108,6 +133,11 @@ public Stream openExportItem(String app, String localRef) throws Exception { } } + /** {@code DELETE /v1/export/{opId}} -> {@code {ok}}. Client abort of an in-flight op. K2GO-507. */ + public JSONObject deleteExportOp(String opId) throws Exception { + return deleteJson(V1 + "/export/" + encodeSegment(opId)); + } + private static JSONObject postJson(String urlStr, JSONObject body) throws Exception { HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection(); try { @@ -126,7 +156,7 @@ private static JSONObject postJson(String urlStr, JSONObject body) throws Except boolean ok = code >= 200 && code < 400; String text = readAll(ok ? c.getInputStream() : c.getErrorStream()); if (!ok) { - throw new Exception("HTTP " + code + ": " + text); + throw new CxHttpException(code, text); } return new JSONObject(text.isEmpty() ? "{}" : text); } finally { @@ -146,7 +176,7 @@ private static JSONObject deleteJson(String urlStr) throws Exception { boolean ok = code >= 200 && code < 400; String text = readAll(ok ? c.getInputStream() : c.getErrorStream()); if (!ok) { - throw new Exception("HTTP " + code + ": " + text); + throw new CxHttpException(code, text); } return new JSONObject(text.isEmpty() ? "{}" : text); } finally { @@ -166,7 +196,7 @@ private static JSONObject getJson(String urlStr) throws Exception { boolean ok = code >= 200 && code < 400; String text = readAll(ok ? c.getInputStream() : c.getErrorStream()); if (!ok) { - throw new Exception("HTTP " + code + ": " + text); + throw new CxHttpException(code, text); } return new JSONObject(text.isEmpty() ? "{}" : text); } finally { @@ -215,6 +245,24 @@ private static String parseContentDispositionFilename(String header) { return semi >= 0 ? value.substring(0, semi).trim() : value; } + /** + * A non-2xx/3xx HTTP response, carrying the status code so a caller can branch on it: the export + * status poll treats {@code code() == 404} as "operation swept" and re-prepares. Extends + * {@link Exception}, so callers that only {@code catch (Exception)} keep working. K2GO-507. + */ + public static final class CxHttpException extends Exception { + private final int code; + + CxHttpException(int code, String message) { + super("HTTP " + code + ": " + message); + this.code = code; + } + + public int code() { + return code; + } + } + /** A live streaming response: the body plus the server-suggested name. Close to release the socket. */ public static final class Stream implements Closeable { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreExportSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreExportSource.java index 629c9f546..06a6acbc7 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreExportSource.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/CxCoreExportSource.java @@ -3,9 +3,9 @@ * Name : CxCoreExportSource.java * Author : AppDevForAll * Copyright : Copyright (c) 2026 AppDevForAll - * Description : K2GO-427. Data-layer implementation of the export source port against - * cx-core (through dash-node's /v1 relay): POST /v1/export/plan, the - * streaming GET /v1/export/item, and the collection-manifest assembly. + * Description : K2GO-427 / K2GO-507. Data-layer implementation of the export source port against + * cx-core (through dash-node's /v1 relay): POST /v1/export/plan, the export long + * operation (prepare / status / fetch / abort), and the collection-manifest assembly. * ============================================================================ */ package org.appdevforall.k2go.contentexchange.data; @@ -13,6 +13,8 @@ import org.appdevforall.k2go.contentexchange.domain.ContentExportSource; import org.appdevforall.k2go.contentexchange.domain.ExportItem; import org.appdevforall.k2go.contentexchange.domain.ExportPlan; +import org.appdevforall.k2go.contentexchange.domain.ExportPrep; +import org.appdevforall.k2go.contentexchange.domain.ExportStatus; import org.appdevforall.k2go.contentexchange.domain.ItemRef; import org.json.JSONArray; import org.json.JSONObject; @@ -93,11 +95,61 @@ public ExportPlan plan(List refs) throws Exception { } @Override - public ItemPayload open(ItemRef ref) throws Exception { - CxCoreDataSource.Stream stream = dataSource.openExportItem(ref.app(), ref.localRef()); + public ExportPrep prepare(ItemRef ref) throws Exception { + JSONObject r = dataSource.postExportPrepare(ref.app(), ref.localRef()); + String opId = r.optString("opId", ""); + if (opId.isEmpty()) { + throw new Exception("export prepare returned no opId"); + } + boolean ready = "ready".equals(r.optString("state", "")); + return new ExportPrep(opId, ready, r.optLong("totalBytes", 0L)); + } + + @Override + public ExportStatus status(String opId) throws Exception { + JSONObject r; + try { + r = dataSource.getExportStatus(opId); + } catch (CxCoreDataSource.CxHttpException e) { + if (e.code() == 404) { + return ExportStatus.gone(); // the op was swept: the caller re-prepares + } + throw e; + } + ExportStatus.State state; + switch (r.optString("state", "")) { + case "ready": + state = ExportStatus.State.READY; + break; + case "error": + state = ExportStatus.State.ERROR; + break; + default: + state = ExportStatus.State.STAGING; + break; + } + String error = r.isNull("error") ? null : r.optString("error", null); + return new ExportStatus(state, r.optLong("stagedBytes", 0L), r.optLong("totalBytes", 0L), error); + } + + @Override + public ItemPayload fetch(String opId) throws Exception { + CxCoreDataSource.Stream stream = dataSource.openExportFetch(opId); return new ItemPayload(stream.body(), stream.filename(), stream); } + @Override + public void abort(String opId) { + if (opId == null || opId.isEmpty()) { + return; + } + try { + dataSource.deleteExportOp(opId); + } catch (Exception ignored) { + // Best-effort: a swept or already-dropped op 404s; the box's TTL sweep is the backstop. + } + } + @Override public byte[] buildManifest(List order, Map payloadNames) throws Exception { return CollectionManifest.build(entries, order, payloadNames); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentExportSource.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentExportSource.java index d1e2fd198..9e1bdb7a6 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentExportSource.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ContentExportSource.java @@ -7,10 +7,17 @@ import java.util.Map; /** - * Domain port for the BOX side of an export: plan the items, stream one item's archive, and - * build the collection manifest. The Data layer implements it against the core REST API - * (through dash-node's {@code /v1/*} relay); the domain never learns the transport or the - * JSON shape. + * Domain port for the BOX side of an export: plan the items, run the per-item staging long + * operation (prepare, poll, fetch), and build the collection manifest. The Data layer implements + * it against the core REST API (through dash-node's {@code /v1/*} relay); the domain never learns + * the transport or the JSON shape. + * + *

K2GO-507: a large item (a multi-GB Kolibri channel) is staged on the box before any byte + * streams, so a single blocking request times out. The export is therefore a long operation: the + * caller {@link #prepare}s an item, {@link #status}-polls while the box stages it (the poll is the + * liveness signal, so there is no wall-clock timeout), then {@link #fetch}es the staged stream. + * {@link #abort} drops an operation the caller gives up on. The box owns the operation state; the + * caller only mirrors it, so there is no competing "where is this export" on the app side. * *

The manifest is built here rather than in the carrier because the source holds the * authoritative per-item entries the plan returned (identity, dedup, integrity); the carrier @@ -24,8 +31,17 @@ public interface ContentExportSource { /** Plan the given items: exact sizes + skip list, moving no payload. */ ExportPlan plan(List refs) throws Exception; - /** Open the streaming archive for one item. The caller copies the stream, then closes it. */ - ItemPayload open(ItemRef ref) throws Exception; + /** Start staging one item on the box: returns the operation id and whether it is already ready. */ + ExportPrep prepare(ItemRef ref) throws Exception; + + /** One status reading of a staging operation. A swept operation reports {@code GONE}. */ + ExportStatus status(String opId) throws Exception; + + /** Open the staged stream for a ready operation. The caller copies the stream, then closes it. */ + ItemPayload fetch(String opId) throws Exception; + + /** Best-effort drop of an operation the caller abandons (cancel or error). Never throws. */ + void abort(String opId); /** * Build the top-level {@code manifest.json} over the items that were written, in the given 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 028cac4cc..cadf48aaa 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 @@ -16,9 +16,19 @@ public final class ExportJob { public static final int DONE = 2; public static final int FAILED = 3; + /** K2GO-507: the two phases of an active item's progress bar. The box stages the item + * ({@link #PHASE_PREPARE}, fed by stagedBytes) before it streams ({@link #PHASE_WRITE}, fed by + * copiedBytes). The bar maps prepare to 0..50 percent and write to 50..100 percent. */ + public static final int PHASE_PREPARE = 0; + public static final int PHASE_WRITE = 1; + private int[] status = new int[0]; private long[] planned = new long[0]; private long[] copied = new long[0]; + /** K2GO-507: per-item phase and bytes staged so far. These mirror the box's op status (the single + * source of truth); the job never stores a competing "where is this export", it projects the poll. */ + private int[] phase = new int[0]; + private long[] staged = new long[0]; private int index = -1; /** @@ -30,6 +40,8 @@ public void begin(long[] plannedBytes) { status = new int[n]; planned = new long[n]; copied = new long[n]; + phase = new int[n]; + staged = new long[n]; index = -1; for (int i = 0; i < n; i++) { if (plannedBytes[i] < 0) { @@ -75,10 +87,35 @@ public void setActive(int i) { if (i >= 0 && i < status.length) { status[i] = ACTIVE; copied[i] = 0L; + // An item starts in the prepare phase: the box stages it before it streams (K2GO-507). + phase[i] = PHASE_PREPARE; + staged[i] = 0L; index = i; } } + public int phase(int i) { + return i >= 0 && i < phase.length ? phase[i] : PHASE_WRITE; + } + + /** Move the active item from staging to streaming (prepare -> write). */ + public void setPhase(int i, int newPhase) { + if (i >= 0 && i < phase.length) { + phase[i] = newPhase; + } + } + + public long staged(int i) { + return i >= 0 && i < staged.length ? staged[i] : 0L; + } + + /** Record the absolute bytes staged so far on the box for item {@code i} (prepare-phase progress). */ + public void setStaged(int i, long bytes) { + if (i >= 0 && i < staged.length) { + staged[i] = Math.max(0L, bytes); + } + } + /** Record the absolute bytes written so far for item {@code i}. */ public void setCopied(int i, long bytes) { if (i >= 0 && i < copied.length) { @@ -199,12 +236,28 @@ public int overallPercent() { return (int) Math.min(100L, (long) settled * 100L / n); } - /** Percent of the active item written so far (0 when its size is unknown). */ + /** + * The active item's two-phase bar value (K2GO-507): the prepare phase fills 0..50 from stagedBytes, + * the write phase fills 50..100 from copiedBytes, both against the item's planned size. Returns 0 + * when no item is active; when the size is unknown the prepare phase reads 0 and the write phase + * reads 50 (the bar still advances by phase, it just cannot show a within-phase fraction). + */ public int currentItemPercent() { int i = index; - if (i < 0 || i >= planned.length || planned[i] <= 0) { + if (i < 0 || i >= planned.length) { + return 0; + } + if (phase[i] == PHASE_PREPARE) { + return half(staged[i], planned[i]); // 0..50 + } + return 50 + half(copied[i], planned[i]); // 50..100 + } + + /** {@code done/total} scaled into 0..50, or 0 when the total is unknown. */ + private static int half(long done, long total) { + if (total <= 0) { return 0; } - return (int) Math.min(100L, copied[i] * 100L / planned[i]); + return (int) Math.min(50L, done * 50L / total); } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportPrep.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportPrep.java new file mode 100644 index 000000000..d071c25d3 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportPrep.java @@ -0,0 +1,43 @@ +/* + * ============================================================================ + * Name : ExportPrep.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-507. The result of preparing one export item: the long-operation id + * plus whether the box already has it staged. Pure value, no Android or JSON. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * The outcome of {@link ContentExportSource#prepare}: the box allocated an export operation and + * either started staging it ({@code ready == false}) or has it available to fetch at once + * ({@code ready == true}, e.g. a direct stream with nothing to stage). + */ +public final class ExportPrep { + + private final String opId; + private final boolean ready; + private final long totalBytes; + + public ExportPrep(String opId, boolean ready, long totalBytes) { + this.opId = opId != null ? opId : ""; + this.ready = ready; + this.totalBytes = Math.max(0L, totalBytes); + } + + /** The operation id to poll ({@link ContentExportSource#status}) and fetch. */ + public String opId() { + return opId; + } + + /** True when the item needs no staging and can be fetched immediately. */ + public boolean ready() { + return ready; + } + + /** The item's total size in bytes, as the box reports it (0 when unknown). */ + public long totalBytes() { + return totalBytes; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportStatus.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportStatus.java new file mode 100644 index 000000000..bcdc9cf65 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportStatus.java @@ -0,0 +1,58 @@ +/* + * ============================================================================ + * Name : ExportStatus.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-507. One poll of an export operation's staging progress on the box. + * Pure value, no Android or JSON: the Data layer maps the REST status to this. + * ============================================================================ + */ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * A single status reading for an in-flight export operation. {@code stagedBytes} is both the + * prepare-phase progress and the liveness heartbeat: it grows while the box stages the item. + * + *

{@link State#GONE} marks an operation the box no longer knows (its registry entry was swept), + * which tells the caller to re-prepare rather than keep polling a dead id. + */ +public final class ExportStatus { + + public enum State { STAGING, READY, ERROR, GONE } + + private final State state; + private final long stagedBytes; + private final long totalBytes; + private final String error; + + public ExportStatus(State state, long stagedBytes, long totalBytes, String error) { + this.state = state != null ? state : State.ERROR; + this.stagedBytes = Math.max(0L, stagedBytes); + this.totalBytes = Math.max(0L, totalBytes); + this.error = error; + } + + /** The operation was swept and is unknown to the box: the caller re-prepares. */ + public static ExportStatus gone() { + return new ExportStatus(State.GONE, 0L, 0L, null); + } + + public State state() { + return state; + } + + /** Bytes staged so far (the prepare-phase progress and the liveness signal). */ + public long stagedBytes() { + return stagedBytes; + } + + /** The item's total size in bytes (0 when unknown). */ + public long totalBytes() { + return totalBytes; + } + + /** The failure detail when {@link #state} is {@link State#ERROR}, else null. */ + public String error() { + return error; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java index d4c97ae9e..42aad3243 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java @@ -39,6 +39,8 @@ import org.appdevforall.k2go.contentexchange.domain.ExportFilenames; import org.appdevforall.k2go.contentexchange.domain.ExportJob; import org.appdevforall.k2go.contentexchange.domain.ExportPlan; +import org.appdevforall.k2go.contentexchange.domain.ExportPrep; +import org.appdevforall.k2go.contentexchange.domain.ExportStatus; import org.appdevforall.k2go.contentexchange.domain.ItemRef; import org.appdevforall.k2go.notifications.NotificationIds; @@ -69,6 +71,11 @@ public final class ContentExportService extends Service { private static final int COPY_BUFFER = 64 * 1024; private static final long PUBLISH_INTERVAL_MS = 250L; private static final long NOTIFY_INTERVAL_MS = 1000L; + /** K2GO-507: gap between export-staging status polls (mirrors content/RestContentClient). */ + private static final long POLL_INTERVAL_MS = 1000L; + /** K2GO-507: consecutive status-poll failures tolerated before an item fails. A staging run lasts + * minutes, so one relay blip or a busy core must not discard it (mirrors RestContentClient). */ + private static final int MAX_POLL_ERRORS = 10; /** The single run state the progress fragment observes. */ private static final ExportSession SESSION = new ExportSession(); @@ -244,15 +251,27 @@ private void drain(boolean fresh) { SESSION.publish(); notifyNow(); - try (ContentExportSource.ItemPayload payload = source.open(ref)) { - String name = ExportFilenames.forItem(SESSION.label(i), payload.filename(), ref, used); - // Write into the item's per-app subfolder; the sink reports the stored path - // ("app/name"), which becomes the manifest payload. - ExportCarrier.PayloadSink sink = carrier.openPayload(ref.app(), name); - SESSION.setPayloadName(i, sink.name()); - copy(payload.stream(), sink.stream(), i, job, runStart); + String opId = null; + try { + // Prepare phase (K2GO-507): ask the box to stage the item and poll until it is ready. + // The poll feeds the prepare-half bar and IS the liveness signal, so there is no + // wall-clock timeout; only the later fetch has a per-read stall timeout. + opId = stage(source, ref, i, job); + // Write phase: fetch the staged stream and copy it to the drive. + job.setPhase(i, ExportJob.PHASE_WRITE); + SESSION.publish(); + try (ContentExportSource.ItemPayload payload = source.fetch(opId)) { + String name = ExportFilenames.forItem(SESSION.label(i), payload.filename(), ref, used); + // Write into the item's per-app subfolder; the sink reports the stored path + // ("app/name"), which becomes the manifest payload. + ExportCarrier.PayloadSink sink = carrier.openPayload(ref.app(), name); + SESSION.setPayloadName(i, sink.name()); + copy(payload.stream(), sink.stream(), i, job, runStart); + } + // The core clears the op when the fetch stream closes, so the happy path does not abort. job.setDone(i); } catch (IOException e) { + source.abort(opId); // no-op when opId is null or the op is already dropped job.setFailed(i); SESSION.publish(); if (isNoSpace(e)) { @@ -262,6 +281,7 @@ private void drain(boolean fresh) { } continue; // a per-item failure: skip it, keep going } catch (Exception e) { + source.abort(opId); job.setFailed(i); SESSION.publish(); continue; @@ -333,6 +353,93 @@ private void copy(InputStream in, OutputStream out, int i, ExportJob job, long r } } + /** + * Prepare one item and poll the box until it is staged, feeding the prepare-half bar from the + * staged byte count. Returns the opId to fetch. The poll is the liveness signal (K2GO-507): a slow + * multi-GB stage keeps the operation alive as long as its byte count grows, so there is no + * wall-clock timeout here. A swept operation (status 404 -> {@code GONE}) triggers exactly one + * re-prepare; a second sweep fails the item. Cancellation and a box staging error abort the + * operation here before throwing, so the caller does not double-abort (its opId is still null). + */ + private String stage(ContentExportSource source, ItemRef ref, int i, ExportJob job) throws Exception { + ExportPrep prep = source.prepare(ref); + String opId = prep.opId(); + if (prep.ready()) { + return opId; // nothing to stage: Kiwix/Calibre stream directly + } + boolean reprepared = false; + boolean handedOff = false; // true once a READY op is returned: the fetch owns it from then on + int pollErrors = 0; + try { + while (true) { + if (SESSION.isCancelled()) { + throw new IOException("cancelled"); + } + sleepPoll(); + if (SESSION.isCancelled()) { + throw new IOException("cancelled"); + } + ExportStatus st; + try { + st = source.status(opId); + } catch (Exception e) { + // A swept op returns GONE (handled below), not an exception; this is a transient + // poll failure (relay blip, busy core). Keep the same op and retry, up to the blip + // budget, so a staging run of several minutes is not lost to one hiccup. + if (++pollErrors > MAX_POLL_ERRORS) { + throw e; + } + continue; + } + pollErrors = 0; + switch (st.state()) { + case READY: + handedOff = true; + return opId; + case ERROR: + throw new Exception(st.error() != null && !st.error().isEmpty() + ? st.error() : "the box could not stage this item"); + case GONE: + // The op was swept (e.g. a core restart). Re-prepare once; a second loss fails it. + if (reprepared) { + throw new Exception("the export operation was lost"); + } + reprepared = true; + prep = source.prepare(ref); + opId = prep.opId(); + if (prep.ready()) { + handedOff = true; + return opId; + } + break; + case STAGING: + default: + job.setStaged(i, st.stagedBytes()); + SESSION.publish(); + maybeNotify(SystemClock.elapsedRealtime()); + break; + } + } + } finally { + // stage() owns the op until it hands a READY one to the fetch. On any abnormal exit (cancel, + // box staging error, poll-budget exhaustion, worker interrupt) abort the current op so a live + // multi-GB stage is not left running on the box until its TTL sweep. A GONE op is already + // swept, so the abort is a harmless no-op. + if (!handedOff) { + source.abort(opId); + } + } + } + + private static void sleepPoll() throws IOException { + try { + Thread.sleep(POLL_INTERVAL_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("interrupted"); // worker shutdown: end the item + } + } + private void writeManifest(ContentExportSource source, ExportCarrier carrier, ExportJob job) { List order = new ArrayList<>(); Map names = new HashMap<>(); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java index 90b03eacc..7f266a45c 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java @@ -133,7 +133,12 @@ private void renderCurrentItem(boolean running, boolean preparing) { if (running && !preparing && i >= 0) { itemLabel.setVisibility(View.VISIBLE); itemBar.setVisibility(View.VISIBLE); - itemLabel.setText(session.label(i)); + // K2GO-507: during the prepare half the box is staging the item (it has not started + // streaming yet), so name that so the slow first half of the bar reads as staging. + String title = session.label(i); + itemLabel.setText(session.currentItemPhase() == ExportJob.PHASE_PREPARE + ? getString(R.string.k2go_cx_export_item_preparing_fmt, title) + : title); itemBar.setProgressCompat(session.currentItemPercent(), true); } else { itemLabel.setVisibility(View.GONE); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java index 584206ee2..cb7d0ab48 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java @@ -240,6 +240,11 @@ int currentItemPercent() { return job.currentItemPercent(); } + /** The active item's phase (prepare or write) so the UI can label the staging half. K2GO-507. */ + int currentItemPhase() { + return job.phase(job.index()); + } + /** One per-app progress row (a category), in the order the apps first appear in the request. */ static final class Category { final String app; diff --git a/controller/app/src/main/res/values-ar/strings.xml b/controller/app/src/main/res/values-ar/strings.xml index 55e4a7f9d..8b86731c0 100644 --- a/controller/app/src/main/res/values-ar/strings.xml +++ b/controller/app/src/main/res/values-ar/strings.xml @@ -1447,6 +1447,8 @@ تصدير المحتوى إلى: %1$s جارٍ تحضير التصدير... + جارٍ تحضير %1$s... + %1$s: %2$d%% الإجمالي: %1$d%% متبقٍ %1$s تصدير %1$d عنصر (%2$s) إلى محرك الأقراص المحدد؟ diff --git a/controller/app/src/main/res/values-az/strings.xml b/controller/app/src/main/res/values-az/strings.xml index 041309f6d..24fb37996 100644 --- a/controller/app/src/main/res/values-az/strings.xml +++ b/controller/app/src/main/res/values-az/strings.xml @@ -1467,6 +1467,8 @@ Məzmunu ixrac et Hara: %1$s İxrac hazırlanır... + %1$s hazırlanır... + %1$s: %2$d%% Ümumi: %1$d%% %1$s qalıb %1$d element (%2$s) seçilmiş diskə ixrac edilsin? diff --git a/controller/app/src/main/res/values-bg/strings.xml b/controller/app/src/main/res/values-bg/strings.xml index 5e3f53d9e..f8a46b7e1 100644 --- a/controller/app/src/main/res/values-bg/strings.xml +++ b/controller/app/src/main/res/values-bg/strings.xml @@ -1454,6 +1454,8 @@ Експорт на съдържание Към: %1$s Подготовка на експорта... + Подготовка на %1$s... + %1$s: %2$d%% Общо: %1$d%% Остават %1$s Да се експортират ли %1$d елемента (%2$s) на избрания диск? diff --git a/controller/app/src/main/res/values-bn/strings.xml b/controller/app/src/main/res/values-bn/strings.xml index 7e90cf1c2..7d9b7586d 100644 --- a/controller/app/src/main/res/values-bn/strings.xml +++ b/controller/app/src/main/res/values-bn/strings.xml @@ -1460,6 +1460,8 @@ কনটেন্ট রপ্তানি করুন এখানে: %1$s রপ্তানি প্রস্তুত হচ্ছে... + %1$s প্রস্তুত হচ্ছে... + %1$s: %2$d%% মোট: %1$d%% %1$s বাকি %1$d আইটেম (%2$s) নির্বাচিত ড্রাইভে রপ্তানি করবেন? diff --git a/controller/app/src/main/res/values-cs/strings.xml b/controller/app/src/main/res/values-cs/strings.xml index 87bdf7701..3b4d36ef2 100644 --- a/controller/app/src/main/res/values-cs/strings.xml +++ b/controller/app/src/main/res/values-cs/strings.xml @@ -1454,6 +1454,8 @@ Exportovat obsah Do: %1$s Příprava exportu... + Příprava %1$s... + %1$s: %2$d%% Celkem: %1$d%% Zbývá %1$s Exportovat %1$d položek (%2$s) na vybraný disk? diff --git a/controller/app/src/main/res/values-de/strings.xml b/controller/app/src/main/res/values-de/strings.xml index 1486e2419..cc86f67e7 100644 --- a/controller/app/src/main/res/values-de/strings.xml +++ b/controller/app/src/main/res/values-de/strings.xml @@ -1447,6 +1447,8 @@ Inhalte exportieren Nach: %1$s Export wird vorbereitet... + %1$s wird vorbereitet... + %1$s: %2$d%% Gesamt: %1$d%% %1$s verbleibend %1$d Elemente (%2$s) auf das ausgewählte Laufwerk exportieren? diff --git a/controller/app/src/main/res/values-el/strings.xml b/controller/app/src/main/res/values-el/strings.xml index 74333d515..8fa4f5c3b 100644 --- a/controller/app/src/main/res/values-el/strings.xml +++ b/controller/app/src/main/res/values-el/strings.xml @@ -1454,6 +1454,8 @@ Εξαγωγή περιεχομένου Προς: %1$s Προετοιμασία εξαγωγής... + Προετοιμασία %1$s... + %1$s: %2$d%% Συνολικά: %1$d%% Απομένουν %1$s Εξαγωγή %1$d στοιχείων (%2$s) στην επιλεγμένη μονάδα δίσκου; diff --git a/controller/app/src/main/res/values-es/strings.xml b/controller/app/src/main/res/values-es/strings.xml index 789af6a92..6f76b8ebd 100644 --- a/controller/app/src/main/res/values-es/strings.xml +++ b/controller/app/src/main/res/values-es/strings.xml @@ -1523,6 +1523,8 @@ Exportar contenido A: %1$s Preparando la exportación... + Preparando %1$s... + %1$s: %2$d%% Total: %1$d%% Queda %1$s ¿Exportar %1$d elementos (%2$s) a la unidad seleccionada? diff --git a/controller/app/src/main/res/values-fa/strings.xml b/controller/app/src/main/res/values-fa/strings.xml index 5c8bb8a3c..47f7c73c9 100644 --- a/controller/app/src/main/res/values-fa/strings.xml +++ b/controller/app/src/main/res/values-fa/strings.xml @@ -1447,6 +1447,8 @@ صادر کردن محتوا به: %1$s در حال آماده‌سازی خروجی... + در حال آماده‌سازی %1$s... + %1$s: %2$d%% کلی: %1$d%% %1$s باقی‌مانده %1$d مورد (%2$s) به درایو انتخاب‌شده صادر شود؟ diff --git a/controller/app/src/main/res/values-fr/strings.xml b/controller/app/src/main/res/values-fr/strings.xml index 4f7c9f57a..152e7c460 100644 --- a/controller/app/src/main/res/values-fr/strings.xml +++ b/controller/app/src/main/res/values-fr/strings.xml @@ -1534,6 +1534,8 @@ Exporter le contenu Vers : %1$s Préparation de l\'export... + Préparation de %1$s... + %1$s: %2$d%% Total : %1$d%% %1$s restant Exporter %1$d éléments (%2$s) vers le lecteur sélectionné ? diff --git a/controller/app/src/main/res/values-gu/strings.xml b/controller/app/src/main/res/values-gu/strings.xml index 807c86b4c..9d26c5f48 100644 --- a/controller/app/src/main/res/values-gu/strings.xml +++ b/controller/app/src/main/res/values-gu/strings.xml @@ -1460,6 +1460,8 @@ કન્ટેન્ટ નિકાસ કરો અહીં: %1$s નિકાસ તૈયાર થઈ રહી છે... + %1$s તઈયાર થઈ રહી છે... + %1$s: %2$d%% કુલ: %1$d%% %1$s બાકી %1$d આઇટમ (%2$s) પસંદ કરેલ ડ્રાઇવ પર નિકાસ કરવી? diff --git a/controller/app/src/main/res/values-hi/strings.xml b/controller/app/src/main/res/values-hi/strings.xml index da9a63a20..ac5a8182e 100644 --- a/controller/app/src/main/res/values-hi/strings.xml +++ b/controller/app/src/main/res/values-hi/strings.xml @@ -1524,6 +1524,8 @@ कंटेंट निर्यात करें यहाँ: %1$s निर्यात तैयार हो रहा है... + %1$s तैयार हो रहा है... + %1$s: %2$d%% कुल: %1$d%% %1$s शेष %1$d आइटम (%2$s) चयनित ड्राइव पर निर्यात करें? diff --git a/controller/app/src/main/res/values-hu/strings.xml b/controller/app/src/main/res/values-hu/strings.xml index d3fedc6a1..6468d751a 100644 --- a/controller/app/src/main/res/values-hu/strings.xml +++ b/controller/app/src/main/res/values-hu/strings.xml @@ -1447,6 +1447,8 @@ Tartalom exportálása Ide: %1$s Exportálás előkészítése... + %1$s előkészítése... + %1$s: %2$d%% Összesen: %1$d%% %1$s van hátra Exportál %1$d elemet (%2$s) a kiválasztott meghajtóra? diff --git a/controller/app/src/main/res/values-in/strings.xml b/controller/app/src/main/res/values-in/strings.xml index c17b3aab8..87a592599 100644 --- a/controller/app/src/main/res/values-in/strings.xml +++ b/controller/app/src/main/res/values-in/strings.xml @@ -1454,6 +1454,8 @@ Ekspor konten Ke: %1$s Menyiapkan ekspor... + Menyiapkan %1$s... + %1$s: %2$d%% Total: %1$d%% %1$s tersisa Ekspor %1$d item (%2$s) ke drive yang dipilih? diff --git a/controller/app/src/main/res/values-it/strings.xml b/controller/app/src/main/res/values-it/strings.xml index 386fb92fc..7a79ff076 100644 --- a/controller/app/src/main/res/values-it/strings.xml +++ b/controller/app/src/main/res/values-it/strings.xml @@ -1447,6 +1447,8 @@ Esporta contenuti In: %1$s Preparazione dell\'esportazione... + Preparazione di %1$s... + %1$s: %2$d%% Totale: %1$d%% %1$s rimanenti Esportare %1$d elementi (%2$s) sull\'unità selezionata? diff --git a/controller/app/src/main/res/values-ja/strings.xml b/controller/app/src/main/res/values-ja/strings.xml index 39ae74065..9c900ac3b 100644 --- a/controller/app/src/main/res/values-ja/strings.xml +++ b/controller/app/src/main/res/values-ja/strings.xml @@ -1448,6 +1448,8 @@ コンテンツをエクスポート 宛先: %1$s エクスポートを準備中... + %1$s を準備中... + %1$s: %2$d%% 全体: %1$d%% 残り %1$s %1$d 項目(%2$s)を選択したドライブにエクスポートしますか? diff --git a/controller/app/src/main/res/values-ko/strings.xml b/controller/app/src/main/res/values-ko/strings.xml index 4ae87ee28..0df61d04d 100644 --- a/controller/app/src/main/res/values-ko/strings.xml +++ b/controller/app/src/main/res/values-ko/strings.xml @@ -1448,6 +1448,8 @@ 콘텐츠 내보내기 대상: %1$s 내보내기를 준비하는 중... + %1$s 준비 중... + %1$s: %2$d%% 전체: %1$d%% %1$s 남음 %1$d개 항목(%2$s)을 선택한 드라이브로 내보내시겠습니까? diff --git a/controller/app/src/main/res/values-lt/strings.xml b/controller/app/src/main/res/values-lt/strings.xml index 35eaab6f2..d43eae207 100644 --- a/controller/app/src/main/res/values-lt/strings.xml +++ b/controller/app/src/main/res/values-lt/strings.xml @@ -1464,6 +1464,8 @@ Eksportuoti turinį Į: %1$s Ruošiamas eksportas... + Ruošiama %1$s... + %1$s: %2$d%% Iš viso: %1$d%% Liko %1$s Eksportuoti %1$d elementų (%2$s) į pasirinktą diską? diff --git a/controller/app/src/main/res/values-nl/strings.xml b/controller/app/src/main/res/values-nl/strings.xml index 7e1042236..6f501995a 100644 --- a/controller/app/src/main/res/values-nl/strings.xml +++ b/controller/app/src/main/res/values-nl/strings.xml @@ -1447,6 +1447,8 @@ Inhoud exporteren Naar: %1$s Export voorbereiden... + %1$s voorbereiden... + %1$s: %2$d%% Totaal: %1$d%% %1$s resterend %1$d items (%2$s) naar het geselecteerde station exporteren? diff --git a/controller/app/src/main/res/values-no/strings.xml b/controller/app/src/main/res/values-no/strings.xml index 0ee036d61..e3a31d8a6 100644 --- a/controller/app/src/main/res/values-no/strings.xml +++ b/controller/app/src/main/res/values-no/strings.xml @@ -1457,6 +1457,8 @@ Eksporter innhold Til: %1$s Forbereder eksport... + Forbereder %1$s... + %1$s: %2$d%% Totalt: %1$d%% %1$s igjen Eksportere %1$d elementer (%2$s) til den valgte stasjonen? diff --git a/controller/app/src/main/res/values-pl/strings.xml b/controller/app/src/main/res/values-pl/strings.xml index eb4c80cc0..47af975ec 100644 --- a/controller/app/src/main/res/values-pl/strings.xml +++ b/controller/app/src/main/res/values-pl/strings.xml @@ -1457,6 +1457,8 @@ Eksportuj treści Do: %1$s Przygotowywanie eksportu... + Przygotowywanie %1$s... + %1$s: %2$d%% Łącznie: %1$d%% Pozostało %1$s Wyeksportować %1$d elementów (%2$s) na wybrany dysk? diff --git a/controller/app/src/main/res/values-pt/strings.xml b/controller/app/src/main/res/values-pt/strings.xml index eb9acdf68..b2f5087b2 100644 --- a/controller/app/src/main/res/values-pt/strings.xml +++ b/controller/app/src/main/res/values-pt/strings.xml @@ -1526,6 +1526,8 @@ Exportar conteúdo Para: %1$s Preparando a exportação... + Preparando %1$s... + %1$s: %2$d%% Total: %1$d%% %1$s restantes Exportar %1$d itens (%2$s) para a unidade selecionada? diff --git a/controller/app/src/main/res/values-ro/strings.xml b/controller/app/src/main/res/values-ro/strings.xml index 48f69d5d0..2567500a6 100644 --- a/controller/app/src/main/res/values-ro/strings.xml +++ b/controller/app/src/main/res/values-ro/strings.xml @@ -1447,6 +1447,8 @@ Exportă conținut Către: %1$s Se pregătește exportul... + Se pregăteşte %1$s... + %1$s: %2$d%% Total: %1$d%% %1$s rămase Exporți %1$d elemente (%2$s) pe unitatea selectată? diff --git a/controller/app/src/main/res/values-ru-rRU/strings.xml b/controller/app/src/main/res/values-ru-rRU/strings.xml index e64ac9cb2..41b19464e 100644 --- a/controller/app/src/main/res/values-ru-rRU/strings.xml +++ b/controller/app/src/main/res/values-ru-rRU/strings.xml @@ -1523,6 +1523,8 @@ Экспорт контента На: %1$s Подготовка экспорта... + Подготовка %1$s... + %1$s: %2$d%% Всего: %1$d%% Осталось %1$s Экспортировать %1$d элементов (%2$s) на выбранный накопитель? diff --git a/controller/app/src/main/res/values-sk/strings.xml b/controller/app/src/main/res/values-sk/strings.xml index 71ff85952..137d98403 100644 --- a/controller/app/src/main/res/values-sk/strings.xml +++ b/controller/app/src/main/res/values-sk/strings.xml @@ -1454,6 +1454,8 @@ Export obsahu Do: %1$s Príprava exportu... + Príprava %1$s... + %1$s: %2$d%% Celkovo: %1$d%% Zostáva %1$s Exportovať %1$d položiek (%2$s) na vybraný disk? diff --git a/controller/app/src/main/res/values-sr/strings.xml b/controller/app/src/main/res/values-sr/strings.xml index 15a0271d1..acef7d02a 100644 --- a/controller/app/src/main/res/values-sr/strings.xml +++ b/controller/app/src/main/res/values-sr/strings.xml @@ -1460,6 +1460,8 @@ Извоз садржаја На: %1$s Припрема извоза... + Припрема %1$s... + %1$s: %2$d%% Укупно: %1$d%% Преостало %1$s Извести %1$d ставки (%2$s) на изабрани диск? diff --git a/controller/app/src/main/res/values-sw/strings.xml b/controller/app/src/main/res/values-sw/strings.xml index f73665842..2eb6f8b50 100644 --- a/controller/app/src/main/res/values-sw/strings.xml +++ b/controller/app/src/main/res/values-sw/strings.xml @@ -1467,6 +1467,8 @@ Hamisha maudhui Kwenda: %1$s Inaandaa uhamishaji... + Inaandaa %1$s... + %1$s: %2$d%% Kwa jumla: %1$d%% %1$s zimebaki Hamisha vipengee %1$d (%2$s) kwenye diski iliyochaguliwa? diff --git a/controller/app/src/main/res/values-ta/strings.xml b/controller/app/src/main/res/values-ta/strings.xml index 379e17ce2..4fbb47a4f 100644 --- a/controller/app/src/main/res/values-ta/strings.xml +++ b/controller/app/src/main/res/values-ta/strings.xml @@ -1467,6 +1467,8 @@ உள்ளடக்கத்தை ஏற்றுமதி செய் இதற்கு: %1$s ஏற்றுமதி தயாராகிறது... + %1$s தயாராகிறது... + %1$s: %2$d%% மொத்தம்: %1$d%% %1$s மீதம் %1$d உருப்படிகளை (%2$s) தேர்ந்தெடுத்த டிரைவுக்கு ஏற்றுமதி செய்யவா? diff --git a/controller/app/src/main/res/values-tr/strings.xml b/controller/app/src/main/res/values-tr/strings.xml index caa2c0200..21746b521 100644 --- a/controller/app/src/main/res/values-tr/strings.xml +++ b/controller/app/src/main/res/values-tr/strings.xml @@ -1447,6 +1447,8 @@ İçeriği dışa aktar Hedef: %1$s Dışa aktarma hazırlanıyor... + %1$s hazırlanıyor... + %1$s: %2$d%% Toplam: %1$d%% %1$s kaldı %1$d öge (%2$s) seçili sürücüye aktarılsın mı? diff --git a/controller/app/src/main/res/values-uk/strings.xml b/controller/app/src/main/res/values-uk/strings.xml index 7ea953f6e..b0909d27a 100644 --- a/controller/app/src/main/res/values-uk/strings.xml +++ b/controller/app/src/main/res/values-uk/strings.xml @@ -1447,6 +1447,8 @@ Експорт контенту На: %1$s Підготовка експорту... + Підготовка %1$s... + %1$s: %2$d%% Усього: %1$d%% Залишилось %1$s Експортувати %1$d елементів (%2$s) на вибраний накопичувач? diff --git a/controller/app/src/main/res/values-vi/strings.xml b/controller/app/src/main/res/values-vi/strings.xml index f920845d2..5bbb5a3fd 100644 --- a/controller/app/src/main/res/values-vi/strings.xml +++ b/controller/app/src/main/res/values-vi/strings.xml @@ -1447,6 +1447,8 @@ Xuất nội dung Đến: %1$s Đang chuẩn bị xuất... + Đang chuẩn bị %1$s... + %1$s: %2$d%% Tổng: %1$d%% Còn %1$s Xuất %1$d mục (%2$s) ra ổ đĩa đã chọn? diff --git a/controller/app/src/main/res/values-yo/strings.xml b/controller/app/src/main/res/values-yo/strings.xml index 0797f3748..f9d62b7e8 100644 --- a/controller/app/src/main/res/values-yo/strings.xml +++ b/controller/app/src/main/res/values-yo/strings.xml @@ -1467,6 +1467,8 @@ Kó àkóónú jáde Sí: %1$s Ń múra sílẹ̀ fún ìkójáde... + Ń múra %1$s sílẹ̀... + %1$s: %2$d%% Lápapọ̀: %1$d%% %1$s ló kù Kó àwọn nǹkan %1$d (%2$s) jáde sí drive tí a yàn? diff --git a/controller/app/src/main/res/values-zh-rCN/strings.xml b/controller/app/src/main/res/values-zh-rCN/strings.xml index f50eb4c35..4a9f50b82 100644 --- a/controller/app/src/main/res/values-zh-rCN/strings.xml +++ b/controller/app/src/main/res/values-zh-rCN/strings.xml @@ -1448,6 +1448,8 @@ 导出内容 目标:%1$s 正在准备导出... + 正在准备 %1$s... + %1$s: %2$d%% 总进度:%1$d%% 剩余 %1$s 将 %1$d 个项目(%2$s)导出到所选驱动器吗? diff --git a/controller/app/src/main/res/values/strings.xml b/controller/app/src/main/res/values/strings.xml index dd907a7e8..c032967d9 100644 --- a/controller/app/src/main/res/values/strings.xml +++ b/controller/app/src/main/res/values/strings.xml @@ -1642,6 +1642,8 @@ Export content To: %1$s Preparing export... + Preparing %1$s... + %1$s: %2$d%% Overall: %1$d%% %1$s left Export %1$d items (%2$s) to the selected drive? diff --git a/controller/app/src/main/res/values/strings_untranslated.xml b/controller/app/src/main/res/values/strings_untranslated.xml index 65604ef29..09d5507a2 100644 --- a/controller/app/src/main/res/values/strings_untranslated.xml +++ b/controller/app/src/main/res/values/strings_untranslated.xml @@ -16,7 +16,5 @@ By category - - %1$s: %2$d%% diff --git a/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ExportJobTest.java b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ExportJobTest.java index ca3e5348b..a60ac19e8 100644 --- a/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ExportJobTest.java +++ b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/ExportJobTest.java @@ -29,7 +29,57 @@ public void overallPercentIsByteWeighted() { job.setActive(1); job.setCopied(1, 50L); // +50 of the 100-byte item assertEquals(95, job.overallPercent()); - assertEquals(50, job.currentItemPercent()); + // Overall is byte-weighted by copied bytes regardless of phase; the item bar is two-phase. + job.setPhase(1, ExportJob.PHASE_WRITE); + assertEquals(75, job.currentItemPercent()); // write half: 50 + 50% of 50 + } + + @Test + public void currentItemBarIsTwoPhase() { + ExportJob job = new ExportJob(); + job.begin(new long[]{100L}); + job.setActive(0); + // An active item starts in the prepare phase: the first half of the bar tracks stagedBytes. + assertEquals(ExportJob.PHASE_PREPARE, job.phase(0)); + assertEquals(0, job.currentItemPercent()); + job.setStaged(0, 50L); + assertEquals(25, job.currentItemPercent()); // half-staged = quarter of the whole bar + job.setStaged(0, 100L); + assertEquals(50, job.currentItemPercent()); // fully staged = the midpoint + // The write phase fills the second half from copiedBytes. + job.setPhase(0, ExportJob.PHASE_WRITE); + assertEquals(50, job.currentItemPercent()); // nothing written yet + job.setCopied(0, 50L); + assertEquals(75, job.currentItemPercent()); + job.setCopied(0, 100L); + assertEquals(100, job.currentItemPercent()); + } + + @Test + public void currentItemBarWithUnknownSizeStillAdvancesByPhase() { + ExportJob job = new ExportJob(); + job.begin(new long[]{0L}); // size unknown + job.setActive(0); + job.setStaged(0, 123L); + assertEquals(0, job.currentItemPercent()); // prepare half cannot show a fraction + job.setPhase(0, ExportJob.PHASE_WRITE); + assertEquals(50, job.currentItemPercent()); // but the bar still jumps to the midpoint + } + + @Test + public void setActiveResetsPhaseAndStaged() { + ExportJob job = new ExportJob(); + job.begin(new long[]{100L}); + job.setActive(0); + job.setStaged(0, 40L); + job.setPhase(0, ExportJob.PHASE_WRITE); + job.setCopied(0, 30L); + // A retry re-activates the item: it returns to the prepare phase with staged/copied cleared. + job.setActive(0); + assertEquals(ExportJob.PHASE_PREPARE, job.phase(0)); + assertEquals(0L, job.staged(0)); + assertEquals(0L, job.copied(0)); + assertEquals(0, job.currentItemPercent()); } @Test