Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@
* job and then POLLs its structured status every ~1s. The job lives in
* the dashboard process (durable, resumable), so there is no connection
* to lose — the app can drop and re-attach by polling the same jobId.
* ADFA-4897: start() acts as start-or-attach — before creating a job it
* checks GET /:type/jobs for an ACTIVE job with the same target ids and,
* if found, polls that one instead, so a queue re-drained after process
* death re-attaches to the in-flight download rather than duplicating it.
* Still driven by the foreground InstallService so polling continues
* across UI/config changes.
*
* Contract (static/dashboard/routes.ts + sockets/jobs.ts), per content <type>
* ("kiwix", "books", ...) — ADFA-4893 made this client type-parametric:
* POST /api/<type>/download <body> -> { id, ... }
* GET /api/<type>/jobs -> [ { id, ids, phase, ... }, ... ]
* GET /api/<type>/jobs/:id -> { phase, percent, speed(bytes/s),
* detail, error, retryAttempt, retryTotal }
* POST /api/<type>/jobs/:id/{cancel,pause,resume} -> { ok:true }
Expand Down Expand Up @@ -95,6 +100,18 @@ public void addZim(@NonNull String zimFilename, @NonNull Listener l) {
public void start(@NonNull JSONObject body, @NonNull Listener l) {
this.listener = l;
AppExecutors.get().io().execute(() -> {
// ADFA-4897: re-attach instead of re-POST. The server job engine is durable (jobs.db +
// reconcileOnBoot), so a job we started before a process death survives. Before creating a
// new job, look for an ACTIVE one whose target ids match this body's items and, if found,
// just poll it — so a relaunched queue re-attaches to the in-flight download instead of
// starting a duplicate. Any error here falls through to a normal fresh POST.
String existing = findActiveJob(body);
if (finished) return; // a cancel landed during the lookup
if (existing != null) {
jobId = existing;
main.postDelayed(pollTask, POLL_MS);
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.
Expand Down Expand Up @@ -233,6 +250,76 @@ private static String formatRate(long bps) {
: String.format(java.util.Locale.US, "%.1f %s", v, units[i]);
}

/** ADFA-4897: id of an ACTIVE server job whose target ids intersect this body's item ids, or null
* if none / on any error (so a fresh start just POSTs a new job). */
private String findActiveJob(JSONObject body) {
try {
java.util.Set<String> want = idsFromBody(body);
if (want.isEmpty()) return null;
JSONArray list = httpArray("GET", base + "/jobs");
for (int i = 0; i < list.length(); i++) {
JSONObject job = list.optJSONObject(i);
if (job == null || !isActivePhase(job.optString("phase", ""))) continue;
java.util.Set<String> have = idsFromJob(job);
for (String id : want) if (have.contains(id)) {
String jid = job.optString("id", "");
if (!jid.isEmpty()) return jid;
}
}
} catch (Exception ignore) { /* fall through to a fresh POST */ }
return null;
}

/** Item ids in a start body: kiwix {ids:[..]} (strings), books {items:[{id,..}]} (objects). */
private static java.util.Set<String> idsFromBody(JSONObject body) {
java.util.Set<String> out = new java.util.HashSet<>();
JSONArray ids = body.optJSONArray("ids");
if (ids != null) for (int i = 0; i < ids.length(); i++) {
String s = ids.optString(i, ""); if (!s.isEmpty()) out.add(s);
}
JSONArray items = body.optJSONArray("items");
if (items != null) for (int i = 0; i < items.length(); i++) {
JSONObject o = items.optJSONObject(i);
if (o != null) { String s = o.optString("id", ""); if (!s.isEmpty()) out.add(s); }
}
return out;
}

/** Item ids in a job's target (toApi 'ids'): kiwix elements are strings, books elements are objects. */
private static java.util.Set<String> idsFromJob(JSONObject job) {
java.util.Set<String> out = new java.util.HashSet<>();
JSONArray arr = job.optJSONArray("ids");
if (arr != null) for (int i = 0; i < arr.length(); i++) {
Object el = arr.opt(i);
if (el instanceof JSONObject) { String s = ((JSONObject) el).optString("id", ""); if (!s.isEmpty()) out.add(s); }
else if (el != null) { String s = String.valueOf(el); if (!s.isEmpty()) out.add(s); }
}
return out;
}

/** Non-terminal phase — worth attaching to (queued/downloading/indexing/processing/paused). */
private static boolean isActivePhase(String phase) {
return !("done".equals(phase) || "error".equals(phase) || "canceled".equals(phase));
}

private static JSONArray httpArray(String method, String urlStr) throws Exception {
HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection();
try {
c.setUseCaches(false);
c.setConnectTimeout(4000);
c.setReadTimeout(4000);
c.setRequestMethod(method);
c.setRequestProperty("Accept", "application/json");
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 JSONArray(text.isEmpty() ? "[]" : text);
} finally {
c.disconnect();
}
}

private static JSONObject httpJson(String method, String urlStr, JSONObject body) throws Exception {
HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection();
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,13 @@ public int onStartCommand(Intent intent, int flags, int startId) {
SESSION.attach(this);
String action = intent != null ? intent.getAction() : null;

if (ACTION_CANCEL.equals(action)) { SESSION.cancelAndPurge(); return START_NOT_STICKY; }
if (ACTION_CANCEL.equals(action)) {
// ADFA-4897: Cancel abandons the order -> drop the remaining wishlist (DONE books were
// already removed one by one via onItemDone) so a later drain does not re-add them.
BooksWishlist.clear(getApplicationContext());
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; }

Expand All @@ -135,7 +141,8 @@ public int onStartCommand(Intent intent, int flags, int startId) {
} 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
// keys = ids: the book id is both the download id and the wishlist key (ADFA-4897).
SESSION.begin(ids, titles, null, bodies); // books: no per-item byte size -> count-based percent
}
return START_NOT_STICKY;
}
Expand All @@ -149,6 +156,11 @@ public int onStartCommand(Intent intent, int flags, int startId) {

@Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); }

/** ADFA-4897: book confirmed added to the library -> drop it from the durable wishlist. */
@Override public void onItemDone(String key) {
if (key != null && !key.isEmpty()) BooksWishlist.remove(getApplicationContext(), key);
}

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel ch = new NotificationChannel(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
* order to the existing BooksDownloadService — the same foreground, one-at-a-time,
* per-item-retry engine used by Get More — so provisioning is seamless and needs no
* new download machinery. Books is a LIVE operation (server up), so this must only be
* called when the server is alive. Idempotent: the wishlist is cleared once handed
* off (the service then owns retry), so it won't re-drain.
* called when the server is alive. ADFA-4897: the wishlist is NOT cleared at hand-off;
* the service drops each entry only once its book is confirmed added, so a process death
* re-drains only what did not finish. Re-entrant: a running session short-circuits drain().
* ============================================================================
*/
package org.iiab.controller.redesign;
Expand Down Expand Up @@ -67,11 +68,10 @@ public static void drain(Context ctx) {
}
if (ids.isEmpty()) { BooksWishlist.clear(ctx); return; }
Log.i(TAG, "books drain: handing " + ids.size() + " to BooksDownloadService");
// ADFA-4897: do NOT clear the wishlist here. The service drops each book from the wishlist only
// when it is confirmed added (BooksDownloadService.onItemDone), and clears the rest on an
// explicit Cancel — so a process death leaves the not-done books banked for the next drain.
BooksDownloadService.start(ctx.getApplicationContext(),
ids.toArray(new String[0]), titles.toArray(new String[0]), urls.toArray(new String[0]));
// TODO(ADFA-4874): clearing here means that if the process dies mid-download both the
// wishlist and the service's in-memory state are lost (orphaned partial). The durable
// background-jobs monitor should own this hand-off so it survives process death.
BooksWishlist.clear(ctx); // handed off; the service owns retry from here
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public interface Listener { void onUpdate(); }
public interface Host {
void notify(String label); // update the foreground notification for the current item
void stop(); // stopForeground(true) + stopSelf()
void onItemDone(String key); // item confirmed DONE -> drop its wishlist entry (ADFA-4897)
}

private final String type; // "kiwix" / "books" -> /api/<type>
Expand All @@ -55,7 +56,10 @@ public interface Host {
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).
// {items:[..]}); sizes[i] is the byte weight (0 for books -> count-based percent); keys[i] is the
// owning wishlist key, so the service can drop the entry the moment item i is confirmed DONE
// (ADFA-4897 — the wishlist is the durable order, kept until each item completes).
private String[] keys = new String[0];
private String[] labels = new String[0];
private long[] sizes = new long[0];
private JSONObject[] bodies = new JSONObject[0];
Expand All @@ -82,6 +86,7 @@ public interface Host {
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 String key(int i) { return i >= 0 && i < keys.length ? keys[i] : ""; }
public boolean hasSession() { return status.length > 0; }
public boolean isComplete() {
if (status.length == 0 || running) return false;
Expand Down Expand Up @@ -124,8 +129,9 @@ else if (i == index && (status[i] == ACTIVE || status[i] == PROCESSING) && perce
/** 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) {
public void begin(String[] keys, String[] labels, long[] sizes, JSONObject[] bodies) {
int count = labels != null ? labels.length : 0;
this.keys = keys != null && keys.length == count ? keys : new String[count];
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];
Expand Down Expand Up @@ -174,7 +180,7 @@ public void cancelAndPurge() {
* 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];
keys = new String[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;
Expand Down Expand Up @@ -218,7 +224,14 @@ private void startItem(final int i) {
lastProgressAt = SystemClock.elapsedRealtime(); publish();
}
@Override public void onLog(String line) { /* logcat only */ }
@Override public void onDone() { status[i] = DONE; publish(); pump(); }
@Override public void onDone() {
status[i] = DONE; publish();
// ADFA-4897: item confirmed done -> drop its wishlist entry, so a later process death
// only re-drains what actually did NOT finish (no re-download of completed items).
String k = key(i);
if (host != null && !k.isEmpty()) host.onItemDone(k);
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public final class ZimDownloadService extends Service implements ContentDownload
public static final String EXTRA_FILES = "files";
public static final String EXTRA_LABELS = "labels";
public static final String EXTRA_BYTES = "bytes";
public static final String EXTRA_KEYS = "keys"; // ADFA-4897: wishlist keys, one per file

// Per-item status — same values the UI/checklist already use, sourced from the shared session.
public static final int PENDING = ContentDownloadSession.PENDING;
Expand Down Expand Up @@ -78,9 +79,10 @@ public interface Listener { void onUpdate(); }
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) {
public static void start(Context ctx, String[] keys, String[] files, String[] labels, long[] bytes) {
Intent i = new Intent(ctx, ZimDownloadService.class).setAction(ACTION_START)
.putExtra(EXTRA_FILES, files).putExtra(EXTRA_LABELS, labels).putExtra(EXTRA_BYTES, bytes);
.putExtra(EXTRA_KEYS, keys).putExtra(EXTRA_FILES, files)
.putExtra(EXTRA_LABELS, labels).putExtra(EXTRA_BYTES, bytes);
ContextCompat.startForegroundService(ctx, i);
}

Expand Down Expand Up @@ -112,7 +114,13 @@ public int onStartCommand(Intent intent, int flags, int startId) {
SESSION.attach(this);
String action = intent != null ? intent.getAction() : null;

if (ACTION_CANCEL.equals(action)) { SESSION.cancelAndPurge(); return START_NOT_STICKY; }
if (ACTION_CANCEL.equals(action)) {
// ADFA-4897: Cancel abandons the order -> drop the remaining wishlist so a later drain does
// not re-download it (DONE items were already removed one by one via onItemDone).
ZimWishlist.clear(getApplicationContext());
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; }

Expand All @@ -127,14 +135,15 @@ public int onStartCommand(Intent intent, int flags, int startId) {
if (files == null || files.length == 0) { stopSelf(); return START_NOT_STICKY; }
String[] labels = intent.getStringArrayExtra(EXTRA_LABELS);
long[] bytes = intent.getLongArrayExtra(EXTRA_BYTES);
String[] keys = intent.getStringArrayExtra(EXTRA_KEYS);
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
SESSION.begin(keys, labels, bytes, bodies); // session owns the snapshot from here on
}
return START_NOT_STICKY;
}
Expand All @@ -148,6 +157,12 @@ public int onStartCommand(Intent intent, int flags, int startId) {

@Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); }

/** ADFA-4897: item confirmed downloaded -> drop it from the durable wishlist, so a process death
* after this point never re-downloads it. */
@Override public void onItemDone(String key) {
if (key != null && !key.isEmpty()) ZimWishlist.remove(getApplicationContext(), key);
}

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
Expand Down
Loading
Loading