From 1788ff07bfee2a9436a31421c4f2ee204ca922f3 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Thu, 22 Oct 2026 11:29:54 -0600 Subject: [PATCH] K2GO-503 feat(updaters): overall progress and total ETA for add-ons/assets Aggregate aria2 progress through its RPC into one monotonic bar with aggregate speed and total ETA; unify the duplicated add-ons/assets refresh views into one ContentUpdaterView behind a ContentUpdater adapter (fixes the dancing bar, the duplicate label, and the up-to-date message). --- .../presentation/AddonsDownloadService.java | 3 + .../addons/presentation/AddonsUpdater.java | 57 +++++ .../CodeAssetsDownloadService.java | 3 + .../presentation/CodeAssetsRefresh.java | 197 ----------------- .../presentation/CodeAssetsUpdater.java | 59 ++++++ .../k2go/content/RestContentClient.java | 8 +- .../k2go/redesign/ContentDownloadSession.java | 18 +- .../k2go/redesign/ContentUpdater.java | 59 ++++++ .../ContentUpdaterView.java} | 148 ++++++++----- .../k2go/redesign/ModuleActions.java | 6 +- .../app/src/main/res/values-ar/strings.xml | 5 + .../app/src/main/res/values-az/strings.xml | 5 + .../app/src/main/res/values-bg/strings.xml | 5 + .../app/src/main/res/values-bn/strings.xml | 5 + .../app/src/main/res/values-cs/strings.xml | 5 + .../app/src/main/res/values-de/strings.xml | 5 + .../app/src/main/res/values-el/strings.xml | 5 + .../app/src/main/res/values-es/strings.xml | 5 + .../app/src/main/res/values-fa/strings.xml | 5 + .../app/src/main/res/values-fr/strings.xml | 5 + .../app/src/main/res/values-gu/strings.xml | 5 + .../app/src/main/res/values-hi/strings.xml | 5 + .../app/src/main/res/values-hu/strings.xml | 5 + .../app/src/main/res/values-in/strings.xml | 5 + .../app/src/main/res/values-it/strings.xml | 5 + .../app/src/main/res/values-ja/strings.xml | 5 + .../app/src/main/res/values-ko/strings.xml | 5 + .../app/src/main/res/values-lt/strings.xml | 5 + .../app/src/main/res/values-nl/strings.xml | 5 + .../app/src/main/res/values-no/strings.xml | 5 + .../app/src/main/res/values-pl/strings.xml | 5 + .../app/src/main/res/values-pt/strings.xml | 5 + .../app/src/main/res/values-ro/strings.xml | 5 + .../src/main/res/values-ru-rRU/strings.xml | 5 + .../app/src/main/res/values-sk/strings.xml | 5 + .../app/src/main/res/values-sr/strings.xml | 5 + .../app/src/main/res/values-sw/strings.xml | 5 + .../app/src/main/res/values-ta/strings.xml | 5 + .../app/src/main/res/values-tr/strings.xml | 5 + .../app/src/main/res/values-uk/strings.xml | 5 + .../app/src/main/res/values-vi/strings.xml | 5 + .../app/src/main/res/values-yo/strings.xml | 5 + .../src/main/res/values-zh-rCN/strings.xml | 5 + .../app/src/main/res/values/strings.xml | 5 + .../main/res/values/strings_untranslated.xml | 5 +- static/dashboard/CHANGELOG.md | 1 + static/dashboard/package.json | 2 +- static/dashboard/routes.ts | 1 + static/dashboard/sockets/aria2-download.ts | 199 ++++++++++++++---- static/dashboard/sockets/code_addons.exec.ts | 42 +++- static/dashboard/sockets/code_assets.exec.ts | 10 +- static/dashboard/sockets/jobs.ts | 17 +- 52 files changed, 686 insertions(+), 319 deletions(-) create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsUpdater.java delete mode 100644 controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsRefresh.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsUpdater.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentUpdater.java rename controller/app/src/main/java/org/appdevforall/k2go/{addons/presentation/AddonsRefresh.java => redesign/ContentUpdaterView.java} (52%) diff --git a/controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsDownloadService.java b/controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsDownloadService.java index fbcf41cb0..23d68f9b5 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsDownloadService.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsDownloadService.java @@ -52,6 +52,9 @@ public interface Listener { void onUpdate(); } public static boolean hasFailed() { return SESSION.hasFailed(); } public static int percent() { return SESSION.percent(); } public static long speed() { return SESSION.speed(); } + public static long etaSeconds() { return SESSION.eta(); } + public static boolean lastWasUpToDate() { return SESSION.lastWasUpToDate(); } + public static String currentDetail() { return SESSION.currentDetail(); } public static int reconnectAttempt() { return SESSION.reconnectAttempt(); } public static int reconnectTotal() { return SESSION.reconnectTotal(); } public static void setListener(Listener l) { SESSION.setListener(l == null ? null : l::onUpdate); } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsUpdater.java b/controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsUpdater.java new file mode 100644 index 000000000..ff468a219 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsUpdater.java @@ -0,0 +1,57 @@ +/* + * ============================================================================ + * Name : AddonsUpdater.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-503. The Code on the Go add-ons adapter for the shared ContentUpdaterView: a thin + * delegate over AddonsDownloadService (the aria2 download path) plus the module's + * strings. The whole updater UX lives in ContentUpdaterView; this just wires the module. + * ============================================================================ + */ +package org.appdevforall.k2go.addons.presentation; + +import android.content.Context; + +import org.appdevforall.k2go.R; +import org.appdevforall.k2go.redesign.ContentUpdater; + +public final class AddonsUpdater implements ContentUpdater { + + public static final AddonsUpdater INSTANCE = new AddonsUpdater(); + + private AddonsUpdater() {} + + @Override public void start(Context ctx) { AddonsDownloadService.start(ctx); } + @Override public void pause(Context ctx) { AddonsDownloadService.pause(ctx); } + @Override public void resume(Context ctx) { AddonsDownloadService.resume(ctx); } + @Override public void cancel(Context ctx) { AddonsDownloadService.cancel(ctx); } + @Override public void retry(Context ctx) { AddonsDownloadService.retry(ctx); } + @Override public void finishSession() { AddonsDownloadService.finishSession(); } + + @Override public void setListener(Runnable onUpdate) { + AddonsDownloadService.Listener l = onUpdate == null ? null : onUpdate::run; + AddonsDownloadService.setListener(l); + } + + @Override public boolean isRunning() { return AddonsDownloadService.isRunning(); } + @Override public boolean isPaused() { return AddonsDownloadService.isPaused(); } + @Override public boolean hasSession() { return AddonsDownloadService.hasSession(); } + @Override public boolean isComplete() { return AddonsDownloadService.isComplete(); } + @Override public boolean hasFailed() { return AddonsDownloadService.hasFailed(); } + @Override public int percent() { return AddonsDownloadService.percent(); } + @Override public long speed() { return AddonsDownloadService.speed(); } + @Override public long etaSeconds() { return AddonsDownloadService.etaSeconds(); } + @Override public int reconnectAttempt() { return AddonsDownloadService.reconnectAttempt(); } + @Override public int reconnectTotal() { return AddonsDownloadService.reconnectTotal(); } + @Override public boolean lastWasUpToDate() { return AddonsDownloadService.lastWasUpToDate(); } + @Override public String currentDetail() { return AddonsDownloadService.currentDetail(); } + + @Override public boolean supportsPauseResume() { return true; } + @Override public boolean supportsSpeedEta() { return true; } + + @Override public int titleRes() { return R.string.k2go_code_addons_updating; } + @Override public int doneRes() { return R.string.k2go_code_addons_update_done; } + @Override public int upToDateRes() { return R.string.k2go_code_addons_update_up_to_date; } + @Override public int failedRes() { return R.string.k2go_code_addons_update_failed; } + @Override public int cancelledRes() { return R.string.k2go_code_addons_update_cancelled; } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsDownloadService.java b/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsDownloadService.java index 95e1b7f3c..ff6808d91 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsDownloadService.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsDownloadService.java @@ -52,6 +52,9 @@ public interface Listener { void onUpdate(); } public static boolean hasFailed() { return SESSION.hasFailed(); } public static int percent() { return SESSION.percent(); } public static long speed() { return SESSION.speed(); } + public static long etaSeconds() { return SESSION.eta(); } + public static boolean lastWasUpToDate() { return SESSION.lastWasUpToDate(); } + public static String currentDetail() { return SESSION.currentDetail(); } public static int reconnectAttempt() { return SESSION.reconnectAttempt(); } public static int reconnectTotal() { return SESSION.reconnectTotal(); } public static void setListener(Listener l) { SESSION.setListener(l == null ? null : l::onUpdate); } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsRefresh.java b/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsRefresh.java deleted file mode 100644 index b3d5baf2e..000000000 --- a/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsRefresh.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * ============================================================================ - * Name : CodeAssetsRefresh.java - * Author : AppDevForAll - * Copyright : Copyright (c) 2026 AppDevForAll - * Description : K2GO-437 / K2GO-443. The single "Update build assets" flow, shared by the module detail - * button and the module action sheet row. It gates like the dashboard update (needs - * internet, then metered consent), then drives the durable job engine through - * CodeAssetsDownloadService: a determinate progress bar (percent + speed) with Pause / - * Resume and Cancel, injected right after the trigger view. The download runs in a - * foreground service and on the box, so it survives this view going away: re-opening the - * sheet re-attaches to the running session. - * - * Lifecycle: no persistent app-side state here. Pause/resume/cancel state lives in the - * session + the box job; this view only observes it and re-renders. A terminal state - * (done / failed / cancelled) removes the inline UI and reports it in a snackbar. - * ============================================================================ - */ -package org.appdevforall.k2go.codeassets.presentation; - -import android.app.Activity; -import android.content.Context; -import android.os.Handler; -import android.os.Looper; -import android.text.TextUtils; -import android.view.Gravity; -import android.view.View; -import android.view.ViewGroup; -import android.widget.LinearLayout; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.core.content.ContextCompat; - -import com.google.android.material.progressindicator.LinearProgressIndicator; - -import org.appdevforall.k2go.R; -import org.appdevforall.k2go.util.ByteFormatter; -import org.appdevforall.k2go.util.Snackbars; - -public final class CodeAssetsRefresh { - - private CodeAssetsRefresh() {} - - /** - * Gate (internet, then metered consent) then run the update with progress injected right after - * {@code trigger}. The trigger stays in place (only disabled) as a visible anchor for the snackbar. - */ - public static void start(@NonNull Activity act, @NonNull View trigger) { - if (!org.appdevforall.k2go.networkpolicy.data.AndroidNetworkClassifier.hasInternet(act)) { - Snackbars.make(trigger, act.getString(R.string.k2go_dash_needs_internet)).show(); - return; - } - // Same metered gate as the dashboard update: the box downloads the build assets over the device network. - org.appdevforall.k2go.networkpolicy.presentation.NetworkPolicyGate.guardHeavyStart(act, () -> run(trigger)); - } - - private static void run(@NonNull View trigger) { - final ViewGroup parent = (ViewGroup) trigger.getParent(); - if (parent == null || !trigger.isAttachedToWindow()) return; // host went away during the gate - final Context ctx = trigger.getContext().getApplicationContext(); - final Handler main = new Handler(Looper.getMainLooper()); - final float d = trigger.getResources().getDisplayMetrics().density; - final int side = Math.round(20 * d); - - final LinearLayout progress = new LinearLayout(trigger.getContext()); - progress.setOrientation(LinearLayout.VERTICAL); - LinearLayout.LayoutParams plp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - plp.leftMargin = side; plp.rightMargin = side; plp.topMargin = Math.round(8 * d); - progress.setLayoutParams(plp); - - final TextView label = new TextView(trigger.getContext()); - label.setText(R.string.k2go_code_assets_updating); - label.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodySmall); - label.setTextColor(ContextCompat.getColor(trigger.getContext(), R.color.k2go_muted)); - progress.addView(label); - - final TextView statusLine = new TextView(trigger.getContext()); - statusLine.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodySmall); - statusLine.setTextColor(ContextCompat.getColor(trigger.getContext(), R.color.k2go_muted)); - statusLine.setMaxLines(1); - statusLine.setEllipsize(TextUtils.TruncateAt.END); - LinearLayout.LayoutParams slp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - slp.topMargin = Math.round(2 * d); - statusLine.setLayoutParams(slp); - progress.addView(statusLine); - - final LinearLayout barLine = new LinearLayout(trigger.getContext()); - barLine.setOrientation(LinearLayout.HORIZONTAL); - barLine.setGravity(Gravity.CENTER_VERTICAL); - LinearLayout.LayoutParams barLineLp = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - barLineLp.topMargin = Math.round(4 * d); - barLine.setLayoutParams(barLineLp); - - final LinearProgressIndicator bar = new LinearProgressIndicator(trigger.getContext()); - bar.setIndeterminate(true); - LinearLayout.LayoutParams blp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f); - bar.setLayoutParams(blp); - barLine.addView(bar); - - final int hp = Math.round(12 * d), vp = Math.round(6 * d); - final TextView pauseBtn = new TextView(trigger.getContext()); - pauseBtn.setText(R.string.k2go_dl_pause); - pauseBtn.setAllCaps(true); - pauseBtn.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_LabelLarge); - pauseBtn.setTextColor(ContextCompat.getColor(trigger.getContext(), R.color.k2go_teal)); - pauseBtn.setPadding(hp, vp, hp, vp); - barLine.addView(pauseBtn); - - final TextView cancelBtn = new TextView(trigger.getContext()); - cancelBtn.setText(R.string.k2go_dash_cancel); - cancelBtn.setAllCaps(true); - cancelBtn.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_LabelLarge); - cancelBtn.setTextColor(ContextCompat.getColor(trigger.getContext(), R.color.k2go_teal)); - cancelBtn.setPadding(hp, vp, hp, vp); - barLine.addView(cancelBtn); - progress.addView(barLine); - - parent.addView(progress, parent.indexOfChild(trigger) + 1); - trigger.setEnabled(false); // stays in place as an anchor; re-enabled when the update settles - - pauseBtn.setOnClickListener(v -> { - if (CodeAssetsDownloadService.isPaused()) CodeAssetsDownloadService.resume(ctx); - else CodeAssetsDownloadService.pause(ctx); - }); - cancelBtn.setOnClickListener(v -> { - cancelBtn.setEnabled(false); - CodeAssetsDownloadService.cancel(ctx); - }); - - // Clear the session listener the moment this view leaves the window (sheet dismissed), so the - // static session never keeps a destroyed Activity alive while a download runs on. Deterministic: - // it does not wait for the next session event (a paused download emits none). - final View.OnAttachStateChangeListener detach = new View.OnAttachStateChangeListener() { - @Override public void onViewAttachedToWindow(@NonNull View v) {} - @Override public void onViewDetachedFromWindow(@NonNull View v) { - CodeAssetsDownloadService.setListener(null); - } - }; - - final Runnable[] render = new Runnable[1]; - render[0] = () -> { - if (!trigger.isAttachedToWindow()) { CodeAssetsDownloadService.setListener(null); return; } - final boolean running = CodeAssetsDownloadService.isRunning(); - // hasFailed() BEFORE isComplete(): isComplete() is true for an all-FAILED session too - // (FAILED is "not in progress"), so a failed run must be caught first. - if (!running && CodeAssetsDownloadService.hasFailed()) { - terminal(trigger, parent, progress, detach, R.string.k2go_code_assets_update_failed); - return; - } - if (CodeAssetsDownloadService.isComplete()) { - terminal(trigger, parent, progress, detach, R.string.k2go_code_assets_update_done); - return; - } - if (!CodeAssetsDownloadService.hasSession()) { // cancelled (purged) - terminal(trigger, parent, progress, detach, R.string.k2go_code_assets_update_cancelled); - return; - } - final boolean paused = CodeAssetsDownloadService.isPaused(); - final int pct = CodeAssetsDownloadService.percent(); - bar.setIndeterminate(pct < 0); - if (pct >= 0) bar.setProgressCompat(pct, true); - pauseBtn.setText(paused ? R.string.k2go_dl_resume : R.string.k2go_dl_pause); - if (CodeAssetsDownloadService.reconnectAttempt() > 0) { - statusLine.setText(R.string.k2go_retrying); - } else if (paused) { - statusLine.setText(R.string.k2go_dl_paused); - } else { - final long spd = CodeAssetsDownloadService.speed(); - statusLine.setText(spd > 0 - ? ByteFormatter.toHuman(spd) + "/s" - : trigger.getContext().getString(R.string.k2go_code_assets_updating)); - } - }; - - trigger.addOnAttachStateChangeListener(detach); - // publish() already posts to the main thread, so the listener runs on main: wire it directly. - CodeAssetsDownloadService.setListener(render[0]::run); - CodeAssetsDownloadService.start(ctx); - main.post(render[0]); // initial paint - } - - private static void terminal(@NonNull View trigger, @NonNull ViewGroup parent, @NonNull View progress, - @NonNull View.OnAttachStateChangeListener detach, int msgRes) { - CodeAssetsDownloadService.setListener(null); - trigger.removeOnAttachStateChangeListener(detach); - if (progress.getParent() == parent) parent.removeView(progress); - trigger.setEnabled(true); - if (trigger.isAttachedToWindow()) { - Snackbars.make(trigger, trigger.getContext().getString(msgRes)).show(); - } - CodeAssetsDownloadService.finishSession(); - } -} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsUpdater.java b/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsUpdater.java new file mode 100644 index 000000000..52e2d96e0 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/codeassets/presentation/CodeAssetsUpdater.java @@ -0,0 +1,59 @@ +/* + * ============================================================================ + * Name : CodeAssetsUpdater.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-503. The Code on the Go build-assets adapter for the shared ContentUpdaterView: a + * thin delegate over CodeAssetsDownloadService (the aria2 download path) plus the + * module's strings. The whole updater UX lives in ContentUpdaterView; this wires the + * module. Byte-for-byte the add-ons adapter with a different service and string set: + * the duplication that used to live in the Refresh views is gone. + * ============================================================================ + */ +package org.appdevforall.k2go.codeassets.presentation; + +import android.content.Context; + +import org.appdevforall.k2go.R; +import org.appdevforall.k2go.redesign.ContentUpdater; + +public final class CodeAssetsUpdater implements ContentUpdater { + + public static final CodeAssetsUpdater INSTANCE = new CodeAssetsUpdater(); + + private CodeAssetsUpdater() {} + + @Override public void start(Context ctx) { CodeAssetsDownloadService.start(ctx); } + @Override public void pause(Context ctx) { CodeAssetsDownloadService.pause(ctx); } + @Override public void resume(Context ctx) { CodeAssetsDownloadService.resume(ctx); } + @Override public void cancel(Context ctx) { CodeAssetsDownloadService.cancel(ctx); } + @Override public void retry(Context ctx) { CodeAssetsDownloadService.retry(ctx); } + @Override public void finishSession() { CodeAssetsDownloadService.finishSession(); } + + @Override public void setListener(Runnable onUpdate) { + CodeAssetsDownloadService.Listener l = onUpdate == null ? null : onUpdate::run; + CodeAssetsDownloadService.setListener(l); + } + + @Override public boolean isRunning() { return CodeAssetsDownloadService.isRunning(); } + @Override public boolean isPaused() { return CodeAssetsDownloadService.isPaused(); } + @Override public boolean hasSession() { return CodeAssetsDownloadService.hasSession(); } + @Override public boolean isComplete() { return CodeAssetsDownloadService.isComplete(); } + @Override public boolean hasFailed() { return CodeAssetsDownloadService.hasFailed(); } + @Override public int percent() { return CodeAssetsDownloadService.percent(); } + @Override public long speed() { return CodeAssetsDownloadService.speed(); } + @Override public long etaSeconds() { return CodeAssetsDownloadService.etaSeconds(); } + @Override public int reconnectAttempt() { return CodeAssetsDownloadService.reconnectAttempt(); } + @Override public int reconnectTotal() { return CodeAssetsDownloadService.reconnectTotal(); } + @Override public boolean lastWasUpToDate() { return CodeAssetsDownloadService.lastWasUpToDate(); } + @Override public String currentDetail() { return CodeAssetsDownloadService.currentDetail(); } + + @Override public boolean supportsPauseResume() { return true; } + @Override public boolean supportsSpeedEta() { return true; } + + @Override public int titleRes() { return R.string.k2go_code_assets_updating; } + @Override public int doneRes() { return R.string.k2go_code_assets_update_done; } + @Override public int upToDateRes() { return R.string.k2go_code_assets_update_up_to_date; } + @Override public int failedRes() { return R.string.k2go_code_assets_update_failed; } + @Override public int cancelledRes() { return R.string.k2go_code_assets_update_cancelled; } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/content/RestContentClient.java b/controller/app/src/main/java/org/appdevforall/k2go/content/RestContentClient.java index 5d339d9eb..f07401cf8 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/content/RestContentClient.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/content/RestContentClient.java @@ -53,6 +53,9 @@ public final class RestContentClient { * {@code speed} is a display token WITHOUT the per-second suffix (caller appends it). */ public interface Listener { void onProgress(int percent, String speed); // download phase + /** K2GO-503: progress with the job's total ETA in seconds (-1 unknown). Default forwards to the + * 2-arg form, so existing implementers compile unchanged; only the content session reads it. */ + default void onProgress(int percent, String speed, long etaSeconds) { onProgress(percent, speed); } void onIndexing(); // indexing phase (indeterminate) void onLog(String line); // free-form detail line (for logs) void onDone(); // success (terminal) @@ -147,6 +150,7 @@ private void pollOnce() { String phase = j.optString("phase", ""); int percent = j.optInt("percent", -1); long speed = j.optLong("speed", 0L); + long eta = j.optLong("eta", -1L); // K2GO-503: whole-job seconds remaining (-1 unknown) String detail = j.isNull("detail") ? null : j.optString("detail", null); String error = j.isNull("error") ? null : j.optString("error", null); JSONObject result = j.optJSONObject("result"); @@ -173,8 +177,8 @@ private void pollOnce() { 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)); + final int p = percent; final String rate = formatRate(speed); final long et = eta; + deliver(() -> listener.onProgress(p, rate, et)); } else if ("indexing".equals(phase) || "processing".equals(phase)) { if (!indexing) { indexing = true; deliver(() -> listener.onIndexing()); } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentDownloadSession.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentDownloadSession.java index 299a80cf4..aef964fcb 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentDownloadSession.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentDownloadSession.java @@ -69,6 +69,8 @@ default void onItemError(String key) {} private int index = 0; private int percent = 0; private long speed = 0; + private long eta = -1; // K2GO-503: whole-job seconds remaining (-1 unknown) + private volatile String lastDetail = ""; // K2GO-503: last box 'detail' (for the up-to-date result) public ContentDownloadSession(String type) { this.type = type; } @@ -85,6 +87,11 @@ default void onItemError(String key) {} public int index() { return index; } public int percent() { return percent; } public long speed() { return speed; } + public long eta() { return eta; } + /** K2GO-503: the last 'detail' the box reported (the current item or the terminal note). */ + public String currentDetail() { return lastDetail; } + /** K2GO-503: true when the finished job reported the content was already current ('up to date'). */ + public boolean lastWasUpToDate() { return "up to date".equalsIgnoreCase(lastDetail); } public String[] labels() { return labels; } public long[] sizes() { return sizes; } public String label(int i) { return i >= 0 && i < labels.length ? labels[i] : ""; } @@ -139,7 +146,7 @@ public void begin(String[] keys, String[] labels, long[] sizes, JSONObject[] bod 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; + index = 0; percent = 0; speed = 0; eta = -1; lastDetail = ""; paused = false; reconnectAttempt = 0; reconnectTotal = 0; running = true; lastProgressAt = SystemClock.elapsedRealtime(); @@ -184,7 +191,7 @@ public void cancelAndPurge() { public void purge() { status = new int[0]; keys = new String[0]; labels = new String[0]; sizes = new long[0]; bodies = new JSONObject[0]; - index = 0; percent = 0; speed = 0; + index = 0; percent = 0; speed = 0; eta = -1; lastDetail = ""; running = false; paused = false; reconnectAttempt = 0; reconnectTotal = 0; lastProgressAt = 0L; } @@ -207,10 +214,11 @@ private void startItem(final int i) { client = new RestContentClient(type); 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) { + @Override public void onProgress(int pct, String rate) { onProgress(pct, rate, -1L); } + @Override public void onProgress(int pct, String rate, long etaSeconds) { if (paused) paused = false; reconnectAttempt = 0; - percent = pct; speed = parseRate(rate); + percent = pct; speed = parseRate(rate); eta = etaSeconds; lastProgressAt = SystemClock.elapsedRealtime(); if (status[i] != PROCESSING) status[i] = ACTIVE; publish(); @@ -226,7 +234,7 @@ private void startItem(final int i) { reconnectAttempt = attempt; reconnectTotal = total; lastProgressAt = SystemClock.elapsedRealtime(); publish(); } - @Override public void onLog(String line) { /* logcat only */ } + @Override public void onLog(String line) { lastDetail = line; } // K2GO-503: up-to-date vs installed @Override public void onDone() { status[i] = DONE; publish(); // ADFA-4897: item confirmed done -> drop its wishlist entry, so a later process death diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentUpdater.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentUpdater.java new file mode 100644 index 000000000..9f0d82f84 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentUpdater.java @@ -0,0 +1,59 @@ +/* + * ============================================================================ + * Name : ContentUpdater.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-503. The small contract a module's updater exposes to the shared + * ContentUpdaterView, so the inline progress block, the "checking" state, the + * speed/ETA line, the terminal message, and the listener lifecycle live in ONE place + * instead of being copied per module. A module provides a thin adapter over its + * download service; the view never talks to a module service directly. A new download + * module inherits the whole updater UX by implementing this interface. + * ============================================================================ + */ +package org.appdevforall.k2go.redesign; + +import android.content.Context; + +public interface ContentUpdater { + + // ---- control (the service owns the foreground job; these just post intents) ----------------- + void start(Context ctx); + void pause(Context ctx); + void resume(Context ctx); + void cancel(Context ctx); + void retry(Context ctx); + void finishSession(); + /** Observe session changes on the main thread; null detaches. */ + void setListener(Runnable onUpdate); + + // ---- observed state (read from the shared job; the view never re-derives it) ----------------- + boolean isRunning(); + boolean isPaused(); + boolean hasSession(); + boolean isComplete(); + boolean hasFailed(); + /** -1 while indeterminate (checking / staging), else 0..100. */ + int percent(); + /** Bytes per second (0 when unknown or not a byte transfer). */ + long speed(); + /** Whole-job seconds remaining, or -1 when unknown. */ + long etaSeconds(); + int reconnectAttempt(); + int reconnectTotal(); + /** True when the finished job reported the content was already current (box detail "up to date"). */ + boolean lastWasUpToDate(); + /** The current item / repo the box is working on, for modules that show it instead of speed. */ + String currentDetail(); + + // ---- capabilities (an aria2 download vs a git refresh) -------------------------------------- + boolean supportsPauseResume(); + boolean supportsSpeedEta(); + + // ---- per-module strings --------------------------------------------------------------------- + int titleRes(); // "Updating ..." + int doneRes(); // " updated" + int upToDateRes(); // " already up to date" + int failedRes(); // "Could not update " + int cancelledRes(); // " update cancelled" +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsRefresh.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentUpdaterView.java similarity index 52% rename from controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsRefresh.java rename to controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentUpdaterView.java index 8ea212278..79fbda23b 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/addons/presentation/AddonsRefresh.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ContentUpdaterView.java @@ -1,21 +1,23 @@ /* * ============================================================================ - * Name : AddonsRefresh.java + * Name : ContentUpdaterView.java * Author : AppDevForAll * Copyright : Copyright (c) 2026 AppDevForAll - * Description : K2GO-99 / K2GO-443. The single "Update add-ons" flow, shared by the module detail button - * and the module action sheet row. It gates like the dashboard update (needs internet, then - * metered consent), then drives the durable job engine through AddonsDownloadService: a - * determinate progress bar (percent + speed) with Pause / Resume and Cancel, injected right - * after the trigger view. The download runs in a foreground service and on the box, so it - * survives this view going away: re-opening the sheet re-attaches to the running session. + * Description : K2GO-503. The single "Update " inline flow, shared by every content updater + * (add-ons, build assets, and any future download module) through the ContentUpdater + * contract. It gates like the dashboard update (needs internet, then metered consent), + * then drives the module's durable job: a determinate bar with percent + speed + total + * ETA, a "Checking for updates..." state while the box has no percent yet, Pause / + * Resume (when the module supports it) and Cancel, injected right after the trigger. * - * Lifecycle: no persistent app-side state here. Pause/resume/cancel state lives in the - * session + the box job; this view only observes it and re-renders. A terminal state - * (done / failed / cancelled) removes the inline UI and reports it in a snackbar. + * One owner for the four things each module used to copy: the progress block, the + * status-line text (so it never just repeats the title), the terminal message (done / + * already-up-to-date / failed / cancelled, read from the job), and the listener + * lifecycle. The lifecycle guard distinguishes a not-yet-started session from a purged + * one, so the first paint never reports a fresh start as "cancelled". * ============================================================================ */ -package org.appdevforall.k2go.addons.presentation; +package org.appdevforall.k2go.redesign; import android.app.Activity; import android.content.Context; @@ -37,24 +39,24 @@ import org.appdevforall.k2go.util.ByteFormatter; import org.appdevforall.k2go.util.Snackbars; -public final class AddonsRefresh { +public final class ContentUpdaterView { - private AddonsRefresh() {} + private ContentUpdaterView() {} /** * Gate (internet, then metered consent) then run the update with progress injected right after * {@code trigger}. The trigger stays in place (only disabled) as a visible anchor for the snackbar. */ - public static void start(@NonNull Activity act, @NonNull View trigger) { + public static void mount(@NonNull Activity act, @NonNull View trigger, @NonNull ContentUpdater u) { if (!org.appdevforall.k2go.networkpolicy.data.AndroidNetworkClassifier.hasInternet(act)) { Snackbars.make(trigger, act.getString(R.string.k2go_dash_needs_internet)).show(); return; } - // Same metered gate as the dashboard update: the box downloads the gallery over the device network. - org.appdevforall.k2go.networkpolicy.presentation.NetworkPolicyGate.guardHeavyStart(act, () -> run(trigger)); + // Same metered gate as the dashboard update: the box downloads the content over the device network. + org.appdevforall.k2go.networkpolicy.presentation.NetworkPolicyGate.guardHeavyStart(act, () -> run(trigger, u)); } - private static void run(@NonNull View trigger) { + private static void run(@NonNull View trigger, @NonNull ContentUpdater u) { final ViewGroup parent = (ViewGroup) trigger.getParent(); if (parent == null || !trigger.isAttachedToWindow()) return; // host went away during the gate final Context ctx = trigger.getContext().getApplicationContext(); @@ -70,7 +72,7 @@ private static void run(@NonNull View trigger) { progress.setLayoutParams(plp); final TextView label = new TextView(trigger.getContext()); - label.setText(R.string.k2go_code_addons_updating); + label.setText(u.titleRes()); label.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodySmall); label.setTextColor(ContextCompat.getColor(trigger.getContext(), R.color.k2go_muted)); progress.addView(label); @@ -84,6 +86,7 @@ private static void run(@NonNull View trigger) { ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); slp.topMargin = Math.round(2 * d); statusLine.setLayoutParams(slp); + statusLine.setText(R.string.k2go_update_checking); // first paint before any job state progress.addView(statusLine); final LinearLayout barLine = new LinearLayout(trigger.getContext()); @@ -102,12 +105,14 @@ private static void run(@NonNull View trigger) { final int hp = Math.round(12 * d), vp = Math.round(6 * d); final TextView pauseBtn = new TextView(trigger.getContext()); - pauseBtn.setText(R.string.k2go_dl_pause); - pauseBtn.setAllCaps(true); - pauseBtn.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_LabelLarge); - pauseBtn.setTextColor(ContextCompat.getColor(trigger.getContext(), R.color.k2go_teal)); - pauseBtn.setPadding(hp, vp, hp, vp); - barLine.addView(pauseBtn); + if (u.supportsPauseResume()) { + pauseBtn.setText(R.string.k2go_dl_pause); + pauseBtn.setAllCaps(true); + pauseBtn.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_LabelLarge); + pauseBtn.setTextColor(ContextCompat.getColor(trigger.getContext(), R.color.k2go_teal)); + pauseBtn.setPadding(hp, vp, hp, vp); + barLine.addView(pauseBtn); + } final TextView cancelBtn = new TextView(trigger.getContext()); cancelBtn.setText(R.string.k2go_dash_cancel); @@ -122,12 +127,12 @@ private static void run(@NonNull View trigger) { trigger.setEnabled(false); // stays in place as an anchor; re-enabled when the update settles pauseBtn.setOnClickListener(v -> { - if (AddonsDownloadService.isPaused()) AddonsDownloadService.resume(ctx); - else AddonsDownloadService.pause(ctx); + if (u.isPaused()) u.resume(ctx); + else u.pause(ctx); }); cancelBtn.setOnClickListener(v -> { cancelBtn.setEnabled(false); - AddonsDownloadService.cancel(ctx); + u.cancel(ctx); }); // Clear the session listener the moment this view leaves the window (sheet dismissed), so the @@ -135,62 +140,95 @@ private static void run(@NonNull View trigger) { // it does not wait for the next session event (a paused download emits none). final View.OnAttachStateChangeListener detach = new View.OnAttachStateChangeListener() { @Override public void onViewAttachedToWindow(@NonNull View v) {} - @Override public void onViewDetachedFromWindow(@NonNull View v) { - AddonsDownloadService.setListener(null); - } + @Override public void onViewDetachedFromWindow(@NonNull View v) { u.setListener(null); } }; + // sawSession distinguishes "the session has not begun yet" (the service's onStartCommand runs + // after this first paint) from "the session was purged" (a real cancel). Without it the first + // paint reads a fresh start as cancelled and tears the UI down before it starts (K2GO-503). + final boolean[] sawSession = { false }; final Runnable[] render = new Runnable[1]; render[0] = () -> { - if (!trigger.isAttachedToWindow()) { AddonsDownloadService.setListener(null); return; } - final boolean running = AddonsDownloadService.isRunning(); + if (!trigger.isAttachedToWindow()) { u.setListener(null); return; } + final boolean running = u.isRunning(); // hasFailed() BEFORE isComplete(): isComplete() is true for an all-FAILED session too // (FAILED is "not in progress"), so a failed run must be caught first. - if (!running && AddonsDownloadService.hasFailed()) { - terminal(trigger, parent, progress, detach, R.string.k2go_code_addons_update_failed); + if (!running && u.hasFailed()) { + terminal(u, trigger, parent, progress, detach, u.failedRes()); return; } - if (AddonsDownloadService.isComplete()) { - terminal(trigger, parent, progress, detach, R.string.k2go_code_addons_update_done); + if (u.isComplete()) { + terminal(u, trigger, parent, progress, detach, + u.lastWasUpToDate() ? u.upToDateRes() : u.doneRes()); return; } - if (!AddonsDownloadService.hasSession()) { // cancelled (purged) - terminal(trigger, parent, progress, detach, R.string.k2go_code_addons_update_cancelled); + if (!u.hasSession()) { + if (sawSession[0]) { // had a session, now gone: cancelled (purged) + terminal(u, trigger, parent, progress, detach, u.cancelledRes()); + } // else: not started yet, keep the indeterminate "checking" bar and wait return; } - final boolean paused = AddonsDownloadService.isPaused(); - final int pct = AddonsDownloadService.percent(); - bar.setIndeterminate(pct < 0); - if (pct >= 0) bar.setProgressCompat(pct, true); - pauseBtn.setText(paused ? R.string.k2go_dl_resume : R.string.k2go_dl_pause); - if (AddonsDownloadService.reconnectAttempt() > 0) { + sawSession[0] = true; + final boolean paused = u.isPaused(); + final int pct = u.percent(); + // "Checking for updates..." while the box stages/plans and no real progress has arrived + // yet: the shared session starts at percent 0 and the box reports no bytes during staging, + // so a bare "0%" would otherwise sit frozen. Any real byte flow (percent or speed) ends it. + final boolean checking = pct <= 0 && (!u.supportsSpeedEta() || u.speed() <= 0); + bar.setIndeterminate(checking); + if (!checking && pct >= 0) bar.setProgressCompat(pct, true); + if (u.supportsPauseResume()) pauseBtn.setText(paused ? R.string.k2go_dl_resume : R.string.k2go_dl_pause); + if (u.reconnectAttempt() > 0) { statusLine.setText(R.string.k2go_retrying); } else if (paused) { statusLine.setText(R.string.k2go_dl_paused); + } else if (checking) { + statusLine.setText(R.string.k2go_update_checking); // never repeat the title label } else { - final long spd = AddonsDownloadService.speed(); - statusLine.setText(spd > 0 - ? ByteFormatter.toHuman(spd) + "/s" - : trigger.getContext().getString(R.string.k2go_code_addons_updating)); + statusLine.setText(statusText(trigger.getContext(), u, pct)); } }; trigger.addOnAttachStateChangeListener(detach); - // publish() already posts to the main thread, so the listener runs on main: wire it directly. - AddonsDownloadService.setListener(render[0]::run); - AddonsDownloadService.start(ctx); + // the session posts its updates to the main thread, so the listener runs on main: wire it directly. + u.setListener(render[0]); + u.start(ctx); main.post(render[0]); // initial paint } - private static void terminal(@NonNull View trigger, @NonNull ViewGroup parent, @NonNull View progress, - @NonNull View.OnAttachStateChangeListener detach, int msgRes) { - AddonsDownloadService.setListener(null); + /** "45% 3.2 MB/s 2 min 10 s left" for a byte transfer, or "45% owner/name" for a git refresh. */ + private static String statusText(@NonNull Context ctx, @NonNull ContentUpdater u, int pct) { + StringBuilder sb = new StringBuilder(); + sb.append(pct).append('%'); + if (u.supportsSpeedEta()) { + long spd = u.speed(); + if (spd > 0) sb.append(" · ").append(ByteFormatter.toHuman(spd)).append("/s"); + long eta = u.etaSeconds(); + if (eta >= 0) sb.append(" · ").append(etaText(ctx, eta)); + } else { + String detail = u.currentDetail(); + if (detail != null && !detail.isEmpty()) sb.append(" · ").append(detail); + } + return sb.toString(); + } + + /** Whole-job seconds remaining as a localized "N min M s left" / "M s left". */ + private static String etaText(@NonNull Context ctx, long seconds) { + if (seconds < 0) return ""; + long m = seconds / 60, s = seconds % 60; + return m > 0 ? ctx.getString(R.string.k2go_eta_min_sec, (int) m, (int) s) + : ctx.getString(R.string.k2go_eta_sec, (int) s); + } + + private static void terminal(@NonNull ContentUpdater u, @NonNull View trigger, @NonNull ViewGroup parent, + @NonNull View progress, @NonNull View.OnAttachStateChangeListener detach, int msgRes) { + u.setListener(null); trigger.removeOnAttachStateChangeListener(detach); if (progress.getParent() == parent) parent.removeView(progress); trigger.setEnabled(true); if (trigger.isAttachedToWindow()) { Snackbars.make(trigger, trigger.getContext().getString(msgRes)).show(); } - AddonsDownloadService.finishSession(); + u.finishSession(); } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleActions.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleActions.java index c3fad5aab..d2bd50955 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleActions.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleActions.java @@ -56,10 +56,12 @@ public static final class InstalledAction { static { INSTALLED.put("code_addons", new InstalledAction( R.string.k2go_code_addons_update, R.drawable.ic_refresh, - (act, v) -> org.appdevforall.k2go.addons.presentation.AddonsRefresh.start(act, v))); + (act, v) -> org.appdevforall.k2go.redesign.ContentUpdaterView.mount( + act, v, org.appdevforall.k2go.addons.presentation.AddonsUpdater.INSTANCE))); INSTALLED.put("code_assets", new InstalledAction( R.string.k2go_code_assets_update, R.drawable.ic_refresh, - (act, v) -> org.appdevforall.k2go.codeassets.presentation.CodeAssetsRefresh.start(act, v))); + (act, v) -> org.appdevforall.k2go.redesign.ContentUpdaterView.mount( + act, v, org.appdevforall.k2go.codeassets.presentation.CodeAssetsUpdater.INSTANCE))); // K2GO-422 / K2GO-449: Forgejo "Update repos", gated on live box status (manageable AND repos // present). The gate reads ForgejoStatusClient off the main thread. The module detail screen keeps // its own richer Forgejo flow (install-repos / blocked / update plus the repos opt-in); this entry diff --git a/controller/app/src/main/res/values-ar/strings.xml b/controller/app/src/main/res/values-ar/strings.xml index be1c7e95a..f70cc372b 100644 --- a/controller/app/src/main/res/values-ar/strings.xml +++ b/controller/app/src/main/res/values-ar/strings.xml @@ -1422,4 +1422,9 @@ %1$d عناصر غير متاحة وصلت %1$d دورة غير مكتملة: الخادم لا يحتوي على بعض الملفات. قد تكون الدورات كبيرة جدًا وتستغرق وقتًا طويلًا للتنزيل، خاصةً مع اتصال بطيء. يبدأ التنزيل الآن، ويستمر في الخلفية، ويُستأنف إذا انقطع. + جارٍ البحث عن تحديثات... + متبقٍ %1$d min %2$d s + متبقٍ %1$d s + الإضافات محدّثة بالفعل + أصول البناء محدّثة بالفعل diff --git a/controller/app/src/main/res/values-az/strings.xml b/controller/app/src/main/res/values-az/strings.xml index e25459ecc..3418cd4a3 100644 --- a/controller/app/src/main/res/values-az/strings.xml +++ b/controller/app/src/main/res/values-az/strings.xml @@ -1442,4 +1442,9 @@ %1$d element mövcud deyil %1$d kurs natamam gəldi: serverdə bəzi fayllar yoxdur. Kurslar çox böyük ola və yüklənməsi uzun çəkə bilər, xüsusən yavaş bağlantıda. Yükləmə indi başlayır, arxa planda davam edir və kəsilsə davam etdirilir. + Yeniləmələr yoxlanılır... + %1$d min %2$d s qalıb + %1$d s qalıb + Əlavələr artıq yenilənib + Qurma resursları artıq yenilənib diff --git a/controller/app/src/main/res/values-bg/strings.xml b/controller/app/src/main/res/values-bg/strings.xml index c2dacf0f9..ec63f270a 100644 --- a/controller/app/src/main/res/values-bg/strings.xml +++ b/controller/app/src/main/res/values-bg/strings.xml @@ -1429,4 +1429,9 @@ %1$d елемента не са налични %1$d курс(а) пристигнаха непълни: сървърът няма някои файлове. Курсовете могат да са много големи и да се изтеглят дълго, особено при бавна връзка. Изтеглянето започва сега, продължава във фонов режим и се възобновява, ако бъде прекъснато. + Проверка за актуализации... + %1$d min %2$d s оставащи + %1$d s оставащи + Добавките вече са актуални + Ресурсите за компилиране вече са актуални diff --git a/controller/app/src/main/res/values-bn/strings.xml b/controller/app/src/main/res/values-bn/strings.xml index 42b058760..ae6758107 100644 --- a/controller/app/src/main/res/values-bn/strings.xml +++ b/controller/app/src/main/res/values-bn/strings.xml @@ -1435,4 +1435,9 @@ %1$dটি আইটেম উপলব্ধ নেই %1$dটি কোর্স অসম্পূর্ণ এসেছে: সার্ভারে কিছু ফাইল নেই। কোর্সগুলো অনেক বড় হতে পারে এবং ডাউনলোড হতে অনেক সময় লাগতে পারে, বিশেষ করে ধীর সংযোগে। ডাউনলোড এখনই শুরু হয়, পটভূমিতে চলতে থাকে এবং বাধা পেলে আবার শুরু হয়। + আপডেট খোঁজা হচ্ছে... + %1$d min %2$d s বাকি + %1$d s বাকি + অ্যাড-অন ইতিমধ্যে আপ টু ডেট + বিল্ড অ্যাসেট ইতিমধ্যে আপ টু ডেট diff --git a/controller/app/src/main/res/values-cs/strings.xml b/controller/app/src/main/res/values-cs/strings.xml index 2e36f8627..c7d5b5b49 100644 --- a/controller/app/src/main/res/values-cs/strings.xml +++ b/controller/app/src/main/res/values-cs/strings.xml @@ -1429,4 +1429,9 @@ Nedostupné položky: %1$d Neúplné kurzy: %1$d. Server nemá některé soubory. Kurzy mohou být velmi velké a jejich stahování může trvat dlouho, zvlášť na pomalém připojení. Stahování začne hned, pokračuje na pozadí a po přerušení se obnoví. + Kontrola aktualizací... + zbývá %1$d min %2$d s + zbývá %1$d s + Doplňky jsou již aktuální + Prostředky pro sestavení jsou již aktuální diff --git a/controller/app/src/main/res/values-de/strings.xml b/controller/app/src/main/res/values-de/strings.xml index 522250c86..1517b10e3 100644 --- a/controller/app/src/main/res/values-de/strings.xml +++ b/controller/app/src/main/res/values-de/strings.xml @@ -1422,4 +1422,9 @@ %1$d Elemente nicht verfügbar %1$d Kurs(e) unvollständig: Dem Server fehlen einige Dateien. Kurse können sehr groß sein und lange zum Herunterladen brauchen, besonders bei einer langsamen Verbindung. Der Download startet jetzt, läuft im Hintergrund weiter und wird nach einer Unterbrechung fortgesetzt. + Suche nach Updates... + %1$d min %2$d s verbleibend + %1$d s verbleibend + Add-ons bereits aktuell + Build-Ressourcen bereits aktuell diff --git a/controller/app/src/main/res/values-el/strings.xml b/controller/app/src/main/res/values-el/strings.xml index 5503e7293..3e3942865 100644 --- a/controller/app/src/main/res/values-el/strings.xml +++ b/controller/app/src/main/res/values-el/strings.xml @@ -1429,4 +1429,9 @@ %1$d στοιχεία μη διαθέσιμα %1$d μάθημα(τα) ήρθαν ελλιπή: ο διακομιστής δεν έχει κάποια αρχεία. Τα μαθήματα μπορεί να είναι πολύ μεγάλα και να χρειαστούν πολύ χρόνο για λήψη, ειδικά με αργή σύνδεση. Η λήψη ξεκινά τώρα, συνεχίζεται στο παρασκήνιο και συνεχίζεται αν διακοπεί. + Έλεγχος για ενημερώσεις... + %1$d min %2$d s απομένουν + %1$d s απομένουν + Τα πρόσθετα είναι ήδη ενημερωμένα + Οι πόροι δόμησης είναι ήδη ενημερωμένοι diff --git a/controller/app/src/main/res/values-es/strings.xml b/controller/app/src/main/res/values-es/strings.xml index b6983f35c..ecd44e537 100644 --- a/controller/app/src/main/res/values-es/strings.xml +++ b/controller/app/src/main/res/values-es/strings.xml @@ -1498,4 +1498,9 @@ %1$d elementos no disponibles %1$d curso(s) llegaron incompletos: el servidor no tiene algunos archivos. Los cursos pueden ser muy grandes y tardar mucho en descargarse, sobre todo con una conexión lenta. La descarga empieza ahora, sigue en segundo plano y se reanuda si se interrumpe. + Buscando actualizaciones... + %1$d min %2$d s restantes + %1$d s restantes + Complementos ya actualizados + Recursos de compilación ya actualizados diff --git a/controller/app/src/main/res/values-fa/strings.xml b/controller/app/src/main/res/values-fa/strings.xml index 6478f7c64..1d1361957 100644 --- a/controller/app/src/main/res/values-fa/strings.xml +++ b/controller/app/src/main/res/values-fa/strings.xml @@ -1422,4 +1422,9 @@ %1$d مورد در دسترس نیست %1$d دوره ناقص رسید: سرور برخی از فایل‌ها را ندارد. دوره‌ها ممکن است بسیار بزرگ باشند و دانلودشان زمان زیادی ببرد، به‌ویژه با اتصال کند. دانلود اکنون شروع می‌شود، در پس‌زمینه ادامه می‌یابد و در صورت قطع شدن از سر گرفته می‌شود. + در حال بررسی به‌روزرسانی‌ها... + باقی‌مانده %1$d min %2$d s + باقی‌مانده %1$d s + افزونه‌ها از پیش به‌روز هستند + منابع ساخت از پیش به‌روز هستند diff --git a/controller/app/src/main/res/values-fr/strings.xml b/controller/app/src/main/res/values-fr/strings.xml index 5750b55e7..0dbf49fa7 100644 --- a/controller/app/src/main/res/values-fr/strings.xml +++ b/controller/app/src/main/res/values-fr/strings.xml @@ -1509,4 +1509,9 @@ %1$d éléments indisponibles %1$d cours incomplet(s) : le serveur n\'a pas certains fichiers. Les cours peuvent être très volumineux et longs à télécharger, surtout avec une connexion lente. Le téléchargement commence maintenant, continue en arrière-plan et reprend s\'il est interrompu. + Recherche de mises à jour... + %1$d min %2$d s restant + %1$d s restant + Modules déjà à jour + Ressources de compilation déjà à jour diff --git a/controller/app/src/main/res/values-gu/strings.xml b/controller/app/src/main/res/values-gu/strings.xml index c18cdcde3..838bb7159 100644 --- a/controller/app/src/main/res/values-gu/strings.xml +++ b/controller/app/src/main/res/values-gu/strings.xml @@ -1435,4 +1435,9 @@ %1$d આઇટમ ઉપલબ્ધ નથી %1$d કોર્સ અધૂરા આવ્યા: સર્વર પાસે કેટલીક ફાઇલો નથી. કોર્સ ખૂબ મોટા હોઈ શકે છે અને ડાઉનલોડ થવામાં લાંબો સમય લાગી શકે છે, ખાસ કરીને ધીમા કનેક્શન પર. ડાઉનલોડ હમણાં શરૂ થાય છે, પૃષ્ઠભૂમિમાં ચાલુ રહે છે અને અટકે તો ફરી શરૂ થાય છે. + અપડેટ્સ તપાસી રહ્યું છે... + %1$d min %2$d s બાકી + %1$d s બાકી + એડ-ઓન પહેલેથી જ અપ ટૂ ડેટ + બિલ્ડ સંસાધનો પહેલેથી જ અપ ટૂ ડેટ diff --git a/controller/app/src/main/res/values-hi/strings.xml b/controller/app/src/main/res/values-hi/strings.xml index 7cfc82701..63b0fdd9f 100644 --- a/controller/app/src/main/res/values-hi/strings.xml +++ b/controller/app/src/main/res/values-hi/strings.xml @@ -1499,4 +1499,9 @@ %1$d आइटम उपलब्ध नहीं %1$d कोर्स अधूरे आए: सर्वर में कुछ फ़ाइलें नहीं हैं। कोर्स बहुत बड़े हो सकते हैं और डाउनलोड होने में बहुत समय ले सकते हैं, खासकर धीमे कनेक्शन पर। डाउनलोड अभी शुरू होता है, बैकग्राउंड में चलता रहता है और रुकने पर फिर से शुरू हो जाता है। + अपडेट जाँचे जा रहे हैं... + %1$d min %2$d s शेष + %1$d s शेष + ऐड-ऑन पहले से ही अप टू डेट + बिल्ड संसाधन पहले से ही अप टू डेट diff --git a/controller/app/src/main/res/values-hu/strings.xml b/controller/app/src/main/res/values-hu/strings.xml index 0f5101a9e..47a36ebd9 100644 --- a/controller/app/src/main/res/values-hu/strings.xml +++ b/controller/app/src/main/res/values-hu/strings.xml @@ -1422,4 +1422,9 @@ %1$d elem nem érhető el %1$d kurzus hiányosan érkezett: a szerveren nincs meg néhány fájl. A kurzusok nagyon nagyok lehetnek, és a letöltésük sokáig tarthat, főleg lassú kapcsolaton. A letöltés most indul, a háttérben folytatódik, és megszakadás után újraindul. + Frissítések keresése... + %1$d min %2$d s van hátra + %1$d s van hátra + Kiegészítők már naprakészek + Build-erőforrások már naprakészek diff --git a/controller/app/src/main/res/values-in/strings.xml b/controller/app/src/main/res/values-in/strings.xml index 67e4e9bf5..086eafdb1 100644 --- a/controller/app/src/main/res/values-in/strings.xml +++ b/controller/app/src/main/res/values-in/strings.xml @@ -1429,4 +1429,9 @@ %1$d item tidak tersedia %1$d kursus tiba tidak lengkap: server tidak memiliki beberapa file. Kursus bisa sangat besar dan lama diunduh, terutama dengan koneksi lambat. Unduhan dimulai sekarang, terus berjalan di latar belakang, dan dilanjutkan jika terputus. + Memeriksa pembaruan... + %1$d min %2$d s tersisa + %1$d s tersisa + Add-on sudah terkini + Aset build sudah terkini diff --git a/controller/app/src/main/res/values-it/strings.xml b/controller/app/src/main/res/values-it/strings.xml index 641fdb1f3..18587477e 100644 --- a/controller/app/src/main/res/values-it/strings.xml +++ b/controller/app/src/main/res/values-it/strings.xml @@ -1422,4 +1422,9 @@ %1$d elementi non disponibili Corsi incompleti: %1$d. Il server non ha alcuni file. I corsi possono essere molto grandi e richiedere molto tempo per il download, soprattutto con una connessione lenta. Il download inizia ora, continua in background e riprende se viene interrotto. + Ricerca di aggiornamenti... + %1$d min %2$d s rimanenti + %1$d s rimanenti + Componenti aggiuntivi già aggiornati + Risorse di compilazione già aggiornate diff --git a/controller/app/src/main/res/values-ja/strings.xml b/controller/app/src/main/res/values-ja/strings.xml index 3d9035114..094023b21 100644 --- a/controller/app/src/main/res/values-ja/strings.xml +++ b/controller/app/src/main/res/values-ja/strings.xml @@ -1423,4 +1423,9 @@ %1$d 件は利用できません %1$d 件のコースが不完全です: サーバーに一部のファイルがありません。 コースは非常に大きく、特に低速な接続ではダウンロードに長い時間がかかることがあります。ダウンロードは今すぐ始まり、バックグラウンドで続き、中断されても再開されます。 + 更新を確認中... + あと %1$d 分 %2$d 秒 + あと %1$d 秒 + アドオンはすでに最新です + ビルドアセットはすでに最新です diff --git a/controller/app/src/main/res/values-ko/strings.xml b/controller/app/src/main/res/values-ko/strings.xml index b50cd1bd6..863a8331b 100644 --- a/controller/app/src/main/res/values-ko/strings.xml +++ b/controller/app/src/main/res/values-ko/strings.xml @@ -1423,4 +1423,9 @@ %1$d개 항목을 사용할 수 없음 %1$d개 과정이 불완전합니다: 서버에 일부 파일이 없습니다. 과정은 매우 클 수 있으며, 특히 느린 연결에서는 다운로드하는 데 오래 걸릴 수 있습니다. 다운로드는 지금 시작되며 백그라운드에서 계속되고 중단되면 다시 시작됩니다. + 업데이트 확인 중... + %1$d분 %2$d초 남음 + %1$d초 남음 + 애드온이 이미 최신 상태입니다 + 빌드 자산이 이미 최신 상태입니다 diff --git a/controller/app/src/main/res/values-lt/strings.xml b/controller/app/src/main/res/values-lt/strings.xml index 8209abdf3..504ee0e67 100644 --- a/controller/app/src/main/res/values-lt/strings.xml +++ b/controller/app/src/main/res/values-lt/strings.xml @@ -1439,4 +1439,9 @@ Nepasiekiamų elementų: %1$d Nepilnų kursų: %1$d. Serveryje nėra kai kurių failų. Kursai gali būti labai dideli ir ilgai atsisiųsti, ypač esant lėtam ryšiui. Atsisiuntimas prasideda dabar, tęsiasi fone ir atnaujinamas, jei nutrūksta. + Ieškoma naujinių... + liko %1$d min %2$d s + liko %1$d s + Priedai jau atnaujinti + Kūrimo ištekliai jau atnaujinti diff --git a/controller/app/src/main/res/values-nl/strings.xml b/controller/app/src/main/res/values-nl/strings.xml index 75c577acf..4903fa532 100644 --- a/controller/app/src/main/res/values-nl/strings.xml +++ b/controller/app/src/main/res/values-nl/strings.xml @@ -1422,4 +1422,9 @@ %1$d items niet beschikbaar %1$d cursus(sen) onvolledig: de server heeft sommige bestanden niet. Cursussen kunnen erg groot zijn en lang duren om te downloaden, vooral met een trage verbinding. Het downloaden begint nu, gaat door op de achtergrond en wordt hervat als het wordt onderbroken. + Zoeken naar updates... + %1$d min %2$d s resterend + %1$d s resterend + Add-ons al up-to-date + Buildbronnen al up-to-date diff --git a/controller/app/src/main/res/values-no/strings.xml b/controller/app/src/main/res/values-no/strings.xml index d6313f962..260098ecf 100644 --- a/controller/app/src/main/res/values-no/strings.xml +++ b/controller/app/src/main/res/values-no/strings.xml @@ -1432,4 +1432,9 @@ %1$d elementer er ikke tilgjengelige %1$d kurs ble ufullstendige: serveren mangler noen filer. Kurs kan være svært store og ta lang tid å laste ned, særlig med en treg forbindelse. Nedlastingen starter nå, fortsetter i bakgrunnen og gjenopptas hvis den blir avbrutt. + Ser etter oppdateringer... + %1$d min %2$d s igjen + %1$d s igjen + Tillegg allerede oppdatert + Byggeressurser allerede oppdatert diff --git a/controller/app/src/main/res/values-pl/strings.xml b/controller/app/src/main/res/values-pl/strings.xml index 50971e558..db870cbc7 100644 --- a/controller/app/src/main/res/values-pl/strings.xml +++ b/controller/app/src/main/res/values-pl/strings.xml @@ -1432,4 +1432,9 @@ Niedostępne elementy: %1$d Niekompletne kursy: %1$d. Serwer nie ma niektórych plików. Kursy mogą być bardzo duże, a ich pobieranie może trwać długo, zwłaszcza przy wolnym połączeniu. Pobieranie zaczyna się teraz, trwa w tle i zostanie wznowione po przerwaniu. + Sprawdzanie aktualizacji... + pozostało %1$d min %2$d s + pozostało %1$d s + Dodatki już aktualne + Zasoby kompilacji już aktualne diff --git a/controller/app/src/main/res/values-pt/strings.xml b/controller/app/src/main/res/values-pt/strings.xml index b51c31aea..224b9ff13 100644 --- a/controller/app/src/main/res/values-pt/strings.xml +++ b/controller/app/src/main/res/values-pt/strings.xml @@ -1501,4 +1501,9 @@ %1$d itens indisponíveis %1$d curso(s) chegaram incompletos: o servidor não tem alguns arquivos. Os cursos podem ser muito grandes e demorar para baixar, especialmente com uma conexão lenta. O download começa agora, continua em segundo plano e é retomado se for interrompido. + Procurando atualizações... + %1$d min %2$d s restantes + %1$d s restantes + Complementos já atualizados + Recursos de compilação já atualizados diff --git a/controller/app/src/main/res/values-ro/strings.xml b/controller/app/src/main/res/values-ro/strings.xml index 3c4a8ff1e..8f0b667c3 100644 --- a/controller/app/src/main/res/values-ro/strings.xml +++ b/controller/app/src/main/res/values-ro/strings.xml @@ -1422,4 +1422,9 @@ %1$d elemente indisponibile Cursuri incomplete: %1$d. Serverul nu are unele fișiere. Cursurile pot fi foarte mari și pot dura mult la descărcare, mai ales pe o conexiune lentă. Descărcarea începe acum, continuă în fundal și se reia dacă este întreruptă. + Se caută actualizări... + %1$d min %2$d s rămase + %1$d s rămase + Suplimente deja actualizate + Resurse de compilare deja actualizate diff --git a/controller/app/src/main/res/values-ru-rRU/strings.xml b/controller/app/src/main/res/values-ru-rRU/strings.xml index 2e31ff91f..6b00263a8 100644 --- a/controller/app/src/main/res/values-ru-rRU/strings.xml +++ b/controller/app/src/main/res/values-ru-rRU/strings.xml @@ -1498,4 +1498,9 @@ Недоступно элементов: %1$d Неполных курсов: %1$d. На сервере нет некоторых файлов. Курсы могут быть очень большими, и их загрузка может занять много времени, особенно при медленном соединении. Загрузка начинается сейчас, продолжается в фоне и возобновляется, если прервётся. + Проверка обновлений... + осталось %1$d min %2$d s + осталось %1$d s + Дополнения уже обновлены + Ресурсы сборки уже обновлены diff --git a/controller/app/src/main/res/values-sk/strings.xml b/controller/app/src/main/res/values-sk/strings.xml index abdaf820f..3f1361fb8 100644 --- a/controller/app/src/main/res/values-sk/strings.xml +++ b/controller/app/src/main/res/values-sk/strings.xml @@ -1429,4 +1429,9 @@ Nedostupné položky: %1$d Neúplné kurzy: %1$d. Server nemá niektoré súbory. Kurzy môžu byť veľmi veľké a ich sťahovanie môže trvať dlho, najmä pri pomalom pripojení. Sťahovanie sa začne hneď, pokračuje na pozadí a po prerušení sa obnoví. + Vyhľadávajú sa aktualizácie... + zostáva %1$d min %2$d s + zostáva %1$d s + Doplnky už aktuálne + Zdroje zostavenia už aktuálne diff --git a/controller/app/src/main/res/values-sr/strings.xml b/controller/app/src/main/res/values-sr/strings.xml index a606eb0fa..7f1b66a43 100644 --- a/controller/app/src/main/res/values-sr/strings.xml +++ b/controller/app/src/main/res/values-sr/strings.xml @@ -1435,4 +1435,9 @@ Недоступних ставки: %1$d Непотпуних курсева: %1$d. Сервер нема неке датотеке. Курсеви могу бити веома велики и њихово преузимање може дуго трајати, нарочито на спорој вези. Преузимање почиње сада, наставља се у позадини и наставља се ако се прекине. + Провера ажурирања... + преостало %1$d min %2$d s + преостало %1$d s + Додаци већ ажурирани + Ресурси за изградњу већ ажурирани diff --git a/controller/app/src/main/res/values-sw/strings.xml b/controller/app/src/main/res/values-sw/strings.xml index baacd0062..0c7c2763f 100644 --- a/controller/app/src/main/res/values-sw/strings.xml +++ b/controller/app/src/main/res/values-sw/strings.xml @@ -1442,4 +1442,9 @@ Vipengele %1$d havipatikani Kozi %1$d zimefika bila kukamilika: seva haina baadhi ya faili. Kozi zinaweza kuwa kubwa sana na kuchukua muda mrefu kupakua, hasa kwenye muunganisho wa polepole. Upakuaji unaanza sasa, unaendelea chinichini, na unaendelea ukikatizwa. + Inakagua masasisho... + %1$d min %2$d s zimebaki + %1$d s zimebaki + Viongezi tayari vimesasishwa + Rasilimali za ujenzi tayari zimesasishwa diff --git a/controller/app/src/main/res/values-ta/strings.xml b/controller/app/src/main/res/values-ta/strings.xml index 6ddb0ce69..24aab5922 100644 --- a/controller/app/src/main/res/values-ta/strings.xml +++ b/controller/app/src/main/res/values-ta/strings.xml @@ -1442,4 +1442,9 @@ %1$d உருப்படிகள் கிடைக்கவில்லை %1$d பாடநெறிகள் முழுமையில்லாமல் வந்தன: சேவையகத்தில் சில கோப்புகள் இல்லை. பாடநெறிகள் மிகப் பெரியதாக இருக்கலாம், குறிப்பாக மெதுவான இணைப்பில் பதிவிறக்க நீண்ட நேரம் ஆகலாம். பதிவிறக்கம் இப்போதே தொடங்கி, பின்னணியில் தொடர்ந்து, தடைப்பட்டால் மீண்டும் தொடரும். + புதுப்பிப்புகளைச் சரிபார்க்கிறது... + %1$d min %2$d s மீதம் + %1$d s மீதம் + ஆட்-ஆன்கள் ஏற்கனவே புதுப்பிக்கப்பட்டுள்ளன + பில்ட் வளங்கள் ஏற்கனவே புதுப்பிக்கப்பட்டுள்ளன diff --git a/controller/app/src/main/res/values-tr/strings.xml b/controller/app/src/main/res/values-tr/strings.xml index a7679355e..35ab1fc6d 100644 --- a/controller/app/src/main/res/values-tr/strings.xml +++ b/controller/app/src/main/res/values-tr/strings.xml @@ -1422,4 +1422,9 @@ %1$d öğe kullanılamıyor %1$d kurs eksik geldi: sunucuda bazı dosyalar yok. Kurslar çok büyük olabilir ve özellikle yavaş bir bağlantıda indirilmesi uzun sürebilir. İndirme şimdi başlar, arka planda devam eder ve kesilirse kaldığı yerden sürer. + Güncellemeler denetleniyor... + %1$d min %2$d s kaldı + %1$d s kaldı + Eklentiler zaten güncel + Derleme kaynakları zaten güncel diff --git a/controller/app/src/main/res/values-uk/strings.xml b/controller/app/src/main/res/values-uk/strings.xml index b31b27d15..2ad037cb1 100644 --- a/controller/app/src/main/res/values-uk/strings.xml +++ b/controller/app/src/main/res/values-uk/strings.xml @@ -1422,4 +1422,9 @@ Недоступно елементів: %1$d Неповних курсів: %1$d. На сервері немає деяких файлів. Курси можуть бути дуже великими, і їх завантаження може тривати довго, особливо на повільному з\'єднанні. Завантаження починається зараз, триває у фоні й відновлюється, якщо перерветься. + Перевірка оновлень... + залишилось %1$d min %2$d s + залишилось %1$d s + Додатки вже актуальні + Ресурси збирання вже актуальні diff --git a/controller/app/src/main/res/values-vi/strings.xml b/controller/app/src/main/res/values-vi/strings.xml index 714e6198a..3ac180055 100644 --- a/controller/app/src/main/res/values-vi/strings.xml +++ b/controller/app/src/main/res/values-vi/strings.xml @@ -1422,4 +1422,9 @@ %1$d mục không khả dụng %1$d khóa học bị thiếu: máy chủ không có một số tệp. Khóa học có thể rất lớn và mất nhiều thời gian để tải xuống, nhất là với kết nối chậm. Việc tải xuống bắt đầu ngay, tiếp tục chạy nền và tiếp tục lại nếu bị gián đoạn. + Đang kiểm tra bản cập nhật... + còn %1$d min %2$d s + còn %1$d s + Tiện ích bổ sung đã là mới nhất + Tài nguyên build đã là mới nhất diff --git a/controller/app/src/main/res/values-yo/strings.xml b/controller/app/src/main/res/values-yo/strings.xml index 460098075..079cf6bdf 100644 --- a/controller/app/src/main/res/values-yo/strings.xml +++ b/controller/app/src/main/res/values-yo/strings.xml @@ -1442,4 +1442,9 @@ Nkan %1$d kò sí Ẹ̀kọ́ %1$d dé láìpé: olupin kò ní àwọn fáìlì kan. Àwọn ẹ̀kọ́ lè tóbi gan-an kí wọ́n sì gba àkókò pípẹ́ láti gbàsílẹ̀, pàápàá lórí ìsopọ̀ tó lọ́ra. Ìgbàsílẹ̀ bẹ̀rẹ̀ báyìí, ó ń bá a lọ ní abẹ́lẹ̀, ó sì máa tẹ̀síwájú tí ó bá dáwọ́ dúró. + Ń wá àwọn ìmúdójúìwọ̀n... + %1$d min %2$d s tó kù + %1$d s tó kù + Àwọn afikún ti jẹ́ tuntun tẹ́lẹ̀ + Àwọn ohun èlò ìkọ́ ti jẹ́ tuntun tẹ́lẹ̀ diff --git a/controller/app/src/main/res/values-zh-rCN/strings.xml b/controller/app/src/main/res/values-zh-rCN/strings.xml index b8f58cdac..0c4aefc73 100644 --- a/controller/app/src/main/res/values-zh-rCN/strings.xml +++ b/controller/app/src/main/res/values-zh-rCN/strings.xml @@ -1423,4 +1423,9 @@ %1$d 项不可用 %1$d 门课程不完整:服务器缺少部分文件。 课程可能非常大,下载可能需要很长时间,尤其是在网络较慢时。下载现在开始,会在后台继续,中断后会自动恢复。 + 正在检查更新... + 剩余 %1$d 分 %2$d 秒 + 剩余 %1$d 秒 + 附加组件已是最新 + 构建资源已是最新 diff --git a/controller/app/src/main/res/values/strings.xml b/controller/app/src/main/res/values/strings.xml index e7cb9ee30..e0d0a69aa 100644 --- a/controller/app/src/main/res/values/strings.xml +++ b/controller/app/src/main/res/values/strings.xml @@ -1616,4 +1616,9 @@ %1$d items not available %1$d course(s) arrived incomplete: the server does not have some files. Courses can be very large and take a long time to download, especially on a slow connection. The download starts now, keeps going in the background, and resumes if interrupted. + Checking for updates... + %1$d min %2$d s left + %1$d s left + Add-ons already up to date + Build assets already up to date diff --git a/controller/app/src/main/res/values/strings_untranslated.xml b/controller/app/src/main/res/values/strings_untranslated.xml index acde9a9d1..75d7b9e57 100644 --- a/controller/app/src/main/res/values/strings_untranslated.xml +++ b/controller/app/src/main/res/values/strings_untranslated.xml @@ -1,6 +1,6 @@ - + + diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md index f29fde428..54ce3feef 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.4.4** - Overall progress + total ETA for the content download jobs (K2GO-503). `downloadWithAria2` now aggregates progress across the WHOLE job through aria2's RPC (piece-accurate `completedLength` summed over tellActive/Waiting/Stopped) instead of reporting the last file's percent, so a multi-file download (code-addons / code-assets) shows one monotonic bar. `GET /:type/jobs/:id` gains an `eta` field (whole-job seconds remaining, -1 unknown) alongside `percent`/`speed`. The code-addons runner passes its staged-catalog total as the denominator so the bar and ETA are accurate from the first tick; code-assets uses aria2's learned totals. aria2 is started with `--enable-rpc` on an ephemeral localhost port and shut down on queue drain (it does not exit on its own under RPC); the console readout stays as the fallback when RPC is unreachable, and pause/cancel still kill the process directly. Localhost-only. (K2GO-503) - **1.4.3** - The offline Kolibri subtree reports each topic's size as its DISTINCT files (`subtree_bytes`), measured over the whole range. A file used by several topics counted once per topic before, which inflated folders 1.2x-1.7x; a truncated subtree now also has exact folder sizes. Same rule as the catalog generator. (K2GO-476) - **1.4.2** - A Kolibri job waits for Kolibri to come up (up to 10 min) instead of failing at once when Kolibri is unreachable. After a box restart the engine relaunches the job while Kolibri is still starting, so the job, and the app that re-attaches to it, no longer fail and lose the order. A Kolibri that answers 5xx while starting now counts as not reachable yet, not as a protocol error. (K2GO-475) - **1.4.1** - Kolibri imports are verified, not trusted (K2GO-475). A missing file on Studio no longer aborts the import (`fail_on_error` off). After Kolibri reports COMPLETED, the runner counts the selected resources that Kolibri marks available in its db; none available is an error, some is a success with the counts in the new job field `result` (`{outcome: complete|partial, requested, available, notFound}`, also cleared on retry/resume). Only the engine writes the terminal phase. A restart adopts the import Kolibri is still running instead of queueing a second one. Pause now stops the Kolibri task, and resume queues it again (Kolibri skips the files it has). Any exit of the poll cancels and clears the Kolibri task. Thumbnails of every topic are no longer forced on a partial pick; the caller asks for them. (K2GO-475) diff --git a/static/dashboard/package.json b/static/dashboard/package.json index a8100c1fe..1f295903a 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -1,6 +1,6 @@ { "name": "dashboard-console", - "version": "1.4.3", + "version": "1.4.4", "description": "", "main": "index.js", "scripts": { diff --git a/static/dashboard/routes.ts b/static/dashboard/routes.ts index 8392c7797..e80227f21 100644 --- a/static/dashboard/routes.ts +++ b/static/dashboard/routes.ts @@ -62,6 +62,7 @@ function toApi(job: Job) { phase: job.phase, percent: job.percent, speed: job.speed, + eta: job.eta, detail: job.detail, error: job.error, result: parseResult(job.result), diff --git a/static/dashboard/sockets/aria2-download.ts b/static/dashboard/sockets/aria2-download.ts index 6981d742c..38bd0a1f5 100644 --- a/static/dashboard/sockets/aria2-download.ts +++ b/static/dashboard/sockets/aria2-download.ts @@ -11,6 +11,9 @@ // downloader). If you change a flag here, change that too (nothing enforces it). import { RunnerContext, CanceledError, PausedError, classifyStop, JobPhase } from './jobs'; import { withRetry } from './net-retry'; +import http from 'http'; +import net from 'net'; +import crypto from 'crypto'; /** The canonical aria2 flag set (minus -d, which the caller supplies per dest). */ export function aria2Args(destDir: string): string[] { @@ -62,57 +65,175 @@ export function parseRate(token: string): number { return Math.round(val * (mult[unit] ?? 1)); } +/** A single aria2 JSON-RPC call over localhost. Lengths and speeds come back as decimal strings. */ +function aria2Rpc(port: number, secret: string, method: string, params: unknown[] = []): Promise { + return new Promise((resolve, reject) => { + const payload = JSON.stringify({ jsonrpc: '2.0', id: 'k2go', method, params: [`token:${secret}`, ...params] }); + const req = http.request( + { host: '127.0.0.1', port, path: '/jsonrpc', method: 'POST', + headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } }, + (res) => { + let body = ''; + res.on('data', (c) => { body += c; }); + res.on('end', () => { + try { + const j = JSON.parse(body) as { result?: unknown; error?: { message?: string } }; + if (j.error) reject(new Error(j.error.message || 'aria2 rpc error')); + else resolve(j.result); + } catch (e) { reject(e); } + }); + }); + req.on('error', reject); + req.setTimeout(3000, () => req.destroy(new Error('aria2 rpc timeout'))); + req.write(payload); + req.end(); + }); +} + +/** An ephemeral free localhost port for the aria2 RPC listener. */ +function freePort(): Promise { + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.once('error', reject); + srv.listen(0, '127.0.0.1', () => { + const addr = srv.address(); + const port = typeof addr === 'object' && addr ? addr.port : 0; + srv.close(() => (port ? resolve(port) : reject(new Error('no free port')))); + }); + }); +} + +interface Aria2Status { completedLength?: string; totalLength?: string; } + /** - * Download urls into destDir with aria2c, reporting percent + speed on the job and surviving a - * Wi-Fi drop (the outer loop re-runs aria2, which resumes via --continue). Resolves on success. - * Throws PausedError (partial kept) / CanceledError (caller cleans) / Error (real failure). + * Download urls into destDir with aria2c, reporting OVERALL percent + aggregate speed + total ETA on + * the job and surviving a Wi-Fi drop (the outer loop re-runs aria2, which resumes via --continue). + * Resolves on success. Throws PausedError (partial kept) / CanceledError (caller cleans) / Error. * - * The caller owns the phase label and any verify/finalize: this does the resilient transfer only. + * K2GO-503: progress is aggregated across ALL files through aria2's RPC (piece-accurate + * completedLength), so a multi-file download shows one bar that climbs 0 -> 100 instead of the last + * file's percent. The denominator is the caller's totalBytesHint (accurate from the first tick, + * e.g. the add-ons catalog) raised by what aria2 has learned, and the bar never steps backward. If + * the RPC is unreachable (an aria2 built without it) the console readout is the fallback. The caller + * owns the phase label and any verify/finalize: this does the transfer only. */ export async function downloadWithAria2( ctx: RunnerContext, - opts: { destDir: string; urls?: string[]; inputFile?: string; phase?: JobPhase }, + opts: { destDir: string; urls?: string[]; inputFile?: string; phase?: JobPhase; totalBytesHint?: number }, ): Promise { const phase = opts.phase ?? 'downloading'; // -i inputFile carries a per-URL `out=` so a serve-relative subdir is preserved (code_assets); // urls is the flat form (kiwix/maps, one dir). The out= paths are relative to -d destDir. const transferArgs = opts.inputFile ? ['-i', opts.inputFile] : (opts.urls ?? []); - await withRetry(() => new Promise((resolve, reject) => { - const dl = ctx.spawn('/usr/bin/aria2c', [...aria2Args(opts.destDir), ...transferArgs]); - const onData = (buf: Buffer) => { - const text = buf.toString(); - // A single chunk can carry several summary lines; take the LAST %/rate. - const re = /\((\d+)%\).*?DL:([^\s]+)/g; - let m: RegExpExecArray | null; - let lastPct = -1; - let lastRate = ''; - while ((m = re.exec(text)) !== null) { lastPct = parseInt(m[1], 10); lastRate = m[2]; } - if (lastPct >= 0) { - ctx.reportRetry(0, 0); - ctx.update({ phase, percent: lastPct, speed: parseRate(lastRate) }); + + const hint = typeof opts.totalBytesHint === 'number' && opts.totalBytesHint > 0 ? opts.totalBytesHint : 0; + const rpcSecret = crypto.randomBytes(9).toString('hex'); + let rpcPort = 0, rpcOk = false, lastPct = -1, polling = false; + let sawDownloads = false, drainedTicks = 0, shuttingDown = false; + let sawSpeed = false, stalledTicks = 0; + const rpcArgs: string[] = []; + try { + rpcPort = await freePort(); + rpcArgs.push('--enable-rpc=true', '--rpc-listen-all=false', `--rpc-listen-port=${rpcPort}`, `--rpc-secret=${rpcSecret}`); + } catch { rpcPort = 0; } + + const pollOnce = async (): Promise => { + if (polling || rpcPort === 0) return; + polling = true; + try { + const [gs, active, waiting, stopped] = await Promise.all([ + aria2Rpc(rpcPort, rpcSecret, 'aria2.getGlobalStat'), + aria2Rpc(rpcPort, rpcSecret, 'aria2.tellActive', [['completedLength', 'totalLength']]), + aria2Rpc(rpcPort, rpcSecret, 'aria2.tellWaiting', [0, 5000, ['completedLength', 'totalLength']]), + aria2Rpc(rpcPort, rpcSecret, 'aria2.tellStopped', [0, 5000, ['completedLength', 'totalLength']]), + ]); + rpcOk = true; + const g = gs as { downloadSpeed?: string; numActive?: string; numWaiting?: string }; + // aria2 with --enable-rpc does NOT exit on its own when the command-line queue drains; it + // waits for RPC. Shut it down once the queue is empty (two ticks, so a transient zero mid + // batch never stops a live download) so the process exits and this step resolves; a file + // still missing then fails in the caller's finalize, exactly as a plain aria2 exit would. + const na = Number(g.numActive || 0), nw = Number(g.numWaiting || 0); + if (na + nw > 0) sawDownloads = true; + if (sawDownloads && na === 0 && nw === 0) { + if (++drainedTicks >= 2 && !shuttingDown) { + shuttingDown = true; + aria2Rpc(rpcPort, rpcSecret, 'aria2.shutdown').catch(() => { /* exiting */ }); + } + } else { + drainedTicks = 0; + } + const rows = [...(active as Aria2Status[]), ...(waiting as Aria2Status[]), ...(stopped as Aria2Status[])]; + let completed = 0, seenTotal = 0; + for (const r of rows) { + completed += Number(r.completedLength || 0); + seenTotal += Number(r.totalLength || 0); + } + const total = Math.max(hint, seenTotal); + const speed = Number(g.downloadSpeed || 0); + // Keep the reconnect indicator the withRetry loop used to show: aria2 now rides a blip out + // internally (it does not exit), so surface "reconnecting" when the transfer is active but + // stalled (no bytes) for a few seconds, and clear it the moment bytes flow again. + if (speed > 0) { sawSpeed = true; stalledTicks = 0; } + else if (sawSpeed && na > 0 && !shuttingDown) { stalledTicks++; } + const reconnecting = stalledTicks >= 3; + ctx.reportRetry(reconnecting ? 1 : 0, reconnecting ? 1 : 0); + if (total > 0) { + let pct = Math.min(100, Math.round((completed / total) * 100)); + if (pct >= 100 && na + nw > 0) pct = 99; // never 100% while files remain (no-hint early total) + if (pct < lastPct) pct = lastPct; // monotonic: a late file's size must not drop the bar + lastPct = pct; + const eta = speed > 0 ? Math.round((total - completed) / speed) : -1; + ctx.update({ phase, percent: pct, speed, eta }); + } else { + ctx.update({ phase, speed }); } - }; - dl.stdout?.on('data', onData); - dl.stderr?.on('data', onData); - dl.on('error', reject); - dl.on('exit', (code, signal) => { - if (signal === 'SIGKILL' || ctx.isCanceled()) return reject(new CanceledError()); - if (code === 0) return resolve(); - const err = new Error(`aria2 exited with code ${code}`); - (err as { code?: number }).code = code ?? -1; - reject(err); + } catch { /* aria2 not up yet or already gone: try the next tick */ } + finally { polling = false; } + }; + const pollTimer = rpcPort !== 0 ? setInterval(() => { void pollOnce(); }, 1000) : null; + + try { + await withRetry(() => new Promise((resolve, reject) => { + // Reset the per-run drain/stall flags: withRetry may re-run aria2, and a stale shuttingDown + // would leave the new instance running for RPC forever (it never exits on its own). lastPct + // stays (the re-run continues via --continue, so the bar must not drop). + sawDownloads = false; drainedTicks = 0; shuttingDown = false; sawSpeed = false; stalledTicks = 0; + const dl = ctx.spawn('/usr/bin/aria2c', [...aria2Args(opts.destDir), ...rpcArgs, ...transferArgs]); + const onData = (buf: Buffer) => { + if (rpcOk) return; // once the RPC answers it drives the bar; the console is the fallback + const text = buf.toString(); + // A single chunk can carry several summary lines; take the LAST %/rate. + const re = /\((\d+)%\).*?DL:([^\s]+)/g; + let m: RegExpExecArray | null; + let p = -1, rate = ''; + while ((m = re.exec(text)) !== null) { p = parseInt(m[1], 10); rate = m[2]; } + if (p >= 0) { ctx.reportRetry(0, 0); ctx.update({ phase, percent: p, speed: parseRate(rate) }); } + }; + dl.stdout?.on('data', onData); + dl.stderr?.on('data', onData); + dl.on('error', reject); + dl.on('exit', (code, signal) => { + if (signal === 'SIGKILL' || ctx.isCanceled()) return reject(new CanceledError()); + if (code === 0) return resolve(); + const err = new Error(`aria2 exited with code ${code}`); + (err as { code?: number }).code = code ?? -1; + reject(err); + }); + }), { + delaysMs: RETRY_DELAYS, + tries: RETRY_DELAYS.length + 1, + signal: ctx.signal, + isCanceled: ctx.isCanceled, + isTransient: (e) => ARIA2_TRANSIENT_EXITS.has((e as { code?: number }).code ?? -1), + onRetry: ({ attempt, err }: { attempt: number; err: unknown }) => { + ctx.reportRetry(attempt, RETRY_DELAYS.length); + ctx.log(`[aria2] reconnect ${attempt}/${RETRY_DELAYS.length} after: ${err instanceof Error ? err.message : String(err)}`); + }, }); - }), { - delaysMs: RETRY_DELAYS, - tries: RETRY_DELAYS.length + 1, - signal: ctx.signal, - isCanceled: ctx.isCanceled, - isTransient: (e) => ARIA2_TRANSIENT_EXITS.has((e as { code?: number }).code ?? -1), - onRetry: ({ attempt, err }: { attempt: number; err: unknown }) => { - ctx.reportRetry(attempt, RETRY_DELAYS.length); - ctx.log(`[aria2] reconnect ${attempt}/${RETRY_DELAYS.length} after: ${err instanceof Error ? err.message : String(err)}`); - }, - }); + } finally { + if (pollTimer) clearInterval(pollTimer); + } } /** Map a stop (pause vs cancel) to the error a runner should throw; returns null for a real error. */ diff --git a/static/dashboard/sockets/code_addons.exec.ts b/static/dashboard/sockets/code_addons.exec.ts index df9b83d6d..66717a043 100644 --- a/static/dashboard/sockets/code_addons.exec.ts +++ b/static/dashboard/sockets/code_addons.exec.ts @@ -58,6 +58,36 @@ function runMirror(ctx: RunnerContext, mirror: string, args: string[], capture: }); } +// K2GO-503: the staged catalog carries every file size; sum the bytes this run will actually +// download (match the catalog by basename to the aria2 input's out= entries) so the shared helper +// shows an overall percent and a total ETA from the first tick. Best-effort: 0 just disables the +// hint (the helper still aggregates from aria2's own learned totals). +const CATALOG_REL = 'v1/catalog.json'; +function addonsDownloadBytes(stageDir: string, body: string): number { + let sizeByName: Map; + try { + const cat = JSON.parse(fs.readFileSync(`${stageDir}/${CATALOG_REL}`, 'utf8')) as { + addons?: Array>; + }; + sizeByName = new Map(); + for (const a of cat.addons || []) { + for (const k of ['download', 'sourceTarball']) { + const e = a[k]; + if (e && typeof e.url === 'string' && typeof e.size === 'number') { + const name = e.url.split('/').pop(); + if (name) sizeByName.set(name, e.size); + } + } + } + } catch { return 0; } + let total = 0; + for (const line of body.split('\n')) { + const m = /^\s*out=(.+?)\s*$/.exec(line); + if (m) total += sizeByName.get(m[1]) || 0; + } + return total; +} + const codeAddonsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { const MIRROR = mirrorPath(); if (!fs.existsSync(MIRROR)) throw new Error(`mirror script not found: ${MIRROR}`); @@ -66,7 +96,7 @@ const codeAddonsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { // The mirror stages the small files into STAGE from the published site + the live tree and prints a // status marker plus an aria2 input-file for the heavy binaries. STAGE is NOT pre-cleared, so a // resume keeps its partials; the plan is deterministic and safe to re-run. - ctx.update({ phase: 'downloading', percent: -1, speed: 0, detail: 'add-ons' }); + ctx.update({ phase: 'downloading', percent: -1, speed: 0, eta: -1, detail: 'add-ons' }); let planned: string; try { planned = await runMirror(ctx, MIRROR, @@ -86,7 +116,7 @@ const codeAddonsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { if (marker === '#status=uptodate') { // Same published build: keep the live tree, nothing to download or swap. rmrf(STAGE); - ctx.update({ phase: 'done', percent: 100, speed: 0, detail: 'up to date' }); + ctx.update({ phase: 'done', percent: 100, speed: 0, eta: -1, detail: 'up to date' }); return; } @@ -98,7 +128,7 @@ const codeAddonsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { fs.mkdirSync(STAGE, { recursive: true }); fs.writeFileSync(inputFile, body + '\n'); try { - await downloadWithAria2(ctx, { destDir: STAGE, inputFile, phase: 'downloading' }); + await downloadWithAria2(ctx, { destDir: STAGE, inputFile, phase: 'downloading', totalBytesHint: addonsDownloadBytes(STAGE, body) }); } catch (e) { const se = stopError(ctx); if (se instanceof PausedError) throw se; // keep STAGE: resume continues @@ -110,7 +140,7 @@ const codeAddonsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { ctx.throwIfCanceled(); // --- Verify (aria2 checked each binary by sha-256; no re-hash) ---------- - ctx.update({ phase: 'processing', percent: -1, speed: 0, detail: 'finishing' }); + ctx.update({ phase: 'processing', percent: -1, speed: 0, eta: -1, detail: 'finishing' }); try { await runMirror(ctx, MIRROR, ['--finalize-only', '--out', STAGE, '--serve-base', SERVE_BASE], false); } catch (e) { @@ -121,7 +151,7 @@ const codeAddonsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { ctx.throwIfCanceled(); // --- Swap (atomic rename; restore the previous tree if the move fails) -- - ctx.update({ phase: 'processing', percent: 100, speed: 0, detail: 'installing' }); + ctx.update({ phase: 'processing', percent: 100, speed: 0, eta: -1, detail: 'installing' }); cleanAria2Files(STAGE); rmrf(OLD); if (fs.existsSync(SERVE)) fs.renameSync(SERVE, OLD); @@ -136,7 +166,7 @@ const codeAddonsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { } rmrf(OLD); - ctx.update({ phase: 'done', percent: 100, speed: 0 }); + ctx.update({ phase: 'done', percent: 100, speed: 0, eta: -1 }); }; jobs.registerRunner('code-addons', codeAddonsRunner); diff --git a/static/dashboard/sockets/code_assets.exec.ts b/static/dashboard/sockets/code_assets.exec.ts index 0ff37051d..9a0005811 100644 --- a/static/dashboard/sockets/code_assets.exec.ts +++ b/static/dashboard/sockets/code_assets.exec.ts @@ -62,7 +62,7 @@ const codeAssetsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { // The mirror stages the UNCHANGED files into STAGE from the live tree and prints an aria2 // input-file for only the changed files (empty = nothing changed). STAGE is NOT pre-cleared, so // a resume keeps its partials; the plan is deterministic and safe to re-run. - ctx.update({ phase: 'downloading', percent: -1, speed: 0, detail: 'build assets' }); + ctx.update({ phase: 'downloading', percent: -1, speed: 0, eta: -1, detail: 'build assets' }); let input: string; try { input = await runMirror(ctx, MIRROR, ['--print-aria2-input', '--reuse-from', SERVE, '--out', STAGE], true); @@ -77,7 +77,7 @@ const codeAssetsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { if (input.trim() === '') { // Every file unchanged: keep the live tree, nothing to download or swap. rmrf(STAGE); - ctx.update({ phase: 'done', percent: 100, speed: 0, detail: 'up to date' }); + ctx.update({ phase: 'done', percent: 100, speed: 0, eta: -1, detail: 'up to date' }); return; } @@ -96,7 +96,7 @@ const codeAssetsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { ctx.throwIfCanceled(); // --- Build the page (aria2 verified each file by checksum; no re-hash) -- - ctx.update({ phase: 'processing', percent: -1, speed: 0, detail: 'finishing' }); + ctx.update({ phase: 'processing', percent: -1, speed: 0, eta: -1, detail: 'finishing' }); try { await runMirror(ctx, MIRROR, ['--finalize-only', '--out', STAGE], false); } catch (e) { @@ -107,7 +107,7 @@ const codeAssetsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { ctx.throwIfCanceled(); // --- Swap (atomic rename; restore the previous tree if the move fails) -- - ctx.update({ phase: 'processing', percent: 100, speed: 0, detail: 'installing' }); + ctx.update({ phase: 'processing', percent: 100, speed: 0, eta: -1, detail: 'installing' }); try { fs.rmSync(inputFile, { force: true }); } catch { /* leave nothing non-served behind */ } cleanAria2Files(STAGE); rmrf(OLD); @@ -123,7 +123,7 @@ const codeAssetsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { } rmrf(OLD); - ctx.update({ phase: 'done', percent: 100, speed: 0 }); + ctx.update({ phase: 'done', percent: 100, speed: 0, eta: -1 }); }; jobs.registerRunner('code-assets', codeAssetsRunner); diff --git a/static/dashboard/sockets/jobs.ts b/static/dashboard/sockets/jobs.ts index 8b81cbc9e..9e0ca2eb9 100644 --- a/static/dashboard/sockets/jobs.ts +++ b/static/dashboard/sockets/jobs.ts @@ -29,6 +29,8 @@ export interface Job { phase: JobPhase; percent: number; speed: number; + // K2GO-503: whole-job seconds remaining, or -1 when unknown (indeterminate, idle, or no total). + eta: number; detail: string | null; // free-form current item / message error: string | null; /** K2GO-475: JSON outcome a runner records on success (e.g. a partial import's counts). */ @@ -41,6 +43,7 @@ export interface JobUpdate { phase?: JobPhase; percent?: number; speed?: number; + eta?: number; detail?: string | null; error?: string | null; result?: string | null; @@ -121,6 +124,7 @@ class JobManager { phase TEXT NOT NULL, percent INTEGER NOT NULL DEFAULT -1, speed INTEGER NOT NULL DEFAULT 0, + eta INTEGER NOT NULL DEFAULT -1, detail TEXT, error TEXT, created INTEGER NOT NULL, @@ -129,6 +133,8 @@ class JobManager { // K2GO-475: added after the first release; older databases get the column here. const cols = this.db.prepare(`PRAGMA table_info(jobs)`).all() as Array<{ name: string }>; if (!cols.some((c) => c.name === 'result')) this.db.exec(`ALTER TABLE jobs ADD COLUMN result TEXT`); + // K2GO-503: older databases predate the eta column. + if (!cols.some((c) => c.name === 'eta')) this.db.exec(`ALTER TABLE jobs ADD COLUMN eta INTEGER NOT NULL DEFAULT -1`); } registerRunner(type: JobType, runner: Runner): void { @@ -142,11 +148,11 @@ class JobManager { const id = `${type}-${now}-${Math.random().toString(36).slice(2, 8)}`; const job: Job = { id, type, target: JSON.stringify(items), phase: 'queued', - percent: -1, speed: 0, detail: null, error: null, result: null, created: now, updated: now, + percent: -1, speed: 0, eta: -1, detail: null, error: null, result: null, created: now, updated: now, }; this.db.prepare( - `INSERT INTO jobs (id,type,target,phase,percent,speed,detail,error,result,created,updated) - VALUES (@id,@type,@target,@phase,@percent,@speed,@detail,@error,@result,@created,@updated)` + `INSERT INTO jobs (id,type,target,phase,percent,speed,eta,detail,error,result,created,updated) + VALUES (@id,@type,@target,@phase,@percent,@speed,@eta,@detail,@error,@result,@created,@updated)` ).run(job); this.launch(job); return job; @@ -274,13 +280,14 @@ class JobManager { phase: patch.phase ?? cur.phase, percent: patch.percent ?? cur.percent, speed: patch.speed ?? cur.speed, + eta: patch.eta ?? cur.eta, detail: patch.detail !== undefined ? patch.detail : cur.detail, error: patch.error !== undefined ? patch.error : cur.error, result: patch.result !== undefined ? patch.result : cur.result, updated: Date.now(), }; this.db.prepare( - `UPDATE jobs SET phase=@phase,percent=@percent,speed=@speed,detail=@detail,error=@error,result=@result,updated=@updated WHERE id=@id` + `UPDATE jobs SET phase=@phase,percent=@percent,speed=@speed,eta=@eta,detail=@detail,error=@error,result=@result,updated=@updated WHERE id=@id` ).run(next); } @@ -318,7 +325,7 @@ class JobManager { .then(() => runner(ctx)) .then(() => { const cur = this.get(job.id); - if (cur && ACTIVE.includes(cur.phase)) this.patch(job.id, { phase: 'done', percent: 100 }); + if (cur && ACTIVE.includes(cur.phase)) this.patch(job.id, { phase: 'done', percent: 100, eta: -1 }); }) .catch((err: unknown) => { if (err instanceof PausedError || rt.paused) {