From 6c5ac01b4f37f59e4f040eb39511477bd4073973 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Tue, 25 Aug 2026 20:49:27 -0600 Subject: [PATCH 1/3] =?UTF-8?q?ADFA-4893=20feat(dashnode):=20books=20homol?= =?UTF-8?q?ogated=20=E2=80=94=20visible=20reconnect=20+=20idempotent=20res?= =?UTF-8?q?ume?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Books now follows the ZIM/rootfs reconnect contract: the books runner reports its retry state via ctx.reportRetry (onRetry + cleared per item), so the poll carries retryAttempt/retryTotal and the app can show "Reconnecting… n of 5". And the runner is idempotent on resume — presentTitles() skips books already in the Calibre-Web library (by title) instead of re-downloading + re-uploading, which duplicated entries and reset the percent; this also makes a resume after process death safe. Bump 1.2.7-dev.1. --- static/dashboard/CHANGELOG.md | 1 + static/dashboard/package.json | 2 +- static/dashboard/sockets/books.exec.ts | 17 ++++++++++++++++- static/dashboard/sockets/books.query.ts | 19 +++++++++++++++++++ 4 files changed, 37 insertions(+), 2 deletions(-) diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md index 58e15c4d3..c0abae5f7 100644 --- a/static/dashboard/CHANGELOG.md +++ b/static/dashboard/CHANGELOG.md @@ -4,6 +4,7 @@ One line per version, newest first. Every REST-facing change bumps the version i (the app surfaces it via `/system/dashboard/update-check` and the "Update available" pill), so this file is the human record of what each bump enables. Keep entries short: `version - change (TICKET)`. +- **1.2.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.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 a781f61bd..62dd03272 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -1,6 +1,6 @@ { "name": "dashboard-console", - "version": "1.2.6", + "version": "1.2.7-dev.1", "description": "", "main": "index.js", "scripts": { diff --git a/static/dashboard/sockets/books.exec.ts b/static/dashboard/sockets/books.exec.ts index 403d7215e..93e73d7cf 100644 --- a/static/dashboard/sockets/books.exec.ts +++ b/static/dashboard/sockets/books.exec.ts @@ -7,6 +7,7 @@ import { jobs, RunnerContext, CanceledError, PausedError, classifyStop } from './jobs'; import { getCredential } from './credentials'; import { withRetry } from './net-retry'; +import { presentTitles } from './books.query'; import fs from 'fs'; import path from 'path'; @@ -94,6 +95,9 @@ const booksRunner: (ctx: RunnerContext) => Promise = async (ctx) => { } let done = 0; + // ADFA-4893: idempotent resume — a relaunch skips books already in the library instead of + // re-downloading + re-uploading them (which duplicated entries and reset the percent to 0). + const present = presentTitles(); for (const book of books) { ctx.throwIfCanceled(); const id = String(book.id); @@ -101,6 +105,13 @@ const booksRunner: (ctx: RunnerContext) => Promise = async (ctx) => { const url = String(book.url); ctx.update({ phase: 'processing', detail: title, percent: Math.round((done / books.length) * 100) }); + if (present.has(title.trim().toLowerCase())) { + ctx.log(`[books] skip "${title}" — already in the library (idempotent resume)`); + done++; + ctx.update({ phase: 'processing', percent: Math.round((done / books.length) * 100) }); + continue; + } + const tmp = path.join(TMP_DIR, `pg_${id}.epub`); try { await withRetry(async () => { @@ -148,7 +159,10 @@ const booksRunner: (ctx: RunnerContext) => Promise = async (ctx) => { if (typeof status === 'number') return status >= 500; return true; }, - onRetry: ({ attempt, err }) => ctx.log(`[books] retry ${attempt} for "${title}": ${err instanceof Error ? err.message : String(err)}`), + onRetry: ({ attempt, err }) => { + ctx.reportRetry(attempt, BOOK_TRIES - 1); // ADFA-4893: surface "Reconnecting… n of N" on the poll + ctx.log(`[books] retry ${attempt}/${BOOK_TRIES - 1} for "${title}": ${err instanceof Error ? err.message : String(err)}`); + }, }); } catch (err) { // ADFA-4894: pause stops the fetch but keeps nothing mid-file (books resumes per item on @@ -162,6 +176,7 @@ const booksRunner: (ctx: RunnerContext) => Promise = async (ctx) => { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } + ctx.reportRetry(0, 0); // ADFA-4893: item completed → clear any reconnect state done++; ctx.update({ phase: 'processing', percent: Math.round((done / books.length) * 100) }); } diff --git a/static/dashboard/sockets/books.query.ts b/static/dashboard/sockets/books.query.ts index 0b626f76d..dd988a6d2 100644 --- a/static/dashboard/sockets/books.query.ts +++ b/static/dashboard/sockets/books.query.ts @@ -21,6 +21,25 @@ const CATALOG_DB_PATH = path.join(BOOKS_DIR, 'catalog.db'); const CALIBRE_WEB_LOCAL_URL = 'http://127.0.0.1:8083'; // ADFA-4949: credentials come from the shared store (see sockets/credentials.ts). +/** + * ADFA-4893: normalized titles already in the Calibre-Web library, so the books runner is idempotent — + * a resume (or a re-run after process death) skips books already uploaded instead of duplicating them. + * Title is the only reliable key today (Gutenberg id isn't persisted as a Calibre identifier). Returns + * an empty set if the library DB isn't present yet (nothing to skip). + */ +export function presentTitles(): Set { + const out = new Set(); + if (!fs.existsSync(CALIBRE_DB_PATH)) return out; + const db = new Database(CALIBRE_DB_PATH, { readonly: true }); + try { + const rows = db.prepare('SELECT title FROM books').all() as { title: string }[]; + for (const r of rows) if (r.title) out.add(r.title.trim().toLowerCase()); + } finally { + db.close(); + } + return out; +} + export interface CatalogBook { gutenberg_id: number | string; title: string; From 2b2e5ca69e0c2b63729517e2b92e9940475f274f Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Tue, 25 Aug 2026 21:15:07 -0600 Subject: [PATCH 2/3] ADFA-4893 feat(zim,books): share one REST client; Books gets ZIM's controls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generalize RestContentClient to type-parametric (start(body)) and interpret the poll by percent + retry state, not the phase name, so kiwix (downloading/indexing) and books (processing) share one client. Re-point BooksDownloadService onto it: pause/resume, onPaused/onReconnecting, poll percent, server cancel — dropping its inline POST/poll and the app-side retry loop (the server owns reconnection now). BooksDownloadsFragment gets the morphing Pause⇄Resume⇄Retry + Cancel row and the "Reconnecting… n of N" / paused labels (per-item pill removed); Finish/Run-in- background stay for the standalone Books flow. Books index row gets the item-count bar. ZIM unchanged (no-arg client ctor). --- .../controller/content/RestContentClient.java | 86 ++++---- .../redesign/BooksDownloadService.java | 204 ++++++++---------- .../redesign/BooksDownloadsFragment.java | 47 +++- .../redesign/SetupProgressActivity.java | 8 +- .../layout/fragment_k2go_books_downloads.xml | 33 +++ 5 files changed, 221 insertions(+), 157 deletions(-) diff --git a/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java b/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java index efcc830fb..a7cf0ead6 100644 --- a/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java +++ b/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java @@ -13,14 +13,14 @@ * Still driven by the foreground InstallService so polling continues * across UI/config changes. * - * Contract (static/dashboard/routes.ts + sockets/jobs.ts): - * POST /api/kiwix/download {ids:[...]} -> { id, ... } - * GET /api/kiwix/jobs/:id -> { phase, percent, - * speed(bytes/s), - * detail, error } - * POST /api/kiwix/jobs/:id/cancel -> { ok:true } - * POST /api/kiwix/jobs/:id/pause|resume -> { ok:true } (ADFA-4893) - * phase is one of: queued|downloading|indexing|processing|paused|done|error|canceled. + * Contract (static/dashboard/routes.ts + sockets/jobs.ts), per content + * ("kiwix", "books", ...) — ADFA-4893 made this client type-parametric: + * POST /api//download -> { id, ... } + * GET /api//jobs/:id -> { phase, percent, speed(bytes/s), + * detail, error, retryAttempt, retryTotal } + * POST /api//jobs/:id/{cancel,pause,resume} -> { ok:true } + * The poll is interpreted by percent + retry state, not the exact phase name, so kiwix + * (downloading/indexing) and books (processing) can share one client. * ============================================================================ */ package org.iiab.controller.content; @@ -58,7 +58,7 @@ default void onPaused(int percent) {} default void onReconnecting(int attempt, int total) {} } - private static final String BASE = BoxEndpoints.API + "/kiwix"; + private final String base; // ADFA-4893: per-type API base (/api/kiwix, /api/books, ...) private static final long POLL_MS = 1000L; private static final int MAX_POLL_ERRORS = 10; // tolerate ~10s of transient network blips // ADFA-4893: the START (download) POST is before any server job exists, so the server's own @@ -75,19 +75,32 @@ default void onReconnecting(int attempt, int total) {} private final Runnable pollTask = () -> AppExecutors.get().io().execute(this::pollOnce); - /** Start (download + index) one ZIM on the running server and poll to completion. */ + /** ZIM/kiwix by default (back-compat with existing callers). */ + public RestContentClient() { this("kiwix"); } + + /** ADFA-4893: shared client for any content type ("kiwix", "books", ...) -> /api/<type>. */ + public RestContentClient(@NonNull String type) { this.base = BoxEndpoints.API + "/" + type; } + + /** Start (download + index) one ZIM and poll to completion. Thin wrapper over {@link #start}. */ public void addZim(@NonNull String zimFilename, @NonNull Listener l) { + this.listener = l; + final JSONObject body; + try { body = new JSONObject().put("ids", new JSONArray().put(zimFilename)); } + catch (Exception e) { fail("couldn't build the request"); return; } + start(body, l); + } + + /** ADFA-4893: generic start — POST the type-specific body to /download, then poll to completion. + * Kiwix passes {ids:[...]}, books {items:[{id,title,url}]}; this client is body-agnostic. */ + public void start(@NonNull JSONObject body, @NonNull Listener l) { this.listener = l; AppExecutors.get().io().execute(() -> { - final JSONObject body; - try { body = new JSONObject().put("ids", new JSONArray().put(zimFilename)); } - catch (Exception e) { fail("couldn't build the request"); return; } // ADFA-4893: retry ONLY the kickoff POST (connectivity blip / server still warming) a few // times. An empty id is a server refusal, not a blip, so it fails without retrying. Once the // job exists, the server owns reconnection (visible), not this loop. for (int attempt = 1; !finished; attempt++) { try { - JSONObject resp = httpJson("POST", BASE + "/download", body); + JSONObject resp = httpJson("POST", base + "/download", body); String id = resp.optString("id", ""); if (id.isEmpty()) { fail("content service did not start the job"); return; } jobId = id; @@ -105,7 +118,7 @@ public void addZim(@NonNull String zimFilename, @NonNull Listener l) { private void pollOnce() { if (finished) return; try { - JSONObject j = httpJson("GET", BASE + "/jobs/" + jobId, null); + JSONObject j = httpJson("GET", base + "/jobs/" + jobId, null); pollErrors = 0; String phase = j.optString("phase", ""); int percent = j.optInt("percent", -1); @@ -117,37 +130,32 @@ private void pollOnce() { if (detail != null && !detail.isEmpty()) deliver(() -> listener.onLog(detail)); + // Terminal phases first. switch (phase) { - case "downloading": + case "done": done(); return; + case "error": fail(error != null ? error : "download failed"); return; + case "canceled": fail("canceled"); return; + case "paused": { + // ADFA-4893: not terminal — surface it and keep polling so resume/progress is seen. + final int pp = percent; + deliver(() -> listener.onPaused(pp)); + break; + } + default: { + // ADFA-4893: active phase — interpret by percent + retry, NOT by the phase name, so + // kiwix ("downloading"/"indexing") and books ("processing" with an item %) both work. if (retryAttempt > 0) { final int a = retryAttempt, t = retryTotal; deliver(() -> listener.onReconnecting(a, t)); } else if (percent >= 0) { final int p = percent; final String rate = formatRate(speed); deliver(() -> listener.onProgress(p, rate)); + } else if ("indexing".equals(phase) || "processing".equals(phase)) { + if (!indexing) { indexing = true; deliver(() -> listener.onIndexing()); } } - break; - case "indexing": - case "processing": - if (!indexing) { indexing = true; deliver(() -> listener.onIndexing()); } - break; - case "done": - done(); - return; - case "error": - fail(error != null ? error : "download failed"); - return; - case "canceled": - fail("canceled"); - return; - case "paused": { - // ADFA-4893: not terminal — surface it and keep polling so resume/progress is seen. - final int pp = percent; - deliver(() -> listener.onPaused(pp)); + // else queued / no-percent-yet: keep polling. break; } - default: - break; // queued / unknown: keep polling } main.postDelayed(pollTask, POLL_MS); } catch (Exception e) { @@ -162,7 +170,7 @@ public void cancel() { final String id = jobId; if (id != null && !id.isEmpty()) { AppExecutors.get().io().execute(() -> { - try { httpJson("POST", BASE + "/jobs/" + id + "/cancel", null); } catch (Exception ignore) { /* best effort */ } + try { httpJson("POST", base + "/jobs/" + id + "/cancel", null); } catch (Exception ignore) { /* best effort */ } }); } teardown(); @@ -173,7 +181,7 @@ public void pause() { final String id = jobId; if (id != null && !id.isEmpty()) { AppExecutors.get().io().execute(() -> { - try { httpJson("POST", BASE + "/jobs/" + id + "/pause", null); } catch (Exception ignore) { /* best effort */ } + try { httpJson("POST", base + "/jobs/" + id + "/pause", null); } catch (Exception ignore) { /* best effort */ } }); } } @@ -183,7 +191,7 @@ public void resume() { final String id = jobId; if (id != null && !id.isEmpty()) { AppExecutors.get().io().execute(() -> { - try { httpJson("POST", BASE + "/jobs/" + id + "/resume", null); } catch (Exception ignore) { /* best effort */ } + try { httpJson("POST", base + "/jobs/" + id + "/resume", null); } catch (Exception ignore) { /* best effort */ } }); } } 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 a31a494ae..6295d79d2 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 @@ -30,28 +30,19 @@ import androidx.core.content.ContextCompat; import org.iiab.controller.R; -import org.iiab.controller.config.BoxEndpoints; -import org.iiab.controller.util.AppExecutors; import org.json.JSONArray; import org.json.JSONObject; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; - public final class BooksDownloadService extends Service { private static final String CHANNEL_ID = "books_download_channel"; private static final int NOTIFICATION_ID = 6; - private static final String BASE = BoxEndpoints.API + "/books"; - private static final long POLL_MS = 1000L; 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 EXTRA_IDS = "ids"; public static final String EXTRA_TITLES = "titles"; public static final String EXTRA_URLS = "urls"; @@ -68,9 +59,15 @@ public interface Listener { void onUpdate(); } 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; @@ -89,31 +86,55 @@ public static boolean isActiveNow() { 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 start(Context ctx, String[] ids, String[] titles, String[] urls) { Intent i = new Intent(ctx, BooksDownloadService.class).setAction(ACTION_START) .putExtra(EXTRA_IDS, ids).putExtra(EXTRA_TITLES, titles).putExtra(EXTRA_URLS, urls); ContextCompat.startForegroundService(ctx, i); } - public static void retry(Context ctx, int i) { - if (i < 0 || i >= sStatus.length) return; - sStatus[i] = PENDING; - if (!sRunning) ContextCompat.startForegroundService(ctx, + /** 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; + 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)); } public static void finishSession() { sIds = new String[0]; sTitles = new String[0]; sUrls = new String[0]; sStatus = new int[0]; - sIndex = 0; sRunning = false; sLastProgressAt = 0L; + sIndex = 0; sRunning = false; sPaused = false; + sReconnectAttempt = 0; sReconnectTotal = 0; sLastProgressAt = 0L; } - private static final int MAX_ATTEMPTS = 3; // total tries per book before marking it failed - private static final long RETRY_DELAY_MS = 4000L; - private final Handler main = new Handler(Looper.getMainLooper()); - private volatile String currentJobId; - private volatile boolean canceled = false; - private int attempts = 0; // attempts for the item currently in flight + private org.iiab.controller.content.RestContentClient client; // ADFA-4893: shared REST client (books) @Override public void onCreate() { super.onCreate(); createNotificationChannel(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @@ -122,10 +143,23 @@ public static void finishSession() { public int onStartCommand(Intent intent, int flags, int startId) { String action = intent != null ? intent.getAction() : null; if (ACTION_CANCEL.equals(action)) { - canceled = true; sRunning = false; publish(); + if (client != null) client.cancel(); + sRunning = false; sPaused = false; sReconnectAttempt = 0; sReconnectTotal = 0; + publish(); main.post(() -> { stopForeground(true); stopSelf(); }); return START_NOT_STICKY; } + // ADFA-4893: pause/resume the active job, handled before the sRunning guard (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_RETRY.equals(action)) { @@ -139,9 +173,8 @@ public int onStartCommand(Intent intent, int flags, int startId) { if (sTitles == null) sTitles = ids; if (sUrls == null) sUrls = new String[ids.length]; sStatus = new int[ids.length]; - sIndex = 0; + sIndex = 0; sPaused = false; sReconnectAttempt = 0; sReconnectTotal = 0; } - canceled = false; sRunning = true; sLastProgressAt = android.os.SystemClock.elapsedRealtime(); // ADFA-5146: seed the heartbeat startForeground(NOTIFICATION_ID, buildNotification(currentTitle())); @@ -160,73 +193,47 @@ private void processNext() { int i = firstPending(); if (i < 0) { sessionComplete(); return; } sIndex = i; sStatus[i] = ACTIVE; - attempts = 0; publish(); updateNotification(sTitles[i]); - AppExecutors.get().io().execute(() -> startJob(i)); + startItem(i); } - /** Transient failure (nginx 502 while the engine warms up, a flaky Gutenberg fetch, etc.): - * retry the same book a couple times before giving up, so the wizard doesn't stall on a blip. */ - private void retryOrFail(int i) { - attempts++; - if (attempts < MAX_ATTEMPTS) { - android.util.Log.w("K2Go-Provision", "books job [" + i + "] transient failure, retry " + attempts + "/" + (MAX_ATTEMPTS - 1)); - main.postDelayed(() -> AppExecutors.get().io().execute(() -> startJob(i)), RETRY_DELAY_MS); - } else { - android.util.Log.w("K2Go-Provision", "books job [" + i + "] failed after " + attempts + " attempts"); - fail(i); - } - } - - private void startJob(int i) { - android.util.Log.i("K2Go-Provision", "books job start [" + i + "] id=" + sIds[i] + " title='" + sTitles[i] + "' url=" + sUrls[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]); - JSONObject body = new JSONObject().put("items", new JSONArray().put(item)); - JSONObject resp = httpJson("POST", BASE + "/download", body); - String id = resp.optString("id", ""); - if (id.isEmpty()) { android.util.Log.w("K2Go-Provision", "books job [" + i + "] no job id in response: " + resp); retryOrFail(i); return; } - currentJobId = id; - main.postDelayed(() -> poll(i), POLL_MS); - } catch (Exception e) { - android.util.Log.w("K2Go-Provision", "books job [" + i + "] POST failed: " + e.getMessage()); - retryOrFail(i); - } - } - - private void poll(int i) { - if (canceled) return; - AppExecutors.get().io().execute(() -> { - try { - JSONObject j = httpJson("GET", BASE + "/jobs/" + currentJobId, null); - String phase = j.optString("phase", ""); - sLastProgressAt = android.os.SystemClock.elapsedRealtime(); // ADFA-5146: heartbeat on each answered poll - switch (phase) { - case "done": - android.util.Log.i("K2Go-Provision", "books job done [" + i + "]"); - sStatus[i] = DONE; publish(); main.post(BooksDownloadService.this::processNext); return; - case "error": - case "canceled": - android.util.Log.w("K2Go-Provision", "books job [" + i + "] phase=" + phase + " err=" + j.optString("error")); - retryOrFail(i); return; - case "processing": - if (sStatus[i] != ADDING) { sStatus[i] = ADDING; publish(); } - break; - default: break; // queued - } - main.postDelayed(() -> poll(i), POLL_MS); - } catch (Exception e) { - main.postDelayed(() -> poll(i), POLL_MS); // tolerate transient blips + 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(); } }); } - private void fail(int i) { - sStatus[i] = FAILED; publish(); - main.post(this::processNext); - } - private void sessionComplete() { sRunning = false; publish(); main.post(() -> { stopForeground(true); stopSelf(); }); @@ -271,37 +278,4 @@ private void updateNotification(String title) { if (m != null) m.notify(NOTIFICATION_ID, buildNotification(title)); } - private static JSONObject httpJson(String method, String urlStr, JSONObject body) throws Exception { - HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection(); - try { - c.setUseCaches(false); - c.setConnectTimeout(5000); - c.setReadTimeout(8000); - c.setRequestMethod(method); - c.setRequestProperty("Accept", "application/json"); - if (body != null) { - c.setDoOutput(true); - c.setRequestProperty("Content-Type", "application/json"); - byte[] payload = body.toString().getBytes(StandardCharsets.UTF_8); - try (OutputStream os = c.getOutputStream()) { os.write(payload); } - } - int code = c.getResponseCode(); - boolean ok = code >= 200 && code < 400; - String text = readAll(ok ? c.getInputStream() : c.getErrorStream()); - if (!ok) throw new Exception("HTTP " + code + ": " + text); - return new JSONObject(text.isEmpty() ? "{}" : text); - } finally { - c.disconnect(); - } - } - - private static String readAll(InputStream is) throws Exception { - if (is == null) return ""; - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - byte[] chunk = new byte[4096]; - int n; - while ((n = is.read(chunk)) != -1) buf.write(chunk, 0, n); - is.close(); - return buf.toString(StandardCharsets.UTF_8.name()); - } } 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 0bddbf7a3..0c5530be6 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 @@ -15,6 +15,7 @@ */ package org.iiab.controller.redesign; +import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Typeface; import android.os.Bundle; @@ -39,6 +40,9 @@ 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 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 /** Open as a detail card inside the Finishing-setup index (host owns Back/Finish; observe only). */ @@ -72,6 +76,28 @@ 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(); + } + }); + pauseSupported = DashboardVersion.atLeast(DashboardVersion.installed(requireContext()), 1, 2, 4); + if (fromIndex) { // the index host provides Back/Finish; this card only observes finishBtn.setVisibility(View.GONE); runBgBtn.setVisibility(View.GONE); @@ -91,10 +117,27 @@ private void render() { int done = 0; for (int st : status) if (st == BooksDownloadService.DONE) done++; - detail.setText(getString(R.string.k2go_books_dl_detail_fmt, done, n)); + + boolean anyFailed = BooksDownloadService.hasFailed(); + boolean running = BooksDownloadService.isRunning(); + boolean paused = BooksDownloadService.isPaused(); + int rc = BooksDownloadService.reconnectAttempt(); + if (paused) detail.setText(R.string.k2go_dl_paused); + else if (running && rc > 0) detail.setText(getString(R.string.k2go_dl_attempt, rc, BooksDownloadService.reconnectTotal())); + else detail.setText(getString(R.string.k2go_books_dl_detail_fmt, done, n)); 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); + } + if (!fromIndex) { boolean complete = BooksDownloadService.isComplete(); finishBtn.setEnabled(complete); @@ -109,7 +152,7 @@ private void drawChecklist(String[] titles, int[] status) { @Override public String main(int i) { return titles[i]; } @Override public String sub(int i) { return stateLabel(status[i]); } }, - i -> BooksDownloadService.retry(requireContext().getApplicationContext(), i)); + null); // ADFA-4893: retry handled by the status-screen morph button, not a per-item pill } private String stateLabel(int st) { diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java b/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java index d36cb20e5..3573015b5 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java @@ -611,7 +611,7 @@ private void render() { booksSession, BooksDownloadService.status(), BooksDownloadService.DONE, BooksDownloadService.FAILED, booksSession && BooksDownloadService.isComplete(), content.banked(ContentType.BOOKS), - 0L, -1)); // ADFA-4893: Books has no per-item size yet -> no determinate bar + 0L, booksOverallPercent())); // ADFA-4893: item-count bar, homologated with ZIM // ADFA-4954. Statuses come from an observable snapshot rather than static arrays, so the // ordinals are mapped to the checklist's PENDING=0 / doneVal / failedVal convention here. if (kolibriShown) (kolibriState.hasSession() ? started : waiting).add( @@ -1009,6 +1009,12 @@ private int zimOverallPercent() { ? ZimDownloadService.overallPercent() : -1; } + /** ADFA-4893: Books index row bar — same gating as ZIM, item-count percent from the service. */ + private int booksOverallPercent() { + return (BooksDownloadService.isRunning() && !BooksDownloadService.isComplete()) + ? BooksDownloadService.overallPercent() : -1; + } + private View mapsRow() { ModuleQueueState mq = ModuleQueueRepository.get().current(); boolean done = mapsStartFailed || (mapsInSession() && mq.phase == ModuleQueueState.Phase.DONE); diff --git a/controller/app/src/main/res/layout/fragment_k2go_books_downloads.xml b/controller/app/src/main/res/layout/fragment_k2go_books_downloads.xml index 46956ade9..c7566f8d4 100644 --- a/controller/app/src/main/res/layout/fragment_k2go_books_downloads.xml +++ b/controller/app/src/main/res/layout/fragment_k2go_books_downloads.xml @@ -79,6 +79,39 @@ android:paddingTop="12dp" android:paddingBottom="16dp"> + + + +