diff --git a/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java b/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java
index 6bb620eb0..efcc830fb 100644
--- a/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java
+++ b/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java
@@ -19,7 +19,8 @@
* speed(bytes/s),
* detail, error }
* POST /api/kiwix/jobs/:id/cancel -> { ok:true }
- * phase is one of: queued|downloading|indexing|processing|done|error|canceled.
+ * POST /api/kiwix/jobs/:id/pause|resume -> { ok:true } (ADFA-4893)
+ * phase is one of: queued|downloading|indexing|processing|paused|done|error|canceled.
* ============================================================================
*/
package org.iiab.controller.content;
@@ -51,11 +52,19 @@ public interface Listener {
void onLog(String line); // free-form detail line (for logs)
void onDone(); // success (terminal)
void onError(String message); // failure (terminal)
+ /** ADFA-4893: 'paused' phase (best-effort). Default no-op so existing implementers compile unchanged. */
+ default void onPaused(int percent) {}
+ /** ADFA-4893: server is reconnecting (attempt n of total) after a network drop; keeps polling. */
+ default void onReconnecting(int attempt, int total) {}
}
private static final String BASE = BoxEndpoints.API + "/kiwix";
private static final long POLL_MS = 1000L;
private static final int MAX_POLL_ERRORS = 10; // tolerate ~10s of transient network blips
+ // ADFA-4893: the START (download) POST is before any server job exists, so the server's own
+ // reconnect can't cover a still-warming box; give the kickoff a few quick tries before failing.
+ private static final int START_TRIES = 3;
+ private static final long START_RETRY_MS = 2000L;
private final Handler main = new Handler(Looper.getMainLooper());
private Listener listener;
@@ -70,15 +79,25 @@ public interface Listener {
public void addZim(@NonNull String zimFilename, @NonNull Listener l) {
this.listener = l;
AppExecutors.get().io().execute(() -> {
- try {
- JSONObject body = new JSONObject().put("ids", new JSONArray().put(zimFilename));
- JSONObject resp = httpJson("POST", BASE + "/download", body);
- String id = resp.optString("id", "");
- if (id.isEmpty()) { fail("content service did not start the job"); return; }
- jobId = id;
- main.postDelayed(pollTask, POLL_MS);
- } catch (Exception e) {
- fail("couldn't reach the content service");
+ final JSONObject body;
+ try { body = new JSONObject().put("ids", new JSONArray().put(zimFilename)); }
+ catch (Exception e) { fail("couldn't build the request"); return; }
+ // ADFA-4893: retry ONLY the kickoff POST (connectivity blip / server still warming) a few
+ // times. An empty id is a server refusal, not a blip, so it fails without retrying. Once the
+ // job exists, the server owns reconnection (visible), not this loop.
+ for (int attempt = 1; !finished; attempt++) {
+ try {
+ JSONObject resp = httpJson("POST", BASE + "/download", body);
+ String id = resp.optString("id", "");
+ if (id.isEmpty()) { fail("content service did not start the job"); return; }
+ jobId = id;
+ main.postDelayed(pollTask, POLL_MS);
+ return;
+ } catch (Exception e) {
+ if (attempt >= START_TRIES) { fail("couldn't reach the content service"); return; }
+ try { Thread.sleep(START_RETRY_MS); }
+ catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; }
+ }
}
});
}
@@ -93,12 +112,17 @@ private void pollOnce() {
long speed = j.optLong("speed", 0L);
String detail = j.isNull("detail") ? null : j.optString("detail", null);
String error = j.isNull("error") ? null : j.optString("error", null);
+ int retryAttempt = j.optInt("retryAttempt", 0); // ADFA-4893: reconnect state (0 when not retrying)
+ int retryTotal = j.optInt("retryTotal", 0);
if (detail != null && !detail.isEmpty()) deliver(() -> listener.onLog(detail));
switch (phase) {
case "downloading":
- if (percent >= 0) {
+ if (retryAttempt > 0) {
+ final int a = retryAttempt, t = retryTotal;
+ deliver(() -> listener.onReconnecting(a, t));
+ } else if (percent >= 0) {
final int p = percent; final String rate = formatRate(speed);
deliver(() -> listener.onProgress(p, rate));
}
@@ -116,6 +140,12 @@ private void pollOnce() {
case "canceled":
fail("canceled");
return;
+ case "paused": {
+ // ADFA-4893: not terminal — surface it and keep polling so resume/progress is seen.
+ final int pp = percent;
+ deliver(() -> listener.onPaused(pp));
+ break;
+ }
default:
break; // queued / unknown: keep polling
}
@@ -128,6 +158,7 @@ private void pollOnce() {
/** Best-effort cancel of the in-flight job. */
public void cancel() {
+ finished = true; // ADFA-4893: also stops the START retry loop if a cancel lands mid-kickoff
final String id = jobId;
if (id != null && !id.isEmpty()) {
AppExecutors.get().io().execute(() -> {
@@ -137,6 +168,26 @@ public void cancel() {
teardown();
}
+ /** ADFA-4893: best-effort pause of the in-flight job. Keeps polling so 'paused' is observed and resume works. */
+ public void pause() {
+ final String id = jobId;
+ if (id != null && !id.isEmpty()) {
+ AppExecutors.get().io().execute(() -> {
+ try { httpJson("POST", BASE + "/jobs/" + id + "/pause", null); } catch (Exception ignore) { /* best effort */ }
+ });
+ }
+ }
+
+ /** ADFA-4893: best-effort resume of a paused job; polling continues, so progress flows again. */
+ public void resume() {
+ final String id = jobId;
+ if (id != null && !id.isEmpty()) {
+ AppExecutors.get().io().execute(() -> {
+ try { httpJson("POST", BASE + "/jobs/" + id + "/resume", null); } catch (Exception ignore) { /* best effort */ }
+ });
+ }
+ }
+
private void done() {
if (finished) return;
finished = true;
diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java b/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java
index 4b5801dfc..d36cb20e5 100644
--- a/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java
+++ b/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java
@@ -605,13 +605,13 @@ private void render() {
zimSession, ZimDownloadService.status(),
ZimDownloadService.DONE, ZimDownloadService.FAILED,
zimSession && ZimDownloadService.isComplete(), content.banked(ContentType.ZIM),
- ZimDownloadService.speed()));
+ ZimDownloadService.speed(), zimOverallPercent()));
if (booksShown) (booksSession ? started : waiting).add(
streamRow(getString(R.string.k2go_gm_books_title), "books",
booksSession, BooksDownloadService.status(),
BooksDownloadService.DONE, BooksDownloadService.FAILED,
booksSession && BooksDownloadService.isComplete(), content.banked(ContentType.BOOKS),
- 0L));
+ 0L, -1)); // ADFA-4893: Books has no per-item size yet -> no determinate bar
// ADFA-4954. Statuses come from an observable snapshot rather than static arrays, so the
// ordinals are mapped to the checklist's PENDING=0 / doneVal / failedVal convention here.
if (kolibriShown) (kolibriState.hasSession() ? started : waiting).add(
@@ -619,7 +619,7 @@ private void render() {
kolibriState.hasSession(), kolibriState.statusOrdinals(),
KolibriSeedState.Status.DONE.ordinal(), KolibriSeedState.Status.FAILED.ordinal(),
kolibriState.hasSession() && kolibriState.isComplete(), kolibriBanked,
- kolibriState.speedBytesPerSec()));
+ kolibriState.speedBytesPerSec(), -1)); // ADFA-4893: Kolibri keeps its indicator
for (View v : started) sections.addView(v);
for (View v : waiting) sections.addView(v);
@@ -894,7 +894,7 @@ private String rateSuffix(long bytesPerSec) {
}
private View streamRow(String heading, String key, boolean sess, int[] status, int doneVal, int failedVal,
- boolean complete, int wishlistCount, long bytesPerSec) {
+ boolean complete, int wishlistCount, long bytesPerSec, int barPercent) {
int n = sess && status != null ? status.length : wishlistCount;
int done = 0, failed = 0;
if (sess && status != null) for (int st : status) { if (st == doneVal) done++; else if (st == failedVal) failed++; }
@@ -959,6 +959,7 @@ private View streamRow(String heading, String key, boolean sess, int[] status, i
sub.setText(state);
sub.setTextColor(ContextCompat.getColor(this, (sess && failed > 0) ? R.color.k2go_amber_text : R.color.k2go_muted));
col.addView(sub);
+ addRowProgressBar(col, barPercent, sess && !complete); // ADFA-4893: determinate bar for REST streams (ZIM)
row.addView(col, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
ImageView chev = new ImageView(this);
@@ -981,12 +982,18 @@ private View streamRow(String heading, String key, boolean sess, int[] status, i
* it). Only shown while the module is running and has a task table (percent >= 0); otherwise the
* row keeps its indeterminate indicator. Lifted off the card's bottom edge with a small margin. */
private void addRowProgressBar(LinearLayout col, ModuleQueueState mq, boolean running) {
- if (!(running && mq.percent >= 0)) return;
+ addRowProgressBar(col, mq.percent, running); // ADFA-5228 (proot rows)
+ }
+
+ /** ADFA-4893: same determinate row bar driven by a plain percent, for REST streams (ZIM). Hidden
+ * when not running or percent < 0, so a paused/indeterminate stream keeps its indicator. */
+ private void addRowProgressBar(LinearLayout col, int percent, boolean running) {
+ if (!(running && percent >= 0)) return;
com.google.android.material.progressindicator.LinearProgressIndicator bar =
new com.google.android.material.progressindicator.LinearProgressIndicator(this);
bar.setIndeterminate(false);
bar.setMax(100);
- bar.setProgressCompat(mq.percent, true);
+ bar.setProgressCompat(percent, true);
LinearLayout.LayoutParams barLp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
barLp.topMargin = px(8);
@@ -994,6 +1001,14 @@ private void addRowProgressBar(LinearLayout col, ModuleQueueState mq, boolean ru
col.addView(bar, barLp);
}
+ /** ADFA-4893: the ZIM index row bar shares one formula with the status screen — see
+ * {@link ZimDownloadService#overallPercent()}. Here we only gate visibility: -1 (no bar) unless a
+ * job is actively running, so a terminal/failed row falls back to its indicator. */
+ private int zimOverallPercent() {
+ return (ZimDownloadService.isRunning() && !ZimDownloadService.isComplete())
+ ? ZimDownloadService.overallPercent() : -1;
+ }
+
private View mapsRow() {
ModuleQueueState mq = ModuleQueueRepository.get().current();
boolean done = mapsStartFailed || (mapsInSession() && mq.phase == ModuleQueueState.Phase.DONE);
diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java b/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java
index ea606dca7..5304e9573 100644
--- a/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java
+++ b/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java
@@ -41,6 +41,8 @@ public final class ZimDownloadService extends Service {
public static final String ACTION_START = "org.iiab.controller.ZIM_DOWNLOAD_START";
public static final String ACTION_RETRY = "org.iiab.controller.ZIM_DOWNLOAD_RETRY";
public static final String ACTION_CANCEL = "org.iiab.controller.ZIM_DOWNLOAD_CANCEL";
+ public static final String ACTION_PAUSE = "org.iiab.controller.ZIM_DOWNLOAD_PAUSE"; // ADFA-4893
+ public static final String ACTION_RESUME = "org.iiab.controller.ZIM_DOWNLOAD_RESUME"; // ADFA-4893
public static final String EXTRA_FILES = "files";
public static final String EXTRA_LABELS = "labels";
public static final String EXTRA_BYTES = "bytes";
@@ -59,9 +61,15 @@ public interface Listener { void onUpdate(); }
private static int sPercent = 0;
private static long sSpeed = 0;
private static volatile long sLastProgressAt = 0L; // ADFA-5146: last-progress heartbeat (elapsedRealtime)
+ private static volatile boolean sPaused = false; // ADFA-4893: active job paused on the server (session-level)
+ private static volatile int sReconnectAttempt = 0; // ADFA-4893: >0 while the server reconnects (n of total)
+ private static volatile int sReconnectTotal = 0;
private static Listener sListener;
public static boolean isRunning() { return sRunning; }
+ public static boolean isPaused() { return sPaused; }
+ public static int reconnectAttempt() { return sReconnectAttempt; }
+ public static int reconnectTotal() { return sReconnectTotal; }
public static boolean hasSession() { return sFiles.length > 0; }
/** All items are terminal (done/failed) and nothing is in flight. */
public static boolean isComplete() {
@@ -86,17 +94,49 @@ public static boolean isActiveNow() {
public static long speed() { return sSpeed; }
public static void setListener(Listener l) { sListener = l; }
+ /** ADFA-4893: byte-weighted overall percent across the session (0-100). The single source both the
+ * status-screen bar (ZimPreparingFragment) and the index row bar (SetupProgressActivity) read, so
+ * the two can never drift. Active item contributes its live percent; done/failed count in full. */
+ public static int overallPercent() {
+ long total = 0, done = 0;
+ for (int i = 0; i < sBytes.length && i < sStatus.length; i++) {
+ total += sBytes[i];
+ if (sStatus[i] == DONE || sStatus[i] == FAILED) done += sBytes[i];
+ else if (i == sIndex && (sStatus[i] == ACTIVE || sStatus[i] == INDEXING) && sPercent >= 0)
+ done += sBytes[i] * sPercent / 100;
+ }
+ return total > 0 ? (int) Math.min(100, done * 100 / total) : (isComplete() ? 100 : 0);
+ }
+
public static void start(Context ctx, String[] files, String[] labels, long[] bytes) {
Intent i = new Intent(ctx, ZimDownloadService.class).setAction(ACTION_START)
.putExtra(EXTRA_FILES, files).putExtra(EXTRA_LABELS, labels).putExtra(EXTRA_BYTES, bytes);
ContextCompat.startForegroundService(ctx, i);
}
- /** Re-queue a failed item; resume processing if the session had already stopped. */
- public static void retry(Context ctx, int i) {
- if (i < 0 || i >= sStatus.length) return;
- sStatus[i] = PENDING;
- if (!sRunning) {
+ /** ADFA-4893: pause the active job (the server keeps the partial). No-op if nothing is running. */
+ public static void pause(Context ctx) {
+ if (!sRunning) return;
+ ContextCompat.startForegroundService(ctx, new Intent(ctx, ZimDownloadService.class).setAction(ACTION_PAUSE));
+ }
+
+ /** ADFA-4893: resume a paused job; polling/progress continues from the partial. */
+ public static void resume(Context ctx) {
+ ContextCompat.startForegroundService(ctx, new Intent(ctx, ZimDownloadService.class).setAction(ACTION_RESUME));
+ }
+
+ /** ADFA-4893: true when any item is FAILED (so the status screen can offer a single Retry). */
+ public static boolean hasFailed() {
+ for (int st : sStatus) if (st == FAILED) return true;
+ return false;
+ }
+
+ /** ADFA-4893: re-queue ALL failed items and resume the session — the status-screen Retry (the
+ * Pause button morphs into it), so a failed run doesn't fall back to a separate per-item control. */
+ public static void retryFailed(Context ctx) {
+ boolean any = false;
+ for (int i = 0; i < sStatus.length; i++) if (sStatus[i] == FAILED) { sStatus[i] = PENDING; any = true; }
+ if (any && !sRunning) {
ContextCompat.startForegroundService(ctx, new Intent(ctx, ZimDownloadService.class).setAction(ACTION_RETRY));
}
}
@@ -104,15 +144,12 @@ public static void retry(Context ctx, int i) {
/** Clear the session so a new selection can start fresh. */
public static void finishSession() {
sFiles = new String[0]; sLabels = new String[0]; sBytes = new long[0]; sStatus = new int[0];
- sIndex = 0; sPercent = 0; sSpeed = 0; sRunning = false; sLastProgressAt = 0L;
+ sIndex = 0; sPercent = 0; sSpeed = 0; sRunning = false; sPaused = false;
+ sReconnectAttempt = 0; sReconnectTotal = 0; sLastProgressAt = 0L;
}
- private static final int MAX_ATTEMPTS = 3; // total tries per ZIM before marking it failed
- private static final long RETRY_DELAY_MS = 4000L;
-
private final Handler main = new Handler(Looper.getMainLooper());
private RestContentClient client;
- private int attempts = 0; // attempts for the ZIM currently in flight
@Override public void onCreate() { super.onCreate(); createNotificationChannel(); }
@Nullable @Override public IBinder onBind(Intent intent) { return null; }
@@ -123,12 +160,28 @@ public int onStartCommand(Intent intent, int flags, int startId) {
if (ACTION_CANCEL.equals(action)) {
if (client != null) client.cancel();
- sRunning = false;
+ sRunning = false; sPaused = false; sReconnectAttempt = 0; sReconnectTotal = 0;
publish();
main.post(() -> { stopForeground(true); stopSelf(); });
return START_NOT_STICKY;
}
+ // ADFA-4893: pause/resume the active job. Handled BEFORE the sRunning guard (the session is
+ // still "running" while paused). The queue never advances during a pause because the paused
+ // job never reaches onDone/onError, so processNext() isn't called.
+ if (ACTION_PAUSE.equals(action)) {
+ if (client != null) client.pause();
+ sPaused = true;
+ publish();
+ return START_NOT_STICKY;
+ }
+ if (ACTION_RESUME.equals(action)) {
+ if (client != null) client.resume();
+ sPaused = false;
+ publish();
+ return START_NOT_STICKY;
+ }
+
if (sRunning) return START_NOT_STICKY;
if (ACTION_RETRY.equals(action)) {
@@ -142,7 +195,7 @@ public int onStartCommand(Intent intent, int flags, int startId) {
if (sLabels == null) sLabels = sFiles;
if (sBytes == null) sBytes = new long[sFiles.length];
sStatus = new int[sFiles.length];
- sIndex = 0; sPercent = 0; sSpeed = 0;
+ sIndex = 0; sPercent = 0; sSpeed = 0; sPaused = false; sReconnectAttempt = 0; sReconnectTotal = 0;
sLastProgressAt = android.os.SystemClock.elapsedRealtime(); // ADFA-5146: seed the heartbeat at session start
}
@@ -165,7 +218,6 @@ private void processNext() {
int i = firstPending();
if (i < 0) { sessionComplete(); return; }
sIndex = i; sPercent = 0; sStatus[i] = ACTIVE;
- attempts = 0;
publish();
updateNotification(sLabels[i]);
startItem(i);
@@ -176,34 +228,39 @@ private void startItem(final int i) {
client = new RestContentClient();
client.addZim(sFiles[i], new RestContentClient.Listener() {
@Override public void onProgress(int percent, String speed) {
+ if (sPaused) sPaused = false; // ADFA-4893: progress means the server resumed
+ sReconnectAttempt = 0; // ADFA-4893: progress means the reconnect succeeded
sPercent = percent; sSpeed = parseRate(speed);
sLastProgressAt = android.os.SystemClock.elapsedRealtime(); // ADFA-5146: heartbeat on each poll
if (sStatus[i] != INDEXING) sStatus[i] = ACTIVE;
publish(); updateNotification(sLabels[i]);
}
@Override public void onIndexing() { sStatus[i] = INDEXING; sLastProgressAt = android.os.SystemClock.elapsedRealtime(); publish(); }
+ @Override public void onPaused(int percent) {
+ // ADFA-4893: server acknowledged the pause. Keep the heartbeat fresh (a pause is
+ // intentional, not a dead session) and let the screen render the paused state.
+ sPercent = percent; sPaused = true;
+ sLastProgressAt = android.os.SystemClock.elapsedRealtime();
+ publish();
+ }
+ @Override public void onReconnecting(int attempt, int total) {
+ // ADFA-4893: the server lost the link and is retrying (n of total). Surface it so the
+ // screen shows "Reconnecting n/N"; keep the heartbeat fresh — this is not a dead session.
+ sReconnectAttempt = attempt; sReconnectTotal = total;
+ sLastProgressAt = android.os.SystemClock.elapsedRealtime();
+ publish();
+ }
@Override public void onLog(String line) { /* logcat only */ }
@Override public void onDone() { android.util.Log.i("K2Go-Provision", "zim job done [" + i + "]"); sStatus[i] = DONE; publish(); processNext(); }
@Override public void onError(String message) {
+ // ADFA-4893: the server owns reconnection (5 visible attempts). When it gives up we mark
+ // the item FAILED and let the user retry it (checklist tap) — no invisible app-side re-POST.
android.util.Log.w("K2Go-Provision", "zim job [" + i + "] error: " + message);
- retryOrFail(i);
+ sStatus[i] = FAILED; sReconnectAttempt = 0; publish(); processNext();
}
});
}
- /** Transient failure (server warming up, a flaky mirror): retry the same ZIM a couple times
- * before giving up, so a blip doesn't leave content missing. */
- private void retryOrFail(int i) {
- attempts++;
- if (attempts < MAX_ATTEMPTS) {
- android.util.Log.w("K2Go-Provision", "zim job [" + i + "] transient failure, retry " + attempts + "/" + (MAX_ATTEMPTS - 1));
- main.postDelayed(() -> startItem(i), RETRY_DELAY_MS);
- } else {
- android.util.Log.w("K2Go-Provision", "zim job [" + i + "] failed after " + attempts + " attempts");
- sStatus[i] = FAILED; publish(); processNext();
- }
- }
-
private void sessionComplete() {
sRunning = false;
publish();
diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ZimPreparingFragment.java b/controller/app/src/main/java/org/iiab/controller/redesign/ZimPreparingFragment.java
index 76c13de55..a24c29c43 100644
--- a/controller/app/src/main/java/org/iiab/controller/redesign/ZimPreparingFragment.java
+++ b/controller/app/src/main/java/org/iiab/controller/redesign/ZimPreparingFragment.java
@@ -12,16 +12,19 @@
*/
package org.iiab.controller.redesign;
+import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
+import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import java.util.Locale;
@@ -33,6 +36,9 @@ public class ZimPreparingFragment extends Fragment {
private TextView label, pct, detail;
private ProgressBar bar;
private LinearLayout listv;
+ private LinearLayout controls; // ADFA-4893: session control row (pause/resume + cancel)
+ private Button pauseBtn, cancelBtn;
+ private boolean pauseSupported = false; // ADFA-4893: box dash-node >= 1.2.4 exposes pause/resume (4894)
/**
* ADFA-5074: {@code newInstance(boolean fromIndex)} used to live here, and every caller now
@@ -53,6 +59,33 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
detail = root.findViewById(R.id.k2go_zprep_detail);
bar = root.findViewById(R.id.k2go_zprep_bar);
listv = root.findViewById(R.id.k2go_zprep_list);
+ // ADFA-4893: session controls on the status screen. Poll (service) drives label + visibility.
+ controls = root.findViewById(R.id.k2go_zprep_controls);
+ pauseBtn = root.findViewById(R.id.k2go_zprep_pause);
+ cancelBtn = root.findViewById(R.id.k2go_zprep_cancel);
+ // ADFA-4893: the primary button morphs Pause -> Resume -> Retry; the action is decided at tap
+ // time from the live state, so we don't remove/re-add buttons across states.
+ pauseBtn.setOnClickListener(v -> {
+ android.content.Context ctx = requireContext().getApplicationContext();
+ if (!ZimDownloadService.isRunning() && ZimDownloadService.hasFailed()) ZimDownloadService.retryFailed(ctx);
+ else if (ZimDownloadService.isPaused()) ZimDownloadService.resume(ctx);
+ else ZimDownloadService.pause(ctx);
+ });
+ // Cancel is always available: cancels a running session, or dismisses a failed/terminal one.
+ cancelBtn.setOnClickListener(v -> {
+ android.content.Context ctx = requireContext().getApplicationContext();
+ if (ZimDownloadService.isRunning()) {
+ ContextCompat.startForegroundService(ctx,
+ new Intent(ctx, ZimDownloadService.class).setAction(ZimDownloadService.ACTION_CANCEL));
+ } else {
+ ZimDownloadService.finishSession();
+ render();
+ }
+ });
+ // ADFA-4893: only offer the controls when the box's dash-node exposes pause/resume (>= 1.2.4,
+ // ADFA-4894). atLeast() returns false for an unknown/older version, so old boxes hide the row
+ // (notification Cancel still works) instead of showing a Pause that 404s.
+ pauseSupported = DashboardVersion.atLeast(DashboardVersion.installed(requireContext()), 1, 2, 4);
// ADFA-5074: the shared animation block declares no asset; the rule picks it.
org.iiab.controller.util.ProgressVisuals.apply(root, org.iiab.controller.system.domain.ContentType.ZIM);
@@ -70,8 +103,10 @@ private void render() {
int idx = ZimDownloadService.index();
int p = ZimDownloadService.percent();
int n = labels.length;
- if (n == 0) return;
+ if (n == 0) { controls.setVisibility(View.GONE); return; }
+ // Byte figures for the "X of Y · N of M" detail line; the bar percent comes from the single
+ // shared source (ZimDownloadService.overallPercent) so the status screen and the index can't drift.
long totalBytes = 0, doneBytes = 0;
int doneCount = 0;
for (int i = 0; i < n; i++) {
@@ -83,30 +118,65 @@ private void render() {
doneBytes += bytes[i] * p / 100;
}
}
- int overall = totalBytes > 0 ? (int) Math.min(100, doneBytes * 100 / totalBytes)
- : (ZimDownloadService.isComplete() ? 100 : 0);
+ int overall = ZimDownloadService.overallPercent();
bar.setProgress(overall);
pct.setText(overall + "%");
- boolean allDone = ZimDownloadService.isComplete();
- label.setText(allDone
- ? getString(R.string.k2go_zim_all_ready)
- : getString(R.string.k2go_zim_downloading_fmt, idx < n ? labels[idx] : ""));
+ boolean anyFailed = ZimDownloadService.hasFailed();
+ boolean running = ZimDownloadService.isRunning();
+ boolean paused = ZimDownloadService.isPaused();
+ int rc = ZimDownloadService.reconnectAttempt();
+ boolean allOk = ZimDownloadService.isComplete() && !anyFailed;
+
+ // Label reflects the true state — honest: never "all ready" when something failed.
+ if (!running && anyFailed) {
+ int f = firstFailed(status);
+ label.setText(f >= 0 ? labels[f] + getString(R.string.k2go_zim_item_failed_suffix)
+ : getString(R.string.k2go_zim_downloading_fmt, ""));
+ } else if (paused) {
+ label.setText(R.string.k2go_dl_paused);
+ } else if (running && rc > 0) {
+ // ADFA-4893: match rootfs wording exactly — "Reconnecting… n of N" (static ellipsis).
+ label.setText(getString(R.string.k2go_dl_attempt, rc, ZimDownloadService.reconnectTotal()));
+ } else if (allOk) {
+ label.setText(R.string.k2go_zim_all_ready);
+ } else {
+ label.setText(getString(R.string.k2go_zim_downloading_fmt, idx < n ? labels[idx] : ""));
+ }
+
long sp = ZimDownloadService.speed();
- String speedPart = (!allDone && sp > 0)
+ String speedPart = (running && !paused && rc <= 0 && sp > 0)
? " · " + humanRate(sp) + getString(R.string.k2go_rate_per_second) : "";
detail.setText(getString(R.string.k2go_zim_prep_detail_fmt,
gb(doneBytes / (1024L * 1024L)), gb(totalBytes / (1024L * 1024L)), speedPart, doneCount, n));
+ // ADFA-4893: [primary][Cancel] row. The primary morphs Pause -> Resume -> Retry; Cancel is always
+ // present. Shown while running (needs pause support, dash-node >= 1.2.4) OR whenever an item failed
+ // (Retry works on any version). Old boxes keep the notification Cancel while running.
+ boolean showControls = (running && pauseSupported) || anyFailed;
+ controls.setVisibility(showControls ? View.VISIBLE : View.GONE);
+ if (showControls) {
+ if (!running && anyFailed) pauseBtn.setText(R.string.k2go_dl_retry);
+ else if (paused) pauseBtn.setText(R.string.k2go_dl_resume);
+ else pauseBtn.setText(R.string.k2go_dl_pause);
+ }
+
drawChecklist(labels, status);
}
private void drawChecklist(String[] labels, int[] status) {
+ // ADFA-4893: no per-item Retry pill — the status-screen Retry (the morphing primary button) owns
+ // retry now, so the checklist is display-only and the retry affordance stays one consistent size.
ProvisioningChecklist.render(requireContext(), listv, labels.length, status,
ZimDownloadService.DONE, ZimDownloadService.FAILED,
i -> (status[i] == ZimDownloadService.FAILED)
? labels[i] + getString(R.string.k2go_zim_item_failed_suffix) : labels[i],
- i -> ZimDownloadService.retry(requireContext().getApplicationContext(), i));
+ null);
+ }
+
+ private static int firstFailed(int[] status) {
+ for (int i = 0; i < status.length; i++) if (status[i] == ZimDownloadService.FAILED) return i;
+ return -1;
}
private String gb(long mb) { // ADFA-4910: one standard size formatter for the whole UI
diff --git a/controller/app/src/main/res/layout/fragment_k2go_zim_preparing.xml b/controller/app/src/main/res/layout/fragment_k2go_zim_preparing.xml
index 399a0e987..a010ead4a 100644
--- a/controller/app/src/main/res/layout/fragment_k2go_zim_preparing.xml
+++ b/controller/app/src/main/res/layout/fragment_k2go_zim_preparing.xml
@@ -75,6 +75,39 @@
android:textAppearance="?attr/textAppearanceBodySmall"
android:textColor="@color/k2go_muted" />
+
+
+
+
+
+
+
+
جارٍ تحضير المحتوى…
تنزيلات كبيرة. يمكنك تركه قيد التشغيل.جارٍ تنزيل %1$s
- %1$s من %2$s%3$s · %4$d من %5$d عنصر · يُستأنف إذا انقطع
+ %1$s من %2$s%3$s · %4$d من %5$d عنصراتركه قيد التشغيلسنُعلمك عندما يكون محتواك جاهزًا.التشغيل في الخلفية
diff --git a/controller/app/src/main/res/values-az/strings_k2go.xml b/controller/app/src/main/res/values-az/strings_k2go.xml
index 44051fc9a..959222801 100644
--- a/controller/app/src/main/res/values-az/strings_k2go.xml
+++ b/controller/app/src/main/res/values-az/strings_k2go.xml
@@ -525,7 +525,7 @@
Məzmun hazırlanır…Böyük yükləmələr. İşləməyə buraxa bilərsiniz.%1$s yüklənir
- %2$s%3$s-dən %1$s · %5$d elementdən %4$d · kəsilsə davam edir
+ %2$s%3$s-dən %1$s · %5$d elementdən %4$dİşləməyə buraxMəzmununuz hazır olduqda sizə bildiriş göndərəcəyik.Arxa planda işlət
diff --git a/controller/app/src/main/res/values-bg/strings_k2go.xml b/controller/app/src/main/res/values-bg/strings_k2go.xml
index 48410f74f..a37b357ec 100644
--- a/controller/app/src/main/res/values-bg/strings_k2go.xml
+++ b/controller/app/src/main/res/values-bg/strings_k2go.xml
@@ -525,7 +525,7 @@
Подготовка на съдържанието…Големи изтегляния. Можете да го оставите да работи.Изтегляне на %1$s
- %1$s от %2$s%3$s · %4$d от %5$d елемента · възобновява се при прекъсване
+ %1$s от %2$s%3$s · %4$d от %5$d елементаОставете го да работиЩе ви уведомим, когато съдържанието ви е готово.Изпълни във фонов режим
diff --git a/controller/app/src/main/res/values-bn/strings_k2go.xml b/controller/app/src/main/res/values-bn/strings_k2go.xml
index 44c8036e3..de1ab14ca 100644
--- a/controller/app/src/main/res/values-bn/strings_k2go.xml
+++ b/controller/app/src/main/res/values-bn/strings_k2go.xml
@@ -525,7 +525,7 @@
কনটেন্ট প্রস্তুত হচ্ছে…বড় ডাউনলোড। আপনি এটি চালু রেখে যেতে পারেন।%1$s ডাউনলোড হচ্ছে
- %2$s%3$s-এর মধ্যে %1$s · %5$dটির মধ্যে %4$dটি আইটেম · বিচ্ছিন্ন হলে আবার শুরু হয়
+ %2$s%3$s-এর মধ্যে %1$s · %5$dটির মধ্যে %4$dটি আইটেমচালু রেখে যানআপনার কনটেন্ট প্রস্তুত হলে আমরা আপনাকে জানাব।ব্যাকগ্রাউন্ডে চালান
diff --git a/controller/app/src/main/res/values-cs/strings_k2go.xml b/controller/app/src/main/res/values-cs/strings_k2go.xml
index ebaf407a7..acf8e71dd 100644
--- a/controller/app/src/main/res/values-cs/strings_k2go.xml
+++ b/controller/app/src/main/res/values-cs/strings_k2go.xml
@@ -525,7 +525,7 @@
Příprava obsahu…Velká stahování. Můžete je nechat běžet.Stahování %1$s
- %1$s z %2$s%3$s · %4$d z %5$d položek · naváže, pokud se přeruší
+ %1$s z %2$s%3$s · %4$d z %5$d položekNechte to běžetUpozorníme vás, až bude váš obsah připraven.Spustit na pozadí
diff --git a/controller/app/src/main/res/values-de/strings_k2go.xml b/controller/app/src/main/res/values-de/strings_k2go.xml
index 7c9a099ed..13192a2f3 100644
--- a/controller/app/src/main/res/values-de/strings_k2go.xml
+++ b/controller/app/src/main/res/values-de/strings_k2go.xml
@@ -526,7 +526,7 @@
Inhalte werden vorbereitet…Große Downloads. Du kannst es laufen lassen.%1$s wird heruntergeladen
- %1$s von %2$s%3$s · %4$d von %5$d Elementen · setzt bei Abbruch fort
+ %1$s von %2$s%3$s · %4$d von %5$d ElementenLass es laufenWir benachrichtigen dich, wenn deine Inhalte bereit sind.Im Hintergrund ausführen
diff --git a/controller/app/src/main/res/values-el/strings_k2go.xml b/controller/app/src/main/res/values-el/strings_k2go.xml
index 5c0ed9a82..d0ff3d5c8 100644
--- a/controller/app/src/main/res/values-el/strings_k2go.xml
+++ b/controller/app/src/main/res/values-el/strings_k2go.xml
@@ -526,7 +526,7 @@
Προετοιμασία περιεχομένου…Μεγάλες λήψεις. Μπορείτε να το αφήσετε να εκτελείται.Λήψη %1$s
- %1$s από %2$s%3$s · %4$d από %5$d στοιχεία · επαναλαμβάνεται αν διακοπεί
+ %1$s από %2$s%3$s · %4$d από %5$d στοιχείαΑφήστε το να εκτελείταιΘα σας ειδοποιήσουμε όταν το περιεχόμενό σας είναι έτοιμο.Εκτέλεση στο παρασκήνιο
diff --git a/controller/app/src/main/res/values-es/strings_k2go.xml b/controller/app/src/main/res/values-es/strings_k2go.xml
index fc73679c4..da363efa4 100644
--- a/controller/app/src/main/res/values-es/strings_k2go.xml
+++ b/controller/app/src/main/res/values-es/strings_k2go.xml
@@ -525,7 +525,7 @@
Preparando contenido…Descargas grandes. Puedes dejarlo en marcha.Descargando %1$s
- %1$s de %2$s%3$s · %4$d de %5$d elementos · se reanuda si se corta
+ %1$s de %2$s%3$s · %4$d de %5$d elementosDéjalo en marchaTe avisaremos cuando tu contenido esté listo.Ejecutar en segundo plano
diff --git a/controller/app/src/main/res/values-fa/strings_k2go.xml b/controller/app/src/main/res/values-fa/strings_k2go.xml
index 8e5023170..eb739f8ee 100644
--- a/controller/app/src/main/res/values-fa/strings_k2go.xml
+++ b/controller/app/src/main/res/values-fa/strings_k2go.xml
@@ -525,7 +525,7 @@
در حال آمادهسازی محتوا…دانلودهای بزرگ. میتوانید آن را در حال اجرا رها کنید.در حال دانلود %1$s
- %1$s از %2$s%3$s · %4$d از %5$d مورد · در صورت قطع از سر گرفته میشود
+ %1$s از %2$s%3$s · %4$d از %5$d موردآن را در حال اجرا رها کنیدوقتی محتوای شما آماده شد به شما اطلاع میدهیم.اجرا در پسزمینه
diff --git a/controller/app/src/main/res/values-fr/strings_k2go.xml b/controller/app/src/main/res/values-fr/strings_k2go.xml
index 406890ada..81936de4d 100644
--- a/controller/app/src/main/res/values-fr/strings_k2go.xml
+++ b/controller/app/src/main/res/values-fr/strings_k2go.xml
@@ -531,7 +531,7 @@
Préparation du contenu…Téléchargements volumineux. Vous pouvez le laisser tourner.Téléchargement de %1$s
- %1$s sur %2$s%3$s · %4$d sur %5$d éléments · reprend en cas de coupure
+ %1$s sur %2$s%3$s · %4$d sur %5$d élémentsLaissez-le tournerNous vous préviendrons lorsque votre contenu sera prêt.Exécuter en arrière-plan
diff --git a/controller/app/src/main/res/values-gu/strings_k2go.xml b/controller/app/src/main/res/values-gu/strings_k2go.xml
index 909f4d6de..86d3169be 100644
--- a/controller/app/src/main/res/values-gu/strings_k2go.xml
+++ b/controller/app/src/main/res/values-gu/strings_k2go.xml
@@ -525,7 +525,7 @@
કન્ટેન્ટ તૈયાર થઈ રહ્યું છે…મોટા ડાઉનલોડ. તમે તેને ચાલુ છોડી શકો છો.%1$s ડાઉનલોડ થઈ રહ્યું છે
- %2$s%3$s માંથી %1$s · %5$d આઇટમમાંથી %4$d · છૂટે તો ફરી ચાલુ થાય છે
+ %2$s%3$s માંથી %1$s · %5$d આઇટમમાંથી %4$dતેને ચાલુ છોડોતમારું કન્ટેન્ટ તૈયાર થાય ત્યારે અમે તમને જણાવીશું.બૅકગ્રાઉન્ડમાં ચલાવો
diff --git a/controller/app/src/main/res/values-hi/strings_k2go.xml b/controller/app/src/main/res/values-hi/strings_k2go.xml
index 004585903..622bcd894 100644
--- a/controller/app/src/main/res/values-hi/strings_k2go.xml
+++ b/controller/app/src/main/res/values-hi/strings_k2go.xml
@@ -525,7 +525,7 @@
सामग्री तैयार हो रही है…बड़े डाउनलोड। आप इसे चलता छोड़ सकते हैं।%1$s डाउनलोड हो रहा है
- %2$s%3$s में से %1$s · %5$d में से %4$d आइटम · बंद होने पर फिर से शुरू होता है
+ %2$s%3$s में से %1$s · %5$d में से %4$d आइटमइसे चलता छोड़ेंआपकी सामग्री तैयार होने पर हम आपको सूचित करेंगे।बैकग्राउंड में चलाएँ
diff --git a/controller/app/src/main/res/values-hu/strings_k2go.xml b/controller/app/src/main/res/values-hu/strings_k2go.xml
index 4b87de002..c1efcd920 100644
--- a/controller/app/src/main/res/values-hu/strings_k2go.xml
+++ b/controller/app/src/main/res/values-hu/strings_k2go.xml
@@ -525,7 +525,7 @@
Tartalom előkészítése…Nagy letöltések. Hagyhatod futni.%1$s letöltése
- %1$s / %2$s%3$s · %4$d / %5$d elem · folytatódik, ha megszakad
+ %1$s / %2$s%3$s · %4$d / %5$d elemHagyd futniÉrtesítünk, amikor a tartalmad kész.Futtatás a háttérben
diff --git a/controller/app/src/main/res/values-in/strings_k2go.xml b/controller/app/src/main/res/values-in/strings_k2go.xml
index 3995a9974..303eaf011 100644
--- a/controller/app/src/main/res/values-in/strings_k2go.xml
+++ b/controller/app/src/main/res/values-in/strings_k2go.xml
@@ -525,7 +525,7 @@
Menyiapkan konten…Unduhan besar. Anda boleh membiarkannya berjalan.Mengunduh %1$s
- %1$s dari %2$s%3$s · %4$d dari %5$d item · melanjutkan jika terputus
+ %1$s dari %2$s%3$s · %4$d dari %5$d itemBiarkan berjalanKami akan memberi tahu Anda saat konten siap.Jalankan di latar belakang
diff --git a/controller/app/src/main/res/values-it/strings_k2go.xml b/controller/app/src/main/res/values-it/strings_k2go.xml
index f4e07eece..b50f44b24 100644
--- a/controller/app/src/main/res/values-it/strings_k2go.xml
+++ b/controller/app/src/main/res/values-it/strings_k2go.xml
@@ -525,7 +525,7 @@
Preparazione dei contenuti…Download di grandi dimensioni. Puoi lasciarlo in esecuzione.Download di %1$s
- %1$s di %2$s%3$s · %4$d di %5$d elementi · riprende se si interrompe
+ %1$s di %2$s%3$s · %4$d di %5$d elementiLascialo in esecuzioneTi avviseremo quando i tuoi contenuti saranno pronti.Esegui in background
diff --git a/controller/app/src/main/res/values-ja/strings_k2go.xml b/controller/app/src/main/res/values-ja/strings_k2go.xml
index 9627803a7..ac576140d 100644
--- a/controller/app/src/main/res/values-ja/strings_k2go.xml
+++ b/controller/app/src/main/res/values-ja/strings_k2go.xml
@@ -525,7 +525,7 @@
コンテンツを準備中…大規模なダウンロードです。実行したまま離れても構いません。%1$s をダウンロード中
- %2$s%3$s のうち %1$s · %5$d 件のうち %4$d 件 · 中断しても再開
+ %2$s%3$s のうち %1$s · %5$d 件のうち %4$d 件実行したままにするコンテンツの準備ができたら通知します。バックグラウンドで実行
diff --git a/controller/app/src/main/res/values-ko/strings_k2go.xml b/controller/app/src/main/res/values-ko/strings_k2go.xml
index 21fa7c7fa..0585d69b2 100644
--- a/controller/app/src/main/res/values-ko/strings_k2go.xml
+++ b/controller/app/src/main/res/values-ko/strings_k2go.xml
@@ -525,7 +525,7 @@
콘텐츠를 준비하는 중…대규모 다운로드입니다. 실행한 채로 벗어나도 됩니다.%1$s 다운로드 중
- %2$s%3$s 중 %1$s · %5$d개 중 %4$d개 항목 · 중단되면 재개
+ %2$s%3$s 중 %1$s · %5$d개 중 %4$d개 항목실행한 채로 두기콘텐츠가 준비되면 알려드리겠습니다.백그라운드에서 실행
diff --git a/controller/app/src/main/res/values-lt/strings_k2go.xml b/controller/app/src/main/res/values-lt/strings_k2go.xml
index 152685e9a..997c6c218 100644
--- a/controller/app/src/main/res/values-lt/strings_k2go.xml
+++ b/controller/app/src/main/res/values-lt/strings_k2go.xml
@@ -531,7 +531,7 @@
Ruošiamas turinys…Dideli atsisiuntimai. Galite palikti veikti.Atsisiunčiama %1$s
- %1$s iš %2$s%3$s · %4$d iš %5$d elementų · atsinaujina, jei nutrūksta
+ %1$s iš %2$s%3$s · %4$d iš %5$d elementųPalikite veiktiPranešime, kai turinys bus paruoštas.Vykdyti fone
diff --git a/controller/app/src/main/res/values-nl/strings_k2go.xml b/controller/app/src/main/res/values-nl/strings_k2go.xml
index 4022517c4..bfb4281b2 100644
--- a/controller/app/src/main/res/values-nl/strings_k2go.xml
+++ b/controller/app/src/main/res/values-nl/strings_k2go.xml
@@ -525,7 +525,7 @@
Inhoud voorbereiden…Grote downloads. Je kunt het laten doorlopen.%1$s downloaden
- %1$s van %2$s%3$s · %4$d van %5$d items · hervat bij onderbreking
+ %1$s van %2$s%3$s · %4$d van %5$d itemsLaat het doorlopenWe laten het je weten wanneer je inhoud klaar is.Op achtergrond uitvoeren
diff --git a/controller/app/src/main/res/values-no/strings_k2go.xml b/controller/app/src/main/res/values-no/strings_k2go.xml
index ec9690b33..fc3f7a539 100644
--- a/controller/app/src/main/res/values-no/strings_k2go.xml
+++ b/controller/app/src/main/res/values-no/strings_k2go.xml
@@ -531,7 +531,7 @@
Forbereder innhold…Store nedlastinger. Du kan la den kjøre.Laster ned %1$s
- %1$s av %2$s%3$s · %4$d av %5$d elementer · gjenopptas hvis den faller ut
+ %1$s av %2$s%3$s · %4$d av %5$d elementerLa den kjøreVi varsler deg når innholdet ditt er klart.Kjør i bakgrunnen
diff --git a/controller/app/src/main/res/values-pl/strings_k2go.xml b/controller/app/src/main/res/values-pl/strings_k2go.xml
index 77707bb68..9556c086d 100644
--- a/controller/app/src/main/res/values-pl/strings_k2go.xml
+++ b/controller/app/src/main/res/values-pl/strings_k2go.xml
@@ -531,7 +531,7 @@
Przygotowywanie treści…Duże pobieranie. Możesz zostawić je uruchomione.Pobieranie %1$s
- %1$s z %2$s%3$s · %4$d z %5$d elementów · wznawia się po przerwaniu
+ %1$s z %2$s%3$s · %4$d z %5$d elementówZostaw uruchomionePowiadomimy Cię, gdy treść będzie gotowa.Uruchom w tle
diff --git a/controller/app/src/main/res/values-pt/strings_k2go.xml b/controller/app/src/main/res/values-pt/strings_k2go.xml
index ec56787b5..a35c41cdb 100644
--- a/controller/app/src/main/res/values-pt/strings_k2go.xml
+++ b/controller/app/src/main/res/values-pt/strings_k2go.xml
@@ -525,7 +525,7 @@
A preparar o conteúdo…Transferências grandes. Pode deixá-la a decorrer.A transferir %1$s
- %1$s de %2$s%3$s · %4$d de %5$d itens · retoma se cair
+ %1$s de %2$s%3$s · %4$d de %5$d itensDeixe a decorrerNotificá-lo-emos quando o seu conteúdo estiver pronto.Executar em segundo plano
diff --git a/controller/app/src/main/res/values-ro/strings_k2go.xml b/controller/app/src/main/res/values-ro/strings_k2go.xml
index b9c0515bc..328dc9e1b 100644
--- a/controller/app/src/main/res/values-ro/strings_k2go.xml
+++ b/controller/app/src/main/res/values-ro/strings_k2go.xml
@@ -525,7 +525,7 @@
Se pregătește conținutul…Descărcări mari. O poți lăsa să ruleze.Se descarcă %1$s
- %1$s din %2$s%3$s · %4$d din %5$d elemente · se reia dacă se întrerupe
+ %1$s din %2$s%3$s · %4$d din %5$d elementeLas-o să rulezeTe vom anunța când conținutul este gata.Rulează în fundal
diff --git a/controller/app/src/main/res/values-ru-rRU/strings_k2go.xml b/controller/app/src/main/res/values-ru-rRU/strings_k2go.xml
index ad28c0cfa..3e3f0515c 100644
--- a/controller/app/src/main/res/values-ru-rRU/strings_k2go.xml
+++ b/controller/app/src/main/res/values-ru-rRU/strings_k2go.xml
@@ -525,7 +525,7 @@
Подготовка контента…Большие загрузки. Можно оставить работать.Загрузка %1$s
- %1$s из %2$s%3$s · %4$d из %5$d элементов · возобновится при обрыве
+ %1$s из %2$s%3$s · %4$d из %5$d элементовОставьте работатьМы уведомим вас, когда контент будет готов.Работать в фоне
diff --git a/controller/app/src/main/res/values-sk/strings_k2go.xml b/controller/app/src/main/res/values-sk/strings_k2go.xml
index aaf2e45c9..3033152d1 100644
--- a/controller/app/src/main/res/values-sk/strings_k2go.xml
+++ b/controller/app/src/main/res/values-sk/strings_k2go.xml
@@ -525,7 +525,7 @@
Pripravuje sa obsah…Veľké sťahovania. Môžete to nechať bežať.Sťahuje sa %1$s
- %1$s z %2$s%3$s · %4$d z %5$d položiek · po výpadku sa obnoví
+ %1$s z %2$s%3$s · %4$d z %5$d položiekNechajte to bežaťUpozorníme vás, keď bude váš obsah pripravený.Spustiť na pozadí
diff --git a/controller/app/src/main/res/values-sr/strings_k2go.xml b/controller/app/src/main/res/values-sr/strings_k2go.xml
index ad12f0385..91af75f16 100644
--- a/controller/app/src/main/res/values-sr/strings_k2go.xml
+++ b/controller/app/src/main/res/values-sr/strings_k2go.xml
@@ -525,7 +525,7 @@
Припрема садржаја…Велика преузимања. Можете их оставити да раде.Преузимање %1$s
- %1$s од %2$s%3$s · %4$d од %5$d ставки · наставља се ако прекине
+ %1$s од %2$s%3$s · %4$d од %5$d ставкиОставите да радиОбавестићемо вас када ваш садржај буде спреман.Ради у позадини
diff --git a/controller/app/src/main/res/values-sw/strings_k2go.xml b/controller/app/src/main/res/values-sw/strings_k2go.xml
index f8b0a8901..f366c24cb 100644
--- a/controller/app/src/main/res/values-sw/strings_k2go.xml
+++ b/controller/app/src/main/res/values-sw/strings_k2go.xml
@@ -525,7 +525,7 @@
Inaandaa maudhui…Upakuaji mkubwa. Unaweza kuiacha ikiendelea.Inapakua %1$s
- %1$s kati ya %2$s%3$s · %4$d kati ya vipengele %5$d · huendelea ikikatika
+ %1$s kati ya %2$s%3$s · %4$d kati ya vipengele %5$dIache ikiendeleaTutakuarifu maudhui yako yatakapokuwa tayari.Endesha chinichini
diff --git a/controller/app/src/main/res/values-ta/strings_k2go.xml b/controller/app/src/main/res/values-ta/strings_k2go.xml
index 4822795f2..0b6ce4a88 100644
--- a/controller/app/src/main/res/values-ta/strings_k2go.xml
+++ b/controller/app/src/main/res/values-ta/strings_k2go.xml
@@ -525,7 +525,7 @@
உள்ளடக்கம் தயாராகிறது…பெரிய பதிவிறக்கங்கள். இதை இயங்க விட்டுவிடலாம்.%1$s பதிவிறக்கப்படுகிறது
- %2$s%3$s-இல் %1$s · %5$d-இல் %4$d பொருள்கள் · துண்டித்தால் மீண்டும் தொடரும்
+ %2$s%3$s-இல் %1$s · %5$d-இல் %4$d பொருள்கள்இயங்க விடுஉங்கள் உள்ளடக்கம் தயாராகும்போது நாங்கள் உங்களுக்குத் தெரிவிப்போம்.பின்னணியில் இயக்கு
diff --git a/controller/app/src/main/res/values-tr/strings_k2go.xml b/controller/app/src/main/res/values-tr/strings_k2go.xml
index d79c76d89..183d421cd 100644
--- a/controller/app/src/main/res/values-tr/strings_k2go.xml
+++ b/controller/app/src/main/res/values-tr/strings_k2go.xml
@@ -525,7 +525,7 @@
İçerik hazırlanıyor…Büyük indirmeler. Çalışır durumda bırakabilirsiniz.%1$s indiriliyor
- %1$s / %2$s%3$s · %4$d / %5$d öge · bağlantı koparsa sürer
+ %1$s / %2$s%3$s · %4$d / %5$d ögeÇalışır durumda bırakınİçeriğiniz hazır olduğunda sizi bilgilendireceğiz.Arka planda çalıştır
diff --git a/controller/app/src/main/res/values-uk/strings_k2go.xml b/controller/app/src/main/res/values-uk/strings_k2go.xml
index 1dd5e3322..e5dd61a4d 100644
--- a/controller/app/src/main/res/values-uk/strings_k2go.xml
+++ b/controller/app/src/main/res/values-uk/strings_k2go.xml
@@ -525,7 +525,7 @@
Підготовка контенту…Великі завантаження. Ви можете залишити їх виконуватися.Завантаження %1$s
- %1$s з %2$s%3$s · %4$d з %5$d елементів · відновлюється в разі розриву
+ %1$s з %2$s%3$s · %4$d з %5$d елементівЗалишіть виконуватисяМи сповістимо вас, коли контент буде готовий.Виконувати у фоні
diff --git a/controller/app/src/main/res/values-vi/strings_k2go.xml b/controller/app/src/main/res/values-vi/strings_k2go.xml
index 7e4d6d748..671add754 100644
--- a/controller/app/src/main/res/values-vi/strings_k2go.xml
+++ b/controller/app/src/main/res/values-vi/strings_k2go.xml
@@ -525,7 +525,7 @@
Đang chuẩn bị nội dung…Tải lớn. Bạn có thể để nó tiếp tục chạy.Đang tải %1$s
- %1$s trong %2$s%3$s · %4$d trong %5$d mục · tiếp tục lại nếu mất kết nối
+ %1$s trong %2$s%3$s · %4$d trong %5$d mụcĐể nó tiếp tục chạyChúng tôi sẽ thông báo khi nội dung của bạn sẵn sàng.Chạy nền
diff --git a/controller/app/src/main/res/values-yo/strings_k2go.xml b/controller/app/src/main/res/values-yo/strings_k2go.xml
index e453222c1..1654c20a8 100644
--- a/controller/app/src/main/res/values-yo/strings_k2go.xml
+++ b/controller/app/src/main/res/values-yo/strings_k2go.xml
@@ -525,7 +525,7 @@
Ń múra àkóónú sílẹ̀…Gbígbà sílẹ̀ ńlá. O lè fi í sílẹ̀ kí ó máa ṣiṣẹ́.Ń gba %1$s sílẹ̀
- %1$s nínú %2$s%3$s · %4$d nínú nkan %5$d · ń tẹ̀síwájú tí ó bá dánù
+ %1$s nínú %2$s%3$s · %4$d nínú nkan %5$dFi í sílẹ̀ kí ó máa ṣiṣẹ́A óò fi tó ọ létí nígbà tí àkóónú rẹ bá múra tán.Ṣiṣẹ́ lẹ́yìn ẹ̀rọ
diff --git a/controller/app/src/main/res/values-zh-rCN/strings_k2go.xml b/controller/app/src/main/res/values-zh-rCN/strings_k2go.xml
index 900db20de..5d9e93107 100644
--- a/controller/app/src/main/res/values-zh-rCN/strings_k2go.xml
+++ b/controller/app/src/main/res/values-zh-rCN/strings_k2go.xml
@@ -525,7 +525,7 @@
正在准备内容…大型下载。您可以让它继续运行。正在下载 %1$s
- %2$s%3$s 中的 %1$s · %5$d 个项目中的 %4$d 个 · 中断后恢复
+ %2$s%3$s 中的 %1$s · %5$d 个项目中的 %4$d 个让它继续运行内容准备就绪后我们会通知您。在后台运行
diff --git a/controller/app/src/main/res/values/strings_k2go.xml b/controller/app/src/main/res/values/strings_k2go.xml
index 429fb3293..5abf0bf6c 100644
--- a/controller/app/src/main/res/values/strings_k2go.xml
+++ b/controller/app/src/main/res/values/strings_k2go.xml
@@ -643,7 +643,7 @@
Preparing content…Large downloads. You can leave it running.Downloading %1$s
- %1$s of %2$s%3$s · %4$d of %5$d items · resumes if it drops
+ %1$s of %2$s%3$s · %4$d of %5$d itemsLeave it runningWe’ll notify you when your content is ready.Run in background
diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md
index 07dc4de15..58e15c4d3 100644
--- a/static/dashboard/CHANGELOG.md
+++ b/static/dashboard/CHANGELOG.md
@@ -4,6 +4,7 @@ One line per version, newest first. Every REST-facing change bumps the version i
(the app surfaces it via `/system/dashboard/update-check` and the "Update available" pill), so this
file is the human record of what each bump enables. Keep entries short: `version - change (TICKET)`.
+- **1.2.6** - Visible reconnect + honest resume for kiwix (ADFA-4893). The outer reconnect loop now surfaces its state on the poll — `GET /kiwix/jobs/:id` gains `retryAttempt`/`retryTotal` (in-memory, no DB change) — so the app can show "Reconnecting n/5". The schedule is now an explicit **3/6/9/18/36 s** (5 visible waits) instead of exponential, and **pause breaks a backoff wait immediately** (the loop takes `ctx.signal`), so the on-screen X during a reconnect pauses at once. Resume no longer flashes 0%: `runKiwix` stopped sending `percent: 0` on its initial update, so a resumed job keeps its retained percent until aria2 `--continue` re-reports (a fresh job stays `-1` until the first progress). (ADFA-4893)
- **1.2.5** - maps stop/cancel actually stop (ADFA-4896, server half). The maps runner shelled through `sudo`, so pause/cancel only killed the wrapper — the `tile-extract.py` worker kept running, finished in the background, and the region ended up listed even after cancel. Fixes: the extract now spawns **detached** and the engine kills the whole **process group** (`-pid`) so the worker dies with it; the engine also drops **late updates** once a job is paused/canceled, so a slow-dying line can't resurrect the phase; and the maps runner now honors **pause vs cancel** (`classifyStop`) and **purges the partial** on any non-success — it prunes the half-written pmtiles the script leaves in `/library/downloads/maps` (which `tile-extract.py delete` does NOT touch) and runs `delete` (which refreshes extracts.json) for the rare race where the extract finished just as the stop landed. Pause is stop+restart (resume re-extracts clean), cancel removes the region entirely. `cancel()` now also finalizes a **paused** job to `canceled` (Cancel-after-Stop) instead of leaving it stuck at `paused`. No maps per-layer checkpoint yet (→ ADFA-4898). Device-verified: group-kill reaches the pmtiles worker under proot (no background survivor / phantom region). (ADFA-4896)
- **1.2.4** - Download control surface (ADFA-4894, the engine half; app buttons land under ADFA-4896). Adds a **`paused`** job phase and `pause(id)` / `resume(id)` / `retry(id)` to the durable engine, exposed as `POST /:type/jobs/:id/{pause,resume,retry}`. Pause stops the runner but KEEPS the partial (resume continues via aria2 `--continue` for kiwix / per-item for books — the PAUSED-vs-CANCELLED distinction mirrors the APK ADFA-5119); retry re-runs an errored job. maps resume still restarts layers (no per-layer checkpoint yet → ADFA-4898). (ADFA-4894)
- **1.2.3-dev** - Resilient content downloads (ADFA-4894, Area 1 of the ADFA-4893 contract). A network drop mid-job recovers or fails cleanly instead of failing the whole batch at the first blip: a shared `withRetry` backoff helper; job cancel now aborts an in-flight `fetch` (new `AbortSignal` on the runner), not just child processes; **books** get a per-attempt timeout + per-item retry/backoff and no longer fail a batch on one dropped EPUB; **kiwix** prunes the partial `.zim` + `.aria2` on cancel (clean-on-cancel) and gains aria2 reconnect flags (`--max-tries`/`--retry-wait`/`--timeout`, documented divergence from the app's `--max-tries=1` outer-loop model). kiwix also gets an **outer** reconnect loop (`withRetry` around aria2) so a full Wi-Fi drop — where aria2 exits on DNS (code 19) and can't retry itself — recovers across the handoff, resuming via `--continue`; books' retry budget widened to ~30s to outlast a real reassociation. Maps per-layer checkpoint is pending the on-box `tile-extract.py`. Version stays `1.2.3-dev.N` through the PR (device-verified on -dev.1); final bump to `1.2.3` at merge. (ADFA-4894)
diff --git a/static/dashboard/package.json b/static/dashboard/package.json
index 9e08f379a..a781f61bd 100644
--- a/static/dashboard/package.json
+++ b/static/dashboard/package.json
@@ -1,6 +1,6 @@
{
"name": "dashboard-console",
- "version": "1.2.5",
+ "version": "1.2.6",
"description": "",
"main": "index.js",
"scripts": {
diff --git a/static/dashboard/routes.ts b/static/dashboard/routes.ts
index aee816285..c84bfdd43 100644
--- a/static/dashboard/routes.ts
+++ b/static/dashboard/routes.ts
@@ -696,7 +696,8 @@ apiRouter.post('/:type/download', (req: Request, res: Response): void => {
apiRouter.get('/:type/jobs/:id', (req: Request, res: Response): void => {
const job = jobs.get(String(req.params.id));
if (!job || job.type !== String(req.params.type)) { res.status(404).json({ error: 'not found' }); return; }
- res.json(toApi(job));
+ // ADFA-4893: merge the live reconnect state so the poll can surface "Reconnecting n/total".
+ res.json({ ...toApi(job), ...jobs.retrySnapshot(job.id) });
});
// Live log tail for a job (ADFA-4879). Opt-in: a client polls ?since= and appends the
diff --git a/static/dashboard/sockets/jobs.ts b/static/dashboard/sockets/jobs.ts
index 1fbc74069..7cd743a0f 100644
--- a/static/dashboard/sockets/jobs.ts
+++ b/static/dashboard/sockets/jobs.ts
@@ -62,6 +62,8 @@ export interface RunnerContext {
/** Spawn a child that is killed automatically on cancel and untracked on exit. */
spawn(cmd: string, args: string[], opts?: SpawnOptions): ChildProcess;
log(line: string): void;
+ /** ADFA-4893: report reconnect progress so the poll surfaces "Reconnecting n/total". (0,0) clears it. */
+ reportRetry(attempt: number, total: number): void;
}
export type Runner = (ctx: RunnerContext) => Promise;
@@ -94,7 +96,7 @@ const ACTIVE: JobPhase[] = ['queued', 'downloading', 'indexing', 'processing'];
class JobManager {
private db: Database.Database;
private runners = new Map();
- private runtime = new Map; ac: AbortController }>();
+ private runtime = new Map; ac: AbortController; retryAttempt: number; retryTotal: number }>();
// ADFA-4879: bounded rolling log tail per job for the live-log REST endpoint.
private readonly logTail = new RollingLog();
@@ -222,6 +224,12 @@ class JobManager {
return true;
}
+ /** ADFA-4893: live reconnect state for the poll (in-memory; 0/0 when not reconnecting). */
+ retrySnapshot(id: string): { retryAttempt: number; retryTotal: number } {
+ const rt = this.runtime.get(id);
+ return { retryAttempt: rt?.retryAttempt ?? 0, retryTotal: rt?.retryTotal ?? 0 };
+ }
+
/** Resume jobs that were mid-flight when the dashboard last stopped. */
reconcileOnBoot(): void {
const stuck = this.db.prepare(
@@ -266,7 +274,7 @@ class JobManager {
const runner = this.runners.get(job.type);
if (!runner) { this.patch(job.id, { phase: 'error', error: `no runner for ${job.type}` }); return; }
- const rt = { canceled: false, paused: false, procs: new Set(), ac: new AbortController() };
+ const rt = { canceled: false, paused: false, procs: new Set(), ac: new AbortController(), retryAttempt: 0, retryTotal: 0 };
this.runtime.set(job.id, rt);
let items: unknown[] = [];
@@ -282,6 +290,7 @@ class JobManager {
throwIfCanceled: () => { if (rt.canceled) throw new CanceledError(); },
isPaused: () => rt.paused,
signal: rt.ac.signal,
+ reportRetry: (attempt, total) => { rt.retryAttempt = attempt; rt.retryTotal = total; },
spawn: (cmd, args, opts) => {
const child = opts ? spawn(cmd, args, opts) : spawn(cmd, args);
rt.procs.add(child);
diff --git a/static/dashboard/sockets/kiwix.exec.ts b/static/dashboard/sockets/kiwix.exec.ts
index 19d96317a..08946ba7b 100644
--- a/static/dashboard/sockets/kiwix.exec.ts
+++ b/static/dashboard/sockets/kiwix.exec.ts
@@ -65,9 +65,9 @@ const ARIA2_ARGS: string[] = [
// (file exists) — those are terminal. Budget ~30s to outlast a Wi-Fi reassociation.
// 1 unknown · 2 timeout · 6 network · 7 unfinished · 19 DNS · 29 HTTP 503
const ARIA2_TRANSIENT_EXITS = new Set([1, 2, 6, 7, 19, 29]);
-const KIWIX_DL_TRIES = 5;
-const KIWIX_RETRY_BASE_MS = 2_000;
-const KIWIX_RETRY_MAX_MS = 15_000;
+// ADFA-4893: 5 VISIBLE reconnect waits (3, 6, 9, 18, 36 s ≈ 72 s total). Surfaced on the poll as
+// "Reconnecting n/5"; the app renders it and can cancel a wait (which pauses via ctx.signal).
+const KIWIX_RETRY_DELAYS = [3_000, 6_000, 9_000, 18_000, 36_000];
/** Convert an aria2 rate token ("34MiB", "512KiB", "1.2MB") to bytes/sec. */
function parseRate(token: string): number {
@@ -144,7 +144,9 @@ const kiwixRunner: (ctx: RunnerContext) => Promise = async (ctx) => {
ctx.throwIfCanceled();
// --- Download phase -----------------------------------------------------
- ctx.update({ phase: 'downloading', percent: 0, speed: 0, detail: files.join(', ') });
+ // ADFA-4893: don't send percent here — a fresh job keeps -1 (indeterminate until aria2 reports),
+ // and a RESUME keeps its retained percent instead of flashing 0 before --continue re-reports.
+ ctx.update({ phase: 'downloading', speed: 0, detail: files.join(', ') });
// Each id already carries its project subdir on the mirror (/zim//).
const urls = ids.map((z) => BASE_URL + z);
@@ -159,7 +161,7 @@ const kiwixRunner: (ctx: RunnerContext) => Promise = async (ctx) => {
let lastPct = -1;
let lastRate = '';
while ((m = re.exec(text)) !== null) { lastPct = parseInt(m[1], 10); lastRate = m[2]; }
- if (lastPct >= 0) ctx.update({ phase: 'downloading', percent: lastPct, speed: parseRate(lastRate) });
+ if (lastPct >= 0) { ctx.reportRetry(0, 0); ctx.update({ phase: 'downloading', percent: lastPct, speed: parseRate(lastRate) }); }
};
dl.stdout?.on('data', onData);
dl.stderr?.on('data', onData);
@@ -174,12 +176,15 @@ const kiwixRunner: (ctx: RunnerContext) => Promise = async (ctx) => {
reject(err);
});
}), {
- tries: KIWIX_DL_TRIES,
- baseMs: KIWIX_RETRY_BASE_MS,
- maxMs: KIWIX_RETRY_MAX_MS,
+ delaysMs: KIWIX_RETRY_DELAYS, // ADFA-4893: 3/6/9/18/36 s, 5 visible reconnects
+ tries: KIWIX_RETRY_DELAYS.length + 1,
+ signal: ctx.signal, // pause/cancel breaks the backoff sleep at once
isCanceled: ctx.isCanceled,
isTransient: (e) => ARIA2_TRANSIENT_EXITS.has((e as { code?: number }).code ?? -1),
- onRetry: ({ attempt, err }) => ctx.log(`[kiwix] reconnect attempt ${attempt} after: ${err instanceof Error ? err.message : String(err)}`),
+ onRetry: ({ attempt, err }) => {
+ ctx.reportRetry(attempt, KIWIX_RETRY_DELAYS.length); // poll shows "Reconnecting attempt/5"
+ ctx.log(`[kiwix] reconnect ${attempt}/${KIWIX_RETRY_DELAYS.length} after: ${err instanceof Error ? err.message : String(err)}`);
+ },
});
} catch (e) {
// ADFA-4894: pause KEEPS the partial (+ .aria2) so resume continues via --continue; cancel
diff --git a/static/dashboard/sockets/net-retry.test.ts b/static/dashboard/sockets/net-retry.test.ts
index 647a5882d..70976faec 100644
--- a/static/dashboard/sockets/net-retry.test.ts
+++ b/static/dashboard/sockets/net-retry.test.ts
@@ -13,6 +13,23 @@ test('withRetry: returns on the first success, no retries', async () => {
assert.equal(calls, 1);
});
+test('withRetry: ADFA-4893 delaysMs drives the exact schedule (3/6/9/18/36), tries defaults to N+1', async () => {
+ const waited: number[] = [];
+ const onRetried: number[] = [];
+ let calls = 0;
+ await assert.rejects(
+ withRetry(async () => { calls++; throw new Error('down'); }, {
+ delaysMs: [3000, 6000, 9000, 18000, 36000],
+ sleep: async (ms: number) => { waited.push(ms); },
+ onRetry: ({ attempt }) => { onRetried.push(attempt); },
+ }),
+ /down/,
+ );
+ assert.equal(calls, 6); // N+1 attempts = 5 visible reconnects
+ assert.deepEqual(waited, [3000, 6000, 9000, 18000, 36000]); // exact schedule, no jitter
+ assert.deepEqual(onRetried, [1, 2, 3, 4, 5]); // "Reconnecting n/5" ordinals
+});
+
test('withRetry: retries a transient failure then succeeds', async () => {
let calls = 0;
const out = await withRetry(async (attempt) => {
diff --git a/static/dashboard/sockets/net-retry.ts b/static/dashboard/sockets/net-retry.ts
index 2a9830ebf..7d4a7bf1b 100644
--- a/static/dashboard/sockets/net-retry.ts
+++ b/static/dashboard/sockets/net-retry.ts
@@ -19,6 +19,10 @@ export interface RetryOpts {
baseMs?: number;
/** Upper bound on a single backoff. Default 8000. */
maxMs?: number;
+ /** ADFA-4893: explicit backoff schedule in ms; overrides baseMs/maxMs/jitter. The wait after a
+ * failed attempt k (1-based) is delaysMs[k-1] (clamped to the last entry). With N delays and
+ * tries defaulting to N+1, this yields N visible reconnect waits. */
+ delaysMs?: number[];
/** Fraction of jitter added to each delay [0..1]. Default 0.2. */
jitter?: number;
/** Aborts the loop (between and, via fetch, within attempts). */
@@ -56,7 +60,7 @@ function aborted(opts: RetryOpts): boolean {
* @param fn receives the 1-based attempt number.
*/
export async function withRetry(fn: (attempt: number) => Promise, opts: RetryOpts = {}): Promise {
- const tries = Math.max(1, opts.tries ?? 4);
+ const tries = Math.max(1, opts.tries ?? (opts.delaysMs ? opts.delaysMs.length + 1 : 4));
const baseMs = opts.baseMs ?? 500;
const maxMs = opts.maxMs ?? 8000;
const jitter = opts.jitter ?? 0.2;
@@ -72,8 +76,9 @@ export async function withRetry(fn: (attempt: number) => Promise, opts: Re
lastErr = err;
if (err instanceof Aborted || aborted(opts)) throw new Aborted();
if (attempt >= tries || !isTransient(err)) throw err;
- const backoff = Math.min(maxMs, baseMs * 2 ** (attempt - 1));
- const delayMs = Math.round(backoff * (1 + Math.random() * jitter));
+ const delayMs = opts.delaysMs
+ ? opts.delaysMs[Math.min(attempt - 1, opts.delaysMs.length - 1)]
+ : Math.round(Math.min(maxMs, baseMs * 2 ** (attempt - 1)) * (1 + Math.random() * jitter));
opts.onRetry?.({ attempt, delayMs, err });
await sleep(delayMs, opts.signal); // throws Aborted if the signal fires mid-backoff
}