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 @@ -19,7 +19,8 @@
* speed(bytes/s),
* detail, error }
* POST /api/kiwix/jobs/:id/cancel -> { ok:true }
* phase is one of: queued|downloading|indexing|processing|done|error|canceled.
* POST /api/kiwix/jobs/:id/pause|resume -> { ok:true } (ADFA-4893)
* phase is one of: queued|downloading|indexing|processing|paused|done|error|canceled.
* ============================================================================
*/
package org.iiab.controller.content;
Expand Down Expand Up @@ -51,11 +52,19 @@ public interface Listener {
void onLog(String line); // free-form detail line (for logs)
void onDone(); // success (terminal)
void onError(String message); // failure (terminal)
/** ADFA-4893: 'paused' phase (best-effort). Default no-op so existing implementers compile unchanged. */
default void onPaused(int percent) {}
/** ADFA-4893: server is reconnecting (attempt n of total) after a network drop; keeps polling. */
default void onReconnecting(int attempt, int total) {}
}

private static final String BASE = BoxEndpoints.API + "/kiwix";
private static final long POLL_MS = 1000L;
private static final int MAX_POLL_ERRORS = 10; // tolerate ~10s of transient network blips
// ADFA-4893: the START (download) POST is before any server job exists, so the server's own
// reconnect can't cover a still-warming box; give the kickoff a few quick tries before failing.
private static final int START_TRIES = 3;
private static final long START_RETRY_MS = 2000L;

private final Handler main = new Handler(Looper.getMainLooper());
private Listener listener;
Expand All @@ -70,15 +79,25 @@ public interface Listener {
public void addZim(@NonNull String zimFilename, @NonNull Listener l) {
this.listener = l;
AppExecutors.get().io().execute(() -> {
try {
JSONObject body = new JSONObject().put("ids", new JSONArray().put(zimFilename));
JSONObject resp = httpJson("POST", BASE + "/download", body);
String id = resp.optString("id", "");
if (id.isEmpty()) { fail("content service did not start the job"); return; }
jobId = id;
main.postDelayed(pollTask, POLL_MS);
} catch (Exception e) {
fail("couldn't reach the content service");
final JSONObject body;
try { body = new JSONObject().put("ids", new JSONArray().put(zimFilename)); }
catch (Exception e) { fail("couldn't build the request"); return; }
// ADFA-4893: retry ONLY the kickoff POST (connectivity blip / server still warming) a few
// times. An empty id is a server refusal, not a blip, so it fails without retrying. Once the
// job exists, the server owns reconnection (visible), not this loop.
for (int attempt = 1; !finished; attempt++) {
try {
JSONObject resp = httpJson("POST", BASE + "/download", body);
String id = resp.optString("id", "");
if (id.isEmpty()) { fail("content service did not start the job"); return; }
jobId = id;
main.postDelayed(pollTask, POLL_MS);
return;
} catch (Exception e) {
if (attempt >= START_TRIES) { fail("couldn't reach the content service"); return; }
try { Thread.sleep(START_RETRY_MS); }
catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; }
}
}
});
}
Expand All @@ -93,12 +112,17 @@ private void pollOnce() {
long speed = j.optLong("speed", 0L);
String detail = j.isNull("detail") ? null : j.optString("detail", null);
String error = j.isNull("error") ? null : j.optString("error", null);
int retryAttempt = j.optInt("retryAttempt", 0); // ADFA-4893: reconnect state (0 when not retrying)
int retryTotal = j.optInt("retryTotal", 0);

if (detail != null && !detail.isEmpty()) deliver(() -> listener.onLog(detail));

switch (phase) {
case "downloading":
if (percent >= 0) {
if (retryAttempt > 0) {
final int a = retryAttempt, t = retryTotal;
deliver(() -> listener.onReconnecting(a, t));
} else if (percent >= 0) {
final int p = percent; final String rate = formatRate(speed);
deliver(() -> listener.onProgress(p, rate));
}
Expand All @@ -116,6 +140,12 @@ private void pollOnce() {
case "canceled":
fail("canceled");
return;
case "paused": {
// ADFA-4893: not terminal — surface it and keep polling so resume/progress is seen.
final int pp = percent;
deliver(() -> listener.onPaused(pp));
break;
}
default:
break; // queued / unknown: keep polling
}
Expand All @@ -128,6 +158,7 @@ private void pollOnce() {

/** Best-effort cancel of the in-flight job. */
public void cancel() {
finished = true; // ADFA-4893: also stops the START retry loop if a cancel lands mid-kickoff
final String id = jobId;
if (id != null && !id.isEmpty()) {
AppExecutors.get().io().execute(() -> {
Expand All @@ -137,6 +168,26 @@ public void cancel() {
teardown();
}

/** ADFA-4893: best-effort pause of the in-flight job. Keeps polling so 'paused' is observed and resume works. */
public void pause() {
final String id = jobId;
if (id != null && !id.isEmpty()) {
AppExecutors.get().io().execute(() -> {
try { httpJson("POST", BASE + "/jobs/" + id + "/pause", null); } catch (Exception ignore) { /* best effort */ }
});
}
}

/** ADFA-4893: best-effort resume of a paused job; polling continues, so progress flows again. */
public void resume() {
final String id = jobId;
if (id != null && !id.isEmpty()) {
AppExecutors.get().io().execute(() -> {
try { httpJson("POST", BASE + "/jobs/" + id + "/resume", null); } catch (Exception ignore) { /* best effort */ }
});
}
}

private void done() {
if (finished) return;
finished = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -605,21 +605,21 @@ private void render() {
zimSession, ZimDownloadService.status(),
ZimDownloadService.DONE, ZimDownloadService.FAILED,
zimSession && ZimDownloadService.isComplete(), content.banked(ContentType.ZIM),
ZimDownloadService.speed()));
ZimDownloadService.speed(), zimOverallPercent()));
if (booksShown) (booksSession ? started : waiting).add(
streamRow(getString(R.string.k2go_gm_books_title), "books",
booksSession, BooksDownloadService.status(),
BooksDownloadService.DONE, BooksDownloadService.FAILED,
booksSession && BooksDownloadService.isComplete(), content.banked(ContentType.BOOKS),
0L));
0L, -1)); // ADFA-4893: Books has no per-item size yet -> no determinate bar
// ADFA-4954. Statuses come from an observable snapshot rather than static arrays, so the
// ordinals are mapped to the checklist's PENDING=0 / doneVal / failedVal convention here.
if (kolibriShown) (kolibriState.hasSession() ? started : waiting).add(
streamRow(getString(R.string.k2go_gm_courses_title), "kolibri",
kolibriState.hasSession(), kolibriState.statusOrdinals(),
KolibriSeedState.Status.DONE.ordinal(), KolibriSeedState.Status.FAILED.ordinal(),
kolibriState.hasSession() && kolibriState.isComplete(), kolibriBanked,
kolibriState.speedBytesPerSec()));
kolibriState.speedBytesPerSec(), -1)); // ADFA-4893: Kolibri keeps its indicator
for (View v : started) sections.addView(v);
for (View v : waiting) sections.addView(v);

Expand Down Expand Up @@ -894,7 +894,7 @@ private String rateSuffix(long bytesPerSec) {
}

private View streamRow(String heading, String key, boolean sess, int[] status, int doneVal, int failedVal,
boolean complete, int wishlistCount, long bytesPerSec) {
boolean complete, int wishlistCount, long bytesPerSec, int barPercent) {
int n = sess && status != null ? status.length : wishlistCount;
int done = 0, failed = 0;
if (sess && status != null) for (int st : status) { if (st == doneVal) done++; else if (st == failedVal) failed++; }
Expand Down Expand Up @@ -959,6 +959,7 @@ private View streamRow(String heading, String key, boolean sess, int[] status, i
sub.setText(state);
sub.setTextColor(ContextCompat.getColor(this, (sess && failed > 0) ? R.color.k2go_amber_text : R.color.k2go_muted));
col.addView(sub);
addRowProgressBar(col, barPercent, sess && !complete); // ADFA-4893: determinate bar for REST streams (ZIM)
row.addView(col, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));

ImageView chev = new ImageView(this);
Expand All @@ -981,19 +982,33 @@ private View streamRow(String heading, String key, boolean sess, int[] status, i
* it). Only shown while the module is running and has a task table (percent >= 0); otherwise the
* row keeps its indeterminate indicator. Lifted off the card's bottom edge with a small margin. */
private void addRowProgressBar(LinearLayout col, ModuleQueueState mq, boolean running) {
if (!(running && mq.percent >= 0)) return;
addRowProgressBar(col, mq.percent, running); // ADFA-5228 (proot rows)
}

/** ADFA-4893: same determinate row bar driven by a plain percent, for REST streams (ZIM). Hidden
* when not running or percent < 0, so a paused/indeterminate stream keeps its indicator. */
private void addRowProgressBar(LinearLayout col, int percent, boolean running) {
if (!(running && percent >= 0)) return;
com.google.android.material.progressindicator.LinearProgressIndicator bar =
new com.google.android.material.progressindicator.LinearProgressIndicator(this);
bar.setIndeterminate(false);
bar.setMax(100);
bar.setProgressCompat(mq.percent, true);
bar.setProgressCompat(percent, true);
LinearLayout.LayoutParams barLp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
barLp.topMargin = px(8);
barLp.bottomMargin = px(4);
col.addView(bar, barLp);
}

/** ADFA-4893: the ZIM index row bar shares one formula with the status screen — see
* {@link ZimDownloadService#overallPercent()}. Here we only gate visibility: -1 (no bar) unless a
* job is actively running, so a terminal/failed row falls back to its indicator. */
private int zimOverallPercent() {
return (ZimDownloadService.isRunning() && !ZimDownloadService.isComplete())
? ZimDownloadService.overallPercent() : -1;
}

private View mapsRow() {
ModuleQueueState mq = ModuleQueueRepository.get().current();
boolean done = mapsStartFailed || (mapsInSession() && mq.phase == ModuleQueueState.Phase.DONE);
Expand Down
Loading
Loading