From 7d9d7fecb41ce00e43e46f2e4133cdfedc939b37 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Tue, 25 Aug 2026 22:40:47 -0600 Subject: [PATCH 1/7] ADFA-4893 refactor(ui): extract shared DownloadControls for the status-screen row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ZimPreparingFragment and BooksDownloadsFragment each carried an identical copy of the control row (the Pause⇄Resume⇄Retry morph + always-Cancel wiring + visibility). Extract it to one DownloadControls helper driven by a small Controller that abstracts each stream's service; both fragments now bind it and call render(). No behavior change — same buttons, same states, same labels (reconnect/paused stay per-fragment on their own detail line). --- .../redesign/BooksDownloadsFragment.java | 55 +++++++-------- .../controller/redesign/DownloadControls.java | 67 +++++++++++++++++++ .../redesign/ZimPreparingFragment.java | 66 +++++++----------- 3 files changed, 116 insertions(+), 72 deletions(-) create mode 100644 controller/app/src/main/java/org/iiab/controller/redesign/DownloadControls.java diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadsFragment.java b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadsFragment.java index 0c5530be6..9a341efd4 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadsFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadsFragment.java @@ -40,8 +40,7 @@ public class BooksDownloadsFragment extends Fragment { private TextView detail; private LinearLayout listv; private Button finishBtn, runBgBtn; - private LinearLayout controls; // ADFA-4893: session control row (pause/resume + cancel) - private Button pauseBtn, cancelBtn; + private DownloadControls dlControls; // ADFA-4893: shared status-screen control row private boolean pauseSupported = false; // ADFA-4893: box dash-node >= 1.2.4 exposes pause/resume private boolean fromIndex; // hosted by the Finishing-setup index: hide own buttons, only observe @@ -56,6 +55,8 @@ public static BooksDownloadsFragment newInstance(boolean fromIndex) { private int px(int dp) { return Math.round(dp * getResources().getDisplayMetrics().density); } + private android.content.Context ctx() { return requireContext().getApplicationContext(); } + @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle s) { @@ -76,27 +77,26 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c requireActivity().getSupportFragmentManager().popBackStack(); }); - // ADFA-4893: session controls, homologated with ZIM — primary morphs Pause -> Resume -> Retry. - controls = root.findViewById(R.id.k2go_bdl_controls); - pauseBtn = root.findViewById(R.id.k2go_bdl_pause); - cancelBtn = root.findViewById(R.id.k2go_bdl_cancel); - pauseBtn.setOnClickListener(v -> { - android.content.Context ctx = requireContext().getApplicationContext(); - if (!BooksDownloadService.isRunning() && BooksDownloadService.hasFailed()) BooksDownloadService.retryFailed(ctx); - else if (BooksDownloadService.isPaused()) BooksDownloadService.resume(ctx); - else BooksDownloadService.pause(ctx); - }); - cancelBtn.setOnClickListener(v -> { - android.content.Context ctx = requireContext().getApplicationContext(); - if (BooksDownloadService.isRunning()) { - ContextCompat.startForegroundService(ctx, - new Intent(ctx, BooksDownloadService.class).setAction(BooksDownloadService.ACTION_CANCEL)); - } else { - BooksDownloadService.finishSession(); - render(); - } - }); + // ADFA-4893: the shared status-screen control row (homologated with ZIM). pauseSupported = DashboardVersion.atLeast(DashboardVersion.installed(requireContext()), 1, 2, 4); + dlControls = new DownloadControls( + root.findViewById(R.id.k2go_bdl_controls), + root.findViewById(R.id.k2go_bdl_pause), + root.findViewById(R.id.k2go_bdl_cancel), + new DownloadControls.Controller() { + @Override public boolean isRunning() { return BooksDownloadService.isRunning(); } + @Override public boolean isPaused() { return BooksDownloadService.isPaused(); } + @Override public boolean hasFailed() { return BooksDownloadService.hasFailed(); } + @Override public boolean pauseSupported() { return pauseSupported; } + @Override public void pause() { BooksDownloadService.pause(ctx()); } + @Override public void resume() { BooksDownloadService.resume(ctx()); } + @Override public void retryFailed() { BooksDownloadService.retryFailed(ctx()); } + @Override public void cancelRunning() { + ContextCompat.startForegroundService(ctx(), + new Intent(ctx(), BooksDownloadService.class).setAction(BooksDownloadService.ACTION_CANCEL)); + } + @Override public void dismiss() { BooksDownloadService.finishSession(); render(); } + }); if (fromIndex) { // the index host provides Back/Finish; this card only observes finishBtn.setVisibility(View.GONE); @@ -118,7 +118,6 @@ private void render() { int done = 0; for (int st : status) if (st == BooksDownloadService.DONE) done++; - boolean anyFailed = BooksDownloadService.hasFailed(); boolean running = BooksDownloadService.isRunning(); boolean paused = BooksDownloadService.isPaused(); int rc = BooksDownloadService.reconnectAttempt(); @@ -128,15 +127,7 @@ private void render() { drawChecklist(titles, status); - // ADFA-4893: morphing control row (Pause -> Resume -> Retry) + Cancel, same as ZIM. Shown while - // running (needs pause support >= 1.2.4) or whenever a book failed (Retry works on any version). - 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); - } + dlControls.render(); // ADFA-4893: shared morph Pause/Resume/Retry + Cancel if (!fromIndex) { boolean complete = BooksDownloadService.isComplete(); diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/DownloadControls.java b/controller/app/src/main/java/org/iiab/controller/redesign/DownloadControls.java new file mode 100644 index 000000000..10be53fec --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/redesign/DownloadControls.java @@ -0,0 +1,67 @@ +/* + * ============================================================================ + * Name : DownloadControls.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4893. Shared status-screen control row for the content download streams + * (ZIM, Books, ...): one primary button that morphs Pause -> Resume -> Retry, plus a + * Cancel that is always present. Both ZimPreparingFragment and BooksDownloadsFragment + * used to carry an identical copy of this wiring; this is the single source. The poll + * (the stream's service) is the source of truth via the Controller getters — the row + * only reads state and dispatches the right action per tap. + * ============================================================================ + */ +package org.iiab.controller.redesign; + +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; + +import org.iiab.controller.R; + +public final class DownloadControls { + + /** Abstracts a stream's service (its static state + actions) so one row drives ZIM or Books. */ + public interface Controller { + boolean isRunning(); + boolean isPaused(); + boolean hasFailed(); + boolean pauseSupported(); // box dash-node >= 1.2.4 exposes pause/resume + void pause(); + void resume(); + void retryFailed(); + void cancelRunning(); // ACTION_CANCEL on the running session + void dismiss(); // clear a terminal/failed session (finishSession) + } + + private final LinearLayout row; + private final Button primary, cancel; + private final Controller c; + + public DownloadControls(LinearLayout row, Button primary, Button cancel, Controller c) { + this.row = row; this.primary = primary; this.cancel = cancel; this.c = c; + // The action is decided at tap time from the live state, so we never remove/re-add buttons. + primary.setOnClickListener(v -> { + if (!c.isRunning() && c.hasFailed()) c.retryFailed(); + else if (c.isPaused()) c.resume(); + else c.pause(); + }); + // Cancel is always available: cancels a running session, or dismisses a failed/terminal one. + cancel.setOnClickListener(v -> { + if (c.isRunning()) c.cancelRunning(); + else c.dismiss(); + }); + } + + /** Reflect the live state: visible while running (needs pause support) or whenever an item failed + * (Retry works on any dash-node version); primary text morphs Pause -> Resume -> Retry. */ + public void render() { + boolean show = (c.isRunning() && c.pauseSupported()) || c.hasFailed(); + row.setVisibility(show ? View.VISIBLE : View.GONE); + if (show) { + if (!c.isRunning() && c.hasFailed()) primary.setText(R.string.k2go_dl_retry); + else if (c.isPaused()) primary.setText(R.string.k2go_dl_resume); + else primary.setText(R.string.k2go_dl_pause); + } + } +} 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 a24c29c43..98a75fe5c 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 @@ -36,9 +36,8 @@ 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) + private DownloadControls dlControls; // ADFA-4893: shared status-screen control row + 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 @@ -59,33 +58,27 @@ 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. + // ADFA-4893: the shared status-screen control row (morph Pause -> Resume -> Retry + Cancel). + // Gate on dash-node >= 1.2.4 (pause/resume); older boxes hide it (notification Cancel stands in). pauseSupported = DashboardVersion.atLeast(DashboardVersion.installed(requireContext()), 1, 2, 4); + dlControls = new DownloadControls( + root.findViewById(R.id.k2go_zprep_controls), + root.findViewById(R.id.k2go_zprep_pause), + root.findViewById(R.id.k2go_zprep_cancel), + new DownloadControls.Controller() { + @Override public boolean isRunning() { return ZimDownloadService.isRunning(); } + @Override public boolean isPaused() { return ZimDownloadService.isPaused(); } + @Override public boolean hasFailed() { return ZimDownloadService.hasFailed(); } + @Override public boolean pauseSupported() { return pauseSupported; } + @Override public void pause() { ZimDownloadService.pause(ctx()); } + @Override public void resume() { ZimDownloadService.resume(ctx()); } + @Override public void retryFailed() { ZimDownloadService.retryFailed(ctx()); } + @Override public void cancelRunning() { + ContextCompat.startForegroundService(ctx(), + new Intent(ctx(), ZimDownloadService.class).setAction(ZimDownloadService.ACTION_CANCEL)); + } + @Override public void dismiss() { ZimDownloadService.finishSession(); render(); } + }); // 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); @@ -103,7 +96,7 @@ private void render() { int idx = ZimDownloadService.index(); int p = ZimDownloadService.percent(); int n = labels.length; - if (n == 0) { controls.setVisibility(View.GONE); return; } + if (n == 0) { dlControls.render(); 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. @@ -150,16 +143,7 @@ private void render() { 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); - } + dlControls.render(); // ADFA-4893: shared morph Pause/Resume/Retry + Cancel drawChecklist(labels, status); } @@ -179,6 +163,8 @@ private static int firstFailed(int[] status) { return -1; } + private android.content.Context ctx() { return requireContext().getApplicationContext(); } + private String gb(long mb) { // ADFA-4910: one standard size formatter for the whole UI return org.iiab.controller.util.ByteFormatter.humanMb(mb); } From 5b125b6fd96f85af6fd68dc17ee836faa3d731b1 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Tue, 25 Aug 2026 22:41:22 -0600 Subject: [PATCH 2/7] ADFA-4893 chore(dashnode): finalize dash-node 1.2.7 (drop -dev) (package.json + CHANGELOG heading). No behavior change. --- static/dashboard/CHANGELOG.md | 2 +- static/dashboard/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md index c0abae5f7..999bdfcd1 100644 --- a/static/dashboard/CHANGELOG.md +++ b/static/dashboard/CHANGELOG.md @@ -4,7 +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.7-dev** - Books homologated to the ZIM contract (ADFA-4893). The books runner now surfaces its reconnect state on the poll (`retryAttempt`/`retryTotal` via `ctx.reportRetry`), so the app can show "Reconnecting… n of N" like ZIM/rootfs (books' per-item budget is 6 tries → shows n of 5, same label). And the runner is now **idempotent on resume**: it skips books already in the Calibre-Web library (matched by title) instead of re-downloading + re-uploading them — which used to duplicate entries and reset the percent to 0 — so a resume, or a re-run after process death, is safe. Version stays `1.2.7-dev.N` through the PR; final `1.2.7` at merge. (ADFA-4893) +- **1.2.7** - Books homologated to the ZIM contract (ADFA-4893). The books runner now surfaces its reconnect state on the poll (`retryAttempt`/`retryTotal` via `ctx.reportRetry`), so the app can show "Reconnecting… n of N" like ZIM/rootfs (books' per-item budget is 6 tries → shows n of 5, same label). And the runner is now **idempotent on resume**: it skips books already in the Calibre-Web library (matched by title) instead of re-downloading + re-uploading them — which used to duplicate entries and reset the percent to 0 — so a resume, or a re-run after process death, is safe. (ADFA-4893) - **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) diff --git a/static/dashboard/package.json b/static/dashboard/package.json index 62dd03272..4560a8c84 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -1,6 +1,6 @@ { "name": "dashboard-console", - "version": "1.2.7-dev.1", + "version": "1.2.7", "description": "", "main": "index.js", "scripts": { From b44e9d07117f2ca3028c5038ac356a8acb3e2546 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Tue, 25 Aug 2026 22:50:59 -0600 Subject: [PATCH 3/7] ADFA-4893 refactor(zim): move the queue/client engine into shared ContentDownloadSession Extract the sequential-queue + RestContentClient wiring + progress/pause/reconnect state that Zim/Books both carry into one ContentDownloadSession (one instance per service, so their static state never collides). ZimDownloadService is now a thin foreground shell: keeps the ZIM specifics (file/label/byte arrays, {ids:[..]} body, byte-weighted percent) + the notification, attaches itself as the session Host, and delegates the queue and all observed state. Public static API unchanged (UI observers untouched). Cancel purges the session (unchanged behavior). Books next. --- .../redesign/ContentDownloadSession.java | 207 ++++++++++++++ .../redesign/ZimDownloadService.java | 267 +++++------------- 2 files changed, 278 insertions(+), 196 deletions(-) create mode 100644 controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java new file mode 100644 index 000000000..ea541d33f --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java @@ -0,0 +1,207 @@ +/* + * ============================================================================ + * Name : ContentDownloadSession.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4893. The one download-session engine shared by the content streams (ZIM, Books, + * ...). It owns the sequential queue, the shared RestContentClient wiring, and all the + * state (progress, paused, reconnect, heartbeat) that the UI observes; ZimDownloadService + * and BooksDownloadService used to carry an identical copy of this. Each service holds ONE + * instance (so their static session state never collides) and delegates to it, attaching + * itself as {@link Host} for the per-type body/percent and the foreground notification. + * The device only POSTs + polls; the server owns download reconnection (visible). + * ============================================================================ + */ +package org.iiab.controller.redesign; + +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; + +import org.iiab.controller.content.RestContentClient; +import org.json.JSONObject; + +public final class ContentDownloadSession { + + /** Per-item status, shared by all streams. */ + public static final int PENDING = 0, ACTIVE = 1, PROCESSING = 2, DONE = 3, FAILED = 4; + + /** UI observer: pinged whenever session state changes (same shape both services exposed). */ + public interface Listener { void onUpdate(); } + + /** Per-type hooks the owning Service provides (body, percent, notification, stop). */ + public interface Host { + JSONObject buildBody(int i); // start body for item i (kiwix {ids:[..]}, books {items:[..]}) + int overallPercent(); // per-type overall percent (byte-weighted vs item-count) + String label(int i); // display label for item i (notification) + void notify(String label); // update the foreground notification + void stop(); // stopForeground(true) + stopSelf() + } + + private final String type; // "kiwix" / "books" -> /api/ + private final Handler main = new Handler(Looper.getMainLooper()); + private static final long POLL_MS = 1000L; + + private Host host; + private Listener listener; + private RestContentClient client; + + private volatile boolean running = false; + private volatile boolean paused = false; + private volatile int reconnectAttempt = 0; + private volatile int reconnectTotal = 0; + private volatile long lastProgressAt = 0L; // ADFA-5146 heartbeat + private int[] status = new int[0]; + private int index = 0; + private int percent = 0; + private long speed = 0; + + public ContentDownloadSession(String type) { this.type = type; } + + /** The Service attaches itself before dispatching an action (foreground/notification live there). */ + public void attach(Host h) { this.host = h; } + public void setListener(Listener l) { this.listener = l; } + + // ---- observed state (the services' static getters delegate here) -------------------------- + public boolean isRunning() { return running; } + public boolean isPaused() { return paused; } + public int reconnectAttempt() { return reconnectAttempt; } + public int reconnectTotal() { return reconnectTotal; } + public int[] status() { return status; } + public int index() { return index; } + public int percent() { return percent; } + public long speed() { return speed; } + public boolean hasSession() { return status.length > 0; } + public boolean isComplete() { + if (status.length == 0 || running) return false; + for (int st : status) if (st == PENDING || st == ACTIVE || st == PROCESSING) return false; + return true; + } + public boolean isActiveNow() { + return hasSession() && !isComplete() + && org.iiab.controller.env.Freshness.fresh( + lastProgressAt, SystemClock.elapsedRealtime(), org.iiab.controller.env.Freshness.STALE_MS); + } + public boolean hasFailed() { + for (int st : status) if (st == FAILED) return true; + return false; + } + /** Overall percent for the bars — delegated to the per-type Host (byte-weighted vs item-count). */ + public int overallPercent() { return host != null ? host.overallPercent() : 0; } + + // ---- actions (the services' onStartCommand / statics delegate here) ------------------------ + + /** Fresh session over {@code count} items (status all PENDING), then start pumping the queue. */ + public void begin(int count) { + status = new int[count]; + index = 0; percent = 0; speed = 0; + paused = false; reconnectAttempt = 0; reconnectTotal = 0; + running = true; + lastProgressAt = SystemClock.elapsedRealtime(); + pump(); + } + + /** Resume the queue after failed items were re-queued to PENDING (ACTION_RETRY). */ + public void resumeQueue() { + running = true; + lastProgressAt = SystemClock.elapsedRealtime(); + pump(); + } + + /** Re-queue ALL failed items to PENDING (for a status-screen Retry). Returns true if any changed. */ + public boolean requeueFailed() { + boolean any = false; + for (int i = 0; i < status.length; i++) if (status[i] == FAILED) { status[i] = PENDING; any = true; } + return any; + } + + public void pauseActive() { + if (client != null) client.pause(); + paused = true; publish(); + } + + public void resumeActive() { + if (client != null) client.resume(); + paused = false; publish(); + } + + /** Cancel the in-flight job AND purge the session so it doesn't sit in limbo / block the next drain, + * then stop the foreground service. */ + public void cancelAndPurge() { + if (client != null) client.cancel(); + purge(); + publish(); + if (host != null) host.stop(); + } + + /** Clear all session state (the services' finishSession()). */ + public void purge() { + status = new int[0]; + index = 0; percent = 0; speed = 0; + running = false; paused = false; reconnectAttempt = 0; reconnectTotal = 0; + lastProgressAt = 0L; + } + + private int firstPending() { + for (int i = 0; i < status.length; i++) if (status[i] == PENDING) return i; + return -1; + } + + private void pump() { + int i = firstPending(); + if (i < 0) { running = false; publish(); if (host != null) host.stop(); return; } + index = i; percent = 0; status[i] = ACTIVE; + publish(); + if (host != null) host.notify(host.label(i)); + startItem(i); + } + + private void startItem(final int i) { + client = new RestContentClient(type); + client.start(host.buildBody(i), new RestContentClient.Listener() { + @Override public void onProgress(int pct, String rate) { + if (paused) paused = false; + reconnectAttempt = 0; + percent = pct; speed = parseRate(rate); + lastProgressAt = SystemClock.elapsedRealtime(); + if (status[i] != PROCESSING) status[i] = ACTIVE; + publish(); + if (host != null) host.notify(host.label(i)); + } + @Override public void onIndexing() { + status[i] = PROCESSING; lastProgressAt = SystemClock.elapsedRealtime(); publish(); + } + @Override public void onPaused(int pct) { + percent = pct; paused = true; lastProgressAt = SystemClock.elapsedRealtime(); publish(); + } + @Override public void onReconnecting(int attempt, int total) { + reconnectAttempt = attempt; reconnectTotal = total; + lastProgressAt = SystemClock.elapsedRealtime(); publish(); + } + @Override public void onLog(String line) { /* logcat only */ } + @Override public void onDone() { status[i] = DONE; publish(); pump(); } + @Override public void onError(String message) { + // ADFA-4893: server owns reconnection (visible); on give-up, FAILED for a manual Retry. + android.util.Log.w("K2Go-Provision", "[" + type + "] job [" + i + "] error: " + message); + status[i] = FAILED; reconnectAttempt = 0; publish(); pump(); + } + }); + } + + private void publish() { main.post(() -> { if (listener != null) listener.onUpdate(); }); } + + /** "3.4 MB" display token -> bytes/sec (books send none -> 0). */ + private static long parseRate(String s) { + if (s == null) return 0; + try { + String t = s.trim(); + int sp = t.indexOf(' '); + if (sp < 0) return 0; + double v = Double.parseDouble(t.substring(0, sp)); + String u = t.substring(sp + 1); + double m = "GB".equals(u) ? 1024d * 1024 * 1024 : "MB".equals(u) ? 1024d * 1024 + : "KB".equals(u) ? 1024d : 1d; + return Math.round(v * m); + } catch (Exception e) { return 0; } + } +} 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 f63253012..e20f4e934 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 @@ -3,13 +3,11 @@ * Name : ZimDownloadService.java * Author : AppDevForAll * Copyright : Copyright (c) 2026 AppDevForAll - * Description : ADFA-4849. Foreground service that downloads the ZIM selection cart through the - * in-server REST job engine (RestContentClient / ADFA-4838/4840): one job per ZIM, - * SEQUENTIALLY, CONTINUING past a failed item. The heavy work runs on the live - * Debian/proot server (durable there); the device only POSTs + polls, so this - * service is light. It holds the session state; the Preparing screen observes it, - * re-attaches, RETRIES failed items (re-queued), and FINISHES (clears the session). - * Resume/checksum of a partial download is the SERVER's job; a retry just re-POSTs. + * Description : ADFA-4849 / ADFA-4893. Foreground shell for the ZIM stream: it owns the notification + * and the ZIM-specific bits (file/label/byte arrays, the {ids:[..]} body, byte-weighted + * percent) and delegates the queue + client + progress/pause/reconnect state to the + * shared ContentDownloadSession. The static getters below keep the same API the UI has + * always observed. The heavy work runs on the server; the device only POSTs + polls. * ============================================================================ */ package org.iiab.controller.redesign; @@ -31,9 +29,10 @@ import androidx.core.content.ContextCompat; import org.iiab.controller.R; -import org.iiab.controller.content.RestContentClient; +import org.json.JSONArray; +import org.json.JSONObject; -public final class ZimDownloadService extends Service { +public final class ZimDownloadService extends Service implements ContentDownloadSession.Host { private static final String CHANNEL_ID = "zim_download_channel"; private static final int NOTIFICATION_ID = 5; @@ -41,72 +40,45 @@ 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 ACTION_PAUSE = "org.iiab.controller.ZIM_DOWNLOAD_PAUSE"; + public static final String ACTION_RESUME = "org.iiab.controller.ZIM_DOWNLOAD_RESUME"; public static final String EXTRA_FILES = "files"; public static final String EXTRA_LABELS = "labels"; public static final String EXTRA_BYTES = "bytes"; - public static final int PENDING = 0, ACTIVE = 1, INDEXING = 2, DONE = 3, FAILED = 4; + // Per-item status — same values the UI/checklist already use, sourced from the shared session. + public static final int PENDING = ContentDownloadSession.PENDING; + public static final int ACTIVE = ContentDownloadSession.ACTIVE; + public static final int INDEXING = ContentDownloadSession.PROCESSING; + public static final int DONE = ContentDownloadSession.DONE; + public static final int FAILED = ContentDownloadSession.FAILED; + /** Kept for the callers that pass {@code this::render}; adapts to the session listener. */ public interface Listener { void onUpdate(); } - // ---- shared state for the single active session (observed by the Preparing screen) ---- - private static volatile boolean sRunning = false; // a job is actively being processed + private static final ContentDownloadSession SESSION = new ContentDownloadSession("kiwix"); + // ZIM-specific session data (labels/files/sizes); the queue/progress state lives in SESSION. private static String[] sFiles = new String[0]; private static String[] sLabels = new String[0]; private static long[] sBytes = new long[0]; - private static int[] sStatus = new int[0]; - private static int sIndex = 0; - 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() { - if (sFiles.length == 0 || sRunning) return false; - for (int st : sStatus) if (st == PENDING || st == ACTIVE || st == INDEXING) return false; - return true; - } - /** ADFA-5146: a non-terminal session still counts as busy only while its heartbeat is fresh. - * A service killed before a terminal state lets {@code sLastProgressAt} go cold, so a dead - * session stops blocking deep operations without the app being force-stopped. */ - public static boolean isActiveNow() { - return hasSession() && !isComplete() - && org.iiab.controller.env.Freshness.fresh( - sLastProgressAt, android.os.SystemClock.elapsedRealtime(), - org.iiab.controller.env.Freshness.STALE_MS); - } + // ---- static API the UI observes (delegates to the shared session) ------------------------- + public static boolean isRunning() { return SESSION.isRunning(); } + public static boolean isPaused() { return SESSION.isPaused(); } + public static int reconnectAttempt() { return SESSION.reconnectAttempt(); } + public static int reconnectTotal() { return SESSION.reconnectTotal(); } + public static boolean hasSession() { return SESSION.hasSession(); } + public static boolean isComplete() { return SESSION.isComplete(); } + public static boolean isActiveNow() { return SESSION.isActiveNow(); } + public static boolean hasFailed() { return SESSION.hasFailed(); } + public static int[] status() { return SESSION.status(); } + public static int index() { return SESSION.index(); } + public static int percent() { return SESSION.percent(); } + public static long speed() { return SESSION.speed(); } + public static int overallPercent() { return SESSION.overallPercent(); } public static String[] labels() { return sLabels; } public static long[] bytes() { return sBytes; } - public static int[] status() { return sStatus; } - public static int index() { return sIndex; } - public static int percent() { return sPercent; } - 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 setListener(Listener l) { SESSION.setListener(l == null ? null : l::onUpdate); } public static void start(Context ctx, String[] files, String[] labels, long[] bytes) { Intent i = new Intent(ctx, ZimDownloadService.class).setAction(ACTION_START) @@ -114,80 +86,44 @@ public static void start(Context ctx, String[] files, String[] labels, long[] by ContextCompat.startForegroundService(ctx, i); } - /** 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; + if (!SESSION.isRunning()) 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. */ + /** ADFA-4893: re-queue ALL failed items and resume — the status-screen Retry (Pause morphs into it). */ 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) { + if (SESSION.requeueFailed() && !SESSION.isRunning()) { ContextCompat.startForegroundService(ctx, new Intent(ctx, ZimDownloadService.class).setAction(ACTION_RETRY)); } } - /** 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; sPaused = false; - sReconnectAttempt = 0; sReconnectTotal = 0; sLastProgressAt = 0L; - } + public static void finishSession() { SESSION.purge(); sFiles = new String[0]; sLabels = new String[0]; sBytes = new long[0]; } private final Handler main = new Handler(Looper.getMainLooper()); - private RestContentClient client; - @Override public void onCreate() { super.onCreate(); createNotificationChannel(); } + @Override public void onCreate() { super.onCreate(); createNotificationChannel(); SESSION.attach(this); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { + SESSION.attach(this); String action = intent != null ? intent.getAction() : null; - if (ACTION_CANCEL.equals(action)) { - if (client != null) client.cancel(); - // ADFA-4893: PURGE the session (same as Books). A canceled item left non-terminal can't be - // dismissed and blocks the next drain (PendingContent.anyUnfinished). finishSession() clears it. - finishSession(); - publish(); - main.post(() -> { stopForeground(true); stopSelf(); }); - return START_NOT_STICKY; - } + if (ACTION_CANCEL.equals(action)) { SESSION.cancelAndPurge(); return START_NOT_STICKY; } + if (ACTION_PAUSE.equals(action)) { SESSION.pauseActive(); return START_NOT_STICKY; } + if (ACTION_RESUME.equals(action)) { SESSION.resumeActive(); 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 (SESSION.isRunning()) return START_NOT_STICKY; if (ACTION_RETRY.equals(action)) { - if (!hasSession()) { stopSelf(); return START_NOT_STICKY; } + if (!SESSION.hasSession()) { stopSelf(); return START_NOT_STICKY; } + startForeground(NOTIFICATION_ID, buildNotification(label(SESSION.index()))); + SESSION.resumeQueue(); } else { // ACTION_START: fresh session from the extras String[] f = intent.getStringArrayExtra(EXTRA_FILES); if (f == null || f.length == 0) { stopSelf(); return START_NOT_STICKY; } @@ -196,94 +132,41 @@ public int onStartCommand(Intent intent, int flags, int startId) { sBytes = intent.getLongArrayExtra(EXTRA_BYTES); if (sLabels == null) sLabels = sFiles; if (sBytes == null) sBytes = new long[sFiles.length]; - sStatus = new int[sFiles.length]; - 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 + startForeground(NOTIFICATION_ID, buildNotification(sLabels.length > 0 ? sLabels[0] : "")); + SESSION.begin(sFiles.length); } - - sRunning = true; - startForeground(NOTIFICATION_ID, buildNotification(currentLabel())); - processNext(); return START_NOT_STICKY; } - private static int firstPending() { - for (int i = 0; i < sStatus.length; i++) if (sStatus[i] == PENDING) return i; - return -1; - } - - private String currentLabel() { - return sIndex >= 0 && sIndex < sLabels.length ? sLabels[sIndex] : ""; + // ---- ContentDownloadSession.Host (ZIM specifics) ------------------------------------------ + @Override public JSONObject buildBody(int i) { + try { return new JSONObject().put("ids", new JSONArray().put(sFiles[i])); } + catch (Exception e) { return new JSONObject(); } } - private void processNext() { - int i = firstPending(); - if (i < 0) { sessionComplete(); return; } - sIndex = i; sPercent = 0; sStatus[i] = ACTIVE; - publish(); - updateNotification(sLabels[i]); - startItem(i); - } + @Override public String label(int i) { return i >= 0 && i < sLabels.length ? sLabels[i] : ""; } - private void startItem(final int i) { - android.util.Log.i("K2Go-Provision", "zim job start [" + i + "] file='" + sFiles[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); - sStatus[i] = FAILED; sReconnectAttempt = 0; publish(); processNext(); - } - }); + /** Byte-weighted overall percent: done/failed count in full, the active item adds its live percent. */ + @Override public int overallPercent() { + int[] status = SESSION.status(); + int idx = SESSION.index(); + int p = SESSION.percent(); + long total = 0, done = 0; + for (int i = 0; i < sBytes.length && i < status.length; i++) { + total += sBytes[i]; + if (status[i] == DONE || status[i] == FAILED) done += sBytes[i]; + else if (i == idx && (status[i] == ACTIVE || status[i] == INDEXING) && p >= 0) done += sBytes[i] * p / 100; + } + return total > 0 ? (int) Math.min(100, done * 100 / total) : (SESSION.isComplete() ? 100 : 0); } - private void sessionComplete() { - sRunning = false; - publish(); - main.post(() -> { stopForeground(true); stopSelf(); }); + @Override public void notify(String label) { + if (!SESSION.isRunning()) return; + NotificationManager m = getSystemService(NotificationManager.class); + if (m != null) m.notify(NOTIFICATION_ID, buildNotification(label)); } - private void publish() { main.post(() -> { if (sListener != null) sListener.onUpdate(); }); } - - private static long parseRate(String s) { - if (s == null) return 0; - try { - String t = s.trim(); - int sp = t.indexOf(' '); - if (sp < 0) return 0; - double v = Double.parseDouble(t.substring(0, sp)); - String u = t.substring(sp + 1); - double m = "GB".equals(u) ? 1024d * 1024 * 1024 : "MB".equals(u) ? 1024d * 1024 - : "KB".equals(u) ? 1024d : 1d; - return Math.round(v * m); - } catch (Exception e) { return 0; } - } + @Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { @@ -295,8 +178,6 @@ private void createNotificationChannel() { } private Notification buildNotification(String currentLabel) { - // ADFA-4987: the redesign progress screen, not the legacy UI. ADFA-5074: the index, not - // this stream's detail — it is the only surface that can end the run. Intent open = new Intent(this, SetupProgressActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, open, @@ -315,10 +196,4 @@ private Notification buildNotification(String currentLabel) { .addAction(0, getString(R.string.k2go_zim_notif_cancel), cancelIntent) .build(); } - - private void updateNotification(String currentLabel) { - if (!sRunning) return; - NotificationManager manager = getSystemService(NotificationManager.class); - if (manager != null) manager.notify(NOTIFICATION_ID, buildNotification(currentLabel)); - } } From 00663b0260d5f8230c16681bb566acc63fb5cd2c Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Tue, 25 Aug 2026 22:57:44 -0600 Subject: [PATCH 4/7] ADFA-4893 fix(zim): rename Host.overallPercent -> computeOverallPercent (name clash) The Host callback and the static UI getter were both overallPercent(); a static method can't implement the interface method. Rename the per-type Host hook to computeOverallPercent(); the static overallPercent() (UI) delegates to it through the session. No behavior change. --- .../org/iiab/controller/redesign/ContentDownloadSession.java | 4 ++-- .../java/org/iiab/controller/redesign/ZimDownloadService.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java index ea541d33f..ca214932c 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java @@ -32,7 +32,7 @@ public interface Listener { void onUpdate(); } /** Per-type hooks the owning Service provides (body, percent, notification, stop). */ public interface Host { JSONObject buildBody(int i); // start body for item i (kiwix {ids:[..]}, books {items:[..]}) - int overallPercent(); // per-type overall percent (byte-weighted vs item-count) + int computeOverallPercent(); // per-type overall percent (byte-weighted vs item-count) String label(int i); // display label for item i (notification) void notify(String label); // update the foreground notification void stop(); // stopForeground(true) + stopSelf() @@ -87,7 +87,7 @@ public boolean hasFailed() { return false; } /** Overall percent for the bars — delegated to the per-type Host (byte-weighted vs item-count). */ - public int overallPercent() { return host != null ? host.overallPercent() : 0; } + public int overallPercent() { return host != null ? host.computeOverallPercent() : 0; } // ---- actions (the services' onStartCommand / statics delegate here) ------------------------ 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 e20f4e934..d8b6d7ca3 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 @@ -147,7 +147,7 @@ public int onStartCommand(Intent intent, int flags, int startId) { @Override public String label(int i) { return i >= 0 && i < sLabels.length ? sLabels[i] : ""; } /** Byte-weighted overall percent: done/failed count in full, the active item adds its live percent. */ - @Override public int overallPercent() { + @Override public int computeOverallPercent() { int[] status = SESSION.status(); int idx = SESSION.index(); int p = SESSION.percent(); From 4a4b426a22252284f54e63f06dc1ff3dd13e6a4b Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Tue, 25 Aug 2026 23:02:52 -0600 Subject: [PATCH 5/7] ADFA-4893 refactor(books): delegate to shared ContentDownloadSession (converge with ZIM) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BooksDownloadService becomes a thin foreground shell like ZimDownloadService: it keeps the Books specifics (id/title/url arrays, {items:[..]} body, item-count percent) + the notification, attaches as the session Host, and delegates the queue and all observed state to ContentDownloadSession. Removes the last copy of the queue/client engine — ZIM and Books now share one mechanism. Public static API unchanged (UI observers untouched); cancel purges the session. --- .../redesign/BooksDownloadService.java | 229 ++++++------------ 1 file changed, 70 insertions(+), 159 deletions(-) diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java index 00ab4f233..78ed74bb2 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java @@ -3,12 +3,12 @@ * Name : BooksDownloadService.java * Author : AppDevForAll * Copyright : Copyright (c) 2026 AppDevForAll - * Description : ADFA-4850. Foreground download manager for Books, following the ZIM pattern - * (CLAUDE.md): sequential, ONE AT A TIME (kind to Project Gutenberg), continuing - * past a failed item, per-item retry, "Finish" to clear the session. Each book is - * its own durable REST job: POST /api/books/download {items:[{id,title,url}]} then - * poll /api/books/jobs/:id (the server downloads the EPUB from Gutenberg and - * uploads it into Calibre-Web). The device only POSTs + polls. + * Description : ADFA-4850 / ADFA-4893. Foreground shell for the Books stream: owns the notification and + * the Books-specific bits (id/title/url arrays, the {items:[{id,title,url}]} body, + * item-count percent) and delegates the queue + client + progress/pause/reconnect state + * to the shared ContentDownloadSession — the same engine ZIM uses, so both behave + * identically. The server downloads each EPUB from Gutenberg and uploads it into + * Calibre-Web; the device only POSTs + polls. * ============================================================================ */ package org.iiab.controller.redesign; @@ -33,7 +33,7 @@ import org.json.JSONArray; import org.json.JSONObject; -public final class BooksDownloadService extends Service { +public final class BooksDownloadService extends Service implements ContentDownloadSession.Host { private static final String CHANNEL_ID = "books_download_channel"; private static final int NOTIFICATION_ID = 6; @@ -41,66 +41,42 @@ public final class BooksDownloadService extends Service { public static final String ACTION_START = "org.iiab.controller.BOOKS_DOWNLOAD_START"; public static final String ACTION_RETRY = "org.iiab.controller.BOOKS_DOWNLOAD_RETRY"; public static final String ACTION_CANCEL = "org.iiab.controller.BOOKS_DOWNLOAD_CANCEL"; - public static final String ACTION_PAUSE = "org.iiab.controller.BOOKS_DOWNLOAD_PAUSE"; // ADFA-4893 - public static final String ACTION_RESUME = "org.iiab.controller.BOOKS_DOWNLOAD_RESUME"; // ADFA-4893 + public static final String ACTION_PAUSE = "org.iiab.controller.BOOKS_DOWNLOAD_PAUSE"; + public static final String ACTION_RESUME = "org.iiab.controller.BOOKS_DOWNLOAD_RESUME"; public static final String EXTRA_IDS = "ids"; public static final String EXTRA_TITLES = "titles"; public static final String EXTRA_URLS = "urls"; - public static final int PENDING = 0, ACTIVE = 1, ADDING = 2, DONE = 3, FAILED = 4; + // Per-item status — same values the UI/checklist already use, sourced from the shared session. + public static final int PENDING = ContentDownloadSession.PENDING; + public static final int ACTIVE = ContentDownloadSession.ACTIVE; + public static final int ADDING = ContentDownloadSession.PROCESSING; + public static final int DONE = ContentDownloadSession.DONE; + public static final int FAILED = ContentDownloadSession.FAILED; + /** Kept for the callers that pass {@code this::render}; adapts to the session listener. */ public interface Listener { void onUpdate(); } - // ---- shared session state (observed by the Downloads screen) ---- - private static volatile boolean sRunning = false; + private static final ContentDownloadSession SESSION = new ContentDownloadSession("books"); + // Books-specific session data; the queue/progress state lives in SESSION. private static String[] sIds = new String[0]; private static String[] sTitles = new String[0]; private static String[] sUrls = new String[0]; - private static int[] sStatus = new int[0]; - private static int sIndex = 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 - 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 sIds.length > 0; } - public static boolean isComplete() { - if (sIds.length == 0 || sRunning) return false; - for (int st : sStatus) if (st == PENDING || st == ACTIVE || st == ADDING) return false; - return true; - } - /** ADFA-5146: busy only while the poll heartbeat is fresh — a killed service lets it go cold. */ - public static boolean isActiveNow() { - return hasSession() && !isComplete() - && org.iiab.controller.env.Freshness.fresh( - sLastProgressAt, android.os.SystemClock.elapsedRealtime(), - org.iiab.controller.env.Freshness.STALE_MS); - } + // ---- static API the UI observes (delegates to the shared session) ------------------------- + public static boolean isRunning() { return SESSION.isRunning(); } + public static boolean isPaused() { return SESSION.isPaused(); } + public static int reconnectAttempt() { return SESSION.reconnectAttempt(); } + public static int reconnectTotal() { return SESSION.reconnectTotal(); } + public static boolean hasSession() { return SESSION.hasSession(); } + public static boolean isComplete() { return SESSION.isComplete(); } + public static boolean isActiveNow() { return SESSION.isActiveNow(); } + public static boolean hasFailed() { return SESSION.hasFailed(); } + public static int[] status() { return SESSION.status(); } + public static int index() { return SESSION.index(); } + public static int overallPercent() { return SESSION.overallPercent(); } public static String[] titles() { return sTitles; } - public static int[] status() { return sStatus; } - public static int index() { return sIndex; } - public static void setListener(Listener l) { sListener = l; } - - /** ADFA-4893: true when any book 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: overall percent by item count (books have no per-item byte size) — one source for the - * status-screen bar and the index row bar, mirroring ZimDownloadService.overallPercent(). */ - public static int overallPercent() { - int n = sStatus.length; - if (n == 0) return isComplete() ? 100 : 0; - int done = 0; - for (int st : sStatus) if (st == DONE || st == FAILED) done++; - return (int) Math.min(100, (long) done * 100 / n); - } + public static void setListener(Listener l) { SESSION.setListener(l == null ? null : l::onUpdate); } public static void start(Context ctx, String[] ids, String[] titles, String[] urls) { Intent i = new Intent(ctx, BooksDownloadService.class).setAction(ACTION_START) @@ -108,66 +84,45 @@ public static void start(Context ctx, String[] ids, String[] titles, String[] ur ContextCompat.startForegroundService(ctx, i); } - /** ADFA-4893: pause the active book job (server keeps state). No-op if nothing is running. */ public static void pause(Context ctx) { - if (!sRunning) return; + if (!SESSION.isRunning()) return; ContextCompat.startForegroundService(ctx, new Intent(ctx, BooksDownloadService.class).setAction(ACTION_PAUSE)); } - /** ADFA-4893: resume a paused book job. */ public static void resume(Context ctx) { ContextCompat.startForegroundService(ctx, new Intent(ctx, BooksDownloadService.class).setAction(ACTION_RESUME)); } /** ADFA-4893: re-queue ALL failed books and resume — the status-screen Retry (Pause morphs into it). */ 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, BooksDownloadService.class).setAction(ACTION_RETRY)); + if (SESSION.requeueFailed() && !SESSION.isRunning()) { + ContextCompat.startForegroundService(ctx, new Intent(ctx, BooksDownloadService.class).setAction(ACTION_RETRY)); + } } - public static void finishSession() { - sIds = new String[0]; sTitles = new String[0]; sUrls = new String[0]; sStatus = new int[0]; - sIndex = 0; sRunning = false; sPaused = false; - sReconnectAttempt = 0; sReconnectTotal = 0; sLastProgressAt = 0L; - } + public static void finishSession() { SESSION.purge(); sIds = new String[0]; sTitles = new String[0]; sUrls = new String[0]; } private final Handler main = new Handler(Looper.getMainLooper()); - private org.iiab.controller.content.RestContentClient client; // ADFA-4893: shared REST client (books) - @Override public void onCreate() { super.onCreate(); createNotificationChannel(); } + @Override public void onCreate() { super.onCreate(); createNotificationChannel(); SESSION.attach(this); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { + SESSION.attach(this); String action = intent != null ? intent.getAction() : null; - if (ACTION_CANCEL.equals(action)) { - if (client != null) client.cancel(); - // ADFA-4893: PURGE the session. A canceled item must not linger non-terminal (ACTIVE), or it - // can't be dismissed (Finish disabled, controls hidden) AND it blocks the next drain - // (PendingContent.anyUnfinished stays true). finishSession() clears hasSession/isComplete. - finishSession(); - publish(); - main.post(() -> { stopForeground(true); stopSelf(); }); - return START_NOT_STICKY; - } - // ADFA-4893: pause/resume the active job, handled before the sRunning guard (paused == running). - 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_CANCEL.equals(action)) { SESSION.cancelAndPurge(); return START_NOT_STICKY; } + if (ACTION_PAUSE.equals(action)) { SESSION.pauseActive(); return START_NOT_STICKY; } + if (ACTION_RESUME.equals(action)) { SESSION.resumeActive(); return START_NOT_STICKY; } + + if (SESSION.isRunning()) return START_NOT_STICKY; if (ACTION_RETRY.equals(action)) { - if (!hasSession()) { stopSelf(); return START_NOT_STICKY; } - } else { + if (!SESSION.hasSession()) { stopSelf(); return START_NOT_STICKY; } + startForeground(NOTIFICATION_ID, buildNotification(label(SESSION.index()))); + SESSION.resumeQueue(); + } else { // ACTION_START: fresh session from the extras String[] ids = intent.getStringArrayExtra(EXTRA_IDS); if (ids == null || ids.length == 0) { stopSelf(); return START_NOT_STICKY; } sIds = ids; @@ -175,74 +130,39 @@ public int onStartCommand(Intent intent, int flags, int startId) { sUrls = intent.getStringArrayExtra(EXTRA_URLS); if (sTitles == null) sTitles = ids; if (sUrls == null) sUrls = new String[ids.length]; - sStatus = new int[ids.length]; - sIndex = 0; sPaused = false; sReconnectAttempt = 0; sReconnectTotal = 0; + startForeground(NOTIFICATION_ID, buildNotification(sTitles.length > 0 ? sTitles[0] : "")); + SESSION.begin(sIds.length); } - sRunning = true; - sLastProgressAt = android.os.SystemClock.elapsedRealtime(); // ADFA-5146: seed the heartbeat - startForeground(NOTIFICATION_ID, buildNotification(currentTitle())); - processNext(); return START_NOT_STICKY; } - private static int firstPending() { - for (int i = 0; i < sStatus.length; i++) if (sStatus[i] == PENDING) return i; - return -1; + // ---- ContentDownloadSession.Host (Books specifics) ---------------------------------------- + @Override public JSONObject buildBody(int i) { + try { + JSONObject item = new JSONObject().put("id", sIds[i]).put("title", sTitles[i]).put("url", sUrls[i]); + return new JSONObject().put("items", new JSONArray().put(item)); + } catch (Exception e) { return new JSONObject(); } } - private String currentTitle() { return sIndex >= 0 && sIndex < sTitles.length ? sTitles[sIndex] : ""; } + @Override public String label(int i) { return i >= 0 && i < sTitles.length ? sTitles[i] : ""; } - private void processNext() { - int i = firstPending(); - if (i < 0) { sessionComplete(); return; } - sIndex = i; sStatus[i] = ACTIVE; - publish(); - updateNotification(sTitles[i]); - startItem(i); - } - - private void startItem(final int i) { - android.util.Log.i("K2Go-Provision", "books job start [" + i + "] id=" + sIds[i] + " title='" + sTitles[i] + "'"); - final JSONObject body; - try { - JSONObject item = new JSONObject().put("id", sIds[i]).put("title", sTitles[i]).put("url", sUrls[i]); - body = new JSONObject().put("items", new JSONArray().put(item)); - } catch (Exception e) { sStatus[i] = FAILED; publish(); processNext(); return; } - // ADFA-4893: books now share the ZIM REST client; the server owns reconnection (visible), and the - // kickoff POST retry lives in the client. No app-side re-POST loop. - client = new org.iiab.controller.content.RestContentClient("books"); - client.start(body, new org.iiab.controller.content.RestContentClient.Listener() { - @Override public void onProgress(int percent, String speed) { - if (sPaused) sPaused = false; - sReconnectAttempt = 0; - sLastProgressAt = android.os.SystemClock.elapsedRealtime(); - if (sStatus[i] != ADDING) sStatus[i] = ACTIVE; - publish(); - } - @Override public void onIndexing() { sStatus[i] = ADDING; sLastProgressAt = android.os.SystemClock.elapsedRealtime(); publish(); } - @Override public void onPaused(int percent) { - sPaused = true; sLastProgressAt = android.os.SystemClock.elapsedRealtime(); publish(); - } - @Override public void onReconnecting(int attempt, int total) { - 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", "books job done [" + i + "]"); sStatus[i] = DONE; publish(); processNext(); } - @Override public void onError(String message) { - // ADFA-4893: server owns reconnection (visible); on give-up mark FAILED for a manual Retry. - android.util.Log.w("K2Go-Provision", "books job [" + i + "] error: " + message); - sStatus[i] = FAILED; sReconnectAttempt = 0; publish(); processNext(); - } - }); + /** Item-count overall percent (books carry no per-item byte size). */ + @Override public int computeOverallPercent() { + int[] status = SESSION.status(); + int n = status.length; + if (n == 0) return SESSION.isComplete() ? 100 : 0; + int done = 0; + for (int st : status) if (st == DONE || st == FAILED) done++; + return (int) Math.min(100, (long) done * 100 / n); } - private void sessionComplete() { - sRunning = false; publish(); - main.post(() -> { stopForeground(true); stopSelf(); }); + @Override public void notify(String label) { + if (!SESSION.isRunning()) return; + NotificationManager m = getSystemService(NotificationManager.class); + if (m != null) m.notify(NOTIFICATION_ID, buildNotification(label)); } - private void publish() { main.post(() -> { if (sListener != null) sListener.onUpdate(); }); } + @Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { @@ -254,8 +174,6 @@ private void createNotificationChannel() { } private Notification buildNotification(String title) { - // ADFA-4987: the redesign progress screen, not the legacy UI. ADFA-5074: the index, not - // this stream's detail — it is the only surface that can end the run. Intent openI = new Intent(this, SetupProgressActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent open = PendingIntent.getActivity(this, 0, openI, @@ -274,11 +192,4 @@ private Notification buildNotification(String title) { .addAction(0, getString(R.string.k2go_zim_notif_cancel), cancel) .build(); } - - private void updateNotification(String title) { - if (!sRunning) return; - NotificationManager m = getSystemService(NotificationManager.class); - if (m != null) m.notify(NOTIFICATION_ID, buildNotification(title)); - } - } From c37dc5d93da4810f1c6c23e64f5f9ae1408eb3d7 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Wed, 26 Aug 2026 00:00:57 -0600 Subject: [PATCH 6/7] Fix ZIM cancel crash: purge clears per-type arrays (ADFA-4893) Cancel purged the shared session state (status -> length 0) but left ZimDownloadService's label/byte arrays populated, so ZimPreparingFragment derived n from labels and indexed status[] off the end -> AIOOBE, which killed the app (and took proot/dash-node down with it). - ContentDownloadSession.purge() now calls Host.onPurged() so the owning service clears its per-type arrays together with the session state; the snapshot the UI reads is length-consistent after a Cancel. - ZimPreparingFragment.render() derives n from the shortest of the arrays it indexes (labels/bytes/status) as defense in depth. Books already popped back on empty, so it never tripped this. --- .../org/iiab/controller/redesign/BooksDownloadService.java | 3 +++ .../iiab/controller/redesign/ContentDownloadSession.java | 7 ++++++- .../org/iiab/controller/redesign/ZimDownloadService.java | 4 ++++ .../org/iiab/controller/redesign/ZimPreparingFragment.java | 7 +++++-- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java index 78ed74bb2..f1d139635 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java @@ -164,6 +164,9 @@ public int onStartCommand(Intent intent, int flags, int startId) { @Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); } + /** Clear the Books-specific arrays alongside the session state (parity with ZIM's onPurged). */ + @Override public void onPurged() { sIds = new String[0]; sTitles = new String[0]; sUrls = new String[0]; } + private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel ch = new NotificationChannel( diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java index ca214932c..60bf81114 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java @@ -36,6 +36,7 @@ public interface Host { String label(int i); // display label for item i (notification) void notify(String label); // update the foreground notification void stop(); // stopForeground(true) + stopSelf() + void onPurged(); // clear the per-type arrays so the snapshot stays consistent } private final String type; // "kiwix" / "books" -> /api/ @@ -134,12 +135,16 @@ public void cancelAndPurge() { if (host != null) host.stop(); } - /** Clear all session state (the services' finishSession()). */ + /** Clear all session state (the services' finishSession()). Also clears the owner's per-type arrays + * via {@link Host#onPurged()} so the snapshot the UI reads stays length-consistent (labels/status/ + * bytes all empty together) — otherwise a Cancel left labels>0 with status=0 and the ZIM fragment + * indexed status[] off the label count → AIOOBE (ADFA-4893). */ public void purge() { status = new int[0]; index = 0; percent = 0; speed = 0; running = false; paused = false; reconnectAttempt = 0; reconnectTotal = 0; lastProgressAt = 0L; + if (host != null) host.onPurged(); } private int firstPending() { 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 d8b6d7ca3..9e708f062 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 @@ -168,6 +168,10 @@ public int onStartCommand(Intent intent, int flags, int startId) { @Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); } + /** Clear the ZIM-specific arrays alongside the session state, so a Cancel purge leaves + * labels/status/bytes empty together (no length mismatch for the fragment to trip over). */ + @Override public void onPurged() { sFiles = new String[0]; sLabels = new String[0]; sBytes = new long[0]; } + private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( 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 98a75fe5c..112281234 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 @@ -95,7 +95,10 @@ private void render() { int[] status = ZimDownloadService.status(); int idx = ZimDownloadService.index(); int p = ZimDownloadService.percent(); - int n = labels.length; + // Derive n from the shortest of the arrays this method indexes (labels/bytes/status). A Cancel + // purge clears them together now, but a snapshot read mid-purge could still see a mismatch — + // clamping here means the loop below can never index past any array (ADFA-4893, defense in depth). + int n = Math.min(labels.length, Math.min(bytes.length, status.length)); if (n == 0) { dlControls.render(); return; } // Byte figures for the "X of Y · N of M" detail line; the bar percent comes from the single @@ -124,7 +127,7 @@ private void render() { // 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) + label.setText(f >= 0 && f < labels.length ? 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); From 8d041bf3fcc76b009ac1f1c7ee5aacba9d464a18 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Wed, 26 Aug 2026 00:40:44 -0600 Subject: [PATCH 7/7] Move per-item snapshot into ContentDownloadSession (ADFA-4893) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to the Cancel-crash fix: instead of each service keeping its own label/size arrays that Host.onPurged() had to clear in lock-step with the session's status[], the session now owns the whole per-item snapshot (labels/sizes/bodies), set together with status in begin() and cleared together in purge(). Length-consistency is now structural — status[] and the metadata the UI indexes off it cannot diverge — so a future content type can't reintroduce the AIOOBE by forgetting to clear an array. - ContentDownloadSession holds labels/sizes/bodies; begin(labels,sizes,bodies); overallPercent() computed here (byte-weighted, count fallback for books). - Host shrinks to notify(label)+stop(); buildBody/label/computeOverallPercent/ onPurged removed. Services build the start bodies once and pass the snapshot in. - ZimPreparingFragment keeps the min-length clamp as cheap defense in depth. --- .../redesign/BooksDownloadService.java | 54 ++++-------- .../redesign/ContentDownloadSession.java | 84 +++++++++++++------ .../redesign/ZimDownloadService.java | 60 ++++--------- .../redesign/ZimPreparingFragment.java | 5 +- 4 files changed, 99 insertions(+), 104 deletions(-) diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java index f1d139635..32d1c2038 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java @@ -58,10 +58,8 @@ public final class BooksDownloadService extends Service implements ContentDownlo public interface Listener { void onUpdate(); } private static final ContentDownloadSession SESSION = new ContentDownloadSession("books"); - // Books-specific session data; the queue/progress state lives in SESSION. - private static String[] sIds = new String[0]; - private static String[] sTitles = new String[0]; - private static String[] sUrls = new String[0]; + // The whole per-item snapshot (id/title/url-as-bodies, titles-as-labels) now lives in SESSION, so + // status and the metadata the UI indexes off it stay length-consistent by construction (ADFA-4893). // ---- static API the UI observes (delegates to the shared session) ------------------------- public static boolean isRunning() { return SESSION.isRunning(); } @@ -75,7 +73,7 @@ public interface Listener { void onUpdate(); } public static int[] status() { return SESSION.status(); } public static int index() { return SESSION.index(); } public static int overallPercent() { return SESSION.overallPercent(); } - public static String[] titles() { return sTitles; } + public static String[] titles() { return SESSION.labels(); } public static void setListener(Listener l) { SESSION.setListener(l == null ? null : l::onUpdate); } public static void start(Context ctx, String[] ids, String[] titles, String[] urls) { @@ -100,7 +98,7 @@ public static void retryFailed(Context ctx) { } } - public static void finishSession() { SESSION.purge(); sIds = new String[0]; sTitles = new String[0]; sUrls = new String[0]; } + public static void finishSession() { SESSION.purge(); } private final Handler main = new Handler(Looper.getMainLooper()); @@ -120,42 +118,29 @@ public int onStartCommand(Intent intent, int flags, int startId) { if (ACTION_RETRY.equals(action)) { if (!SESSION.hasSession()) { stopSelf(); return START_NOT_STICKY; } - startForeground(NOTIFICATION_ID, buildNotification(label(SESSION.index()))); + startForeground(NOTIFICATION_ID, buildNotification(SESSION.label(SESSION.index()))); SESSION.resumeQueue(); } else { // ACTION_START: fresh session from the extras String[] ids = intent.getStringArrayExtra(EXTRA_IDS); if (ids == null || ids.length == 0) { stopSelf(); return START_NOT_STICKY; } - sIds = ids; - sTitles = intent.getStringArrayExtra(EXTRA_TITLES); - sUrls = intent.getStringArrayExtra(EXTRA_URLS); - if (sTitles == null) sTitles = ids; - if (sUrls == null) sUrls = new String[ids.length]; - startForeground(NOTIFICATION_ID, buildNotification(sTitles.length > 0 ? sTitles[0] : "")); - SESSION.begin(sIds.length); + String[] titles = intent.getStringArrayExtra(EXTRA_TITLES); + String[] urls = intent.getStringArrayExtra(EXTRA_URLS); + if (titles == null) titles = ids; + if (urls == null) urls = new String[ids.length]; + JSONObject[] bodies = new JSONObject[ids.length]; + for (int i = 0; i < ids.length; i++) { + try { + JSONObject item = new JSONObject().put("id", ids[i]).put("title", titles[i]).put("url", urls[i]); + bodies[i] = new JSONObject().put("items", new JSONArray().put(item)); + } catch (Exception e) { bodies[i] = new JSONObject(); } + } + startForeground(NOTIFICATION_ID, buildNotification(titles.length > 0 ? titles[0] : "")); + SESSION.begin(titles, null, bodies); // books: no per-item byte size -> count-based percent } return START_NOT_STICKY; } // ---- ContentDownloadSession.Host (Books specifics) ---------------------------------------- - @Override public JSONObject buildBody(int i) { - try { - JSONObject item = new JSONObject().put("id", sIds[i]).put("title", sTitles[i]).put("url", sUrls[i]); - return new JSONObject().put("items", new JSONArray().put(item)); - } catch (Exception e) { return new JSONObject(); } - } - - @Override public String label(int i) { return i >= 0 && i < sTitles.length ? sTitles[i] : ""; } - - /** Item-count overall percent (books carry no per-item byte size). */ - @Override public int computeOverallPercent() { - int[] status = SESSION.status(); - int n = status.length; - if (n == 0) return SESSION.isComplete() ? 100 : 0; - int done = 0; - for (int st : status) if (st == DONE || st == FAILED) done++; - return (int) Math.min(100, (long) done * 100 / n); - } - @Override public void notify(String label) { if (!SESSION.isRunning()) return; NotificationManager m = getSystemService(NotificationManager.class); @@ -164,9 +149,6 @@ public int onStartCommand(Intent intent, int flags, int startId) { @Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); } - /** Clear the Books-specific arrays alongside the session state (parity with ZIM's onPurged). */ - @Override public void onPurged() { sIds = new String[0]; sTitles = new String[0]; sUrls = new String[0]; } - private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel ch = new NotificationChannel( diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java index 60bf81114..af0d4a1ae 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java @@ -4,12 +4,15 @@ * Author : AppDevForAll * Copyright : Copyright (c) 2026 AppDevForAll * Description : ADFA-4893. The one download-session engine shared by the content streams (ZIM, Books, - * ...). It owns the sequential queue, the shared RestContentClient wiring, and all the - * state (progress, paused, reconnect, heartbeat) that the UI observes; ZimDownloadService - * and BooksDownloadService used to carry an identical copy of this. Each service holds ONE - * instance (so their static session state never collides) and delegates to it, attaching - * itself as {@link Host} for the per-type body/percent and the foreground notification. - * The device only POSTs + polls; the server owns download reconnection (visible). + * ...). It owns the sequential queue, the shared RestContentClient wiring, ALL the state + * the UI observes (progress, paused, reconnect, heartbeat) AND the per-item snapshot + * (labels / sizes / start-bodies). Holding the snapshot here — set together with status in + * begin(), cleared together in purge() — makes length-consistency a structural invariant: + * status[] and the metadata the UI indexes off it can never diverge, so a Cancel can't + * leave the fragment indexing one array off another (the AIOOBE we fixed). Each service + * holds ONE instance and delegates to it, attaching itself as {@link Host} only to build + * the foreground notification and stop itself. The device only POSTs + polls; the server + * owns download reconnection (visible). * ============================================================================ */ package org.iiab.controller.redesign; @@ -29,19 +32,16 @@ public final class ContentDownloadSession { /** UI observer: pinged whenever session state changes (same shape both services exposed). */ public interface Listener { void onUpdate(); } - /** Per-type hooks the owning Service provides (body, percent, notification, stop). */ + /** Per-type hooks the owning Service provides. The session owns the queue AND the per-item snapshot, + * so the service is left only with the foreground notification and its own stop — there is no + * per-type array for it to keep length-consistent anymore (ADFA-4893). */ public interface Host { - JSONObject buildBody(int i); // start body for item i (kiwix {ids:[..]}, books {items:[..]}) - int computeOverallPercent(); // per-type overall percent (byte-weighted vs item-count) - String label(int i); // display label for item i (notification) - void notify(String label); // update the foreground notification + void notify(String label); // update the foreground notification for the current item void stop(); // stopForeground(true) + stopSelf() - void onPurged(); // clear the per-type arrays so the snapshot stays consistent } private final String type; // "kiwix" / "books" -> /api/ private final Handler main = new Handler(Looper.getMainLooper()); - private static final long POLL_MS = 1000L; private Host host; private Listener listener; @@ -53,6 +53,12 @@ public interface Host { private volatile int reconnectTotal = 0; private volatile long lastProgressAt = 0L; // ADFA-5146 heartbeat private int[] status = new int[0]; + // Per-item snapshot — same length as status by construction (set together in begin(), cleared + // together in purge()). bodies[i] is the REST start request for item i (kiwix {ids:[..]}, books + // {items:[..]}); sizes[i] is the byte weight (0 for books -> count-based percent). + private String[] labels = new String[0]; + private long[] sizes = new long[0]; + private JSONObject[] bodies = new JSONObject[0]; private int index = 0; private int percent = 0; private long speed = 0; @@ -72,6 +78,10 @@ public interface Host { public int index() { return index; } public int percent() { return percent; } public long speed() { return speed; } + public String[] labels() { return labels; } + public long[] sizes() { return sizes; } + public String label(int i) { return i >= 0 && i < labels.length ? labels[i] : ""; } + public long size(int i) { return i >= 0 && i < sizes.length ? sizes[i] : 0L; } public boolean hasSession() { return status.length > 0; } public boolean isComplete() { if (status.length == 0 || running) return false; @@ -87,13 +97,38 @@ public boolean hasFailed() { for (int st : status) if (st == FAILED) return true; return false; } - /** Overall percent for the bars — delegated to the per-type Host (byte-weighted vs item-count). */ - public int overallPercent() { return host != null ? host.computeOverallPercent() : 0; } + + /** Overall percent for the bars. Byte-weighted when the items carry sizes (ZIM); item-count when + * they don't (books send size 0). One formula, one owner — the services no longer compute this, + * so the status screen and the index bar read the exact same number by construction. */ + public int overallPercent() { + int n = Math.min(sizes.length, status.length); + long total = 0, done = 0; + for (int i = 0; i < n; i++) { + total += sizes[i]; + if (status[i] == DONE || status[i] == FAILED) done += sizes[i]; + else if (i == index && (status[i] == ACTIVE || status[i] == PROCESSING) && percent >= 0) + done += sizes[i] * percent / 100; + } + if (total > 0) return (int) Math.min(100, done * 100 / total); + // No per-item sizes (books): fall back to item count. + int m = status.length; + if (m == 0) return isComplete() ? 100 : 0; + int c = 0; + for (int st : status) if (st == DONE || st == FAILED) c++; + return (int) Math.min(100, (long) c * 100 / m); + } // ---- actions (the services' onStartCommand / statics delegate here) ------------------------ - /** Fresh session over {@code count} items (status all PENDING), then start pumping the queue. */ - public void begin(int count) { + /** Fresh session over the given items (status all PENDING), then start pumping the queue. The + * labels/sizes/bodies snapshot is held here so it stays the same length as status for the whole + * session — the service passes it in and never keeps its own copy. */ + public void begin(String[] labels, long[] sizes, JSONObject[] bodies) { + int count = labels != null ? labels.length : 0; + this.labels = labels != null ? labels : new String[0]; + this.sizes = sizes != null && sizes.length == count ? sizes : new long[count]; + this.bodies = bodies != null && bodies.length == count ? bodies : new JSONObject[count]; status = new int[count]; index = 0; percent = 0; speed = 0; paused = false; reconnectAttempt = 0; reconnectTotal = 0; @@ -135,16 +170,14 @@ public void cancelAndPurge() { if (host != null) host.stop(); } - /** Clear all session state (the services' finishSession()). Also clears the owner's per-type arrays - * via {@link Host#onPurged()} so the snapshot the UI reads stays length-consistent (labels/status/ - * bytes all empty together) — otherwise a Cancel left labels>0 with status=0 and the ZIM fragment - * indexed status[] off the label count → AIOOBE (ADFA-4893). */ + /** Clear all session state AND the per-item snapshot (labels/sizes/bodies) together, so the UI can + * never read a length mismatch after a Cancel (ADFA-4893). */ public void purge() { status = new int[0]; + labels = new String[0]; sizes = new long[0]; bodies = new JSONObject[0]; index = 0; percent = 0; speed = 0; running = false; paused = false; reconnectAttempt = 0; reconnectTotal = 0; lastProgressAt = 0L; - if (host != null) host.onPurged(); } private int firstPending() { @@ -157,13 +190,14 @@ private void pump() { if (i < 0) { running = false; publish(); if (host != null) host.stop(); return; } index = i; percent = 0; status[i] = ACTIVE; publish(); - if (host != null) host.notify(host.label(i)); + if (host != null) host.notify(label(i)); startItem(i); } private void startItem(final int i) { client = new RestContentClient(type); - client.start(host.buildBody(i), new RestContentClient.Listener() { + JSONObject body = i >= 0 && i < bodies.length && bodies[i] != null ? bodies[i] : new JSONObject(); + client.start(body, new RestContentClient.Listener() { @Override public void onProgress(int pct, String rate) { if (paused) paused = false; reconnectAttempt = 0; @@ -171,7 +205,7 @@ private void startItem(final int i) { lastProgressAt = SystemClock.elapsedRealtime(); if (status[i] != PROCESSING) status[i] = ACTIVE; publish(); - if (host != null) host.notify(host.label(i)); + if (host != null) host.notify(label(i)); } @Override public void onIndexing() { status[i] = PROCESSING; lastProgressAt = SystemClock.elapsedRealtime(); publish(); 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 9e708f062..512560995 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 @@ -57,10 +57,8 @@ public final class ZimDownloadService extends Service implements ContentDownload public interface Listener { void onUpdate(); } private static final ContentDownloadSession SESSION = new ContentDownloadSession("kiwix"); - // ZIM-specific session data (labels/files/sizes); the queue/progress state lives in SESSION. - private static String[] sFiles = new String[0]; - private static String[] sLabels = new String[0]; - private static long[] sBytes = new long[0]; + // The whole per-item snapshot (files-as-bodies/labels/sizes) now lives in SESSION, so status and the + // metadata the UI indexes off it stay length-consistent by construction (ADFA-4893). // ---- static API the UI observes (delegates to the shared session) ------------------------- public static boolean isRunning() { return SESSION.isRunning(); } @@ -76,8 +74,8 @@ public interface Listener { void onUpdate(); } public static int percent() { return SESSION.percent(); } public static long speed() { return SESSION.speed(); } public static int overallPercent() { return SESSION.overallPercent(); } - public static String[] labels() { return sLabels; } - public static long[] bytes() { return sBytes; } + public static String[] labels() { return SESSION.labels(); } + public static long[] bytes() { return SESSION.sizes(); } public static void setListener(Listener l) { SESSION.setListener(l == null ? null : l::onUpdate); } public static void start(Context ctx, String[] files, String[] labels, long[] bytes) { @@ -102,7 +100,7 @@ public static void retryFailed(Context ctx) { } } - public static void finishSession() { SESSION.purge(); sFiles = new String[0]; sLabels = new String[0]; sBytes = new long[0]; } + public static void finishSession() { SESSION.purge(); } private final Handler main = new Handler(Looper.getMainLooper()); @@ -122,44 +120,26 @@ public int onStartCommand(Intent intent, int flags, int startId) { if (ACTION_RETRY.equals(action)) { if (!SESSION.hasSession()) { stopSelf(); return START_NOT_STICKY; } - startForeground(NOTIFICATION_ID, buildNotification(label(SESSION.index()))); + startForeground(NOTIFICATION_ID, buildNotification(SESSION.label(SESSION.index()))); SESSION.resumeQueue(); } else { // ACTION_START: fresh session from the extras - String[] f = intent.getStringArrayExtra(EXTRA_FILES); - if (f == null || f.length == 0) { stopSelf(); return START_NOT_STICKY; } - sFiles = f; - sLabels = intent.getStringArrayExtra(EXTRA_LABELS); - sBytes = intent.getLongArrayExtra(EXTRA_BYTES); - if (sLabels == null) sLabels = sFiles; - if (sBytes == null) sBytes = new long[sFiles.length]; - startForeground(NOTIFICATION_ID, buildNotification(sLabels.length > 0 ? sLabels[0] : "")); - SESSION.begin(sFiles.length); + String[] files = intent.getStringArrayExtra(EXTRA_FILES); + if (files == null || files.length == 0) { stopSelf(); return START_NOT_STICKY; } + String[] labels = intent.getStringArrayExtra(EXTRA_LABELS); + long[] bytes = intent.getLongArrayExtra(EXTRA_BYTES); + if (labels == null) labels = files; + JSONObject[] bodies = new JSONObject[files.length]; + for (int i = 0; i < files.length; i++) { + try { bodies[i] = new JSONObject().put("ids", new JSONArray().put(files[i])); } + catch (Exception e) { bodies[i] = new JSONObject(); } + } + startForeground(NOTIFICATION_ID, buildNotification(labels.length > 0 ? labels[0] : "")); + SESSION.begin(labels, bytes, bodies); // session owns the snapshot from here on } return START_NOT_STICKY; } // ---- ContentDownloadSession.Host (ZIM specifics) ------------------------------------------ - @Override public JSONObject buildBody(int i) { - try { return new JSONObject().put("ids", new JSONArray().put(sFiles[i])); } - catch (Exception e) { return new JSONObject(); } - } - - @Override public String label(int i) { return i >= 0 && i < sLabels.length ? sLabels[i] : ""; } - - /** Byte-weighted overall percent: done/failed count in full, the active item adds its live percent. */ - @Override public int computeOverallPercent() { - int[] status = SESSION.status(); - int idx = SESSION.index(); - int p = SESSION.percent(); - long total = 0, done = 0; - for (int i = 0; i < sBytes.length && i < status.length; i++) { - total += sBytes[i]; - if (status[i] == DONE || status[i] == FAILED) done += sBytes[i]; - else if (i == idx && (status[i] == ACTIVE || status[i] == INDEXING) && p >= 0) done += sBytes[i] * p / 100; - } - return total > 0 ? (int) Math.min(100, done * 100 / total) : (SESSION.isComplete() ? 100 : 0); - } - @Override public void notify(String label) { if (!SESSION.isRunning()) return; NotificationManager m = getSystemService(NotificationManager.class); @@ -168,10 +148,6 @@ public int onStartCommand(Intent intent, int flags, int startId) { @Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); } - /** Clear the ZIM-specific arrays alongside the session state, so a Cancel purge leaves - * labels/status/bytes empty together (no length mismatch for the fragment to trip over). */ - @Override public void onPurged() { sFiles = new String[0]; sLabels = new String[0]; sBytes = new long[0]; } - private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( 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 112281234..a548fdbc5 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 @@ -154,7 +154,10 @@ private void render() { 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, + // Row count is min(labels,status): ProvisioningChecklist invokes the row lambda once per count, and + // the lambda indexes status[i]/labels[i], so a length mismatch must not drive it past status[]. + int count = Math.min(labels.length, status.length); + ProvisioningChecklist.render(requireContext(), listv, count, status, ZimDownloadService.DONE, ZimDownloadService.FAILED, i -> (status[i] == ZimDownloadService.FAILED) ? labels[i] + getString(R.string.k2go_zim_item_failed_suffix) : labels[i],