From 43879f26e2523191fbbd17772504467160b9eda6 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Mon, 23 Nov 2026 00:37:03 -0600 Subject: [PATCH 01/12] K2GO-593 feat(install): Forgejo task table for percent and time left The table has the role task names in run order, from a full run on the OnePlus 7T (forgejo 17.0.2). Names that contain the version or the architecture are not in it, because they change on each release. --- .../app/src/main/assets/runrole/forgejo.txt | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 controller/app/src/main/assets/runrole/forgejo.txt diff --git a/controller/app/src/main/assets/runrole/forgejo.txt b/controller/app/src/main/assets/runrole/forgejo.txt new file mode 100644 index 000000000..fa7d1e591 --- /dev/null +++ b/controller/app/src/main/assets/runrole/forgejo.txt @@ -0,0 +1,47 @@ +Assert that "forgejo_install is sameas true" (boolean not string etc) +Assert that "forgejo_enabled | type_debug == 'bool'" (boolean not string etc) +Install Forgejo if 'forgejo_installed' not defined, e.g. in /etc/iiab/iiab_state.yml +Assert forgejo_db_engine is a supported value ('sqlite' or 'mariadb') +Query Codeberg for the latest Forgejo release +Set forgejo_version from the latest release tag +Assert forgejo_version is a valid X.Y.Z release +Record (initial) disk space used +Stop existing Forgejo systemd service (if reinstalling, not proot) +Stop existing Forgejo via pdsm (if reinstalling, proot) +Ensure group 'forgejo' exists +Create user 'forgejo' +Create /library/forgejo directory structure +Make directories data, log, backups writable (0750) +Check whether Forgejo is already installed (app.ini present) +Detect the existing install's DB engine (engine-change guard) +Refuse an unsupported DB engine change on an existing install +Compute a backup timestamp (proot-safe, no fact dependency) +Back up Forgejo (forgejo dump) to /library/forgejo/backups before swapping the binary +Fail if we detect an unsupported CPU architecture +Verify the downloaded Forgejo binary against its GPG signature (fail closed) +Find installed Forgejo binaries in /library/forgejo/bin +mkdir /etc/forgejo (0770 root:forgejo) +Generate Forgejo secrets once (guarded by 'creates'), referenced by *_URI in app.ini +Secure the generated secret files (0640 root:forgejo) +Set 'mysql_install: True' and 'mysql_enabled: True' +MYSQL - run 'mysql' role +FAIL (STOP THE INSTALL) IF 'mysql_installed is undefined' +Create MySQL database for Forgejo: forgejo +Create MySQL username (forgejo) with password, for above database +Install /etc/forgejo/app.ini from template (0664 root:forgejo) +Install systemd unit /etc/systemd/system/forgejo.service (not proot) +Record (final) disk space used +Set 'forgejo_installed: True' +Add 'forgejo_installed: True' to /etc/iiab/iiab_state.yml +Enable/Disable Forgejo (systemd or pdsm) and NGINX +Enable & Restart 'forgejo' systemd service, if forgejo_enabled (not proot) +Disable & Stop 'forgejo' systemd service, if not forgejo_enabled (not proot) +Enable 'forgejo' via pdsm (proot) +Restart 'forgejo' via pdsm (proot) +Stop 'forgejo' via pdsm (proot) +Disable 'forgejo' via pdsm (proot) +Enable http://box/forgejo via NGINX, by installing /etc/nginx/conf.d/forgejo-nginx.conf from template +Disable http://box/forgejo via NGINX, by removing /etc/nginx/conf.d/forgejo-nginx.conf +Reload 'nginx' systemd service (not proot) +Restart 'nginx' via pdsm (proot) +Add 'forgejo' variable values to /etc/iiab/iiab.ini From d418535e05a889cad996277d1a1078a9d46413ad Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Mon, 23 Nov 2026 00:37:04 -0600 Subject: [PATCH 02/12] K2GO-593 feat(dashboard): forgejo-bin job downloads the Forgejo binary A new durable job type. The box resolves the latest release (the codeberg API, as the forgejo role) and downloads the binary with the canonical aria2 flags and the withRetry loop to /library/forgejo/bin/forgejo-. aria2 writes forgejo-.part, and the runner renames it at the end, so the final name exists only for a complete file. Pause keeps the partial, Cancel removes it. The job result gives the version, so the app can pin forgejo_version and the role skips its own download. dash-node 1.6.5. --- static/dashboard/CHANGELOG.md | 1 + static/dashboard/package.json | 4 +- static/dashboard/routes.ts | 5 +- static/dashboard/server.ts | 1 + static/dashboard/sockets/forgejo-bin.exec.ts | 154 +++++++++++++++ static/dashboard/sockets/forgejo-bin.test.ts | 193 +++++++++++++++++++ static/dashboard/sockets/jobs.ts | 2 +- 7 files changed, 355 insertions(+), 5 deletions(-) create mode 100644 static/dashboard/sockets/forgejo-bin.exec.ts create mode 100644 static/dashboard/sockets/forgejo-bin.test.ts diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md index 8ee40e52d..d3204b1c2 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.6.5** - New job type `forgejo-bin` (`POST /forgejo-bin/download` with `{"ids":["forgejo"]}`): downloads the Forgejo binary of the latest release (the codeberg API, as the forgejo role) with aria2 to `/library/forgejo/bin/forgejo-`, with percent, speed, time left, pause, resume, "Reconnecting n/5", and a cancel that removes the partial. The job `result` gives `{"version"}`, so the app pins `forgejo_version` and the role skips its own download. (K2GO-593) - **1.6.4** - Admin passwords change inside Kolibri, Calibre-Web and Forgejo, not only in the stored copy: `POST /credentials/:service/password` (one rule for all three: 8+ characters with upper case, lower case, digit and symbol), `POST /credentials/:service/reset` (the factory password, also when the current one is lost), and `GET /credentials/:service/status` (`ok`, `mismatch` or `unreachable`, plus whether the factory password still signs in; a live sign-in, never stored). (K2GO-552) - **1.6.3** - The `/v1` relay to conex-core forwards the `X-Share-Token` header (never logged). Before, it was dropped, so the sender's close (`DELETE /v1/share/`) got 401 and the share token stayed valid after Done. (K2GO-577) - **1.6.2** - Box logs no longer identify the user, on boxes installed before bake patches 0010-0012 (K2GO-559). At its first start, dash-node applies the same change once: nginx access log without client IP and User-Agent (`/etc/nginx/nginx.conf`), Forgejo router log off (`LOGGER_ROUTER_MODE` empty in `app.ini`), Calibre-Web log level DEBUG -> INFO (`app.db`). A value an admin changed is kept. Each change applies at the service restart (Forgejo: at the next app open, as a pending privacy change; nginx and Calibre-Web: at the next box start). After that restart, the older logs of each changed service are removed once (rotated copies deleted, live log emptied). Markers: `/library/dashboard/log-less.done`, `/library/dashboard/log-less-purge.done`. No REST change. (K2GO-559) diff --git a/static/dashboard/package.json b/static/dashboard/package.json index fdb909307..1135b8e14 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -1,11 +1,11 @@ { "name": "dashboard-console", - "version": "1.6.4", + "version": "1.6.5", "description": "", "main": "index.js", "scripts": { "test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts sockets/credentials.test.ts sockets/passwords.test.ts sockets/net-retry.test.ts sockets/services.test.ts sockets/log-rotate.test.ts sockets/rebuild-status.test.ts sockets/conex-proxy.test.ts sockets/maps.fqr-behavior.test.ts sockets/privacy.test.ts sockets/log-less.test.ts", - "test:db": "node --require ts-node/register --test sockets/jobs.test.ts", + "test:db": "node --require ts-node/register --test sockets/jobs.test.ts sockets/forgejo-bin.test.ts", "typecheck": "tsc --noEmit", "build": "tsc", "start": "node dist/server.js" diff --git a/static/dashboard/routes.ts b/static/dashboard/routes.ts index 222bd768f..6b9f67904 100644 --- a/static/dashboard/routes.ts +++ b/static/dashboard/routes.ts @@ -44,7 +44,7 @@ const ZIMS_DIR = '/library/zims/content/'; const KIWIX_INDEXER = '/usr/bin/iiab-make-kiwix-lib'; const ZIM_NAME_RE = /^[A-Za-z0-9._-]{1,150}\.zim$/; -const VALID_TYPES: JobType[] = ['kiwix', 'maps', 'books', 'kolibri', 'basemaps', 'code-assets', 'code-addons', 'forgejo']; +const VALID_TYPES: JobType[] = ['kiwix', 'maps', 'books', 'kolibri', 'basemaps', 'code-assets', 'code-addons', 'forgejo', 'forgejo-bin']; function isType(t: string): t is JobType { return (VALID_TYPES as string[]).includes(t); } @@ -1247,7 +1247,8 @@ apiRouter.post('/:type/download', (req: Request, res: Response): void => { // K2GO-443: these types must run one job at a time: code-assets / code-addons stage into ONE shared // tree (/library/www/.new), and forgejo fetches+pushes the same repo set (two concurrent runs // would race the staging / the repos). The app re-attaches via start-or-attach; this is the hard guard. - const SINGLE_RUN_TYPES = ['code-assets', 'code-addons', 'forgejo']; + // K2GO-593: forgejo-bin writes one partial file. + const SINGLE_RUN_TYPES = ['code-assets', 'code-addons', 'forgejo', 'forgejo-bin']; if (SINGLE_RUN_TYPES.includes(type) && jobs.list(type).some((j) => ['queued', 'downloading', 'indexing', 'processing', 'paused'].includes(j.phase))) { diff --git a/static/dashboard/server.ts b/static/dashboard/server.ts index 44cc79d96..8db626188 100644 --- a/static/dashboard/server.ts +++ b/static/dashboard/server.ts @@ -13,6 +13,7 @@ import './sockets/kolibri.exec'; import './sockets/code_assets.exec'; // K2GO-443: build-assets runner (aria2 job engine) import './sockets/code_addons.exec'; // K2GO-443: add-ons gallery runner (aria2 job engine) import './sockets/forgejo.exec'; // K2GO-443: forgejo repo-refresh runner (git, per-repo progress) +import './sockets/forgejo-bin.exec'; // K2GO-593: forgejo binary download before the module install import { apiRouter } from './routes'; import { startServiceHeal } from './sockets/service-heal'; import { startLogRotation, stopLogRotation } from './sockets/log-rotate'; diff --git a/static/dashboard/sockets/forgejo-bin.exec.ts b/static/dashboard/sockets/forgejo-bin.exec.ts new file mode 100644 index 000000000..8f3d14bb3 --- /dev/null +++ b/static/dashboard/sockets/forgejo-bin.exec.ts @@ -0,0 +1,154 @@ +// sockets/forgejo-bin.exec.ts - K2GO-593 +// +// Forgejo binary runner for the durable job engine. The forgejo role downloads a ~100 MB binary with +// Ansible get_url: no percent, no pause, no resume, and it runs after `pdsm stop`, which also stops +// dash-node. The app runs this job BEFORE the stop. It puts the binary at the path the role uses +// (/library/forgejo/bin/forgejo-), and the app pins forgejo_version= in local_vars, so the +// role's get_url finds the file and skips the download. The role still downloads the .asc and does +// its GPG check (fail closed) on this file. +// +// The box resolves the version (the same codeberg API as the role) and makes the URL; the app sends +// no URL. aria2 writes to forgejo-.part and the runner renames it at the end, so the final name +// exists only for a complete file (a partial at the final name would make get_url skip and the GPG +// check fail). +import { jobs, RunnerContext, PausedError, CanceledError } from './jobs'; +import { downloadWithAria2, stopError } from './aria2-download'; +import { withRetry } from './net-retry'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +/** forgejo_root_directory/bin in roles/forgejo/defaults/main.yml. */ +const BIN_DIR = process.env.K2GO_FORGEJO_BIN_DIR || '/library/forgejo/bin'; +/** forgejo_releases_api in the role. */ +const RELEASES_API = 'https://codeberg.org/api/v1/repos/forgejo/forgejo/releases/latest'; +const DOWNLOAD_BASE = 'https://codeberg.org/forgejo/forgejo/releases/download'; +// K2G-P5: a neutral agent, the same one books.exec.ts sends. +const USER_AGENT = 'K2Go Dashboard/1.0 (https://github.com/appdevforall/KnowledgeToGo)'; +const API_TIMEOUT_MS = 20_000; +const PART = '.part'; +const RETRY_DELAYS = [3_000, 6_000, 9_000, 18_000, 36_000]; + +/** The role's iset_suffixes map, keyed on `uname -m` (os.machine), the value the role reads. */ +const ISET_SUFFIXES: Record = { + x86_64: 'amd64', + aarch64: 'arm64', + armv7l: 'arm-6', + armv6l: 'arm-6', + armv8l: 'arm-6', +}; + +export function forgejoSuffix(machine: string): string | null { + return ISET_SUFFIXES[machine] ?? null; +} + +/** The role's assert: forgejo_version is X.Y.Z. Also keeps the value safe for a path and a URL. */ +export function isForgejoVersion(v: unknown): v is string { + return typeof v === 'string' && /^[0-9]+\.[0-9]+\.[0-9]+$/.test(v); +} + +/** forgejo_download_url in the role. */ +export function forgejoUrl(version: string, suffix: string): string { + return `${DOWNLOAD_BASE}/v${version}/forgejo-${version}-linux-${suffix}`; +} + +export function finalPath(dir: string, version: string): string { + return path.join(dir, `forgejo-${version}`); +} + +/** + * Remove the partial downloads (forgejo-.part and its .aria2 control file) in dir, except the + * ones of keepVersion. Never touches a complete forgejo- binary or its .asc. + */ +export function removePartials(dir: string, keepVersion: string | null = null): void { + let names: string[] = []; + try { names = fs.readdirSync(dir); } catch { return; } + for (const n of names) { + const m = /^forgejo-([0-9]+\.[0-9]+\.[0-9]+)\.part(\.aria2)?$/.exec(n); + if (!m || m[1] === keepVersion) continue; + try { fs.rmSync(path.join(dir, n), { force: true }); } catch { /* best effort */ } + } +} + +/** The tag of the latest Forgejo release, without the leading "v" (the role's regex_replace). */ +async function latestVersion(ctx: RunnerContext): Promise { + const ac = new AbortController(); + const onStop = () => ac.abort(); + ctx.signal.addEventListener('abort', onStop, { once: true }); + const timer = setTimeout(() => ac.abort(), API_TIMEOUT_MS); + try { + const res = await fetch(RELEASES_API, { + headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' }, + signal: ac.signal, + }); + if (!res.ok) throw new Error(`release lookup failed: HTTP ${res.status}`); + const body = await res.json() as { tag_name?: unknown }; + const version = typeof body.tag_name === 'string' ? body.tag_name.replace(/^v/, '') : ''; + if (!isForgejoVersion(version)) throw new Error(`release lookup gave a bad version: ${String(body.tag_name)}`); + return version; + } finally { + clearTimeout(timer); + ctx.signal.removeEventListener('abort', onStop); + } +} + +const forgejoBinRunner: (ctx: RunnerContext) => Promise = async (ctx) => { + const suffix = forgejoSuffix(os.machine()); + if (!suffix) throw new Error(`no Forgejo binary for CPU architecture ${os.machine()}`); + + ctx.update({ phase: 'downloading', percent: -1, speed: 0, eta: -1, detail: 'forgejo version' }); + let version: string; + try { + version = await withRetry(() => latestVersion(ctx), { + delaysMs: RETRY_DELAYS, + signal: ctx.signal, + isCanceled: ctx.isCanceled, + isTransient: (e) => !(e instanceof Error && /bad version/.test(e.message)), + onRetry: ({ attempt }) => ctx.reportRetry(attempt, RETRY_DELAYS.length), + }); + } catch (e) { + const se = stopError(ctx); + if (se) throw se; + throw e; + } + ctx.reportRetry(0, 0); + const result = JSON.stringify({ version }); + + fs.mkdirSync(BIN_DIR, { recursive: true }); + removePartials(BIN_DIR, version); // a partial of an older release cannot be resumed + const dest = finalPath(BIN_DIR, version); + if (fs.existsSync(dest)) { + ctx.log(`[forgejo-bin] ${path.basename(dest)} is already there`); + ctx.update({ phase: 'done', percent: 100, speed: 0, eta: -1, detail: version, result }); + return; + } + + const part = `forgejo-${version}${PART}`; + const inputFile = path.join(os.tmpdir(), `k2go-forgejo-bin-${process.pid}.aria2-input`); + fs.writeFileSync(inputFile, `${forgejoUrl(version, suffix)}\n out=${part}\n`); + ctx.update({ phase: 'downloading', percent: -1, speed: 0, eta: -1, detail: version }); + try { + await downloadWithAria2(ctx, { destDir: BIN_DIR, inputFile }); + } catch (e) { + const se = stopError(ctx); + if (se instanceof PausedError) throw se; // keep the partial: Resume continues it + if (se instanceof CanceledError) { removePartials(BIN_DIR); throw se; } + throw e; // keep the partial: Retry continues it + } finally { + try { fs.rmSync(inputFile, { force: true }); } catch { /* best effort */ } + } + + const partPath = path.join(BIN_DIR, part); + if (!fs.existsSync(partPath) || fs.existsSync(`${partPath}.aria2`)) { + throw new Error('the Forgejo download did not complete'); + } + fs.renameSync(partPath, dest); + fs.chmodSync(dest, 0o775); // the role's get_url mode + ctx.update({ phase: 'done', percent: 100, speed: 0, eta: -1, detail: version, result }); +}; + +jobs.registerRunner('forgejo-bin', forgejoBinRunner); +// A Cancel of a PAUSED job: its runner already exited and kept the partial for Resume. +jobs.registerDiscard('forgejo-bin', () => removePartials(BIN_DIR)); + +export { forgejoBinRunner }; diff --git a/static/dashboard/sockets/forgejo-bin.test.ts b/static/dashboard/sockets/forgejo-bin.test.ts new file mode 100644 index 000000000..f2a363506 --- /dev/null +++ b/static/dashboard/sockets/forgejo-bin.test.ts @@ -0,0 +1,193 @@ +/// +// K2GO-593: the forgejo-bin runner. Loads jobs.ts (sqlite), so it runs in `npm run test:db`. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { EventEmitter } from 'events'; + +const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'k2go-forgejo-bin-')); +const BIN = path.join(tmp, 'bin'); +process.env.K2GO_FORGEJO_BIN_DIR = BIN; +process.env.K2GO_JOBS_DB = path.join(tmp, 'jobs.db'); + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const mod = require('./forgejo-bin.exec') as typeof import('./forgejo-bin.exec'); +const { forgejoSuffix, isForgejoVersion, forgejoUrl, removePartials, forgejoBinRunner } = mod; +import type { RunnerContext, JobUpdate } from './jobs'; +import { CanceledError } from './jobs'; + +const SUFFIX = forgejoSuffix(os.machine()); + +function stubFetch(tag: unknown, seen: Array>): () => void { + const orig = globalThis.fetch; + globalThis.fetch = (async (_url: unknown, init?: { headers?: Record }) => { + seen.push(init?.headers ?? {}); + return new Response(JSON.stringify({ tag_name: tag }), { status: 200 }); + }) as typeof fetch; + return () => { globalThis.fetch = orig; }; +} + +/** A fake aria2: it writes the files it is told to, then exits as the test says. */ +function fakeCtx(onSpawn: (args: string[], child: EventEmitter & { stdout: EventEmitter; stderr: EventEmitter }) => void) { + const updates: JobUpdate[] = []; + const state = { canceled: false, paused: false, spawned: 0 }; + const ac = new AbortController(); + const ctx = { + job: { id: 'forgejo-bin-test' }, + items: ['forgejo'], + ids: ['forgejo'], + update: (p: JobUpdate) => { updates.push(p); }, + isCanceled: () => state.canceled, + throwIfCanceled: () => { if (state.canceled) throw new CanceledError(); }, + isPaused: () => state.paused, + signal: ac.signal, + spawn: (_cmd: string, args: string[]) => { + state.spawned++; + const child = Object.assign(new EventEmitter(), { stdout: new EventEmitter(), stderr: new EventEmitter() }); + setImmediate(() => onSpawn(args, child)); + return child; + }, + log: () => { /* quiet */ }, + reportRetry: () => { /* not checked here */ }, + } as unknown as RunnerContext; + return { ctx, updates, state, ac }; +} + +function reset(): void { + fs.rmSync(BIN, { recursive: true, force: true }); +} + +test('forgejoSuffix uses the role iset_suffixes map', () => { + assert.equal(forgejoSuffix('aarch64'), 'arm64'); + assert.equal(forgejoSuffix('armv7l'), 'arm-6'); + assert.equal(forgejoSuffix('armv8l'), 'arm-6'); // 32-bit userland on a 64-bit kernel + assert.equal(forgejoSuffix('x86_64'), 'amd64'); + assert.equal(forgejoSuffix('i686'), null); +}); + +test('isForgejoVersion accepts only X.Y.Z', () => { + assert.equal(isForgejoVersion('17.0.2'), true); + for (const bad of ['v17.0.2', '17.0', '17.0.2-rc1', '../1.2.3', '', null, 17]) { + assert.equal(isForgejoVersion(bad), false, String(bad)); + } +}); + +test('forgejoUrl is the role forgejo_download_url', () => { + assert.equal(forgejoUrl('17.0.2', 'arm64'), + 'https://codeberg.org/forgejo/forgejo/releases/download/v17.0.2/forgejo-17.0.2-linux-arm64'); +}); + +test('removePartials keeps binaries, .asc files and the partial of keepVersion', () => { + reset(); + fs.mkdirSync(BIN, { recursive: true }); + const names = ['forgejo-17.0.2', 'forgejo-17.0.2.asc', 'forgejo-17.0.1.part', 'forgejo-17.0.1.part.aria2', + 'forgejo-17.0.2.part', 'forgejo-17.0.2.part.aria2', 'other.part']; + for (const n of names) fs.writeFileSync(path.join(BIN, n), 'x'); + removePartials(BIN, '17.0.2'); + assert.deepEqual(fs.readdirSync(BIN).sort(), + ['forgejo-17.0.2', 'forgejo-17.0.2.asc', 'forgejo-17.0.2.part', 'forgejo-17.0.2.part.aria2', 'other.part']); + removePartials(BIN); + assert.deepEqual(fs.readdirSync(BIN).sort(), ['forgejo-17.0.2', 'forgejo-17.0.2.asc', 'other.part']); +}); + +test('runner: a binary that is already there ends the job with no download', { skip: !SUFFIX }, async () => { + reset(); + fs.mkdirSync(BIN, { recursive: true }); + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2'), 'binary'); + const headers: Array> = []; + const restore = stubFetch('v17.0.2', headers); + try { + const { ctx, updates, state } = fakeCtx(() => assert.fail('no aria2 expected')); + await forgejoBinRunner(ctx); + assert.equal(state.spawned, 0); + const last = updates[updates.length - 1]; + assert.equal(last.phase, 'done'); + assert.deepEqual(JSON.parse(String(last.result)), { version: '17.0.2' }); + assert.match(headers[0]['User-Agent'], /^K2Go Dashboard\//); // K2G-P5: neutral agent + } finally { restore(); } +}); + +test('runner: a bad release tag fails at once, with no retry', { skip: !SUFFIX }, async () => { + reset(); + const headers: Array> = []; + const restore = stubFetch('nightly', headers); + try { + const { ctx } = fakeCtx(() => assert.fail('no aria2 expected')); + await assert.rejects(forgejoBinRunner(ctx), /bad version/); + assert.equal(headers.length, 1); + } finally { restore(); } +}); + +test('runner: a complete download is renamed to the final name, mode 0775', { skip: !SUFFIX }, async () => { + reset(); + const restore = stubFetch('v17.0.2', []); + try { + const { ctx, updates } = fakeCtx((args, child) => { + const input = fs.readFileSync(args[args.indexOf('-i') + 1], 'utf8'); + assert.match(input, /forgejo-17\.0\.2-linux-/); + assert.match(input, /out=forgejo-17\.0\.2\.part/); + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2.part'), 'binary'); + child.emit('exit', 0, null); + }); + await forgejoBinRunner(ctx); + assert.deepEqual(fs.readdirSync(BIN), ['forgejo-17.0.2']); + if (process.platform !== 'win32') { + assert.equal(fs.statSync(path.join(BIN, 'forgejo-17.0.2')).mode & 0o777, 0o775); + } + assert.equal(updates[updates.length - 1].phase, 'done'); + } finally { restore(); } +}); + +test('runner: an aria2 run that leaves its control file is not complete', { skip: !SUFFIX }, async () => { + reset(); + const restore = stubFetch('v17.0.2', []); + try { + const { ctx } = fakeCtx((_args, child) => { + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2.part'), 'half'); + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2.part.aria2'), 'ctl'); + child.emit('exit', 0, null); + }); + await assert.rejects(forgejoBinRunner(ctx), /did not complete/); + assert.equal(fs.existsSync(path.join(BIN, 'forgejo-17.0.2')), false); + assert.equal(fs.existsSync(path.join(BIN, 'forgejo-17.0.2.part')), true); // kept for Retry + } finally { restore(); } +}); + +test('runner: Cancel removes the partial and its control file', { skip: !SUFFIX }, async () => { + reset(); + const restore = stubFetch('v17.0.2', []); + try { + const box: { state?: { canceled: boolean } } = {}; + const { ctx, state } = fakeCtx((_args, child) => { + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2.part'), 'half'); + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2.part.aria2'), 'ctl'); + box.state!.canceled = true; + child.emit('exit', null, 'SIGKILL'); + }); + box.state = state; + await assert.rejects(forgejoBinRunner(ctx), CanceledError); + assert.deepEqual(fs.readdirSync(BIN), []); + } finally { restore(); } +}); + +test('runner: Pause keeps the partial for Resume', { skip: !SUFFIX }, async () => { + reset(); + const restore = stubFetch('v17.0.2', []); + try { + const box: { state?: { paused: boolean } } = {}; + const { ctx, state } = fakeCtx((_args, child) => { + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2.part'), 'half'); + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2.part.aria2'), 'ctl'); + box.state!.paused = true; + child.emit('exit', null, 'SIGTERM'); + }); + box.state = state; + await assert.rejects(forgejoBinRunner(ctx), /paused/); + assert.deepEqual(fs.readdirSync(BIN).sort(), ['forgejo-17.0.2.part', 'forgejo-17.0.2.part.aria2']); + } finally { restore(); } +}); + +// The sqlite file stays open in this process (Windows refuses the delete), so the delete is best effort. +test.after(() => { try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* best effort */ } }); diff --git a/static/dashboard/sockets/jobs.ts b/static/dashboard/sockets/jobs.ts index bba5b843e..9d85ca698 100644 --- a/static/dashboard/sockets/jobs.ts +++ b/static/dashboard/sockets/jobs.ts @@ -13,7 +13,7 @@ import fs from 'fs'; import path from 'path'; import { RollingLog, LogSlice } from './rolling-log'; -export type JobType = 'kiwix' | 'maps' | 'books' | 'kolibri' | 'basemaps' | 'code-assets' | 'code-addons' | 'forgejo'; +export type JobType = 'kiwix' | 'maps' | 'books' | 'kolibri' | 'basemaps' | 'code-assets' | 'code-addons' | 'forgejo' | 'forgejo-bin'; export type JobPhase = | 'queued' | 'downloading' | 'indexing' | 'processing' // ADFA-4894 (control surface): 'paused' is a stopped-but-resumable state — like 'canceled' it From 79894d7d29f5fe99201e369005abcfeff65b6f39 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Mon, 23 Nov 2026 00:50:05 -0600 Subject: [PATCH 03/12] K2GO-593 fix(dashboard): forgejo-bin skip removes an old partial When the binary is already there, a partial of the same version from an earlier error is removed too, so it does not stay on disk. --- .../domain/ModuleDownloadProgress.java} | 0 .../presentation/ModuleDownloadRepository.java} | 0 .../domain/ModuleDownloadProgressTest.java} | 0 static/dashboard/sockets/forgejo-bin.exec.ts | 1 + static/dashboard/sockets/forgejo-bin.test.ts | 3 +++ 5 files changed, 4 insertions(+) rename controller/app/src/main/java/org/appdevforall/k2go/{maps/domain/MapsDownloadProgress.java => install/domain/ModuleDownloadProgress.java} (100%) rename controller/app/src/main/java/org/appdevforall/k2go/{maps/presentation/MapsDownloadRepository.java => install/presentation/ModuleDownloadRepository.java} (100%) rename controller/app/src/test/java/org/appdevforall/k2go/{maps/domain/MapsDownloadProgressTest.java => install/domain/ModuleDownloadProgressTest.java} (100%) diff --git a/controller/app/src/main/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgress.java b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgress.java similarity index 100% rename from controller/app/src/main/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgress.java rename to controller/app/src/main/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgress.java diff --git a/controller/app/src/main/java/org/appdevforall/k2go/maps/presentation/MapsDownloadRepository.java b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownloadRepository.java similarity index 100% rename from controller/app/src/main/java/org/appdevforall/k2go/maps/presentation/MapsDownloadRepository.java rename to controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownloadRepository.java diff --git a/controller/app/src/test/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgressTest.java b/controller/app/src/test/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgressTest.java similarity index 100% rename from controller/app/src/test/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgressTest.java rename to controller/app/src/test/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgressTest.java diff --git a/static/dashboard/sockets/forgejo-bin.exec.ts b/static/dashboard/sockets/forgejo-bin.exec.ts index 8f3d14bb3..ed6363331 100644 --- a/static/dashboard/sockets/forgejo-bin.exec.ts +++ b/static/dashboard/sockets/forgejo-bin.exec.ts @@ -118,6 +118,7 @@ const forgejoBinRunner: (ctx: RunnerContext) => Promise = async (ctx) => { removePartials(BIN_DIR, version); // a partial of an older release cannot be resumed const dest = finalPath(BIN_DIR, version); if (fs.existsSync(dest)) { + removePartials(BIN_DIR); ctx.log(`[forgejo-bin] ${path.basename(dest)} is already there`); ctx.update({ phase: 'done', percent: 100, speed: 0, eta: -1, detail: version, result }); return; diff --git a/static/dashboard/sockets/forgejo-bin.test.ts b/static/dashboard/sockets/forgejo-bin.test.ts index f2a363506..f7bc5745b 100644 --- a/static/dashboard/sockets/forgejo-bin.test.ts +++ b/static/dashboard/sockets/forgejo-bin.test.ts @@ -96,12 +96,15 @@ test('runner: a binary that is already there ends the job with no download', { s reset(); fs.mkdirSync(BIN, { recursive: true }); fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2'), 'binary'); + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2.part'), 'old partial'); + fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2.part.aria2'), 'ctl'); const headers: Array> = []; const restore = stubFetch('v17.0.2', headers); try { const { ctx, updates, state } = fakeCtx(() => assert.fail('no aria2 expected')); await forgejoBinRunner(ctx); assert.equal(state.spawned, 0); + assert.deepEqual(fs.readdirSync(BIN), ['forgejo-17.0.2']); // an old partial is removed const last = updates[updates.length - 1]; assert.equal(last.phase, 'done'); assert.deepEqual(JSON.parse(String(last.result)), { version: '17.0.2' }); From 0415aab19c3d29ed1588986d81e32e20b4954de6 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Mon, 23 Nov 2026 00:50:14 -0600 Subject: [PATCH 04/12] K2GO-593 feat(install): Forgejo binary download before the install The Forgejo install downloads its ~100 MB binary through the dash-node job forgejo-bin while the server is still up, before pdsm stop. The runrole then pins forgejo_version for that run, so the role's get_url skips the download and its GPG check verifies the file. A failed download fails only Forgejo, and Retry is offered. One download type and one card for every module download (maps base maps and the Forgejo binary): percent, speed, time left, Pause/Resume, "Reconnecting n of 5". MapsDownloadProgress and MapsDownloadRepository become ModuleDownloadProgress and ModuleDownloadRepository. The box downloads on the phone's default network, and aria2 continues on mobile data after a Wi-Fi drop. DownloadHold (the start gate's NetworkPolicy rule) holds the job on mobile data with no consent and with Keep offline, and continues it on Wi-Fi or after the user allows it on the card. A user pause is never continued by a network event. Forgejo needs dash-node 1.6.5 (DashNodeRequirement). --- .../domain/DashNodeRequirement.java | 9 +- .../k2go/install/domain/DownloadHold.java | 66 +++++ .../k2go/install/domain/ForgejoBinaryPin.java | 50 ++++ .../domain/ModuleDownloadProgress.java | 87 ++++--- .../install/presentation/InstallService.java | 141 +++++++---- .../install/presentation/ModuleDownload.java | 235 ++++++++++++++++++ .../ModuleDownloadRepository.java | 56 ++--- .../k2go/redesign/DownloadCard.java | 152 +++++++++++ .../k2go/redesign/MapsPreparingFragment.java | 64 +---- .../k2go/redesign/ModuleInstallFragment.java | 12 + .../layout/fragment_k2go_maps_preparing.xml | 67 +---- .../layout/fragment_k2go_module_install.xml | 3 + .../res/layout/view_k2go_download_card.xml | 92 +++++++ .../app/src/main/res/values/strings.xml | 12 + .../domain/DashNodeRequirementTest.java | 6 +- .../k2go/install/domain/DownloadHoldTest.java | 89 +++++++ .../install/domain/ForgejoBinaryPinTest.java | 48 ++++ .../domain/ModuleDownloadProgressTest.java | 58 +++-- 18 files changed, 991 insertions(+), 256 deletions(-) create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/install/domain/DownloadHold.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPin.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownload.java create mode 100644 controller/app/src/main/java/org/appdevforall/k2go/redesign/DownloadCard.java create mode 100644 controller/app/src/main/res/layout/view_k2go_download_card.xml create mode 100644 controller/app/src/test/java/org/appdevforall/k2go/install/domain/DownloadHoldTest.java create mode 100644 controller/app/src/test/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPinTest.java diff --git a/controller/app/src/main/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirement.java b/controller/app/src/main/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirement.java index e7ac18dfb..fca3598db 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirement.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirement.java @@ -7,9 +7,9 @@ * and the box read live elsewhere (redesign.DashboardVersion), so this stays a plain, * unit-testable registry with no Android or network dependency. * - * Forgejo needs the dashboard build that ships its repo status/refresh endpoints (1.3.7): - * an older dash-node makes "Install repos"/"Update repos" and the seed break silently, so - * installing Forgejo is HARD-blocked below that version. Code on the Go add-ons (K2GO-99) + * Forgejo needs the dashboard build that ships its repo status/refresh endpoints (1.3.7) + * and the forgejo-bin download job (1.6.5, K2GO-593): an older dash-node breaks the + * install, so installing Forgejo is HARD-blocked below that version. Code on the Go add-ons (K2GO-99) * needs the dashboard build that ships the /addons/refresh endpoints (1.3.8), so the gallery * can update, so it is HARD-blocked below that version too. Other modules have no hard minimum * (a soft "update the dashboard" suggestion applies to all installs, handled in the gate). @@ -25,7 +25,8 @@ private DashNodeRequirement() {} /** {major, minor, patch} minimum dash-node for {@code moduleKey}, or null when it has no hard minimum. */ @Nullable public static int[] minFor(@Nullable String moduleKey) { - if ("forgejo".equals(moduleKey)) return new int[]{1, 3, 7}; + // K2GO-593: 1.6.5 has the forgejo-bin job, which downloads the binary before the install. + if ("forgejo".equals(moduleKey)) return new int[]{1, 6, 5}; if ("code_addons".equals(moduleKey)) return new int[]{1, 3, 8}; // K2GO-99: needs /addons/refresh // K2GO-437: code_assets install (runrole) and browsing (WebView) do NOT use the dash-node // refresh endpoints; only the "Update build assets" action does, and it degrades gracefully diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/domain/DownloadHold.java b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/DownloadHold.java new file mode 100644 index 000000000..96c5312e8 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/DownloadHold.java @@ -0,0 +1,66 @@ +/* + * ============================================================================ + * Name : DownloadHold.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-593. When the app must stop a module download on the box + * because of the network, and when it may continue it. Pure JVM. + * ============================================================================ + */ +package org.appdevforall.k2go.install.domain; + +import org.appdevforall.k2go.networkpolicy.domain.NetworkClass; +import org.appdevforall.k2go.networkpolicy.domain.NetworkPolicy; +import org.appdevforall.k2go.networkpolicy.domain.NetworkPolicyDecision; + +/** + * The box downloads on the phone's default network, and its aria2 retry loop continues on mobile + * data after a Wi-Fi drop, with no question (seen on a Samsung A16 with 4G). The start gate + * (NetworkPolicyGate) asks only at the start. This rule is the in-flight half: hold the download while + * the network may not be used, and continue it when it may. + * + *

A pause by the user is the user's decision: a network event never continues it, and this rule + * never holds it again. No network at all is not a hold: the box reconnects on its own, and there is + * no traffic to stop. + */ +public final class DownloadHold { + + private DownloadHold() {} + + /** Who stopped the download, if somebody did. */ + public enum StoppedBy { NOBODY, USER, NETWORK } + + /** Why the download is held. */ + public enum Reason { METERED_NO_CONSENT, KEPT_OFFLINE } + + /** What the caller does now. */ + public enum Action { NONE, HOLD, CONTINUE } + + /** + * @param net cost class of the default network now + * @param meteredConsent the user allowed mobile data for this session + * @param onlineAllowed the user allows module installs to connect (online, or allowed this time) + * @param stoppedBy who stopped the download, if somebody did + */ + public static Action decide(NetworkClass net, boolean meteredConsent, boolean onlineAllowed, + StoppedBy stoppedBy) { + if (stoppedBy == StoppedBy.USER || net == NetworkClass.NONE) return Action.NONE; + boolean mayRun = reason(net, meteredConsent, onlineAllowed) == null; + if (stoppedBy == StoppedBy.NOBODY) return mayRun ? Action.NONE : Action.HOLD; + return mayRun ? Action.CONTINUE : Action.NONE; + } + + /** + * Why the network may not be used now, or null when it may. The mobile data rule is the start + * gate's own rule (NetworkPolicy), so the start and the in-flight check cannot disagree. + */ + public static Reason reason(NetworkClass net, boolean meteredConsent, boolean onlineAllowed) { + if (!onlineAllowed) return Reason.KEPT_OFFLINE; + if (POLICY.decideHeavyStart(net, meteredConsent) == NetworkPolicyDecision.NEEDS_CONSENT) { + return Reason.METERED_NO_CONSENT; + } + return null; + } + + private static final NetworkPolicy POLICY = new NetworkPolicy(); +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPin.java b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPin.java new file mode 100644 index 000000000..d3704c475 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPin.java @@ -0,0 +1,50 @@ +/* + * ============================================================================ + * Name : ForgejoBinaryPin.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-593. The local_vars line that makes the forgejo role use + * the binary that dash-node downloaded. Pure JVM. + * ============================================================================ + */ +package org.appdevforall.k2go.install.domain; + +/** + * dash-node downloads the Forgejo binary to {@code /library/forgejo/bin/forgejo-} (job type + * {@code forgejo-bin}). The role resolves {@code forgejo_version: latest} on its own, so the app pins + * the version that dash-node got, and the role's get_url finds the file and skips its download. The + * role then still checks the GPG signature of the file. + * + *

The pin is for this one run: a later update must resolve the newest release again. So the line + * carries a marker, and {@link #UNPIN} removes only the marked line, never a pin the owner wrote. + * The version comes from the box, and it goes into a root shell command, so it is checked here first. + */ +public final class ForgejoBinaryPin { + + private ForgejoBinaryPin() {} + + /** The module that owns this download. */ + public static final String MODULE = "forgejo"; + /** The dash-node job type. */ + public static final String JOB_TYPE = "forgejo-bin"; + + private static final String MARKER = "# k2go-forgejo-bin"; + private static final String LOCAL_VARS = "/etc/iiab/local_vars.yml"; + + /** Removes the marked pin. Safe to run when there is none. */ + public static final String UNPIN = "sed -i '/" + MARKER + "$/d' " + LOCAL_VARS; + + /** The role's assert: X.Y.Z. */ + public static boolean isVersion(String v) { + return v != null && v.matches("[0-9]+\\.[0-9]+\\.[0-9]+"); + } + + /** + * The shell command that pins {@code version}, or null when the version is not X.Y.Z. A pin that a + * killed run left is removed first, so there is never more than one marked line. + */ + public static String pinCommand(String version) { + if (!isVersion(version)) return null; + return UNPIN + " && echo 'forgejo_version: \"" + version + "\" " + MARKER + "' >> " + LOCAL_VARS; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgress.java b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgress.java index ab9444775..11668d456 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgress.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgress.java @@ -1,66 +1,85 @@ /* * ============================================================================ - * Name : MapsDownloadProgress.java + * Name : ModuleDownloadProgress.java * Author : AppDevForAll * Copyright : Copyright (c) 2026 AppDevForAll - * Description : K2GO-394. One base-map download's progress, as the subordinate - * download bar needs it, built from the dash-node REST poll - * (RestContentClient). Pure JVM, no Android, no JSON framework. + * Description : K2GO-394, K2GO-593. The download that a module install does + * through dash-node before its role (maps base maps, the Forgejo + * binary), as the download bar needs it. Pure JVM. * ============================================================================ */ -package org.appdevforall.k2go.maps.domain; +package org.appdevforall.k2go.install.domain; /** - * A snapshot of the base-map download for the subordinate bar. The base maps are downloaded through - * dash-node's durable job engine (the same path as ZIMs), so this is built from the REST poll fields - * ({@code RestContentClient.Listener}) -- a phase, a percent, a speed token, and the reconnect counter - * -- not from aria2's raw RPC. The rule for "which phase" lives in one testable place, not in the UI. + * A snapshot of a module's download for the download bar. The download runs as a dash-node job, so + * this is built from the REST poll fields ({@code RestContentClient.Listener}): a phase, a percent, a + * speed token, the time left and the reconnect counter. The rule for "which phase" lives here, not in + * the UI. */ -public final class MapsDownloadProgress { +public final class ModuleDownloadProgress { - /** The states the download bar distinguishes. RECONNECTING is a network drop the server rides out. */ - public enum Phase { NONE, ACTIVE, PAUSED, RECONNECTING, COMPLETE } + /** + * The states the download bar shows. RECONNECTING is a network drop that the box rides out. HELD + * is a stop that the app made because the network may not be used now (mobile data with no + * consent, or Keep offline); it continues on Wi-Fi or after the user allows it. + */ + public enum Phase { NONE, ACTIVE, PAUSED, HELD, RECONNECTING, COMPLETE } public final Phase phase; - /** 0..100, or -1 when not known yet (queued / no percent reported). */ + /** The module key that owns the download ("maps", "forgejo"), or null for NONE. */ + public final String module; + /** 0..100, or -1 when not known yet. */ public final int percent; /** Display token for the rate WITHOUT the per-second suffix (e.g. "3.4 MB"); the UI appends "/s". */ public final String speed; + /** Seconds left, or -1 when not known. */ + public final long etaSeconds; /** Reconnect counter for "Reconnecting n of N"; both 0 when not reconnecting. */ public final int reconnectAttempt; public final int reconnectTotal; + /** Why the download is HELD; null in the other phases. */ + public final DownloadHold.Reason holdReason; - private MapsDownloadProgress(Phase phase, int percent, String speed, int attempt, int total) { + private ModuleDownloadProgress(Phase phase, String module, int percent, String speed, long eta, + int attempt, int total, DownloadHold.Reason holdReason) { this.phase = phase; + this.module = module; this.percent = percent < 0 ? -1 : Math.min(100, percent); this.speed = speed != null ? speed : ""; + this.etaSeconds = eta < 0 ? -1 : eta; this.reconnectAttempt = Math.max(0, attempt); this.reconnectTotal = Math.max(0, total); + this.holdReason = holdReason; } - /** Nothing is downloading right now -- before the job starts, or after it finishes/clears. */ - public static MapsDownloadProgress none() { - return new MapsDownloadProgress(Phase.NONE, -1, "", 0, 0); + /** Nothing is downloading: before the job starts, or after it ends. */ + public static ModuleDownloadProgress none() { + return new ModuleDownloadProgress(Phase.NONE, null, -1, "", -1, 0, 0, null); } /** A live download at {@code percent} moving at {@code speed} (a display token, no "/s"). */ - public static MapsDownloadProgress active(int percent, String speed) { - return new MapsDownloadProgress(Phase.ACTIVE, percent, speed, 0, 0); + public static ModuleDownloadProgress active(String module, int percent, String speed, long etaSeconds) { + return new ModuleDownloadProgress(Phase.ACTIVE, module, percent, speed, etaSeconds, 0, 0, null); } - /** The user paused the download; the partial is kept and resume continues from it. */ - public static MapsDownloadProgress paused(int percent) { - return new MapsDownloadProgress(Phase.PAUSED, percent, "", 0, 0); + /** The user paused the download; the partial is kept and Resume continues from it. */ + public static ModuleDownloadProgress paused(String module, int percent) { + return new ModuleDownloadProgress(Phase.PAUSED, module, percent, "", -1, 0, 0, null); } - /** The server lost the network and is reconnecting (attempt n of total), keeping the partial. */ - public static MapsDownloadProgress reconnecting(int attempt, int total) { - return new MapsDownloadProgress(Phase.RECONNECTING, -1, "", attempt, total); + /** The app stopped the download for {@code reason}; the partial is kept. */ + public static ModuleDownloadProgress held(String module, int percent, DownloadHold.Reason reason) { + return new ModuleDownloadProgress(Phase.HELD, module, percent, "", -1, 0, 0, reason); + } + + /** The box lost the network and reconnects (attempt n of total), keeping the partial. */ + public static ModuleDownloadProgress reconnecting(String module, int attempt, int total) { + return new ModuleDownloadProgress(Phase.RECONNECTING, module, -1, "", -1, attempt, total, null); } /** The download finished. */ - public static MapsDownloadProgress complete() { - return new MapsDownloadProgress(Phase.COMPLETE, 100, "", 0, 0); + public static ModuleDownloadProgress complete(String module) { + return new ModuleDownloadProgress(Phase.COMPLETE, module, 100, "", 0, 0, 0, null); } public boolean isActive() { @@ -71,6 +90,10 @@ public boolean isPaused() { return phase == Phase.PAUSED; } + public boolean isHeld() { + return phase == Phase.HELD; + } + public boolean isReconnecting() { return phase == Phase.RECONNECTING; } @@ -79,8 +102,14 @@ public boolean isComplete() { return phase == Phase.COMPLETE; } - /** Whether there is a live download to show a bar for (active, paused, or reconnecting). */ + /** Whether there is a download to show a bar for (active, paused, held or reconnecting). */ public boolean isRunning() { - return phase == Phase.ACTIVE || phase == Phase.PAUSED || phase == Phase.RECONNECTING; + return phase == Phase.ACTIVE || phase == Phase.PAUSED || phase == Phase.HELD + || phase == Phase.RECONNECTING; + } + + /** Whether this snapshot is the download of {@code moduleKey}. */ + public boolean isFor(String moduleKey) { + return module != null && module.equals(moduleKey); } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/InstallService.java b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/InstallService.java index a459d7177..62391e9c2 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/InstallService.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/InstallService.java @@ -47,6 +47,7 @@ import org.appdevforall.k2go.download.domain.DownloadRetryPolicy; import org.appdevforall.k2go.install.data.InstallStateStore; import org.appdevforall.k2go.install.domain.AnsibleRunOutcome; +import org.appdevforall.k2go.install.domain.ForgejoBinaryPin; import org.appdevforall.k2go.sync.transport.NetworkStateLiveData; import java.io.BufferedReader; @@ -206,9 +207,12 @@ public final class InstallService extends Service { private static String sRetryMapsVector, sRetryMapsSat, sRetryMapsTerrain; private static boolean sRetryMapsSearch; private boolean mapsSearchOn; - // K2GO-394: the base-map download client for the maps module (dash-node "basemaps" job). Held so - // the UI's Pause/Resume/Cancel reach the in-flight download; null when nothing is downloading. - private volatile org.appdevforall.k2go.content.RestContentClient mapsClient; + // K2GO-394, K2GO-593: the module download through dash-node (maps base maps, the Forgejo binary). + // Held so the UI's Pause/Resume/Cancel reach it; null when nothing downloads. + private volatile ModuleDownload moduleDownload; + // K2GO-593: the Forgejo version that dash-node downloaded, which the forgejo runrole pins. "" when + // the download did not give one (the role then downloads by itself); null before the download. + private volatile String forgejoPinVersion; private File iiabRootDir; // filesDir/rootfs private File debianRootfs; // filesDir/rootfs/installed-rootfs/iiab @@ -238,6 +242,9 @@ public void onCreate() { */ private void onValidatedNetworkReturned() { if (finished || cancelled) return; + // K2GO-593: a module download holds on mobile data with no consent and continues on Wi-Fi. + ModuleDownload md = moduleDownload; + if (md != null) md.evaluate(); // K2GO-394: the maps base-map download is NOT driven from here -- dash-node owns its transport // resilience (its "basemaps" job re-runs aria2 with --continue and reports "Reconnecting n/5"), // the same self-healing path as ZIMs. The app just polls it. The manual Pause/Resume button @@ -332,6 +339,7 @@ public int onStartCommand(Intent intent, int flags, int startId) { // recreation (theme toggle / rotation) and can never launch two concurrent runroles. String[] mods = intent.getStringArrayExtra(EXTRA_MODULES); moduleQueue = new java.util.ArrayDeque<>(); + forgejoPinVersion = null; // K2GO-593: each batch downloads (or finds) the binary again if (mods != null) { for (String m : mods) if (m != null && !m.isEmpty()) moduleQueue.add(m); } @@ -865,6 +873,11 @@ private void runModuleQueue() { boolean anyRealModule = false; for (String m : moduleQueue) if (!"maps".equals(m)) { anyRealModule = true; break; } if (!anyRealModule) { installNextModule(); return; } + // K2GO-593: pdsm stop also stops dash-node, so its download must end before the stop. + if (moduleQueue.contains(ForgejoBinaryPin.MODULE) && forgejoPinVersion == null) { + downloadForgejoBinaryThen(this::runModuleQueue); + return; + } updateNotification(getString(R.string.server_shutting_down)); log("[Modules] Stopping server services before runroles (exclusive rootfs)..."); if (prootEngine == null) prootEngine = new PRootEngine(); @@ -945,12 +958,18 @@ private void installNextModule() { // ADFA-4900: for the wizard maps flow, write the full per-layer maps_* var set before // runrole (the generic _install/_enabled echo can't express quality/off/search). - final String runroleCmd = ("maps".equals(nextModule) && hasMapsConfig) + final String plainCmd = ("maps".equals(nextModule) && hasMapsConfig) ? mapsInstallCmd() : "sed -i -E '/^[[:space:]]*" + nextModule + "_(install|enabled)[[:space:]]*:/d' /etc/iiab/local_vars.yml && " + "echo '" + nextModule + "_install: True' >> /etc/iiab/local_vars.yml && " + "echo '" + nextModule + "_enabled: True' >> /etc/iiab/local_vars.yml && " + "cd /opt/iiab/iiab && ./runrole " + roleName; + // K2GO-593: pin the version that dash-node downloaded, for this run only, so the role uses that + // file. pinCommand is null for a version that is not X.Y.Z: then the role downloads by itself. + final String pin = ForgejoBinaryPin.MODULE.equals(nextModule) + ? ForgejoBinaryPin.pinCommand(forgejoPinVersion) : null; + final String runroleCmd = pin == null ? plainCmd + : pin + " && " + plainCmd + " ; rc=$? ; " + ForgejoBinaryPin.UNPIN + " ; exit $rc"; // K2GO-464: refresh the stale rootfs apt index before the runrole, or a pinned dep 404s as the // box ages. Best-effort (short timeout, || true) so an offline/local-only install still runs. // K2GO-593: a Cancel SIGKILLs the runrole, also during dpkg; finish any interrupted dpkg first. @@ -1077,8 +1096,9 @@ private void revertModuleInLocalVars(String module, Runnable then) { String revertCmd = "sed -i -E '/^[[:space:]]*" + module + "_(install|enabled)[[:space:]]*:/d' /etc/iiab/local_vars.yml && " + "echo '" + module + "_install: False' >> /etc/iiab/local_vars.yml && " + "echo '" + module + "_enabled: False' >> /etc/iiab/local_vars.yml ; " + - // K2GO-593: a killed runrole leaves its task dirs (a partial download) behind. - "rm -rf /root/.ansible/tmp/ansible-tmp-*"; + // K2GO-593: a killed runrole leaves its task dirs (a partial download) behind, and + // the forgejo version pin of that run. + "rm -rf /root/.ansible/tmp/ansible-tmp-* ; " + ForgejoBinaryPin.UNPIN; prootEngine.executeInContainer(this, debianRootfs.getAbsolutePath(), revertCmd, new PRootEngine.OutputListener() { @Override public void onOutputLine(String line) { } @Override public void onProcessExit(int exitCode) { then.run(); } @@ -1274,35 +1294,16 @@ private void downloadMapsBasemapsThenRun(String module, Runnable onReady) { } log("[maps] downloading " + ids.size() + " base-map file(s) via dash-node: " + android.text.TextUtils.join(", ", ids)); - final org.appdevforall.k2go.content.RestContentClient client = - new org.appdevforall.k2go.content.RestContentClient("basemaps"); - mapsClient = client; - client.start(body, new org.appdevforall.k2go.content.RestContentClient.Listener() { - @Override public void onProgress(int percent, String speed) { - org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().post( - org.appdevforall.k2go.maps.domain.MapsDownloadProgress.active(percent, speed)); - } - @Override public void onReconnecting(int attempt, int total) { - org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().post( - org.appdevforall.k2go.maps.domain.MapsDownloadProgress.reconnecting(attempt, total)); - } - @Override public void onPaused(int percent) { - org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().post( - org.appdevforall.k2go.maps.domain.MapsDownloadProgress.paused(percent)); - } - @Override public void onIndexing() { /* base maps have no index phase */ } - @Override public void onLog(String line) { log("[maps-dl] " + line); } - @Override public void onDone() { - mapsClient = null; - org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().clear(); + moduleDownload = new ModuleDownload(this, module, "basemaps", body, new ModuleDownload.Callback() { + @Override public void onDone(org.json.JSONObject result) { + moduleDownload = null; if (cancelled) return; log("[maps] base-map download complete; running the role"); // Keep the runrole off the poll's main-thread callback (it reads assets / prefs). org.appdevforall.k2go.util.AppExecutors.get().io().execute(onReady); } @Override public void onError(String message) { - mapsClient = null; - org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().clear(); + moduleDownload = null; if (cancelled) return; failedModules.add(module); log("[Install] FAILED: " + module + " base-map download (" + message + ")"); @@ -1312,7 +1313,53 @@ private void downloadMapsBasemapsThenRun(String module, Runnable onReady) { org.appdevforall.k2go.util.AppExecutors.get().io().execute( () -> revertModuleInLocalVars(module, InstallService.this::finishModuleQueue)); } - }); + }, this::log); + moduleDownload.start(); + } + + /** + * K2GO-593: download the Forgejo binary through dash-node (job "forgejo-bin") while the server is + * still up, then run {@code then}. The box resolves the version and writes the file where the role + * looks for it; the forgejo runrole pins that version, so its get_url skips the download and its GPG + * check verifies the file. A failed download fails only Forgejo (Retry is offered) and the other + * modules of the batch still install. No local_vars edit was made yet, so nothing is reverted. + */ + private void downloadForgejoBinaryThen(Runnable then) { + final String module = ForgejoBinaryPin.MODULE; + org.json.JSONObject body; + try { + body = new org.json.JSONObject().put("ids", new org.json.JSONArray().put(module)); + } catch (org.json.JSONException e) { + throw new IllegalStateException(e); // a literal body cannot fail + } + log("[forgejo] downloading the Forgejo binary via dash-node before the install"); + moduleDownload = new ModuleDownload(this, module, ForgejoBinaryPin.JOB_TYPE, body, new ModuleDownload.Callback() { + @Override public void onDone(org.json.JSONObject result) { + moduleDownload = null; + if (cancelled) return; + String version = result != null ? result.optString("version", "") : ""; + if (ForgejoBinaryPin.isVersion(version)) { + log("[forgejo] binary " + version + " is ready; the role uses it"); + } else { + log("[forgejo] WARNING: no valid version from the box; the role downloads the binary"); + version = ""; + } + forgejoPinVersion = version; + org.appdevforall.k2go.util.AppExecutors.get().io().execute(then); + } + @Override public void onError(String message) { + moduleDownload = null; + if (cancelled) return; + log("[Install] FAILED: " + module + " download (" + message + ")"); + failedModules.add(module); + org.appdevforall.k2go.analytics.AnalyticsClient.with(InstallService.this).logModuleInstall(module, false); + moduleQueue.remove(module); + persistQueue(); + forgejoPinVersion = ""; + org.appdevforall.k2go.util.AppExecutors.get().io().execute(then); + } + }, this::log); + moduleDownload.start(); } /** @@ -1466,12 +1513,11 @@ private String formatEta(int bucket) { */ private void doPause() { if (finished || cancelled) return; - // K2GO-394: a maps base-map download pauses through dash-node (the "basemaps" job), not the - // rootfs aria2 the checks below govern. The poll reflects the paused state on the download bar. - org.appdevforall.k2go.content.RestContentClient pauseClient = mapsClient; - if (pauseClient != null) { - log("[maps] pause requested"); - pauseClient.pause(); + // K2GO-394, K2GO-593: a module download pauses through dash-node, not the rootfs aria2 that the + // checks below govern. + ModuleDownload pauseDownload = moduleDownload; + if (pauseDownload != null) { + pauseDownload.pause(); return; } if (!InstallProgressRepository.get().current().isRunning()) return; @@ -1645,11 +1691,10 @@ private static int softFailLine(org.appdevforall.k2go.download.domain.Aria2Exit. */ private void doResume() { if (finished || cancelled) return; - // K2GO-394: resume a maps download through dash-node (aria2 --continue picks up the partial). - org.appdevforall.k2go.content.RestContentClient resumeClient = mapsClient; - if (resumeClient != null) { - log("[maps] resume requested"); - resumeClient.resume(); + // K2GO-394, K2GO-593: resume a module download through dash-node (aria2 --continue). + ModuleDownload resumeDownload = moduleDownload; + if (resumeDownload != null) { + resumeDownload.resume(); return; } if (!InstallProgressRepository.get().current().isHeld()) return; @@ -1711,7 +1756,11 @@ private void doCancel() { // server was pdsm-stopped for the runroles) is not raced by teardown's later clear. // K2GO-593: during pdsm stop no module is current yet; the cancel stops the first one. final String running = ModuleQueueRepository.get().current().currentModule; - final String cur = running != null ? running : (moduleQueue != null ? moduleQueue.peek() : null); + // K2GO-593: a cancel during the download before the stop cancels the module that downloads. + final ModuleDownload downloading = moduleDownload; + final String cur = running != null ? running + : downloading != null ? downloading.module() + : (moduleQueue != null ? moduleQueue.peek() : null); stopModuleStallWatch(); // ADFA-4898 P4 // K2GO-593: SIGKILL, not SIGTERM. On SIGTERM proot stayed up and the runrole kept downloading. if (prootEngine != null) prootEngine.forceKill(); @@ -1842,10 +1891,10 @@ private void teardown(boolean clearMarker) { // ADFA-5119: nothing to wait for once this is over — neither the window nor a queued attempt. cancelHeldWindow(); cancelPendingRetry(); - // K2GO-394: cancel an in-flight base-map download and clear its bar. - org.appdevforall.k2go.content.RestContentClient mc = mapsClient; - if (mc != null) { mc.cancel(); mapsClient = null; } - org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().clear(); + // K2GO-394, K2GO-593: cancel an in-flight module download (the box removes its partial). + ModuleDownload md = moduleDownload; + if (md != null) { md.cancel(); moduleDownload = null; } + ModuleDownloadRepository.get().clear(); if (clearMarker) { org.appdevforall.k2go.InstallGuard.end(this); } else { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownload.java b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownload.java new file mode 100644 index 000000000..a8aeaeccc --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownload.java @@ -0,0 +1,235 @@ +/* + * ============================================================================ + * Name : ModuleDownload.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-394, K2GO-593. One module download through a dash-node job + * (maps base maps, the Forgejo binary): start, pause, resume, + * cancel, the hold on mobile data, and the download bar state. + * ============================================================================ + */ +package org.appdevforall.k2go.install.presentation; + +import android.content.Context; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import org.appdevforall.k2go.content.RestContentClient; +import org.appdevforall.k2go.install.domain.DownloadHold; +import org.appdevforall.k2go.install.domain.ModuleDownloadProgress; +import org.appdevforall.k2go.networkpolicy.data.AndroidNetworkClassifier; +import org.appdevforall.k2go.networkpolicy.data.OnlineAllowance; +import org.appdevforall.k2go.networkpolicy.data.SessionMeteredConsentStore; +import org.json.JSONObject; + +/** + * Owns one dash-node download job for {@link InstallService}: the REST client, who stopped it, and the + * download bar ({@link ModuleDownloadRepository}). The box owns the transfer (aria2, resume, + * "Reconnecting n/5"); this class only adds what the box cannot know: whether the phone's network may + * be used now ({@link DownloadHold}). + * + *

"Who stopped it" is the one fact that only the app has: dash-node shows a user pause and a hold + * the same way ('paused'). It lives here, for the life of this download, and nowhere else. The process + * dies with the service that owns this object, and the next run re-attaches to the job + * (RestContentClient) and resumes a paused job that nobody here stopped. + * + *

All methods are synchronized: the poll and the network callback run on the main thread, the + * start runs on the queue thread. + */ +public final class ModuleDownload { + + interface Callback { + /** The job finished. {@code result} is the job's result, or null. Runs on the main thread. */ + void onDone(@Nullable JSONObject result); + + /** The job failed or was canceled on the box. Runs on the main thread. */ + void onError(@NonNull String message); + } + + private final Context app; + private final String module; + private final String jobType; + private final JSONObject body; + private final Callback callback; + private final LogSink logSink; + + interface LogSink { void log(String line); } + + private RestContentClient client; // null until the job starts + private DownloadHold.StoppedBy stoppedBy = DownloadHold.StoppedBy.NOBODY; + private boolean ended; + private int lastPercent = -1; + + ModuleDownload(@NonNull Context ctx, @NonNull String module, @NonNull String jobType, + @NonNull JSONObject body, @NonNull Callback callback, @NonNull LogSink logSink) { + this.app = ctx.getApplicationContext(); + this.module = module; + this.jobType = jobType; + this.body = body; + this.callback = callback; + this.logSink = logSink; + } + + /** The OnlineAllowance kind of a module: maps is a content kind (K2GO-588), the rest are modules. */ + public static String allowanceKind(String module) { + return "maps".equals(module) + ? org.appdevforall.k2go.system.domain.ContentType.MAPS.key() + : OnlineAllowance.MODULES; + } + + String module() { + return module; + } + + /** Start the job, or hold it before the start when the network may not be used now. */ + synchronized void start() { + if (ended) return; + DownloadHold.Reason why = holdReason(); + if (why != null && AndroidNetworkClassifier.classify(app) + != org.appdevforall.k2go.networkpolicy.domain.NetworkClass.NONE) { + hold(why); + return; + } + begin(); + } + + /** The user paused. */ + synchronized void pause() { + if (ended) return; + stoppedBy = DownloadHold.StoppedBy.USER; + if (client != null) client.pause(); + ModuleDownloadRepository.get().post(ModuleDownloadProgress.paused(module, lastPercent)); + logSink.log("[" + module + "-dl] paused by the user"); + } + + /** + * The user resumed, or allowed the network on a hold. A hold that is still true stays held: the + * card shows why, and its button gives the consent. + */ + synchronized void resume() { + if (ended) return; + DownloadHold.Reason why = holdReason(); + if (why != null) { + stoppedBy = DownloadHold.StoppedBy.NETWORK; + ModuleDownloadProgress cur = ModuleDownloadRepository.get().current(); + if (!(cur.isHeld() && cur.holdReason == why)) hold(why); + return; + } + stoppedBy = DownloadHold.StoppedBy.NOBODY; + logSink.log("[" + module + "-dl] resumed"); + if (client == null) { + begin(); + } else { + client.resume(); + ModuleDownloadRepository.get().post(ModuleDownloadProgress.active(module, lastPercent, "", -1)); + } + } + + /** The network or the privacy choice changed: hold or continue as {@link DownloadHold} says. */ + synchronized void evaluate() { + if (ended) return; + DownloadHold.Action a = DownloadHold.decide(AndroidNetworkClassifier.classify(app), + SessionMeteredConsentStore.get().isGranted(), onlineAllowed(), stoppedBy); + if (a == DownloadHold.Action.HOLD) { + DownloadHold.Reason why = holdReason(); + if (why != null) hold(why); + } else if (a == DownloadHold.Action.CONTINUE) { + stoppedBy = DownloadHold.StoppedBy.NOBODY; + logSink.log("[" + module + "-dl] the network may be used again; continuing"); + if (client == null) begin(); else client.resume(); + } + } + + /** Stop the job and remove its partial (the box does that on a cancel). */ + synchronized void cancel() { + if (ended) return; + ended = true; + if (client != null) client.cancel(); + ModuleDownloadRepository.get().clear(); + } + + private void hold(DownloadHold.Reason why) { + stoppedBy = DownloadHold.StoppedBy.NETWORK; + if (client != null) client.pause(); + ModuleDownloadRepository.get().post(ModuleDownloadProgress.held(module, lastPercent, why)); + logSink.log("[" + module + "-dl] held: " + why); + } + + @Nullable + private DownloadHold.Reason holdReason() { + return DownloadHold.reason(AndroidNetworkClassifier.classify(app), + SessionMeteredConsentStore.get().isGranted(), onlineAllowed()); + } + + private boolean onlineAllowed() { + return OnlineAllowance.allows(app, allowanceKind(module)); + } + + private void begin() { + ModuleDownloadRepository.get().post(ModuleDownloadProgress.active(module, -1, "", -1)); + client = new RestContentClient(jobType); + client.start(body, new RestContentClient.Listener() { + @Override public void onProgress(int percent, String speed) { onProgress(percent, speed, -1L); } + + @Override public void onProgress(int percent, String speed, long etaSeconds) { + synchronized (ModuleDownload.this) { + if (ended) return; + lastPercent = percent; + if (stoppedBy == DownloadHold.StoppedBy.NOBODY) { + ModuleDownloadRepository.get().post( + ModuleDownloadProgress.active(module, percent, speed, etaSeconds)); + } + } + evaluate(); + } + + @Override public void onReconnecting(int attempt, int total) { + synchronized (ModuleDownload.this) { + if (ended) return; + if (stoppedBy == DownloadHold.StoppedBy.NOBODY) { + ModuleDownloadRepository.get().post( + ModuleDownloadProgress.reconnecting(module, attempt, total)); + } + } + evaluate(); + } + + @Override public void onPaused(int percent) { + synchronized (ModuleDownload.this) { + if (ended) return; + if (percent >= 0) lastPercent = percent; + // A paused job that nobody here stopped: a job from an earlier run that this run + // re-attached to, or the poll before a resume took effect. Both mean: continue. + if (stoppedBy == DownloadHold.StoppedBy.NOBODY) { + if (holdReason() == null) client.resume(); else hold(holdReason()); + } + } + } + + @Override public void onIndexing() { } + + @Override public void onLog(String line) { logSink.log("[" + module + "-dl] " + line); } + + @Override public void onDone() { onDone(null); } + + @Override public void onDone(JSONObject result) { + synchronized (ModuleDownload.this) { + if (ended) return; + ended = true; + } + ModuleDownloadRepository.get().clear(); + callback.onDone(result); + } + + @Override public void onError(String message) { + synchronized (ModuleDownload.this) { + if (ended) return; + ended = true; + } + ModuleDownloadRepository.get().clear(); + callback.onError(message); + } + }); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownloadRepository.java b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownloadRepository.java index 2fe764dc9..291f7c1a1 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownloadRepository.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownloadRepository.java @@ -1,61 +1,57 @@ /* * ============================================================================ - * Name : MapsDownloadRepository.java + * Name : ModuleDownloadRepository.java * Author : AppDevForAll * Copyright : Copyright (c) 2026 AppDevForAll - * Description : K2GO-394. The one place the maps download progress lives, so the - * install-progress UI observes it instead of polling aria2 itself. + * Description : K2GO-394, K2GO-593. The one place where the progress of a + * module's download lives, so the install screens observe it. * ============================================================================ */ -package org.appdevforall.k2go.maps.presentation; +package org.appdevforall.k2go.install.presentation; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; -import org.appdevforall.k2go.maps.domain.MapsDownloadProgress; +import org.appdevforall.k2go.install.domain.ModuleDownloadProgress; /** - * The subordinate download bar's single source (K2GO-394). {@code InstallService} writes it from the - * dash-node poll ({@code RestContentClient.Listener} for the "basemaps" job); the progress screen - * observes it beside {@code ModuleQueueRepository} (the phase spine). One writer, so there is no - * second place inventing a download percent. - * - *

Starts and resets to {@link MapsDownloadProgress#none()} -- the honest "nothing to show", which - * is also what a non-maps module leaves it at, so the UI simply shows the phase-only Variant 3. + * The download bar's single source. {@link ModuleDownload} writes it from the dash-node poll; the + * install screens observe it beside {@code ModuleQueueRepository} (the phase spine). One writer, so no + * second place makes up a download percent. It is {@link ModuleDownloadProgress#none()} when no + * module downloads, so a module with no download shows only its phase. */ -public final class MapsDownloadRepository { +public final class ModuleDownloadRepository { - private static final MapsDownloadRepository INSTANCE = new MapsDownloadRepository(); + private static final ModuleDownloadRepository INSTANCE = new ModuleDownloadRepository(); - private final MutableLiveData state = - new MutableLiveData<>(MapsDownloadProgress.none()); + private final MutableLiveData state = + new MutableLiveData<>(ModuleDownloadProgress.none()); + // postValue is applied later on the main thread; current() must see the last write at once. + private volatile ModuleDownloadProgress last = ModuleDownloadProgress.none(); - private MapsDownloadRepository() { + private ModuleDownloadRepository() { } - public static MapsDownloadRepository get() { + public static ModuleDownloadRepository get() { return INSTANCE; } - public LiveData state() { + public LiveData state() { return state; } - public MapsDownloadProgress current() { - MapsDownloadProgress v = state.getValue(); - return v != null ? v : MapsDownloadProgress.none(); + public ModuleDownloadProgress current() { + return last; } - /** - * Post a new snapshot. {@code postValue} on purpose: the poll listener delivers on the main thread - * but InstallService clears from its background install thread, so the write must be thread-safe. - */ - public void post(MapsDownloadProgress p) { - state.postValue(p != null ? p : MapsDownloadProgress.none()); + /** Post a new snapshot. postValue, because the writers run on the main and on worker threads. */ + public void post(ModuleDownloadProgress p) { + last = p != null ? p : ModuleDownloadProgress.none(); + state.postValue(last); } - /** Clear back to "nothing downloading" -- on teardown, or when the download finishes. */ + /** Back to "nothing downloads": when the download ends, and on teardown. */ public void clear() { - state.postValue(MapsDownloadProgress.none()); + post(ModuleDownloadProgress.none()); } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/DownloadCard.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/DownloadCard.java new file mode 100644 index 000000000..0139d57dd --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/DownloadCard.java @@ -0,0 +1,152 @@ +/* + * ============================================================================ + * Name : DownloadCard.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-394, K2GO-593. Binds the shared download card + * (view_k2go_download_card) of a module install to + * ModuleDownloadRepository: percent, speed, time left, + * Pause/Resume, "Reconnecting n of 5", and the hold on mobile data. + * ============================================================================ + */ +package org.appdevforall.k2go.redesign; + +import android.content.Context; +import android.content.Intent; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.StringRes; +import androidx.lifecycle.LifecycleOwner; + +import com.google.android.material.progressindicator.LinearProgressIndicator; + +import org.appdevforall.k2go.R; +import org.appdevforall.k2go.install.domain.DownloadHold; +import org.appdevforall.k2go.install.domain.ModuleDownloadProgress; +import org.appdevforall.k2go.install.presentation.EtaText; +import org.appdevforall.k2go.install.presentation.InstallService; +import org.appdevforall.k2go.install.presentation.ModuleDownload; +import org.appdevforall.k2go.install.presentation.ModuleDownloadRepository; +import org.appdevforall.k2go.networkpolicy.data.OnlineAllowance; +import org.appdevforall.k2go.networkpolicy.data.SessionMeteredConsentStore; + +/** + * The view half of a module download. It only renders {@link ModuleDownloadRepository} for one module + * and sends the user's taps to {@link InstallService}; it keeps no download state of its own. + */ +public final class DownloadCard { + + /** Whether the card shows something for this module now (the host uses it for its status line). */ + public interface OnShown { void onShown(boolean shown); } + + private final Context ctx; + private final String module; + private final View card; + private final LinearProgressIndicator bar; + private final TextView pct, rate, note; + private final Button pause, allow; + private OnShown onShown; + + /** + * @param root a view that contains view_k2go_download_card + * @param module the module key whose download this card shows + * @param titleRes the card title + */ + public DownloadCard(@NonNull View root, @NonNull String module, @StringRes int titleRes) { + this.ctx = root.getContext(); + this.module = module; + card = root.findViewById(R.id.k2go_dl_card); + ((TextView) root.findViewById(R.id.k2go_dl_title)).setText(titleRes); + bar = root.findViewById(R.id.k2go_dl_bar); + pct = root.findViewById(R.id.k2go_dl_pct); + rate = root.findViewById(R.id.k2go_dl_rate); + note = root.findViewById(R.id.k2go_dl_note); + pause = root.findViewById(R.id.k2go_dl_pause); + allow = root.findViewById(R.id.k2go_dl_allow); + pause.setOnClickListener(v -> send(isStopped(current()) + ? InstallService.ACTION_RESUME : InstallService.ACTION_PAUSE)); + allow.setOnClickListener(v -> allowNetwork()); + } + + /** Observe the download for the life of {@code owner}. */ + public DownloadCard observe(@NonNull LifecycleOwner owner, OnShown onShown) { + this.onShown = onShown; + ModuleDownloadRepository.get().state().observe(owner, this::render); + return this; + } + + private ModuleDownloadProgress current() { + return ModuleDownloadRepository.get().current(); + } + + private static boolean isStopped(ModuleDownloadProgress p) { + return p.isPaused() || p.isHeld(); + } + + private void render(ModuleDownloadProgress p) { + boolean shown = p != null && p.isRunning() && p.isFor(module); + card.setVisibility(shown ? View.VISIBLE : View.GONE); + if (onShown != null) onShown.onShown(shown); + if (!shown) return; + + note.setVisibility(p.isHeld() ? View.VISIBLE : View.GONE); + allow.setVisibility(p.isHeld() ? View.VISIBLE : View.GONE); + pause.setVisibility(p.isHeld() ? View.GONE : View.VISIBLE); + if (p.isReconnecting()) { + // The box reconnects (aria2 --continue keeps the partial); the percent comes back after. + bar.setIndeterminate(true); + pct.setText(""); + rate.setText(ctx.getString(R.string.k2go_dl_attempt, p.reconnectAttempt, p.reconnectTotal)); + pause.setText(R.string.k2go_dl_pause); + return; + } + bar.setIndeterminate(p.percent < 0); + if (p.percent >= 0) bar.setProgressCompat(p.percent, true); + pct.setText(p.percent >= 0 ? ctx.getString(R.string.dash_format_pct, p.percent) : ""); + if (p.isHeld()) { + boolean metered = p.holdReason == DownloadHold.Reason.METERED_NO_CONSENT; + rate.setText(R.string.k2go_mod_phase_queued); + note.setText(metered ? R.string.k2go_dl_held_metered : R.string.k2go_dl_held_offline); + allow.setText(metered ? R.string.k2go_netpolicy_continue : R.string.k2go_offline_action_allow_once); + return; + } + if (p.isPaused()) { + rate.setText(R.string.k2go_dl_paused); + pause.setText(R.string.k2go_dl_resume); + return; + } + pause.setText(R.string.k2go_dl_pause); + if (p.speed.isEmpty()) { + rate.setText(""); + } else if (p.etaSeconds >= 0) { + rate.setText(ctx.getString(R.string.k2go_dl_speed_eta, p.speed, EtaText.of(ctx, p.etaSeconds))); + } else { + rate.setText(ctx.getString(R.string.k2go_dl_speed, p.speed)); + } + } + + /** + * The tap is the user's consent, for this session only, the same as the start gate gives: mobile + * data (SessionMeteredConsentStore) or, with Keep offline, this kind of install + * (OnlineAllowance). Then the service continues; if a second reason remains, the card shows it. + */ + private void allowNetwork() { + ModuleDownloadProgress p = current(); + if (!p.isHeld()) return; + if (p.holdReason == DownloadHold.Reason.METERED_NO_CONSENT) { + SessionMeteredConsentStore.get().grant(); + } else { + OnlineAllowance.allow(ModuleDownload.allowanceKind(module)); + } + send(InstallService.ACTION_RESUME); + } + + private void send(String action) { + Intent i = new Intent(ctx, InstallService.class); + i.setAction(action); + ctx.startService(i); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/MapsPreparingFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/MapsPreparingFragment.java index 323aa5790..2b2e96ab1 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/MapsPreparingFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/MapsPreparingFragment.java @@ -61,11 +61,6 @@ public static MapsPreparingFragment newInstance(boolean fromIndex) { private View progressRow; // ADFA-5228 private com.google.android.material.progressindicator.LinearProgressIndicator progress; private TextView progressPct, progressEta; - // K2GO-394: subordinate download card (the in-proot aria2c's live progress + Pause/Resume). - private View downloadCard; - private com.google.android.material.progressindicator.LinearProgressIndicator dlBar; - private TextView dlBytes, dlRate; - private android.widget.Button dlPause; private boolean fromIndex = false; // ADFA-4901: hosted by the Finishing-setup index (observe only) private boolean launched = false; // ADFA-4900: guard against re-launching maps on view recreation @@ -89,24 +84,6 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c progress = root.findViewById(R.id.k2go_prep_progress); progressPct = root.findViewById(R.id.k2go_prep_progress_pct); progressEta = root.findViewById(R.id.k2go_prep_progress_eta); - // K2GO-394: the subordinate download card + its Pause/Resume, fed by MapsDownloadRepository. - downloadCard = root.findViewById(R.id.k2go_prep_download); - dlBar = root.findViewById(R.id.k2go_prep_dl_bar); - dlBytes = root.findViewById(R.id.k2go_prep_dl_bytes); - dlRate = root.findViewById(R.id.k2go_prep_dl_rate); - dlPause = root.findViewById(R.id.k2go_prep_dl_pause); - dlPause.setOnClickListener(v -> { - // Toggle by the current phase: pause an active download, resume a paused one. The service - // routes ACTION_PAUSE/RESUME to the in-proot aria2c over RPC (InstallService.doPause/doResume). - boolean paused = org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().current().isPaused(); - android.content.Intent i = new android.content.Intent(requireContext(), - org.appdevforall.k2go.install.presentation.InstallService.class); - i.setAction(paused - ? org.appdevforall.k2go.install.presentation.InstallService.ACTION_RESUME - : org.appdevforall.k2go.install.presentation.InstallService.ACTION_PAUSE); - requireContext().startService(i); - }); - // ADFA-4919: the fromIndex=false branch below is the DEPRECATED standalone Get More route // (its own "Run in background", no index, no gate). Get More now routes through the install // index (SetupLibraryActivity.openMapsIndex), so this branch is unreachable in that flow. @@ -160,10 +137,8 @@ && getActivity() instanceof SetupLibraryActivity } }); - // K2GO-394: the subordinate download bar. Present only while a live in-proot download exists - // (the RPC feed); hidden otherwise, so a stock rootfs with no RPC shows the phase spine alone. - org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().state() - .observe(getViewLifecycleOwner(), this::renderDownload); + // K2GO-394, K2GO-593: the shared download card, shown while the base maps download. + new DownloadCard(root, "maps", R.string.k2go_maps_dl_title).observe(getViewLifecycleOwner(), null); // ADFA-4901: collapsible live log. The status line mirrors the latest line; expanding shows // the full terminal (LogRepository snapshot + live appends), auto-scrolled. @@ -187,41 +162,6 @@ && getActivity() instanceof SetupLibraryActivity return root; } - /** K2GO-394: render (or hide) the subordinate download card from the dash-node progress feed. */ - private void renderDownload(org.appdevforall.k2go.maps.domain.MapsDownloadProgress p) { - if (downloadCard == null) { - return; - } - if (p == null || !p.isRunning()) { - downloadCard.setVisibility(View.GONE); - return; - } - downloadCard.setVisibility(View.VISIBLE); - // A network drop: dash-node is re-establishing (aria2 --continue). Show the attempt counter - // and an indeterminate bar; the partial is kept, so the percent will pick back up on resume. - if (p.isReconnecting()) { - dlBar.setIndeterminate(true); - dlBytes.setText(""); - dlRate.setText(getString(R.string.k2go_dl_attempt, p.reconnectAttempt, p.reconnectTotal)); - dlPause.setText(getString(R.string.k2go_dl_pause)); - return; - } - int pct = p.percent; - dlBar.setIndeterminate(pct < 0); - if (pct >= 0) { - dlBar.setProgressCompat(pct, true); - } - dlBytes.setText(pct >= 0 ? (pct + "%") : ""); - if (p.isPaused()) { - dlRate.setText(getString(R.string.k2go_dl_paused)); - dlPause.setText(getString(R.string.k2go_dl_resume)); - } else { - // The poll gives the rate as a display token ("3.4 MB"); append the per-second suffix. - dlRate.setText(p.speed.isEmpty() ? "" : p.speed + "/s"); - dlPause.setText(getString(R.string.k2go_dl_pause)); - } - } - /** K2GO-374: seed the panel's deque from the current log snapshot when it is expanded. */ private void seedLog() { logLines.clear(); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleInstallFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleInstallFragment.java index 51fbc90da..44afac8fb 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleInstallFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleInstallFragment.java @@ -52,6 +52,7 @@ public static ModuleInstallFragment newInstance(String yamlBaseKey) { private TextView progressPct, progressEta; private org.appdevforall.k2go.widget.LiveLogPanel logPanel; // K2GO-374: shared details panel private boolean terminalDone = false; // this module reached done/failed → stop live status + private boolean downloading = false; // K2GO-593: the download card shows this module's download private final ArrayDeque logLines = new ArrayDeque<>(); private LogRepository.Listener logListener; @@ -75,6 +76,10 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c logPanel = root.findViewById(R.id.k2go_modinst_log_panel); logPanel.setOnExpandListener(this::seedLog); // K2GO-374: seed from the snapshot on expand + // K2GO-593: a module that downloads before its role (Forgejo) shows the shared download card. + new DownloadCard(root, key == null ? "" : key, R.string.k2go_dl_program_title) + .observe(getViewLifecycleOwner(), shown -> { downloading = shown; updateStatus(); }); + updateStatus(); ModuleQueueRepository.get().state().observe(getViewLifecycleOwner(), st -> updateStatus()); // ADFA-4898 P4: surface a "seems stalled" hint over the frozen status line while this module is @@ -142,6 +147,13 @@ private void updateStatus() { status.setText(getString(R.string.k2go_mod_phase_done)); return; } + if (downloading) { + org.appdevforall.k2go.install.domain.ModuleDownloadProgress dl = + org.appdevforall.k2go.install.presentation.ModuleDownloadRepository.get().current(); + status.setText(getString(dl.isHeld() ? R.string.k2go_mod_phase_queued + : dl.isPaused() ? R.string.k2go_dl_paused : R.string.k2go_mod_phase_downloading)); + return; + } if (installing()) { // ADFA-4898: a retry from this card brought the module back to RUNNING — clear the terminal // latch so the live log resumes driving the status line (it stops again on the next terminal). diff --git a/controller/app/src/main/res/layout/fragment_k2go_maps_preparing.xml b/controller/app/src/main/res/layout/fragment_k2go_maps_preparing.xml index e87cd8333..fdf519fb9 100644 --- a/controller/app/src/main/res/layout/fragment_k2go_maps_preparing.xml +++ b/controller/app/src/main/res/layout/fragment_k2go_maps_preparing.xml @@ -79,71 +79,8 @@ - - - - - - - - - - - - - - -