diff --git a/static/dashboard/package.json b/static/dashboard/package.json index 7c53af7c9..c37e773bc 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -4,7 +4,7 @@ "description": "", "main": "index.js", "scripts": { - "test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts", + "test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.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 266b828d0..f35868e77 100644 --- a/static/dashboard/routes.ts +++ b/static/dashboard/routes.ts @@ -9,6 +9,14 @@ import { spawn } from 'child_process'; import { jobs, Job, JobType } from './sockets/jobs'; import { searchCatalog, listLibrary, removeBook, listLanguages } from './sockets/books.query'; import { parseBox, parseEstimate } from './sockets/maps.socket'; +import { + preflight, listInstalledChannels, browseRemoteChannels, resolveIdentifier, + browseChannelTree, estimateSelection, deleteChannel, verifyCredentials, +} from './sockets/kolibri.query'; +import { checkReadiness, KolibriAuthError } from './sockets/kolibri.session'; +import { + describeCredential, setCredential, clearCredential, isServiceName, +} from './sockets/credentials'; // ADFA-4879: FQR helpers reached from the app (in-app region download/delete instead of the // copy-paste-into-a-terminal flow). tile-extract.py is installed on the box by the upstream maps @@ -17,7 +25,7 @@ import { parseBox, parseEstimate } from './sockets/maps.socket'; const MAPS_SCRIPT = '/opt/iiab/maps/tile-extract/tile-extract.py'; const MAPS_NAME_RE = /^[A-Za-z0-9_-]{1,34}$/; -const VALID_TYPES: JobType[] = ['kiwix', 'maps', 'books']; +const VALID_TYPES: JobType[] = ['kiwix', 'maps', 'books', 'kolibri']; function isType(t: string): t is JobType { return (VALID_TYPES as string[]).includes(t); } @@ -153,6 +161,206 @@ apiRouter.post('/maps/delete', (req: Request, res: Response): void => { }); }); +// --- Kolibri: readiness, catálogo y selección (ADFA-4949) ------------------------- +// Consultas directas (no-job). La descarga en sí es un job durable +// (POST /kolibri/download), que sale gratis al añadir 'kolibri' a VALID_TYPES. +// +// Nota de puertos y prefijos: nginx expone Kolibri en /kolibri/ y además le enruta +// /api/, /content/, /device/ y /learn/ en el :8085 compartido. Nosotros hablamos +// con Kolibri directamente en 127.0.0.1:8009 desde dentro, así que no hay colisión. + +/** Traduce un KolibriAuthError al status HTTP correcto. */ +function authStatus(e: unknown): number { + if (e instanceof KolibriAuthError) { + switch (e.reason) { + case 'unreachable': return 503; // el servicio no está listo + case 'credentials': return 401; + case 'permission': return 403; + default: return 502; + } + } + return 500; +} + +// El "gate" de arranque: mientras ready sea false, no tiene sentido lanzar jobs. +// Nunca lanza: siempre devuelve un diagnóstico con los bloqueadores en claro. +apiRouter.get('/kolibri/ready', async (_req: Request, res: Response): Promise => { + try { + const readiness = await checkReadiness(); + // 200 siempre: es un endpoint de estado, no una operación. El cliente mira + // el campo `ready`, no el status. + res.json(readiness); + } catch (e: any) { + res.status(500).json({ ready: false, blockers: [e?.message || 'readiness failed'] }); + } +}); + +// Diagnóstico ampliado: readiness + estado local (canales, bytes en disco, rutas). +apiRouter.get('/kolibri/preflight', async (_req: Request, res: Response): Promise => { + try { + res.json(await preflight()); + } catch (e: any) { + res.status(500).json({ error: e?.message || 'preflight failed' }); + } +}); + +// Qué hay ya en el dispositivo. Lectura local en readonly: no necesita ni sesión +// ni que Kolibri esté arriba. +apiRouter.get('/kolibri/channels', (_req: Request, res: Response): void => { + try { + res.json(listInstalledChannels()); + } catch (e: any) { + res.status(500).json({ error: e?.message || 'channel list failed' }); + } +}); + +// Catálogo remoto para el selector del wizard. ?keyword= y ?language= opcionales. +apiRouter.get('/kolibri/catalog', async (req: Request, res: Response): Promise => { + try { + res.json(await browseRemoteChannels({ + keyword: req.query.keyword ? String(req.query.keyword) : undefined, + language: req.query.language ? String(req.query.language) : undefined, + })); + } catch (e: any) { + res.status(authStatus(e)).json({ error: e?.message || 'catalog fetch failed' }); + } +}); + +// Resuelve un token (xxxxx-xxxxx) o un UUID a su canal. El usuario copia tokens de +// Studio, pero las tareas exigen el hex de 32. +apiRouter.get('/kolibri/resolve/:identifier', async (req: Request, res: Response): Promise => { + try { + res.json(await resolveIdentifier(String(req.params.identifier))); + } catch (e: any) { + const status = e instanceof KolibriAuthError ? authStatus(e) : 404; + res.status(status).json({ error: e?.message || 'not found' }); + } +}); + +// Un nivel del árbol del canal, para elegir subárboles. +// PRECONDICIÓN: los metadatos del canal deben estar ya en la base local, o sea que +// hay que haber importado el canal antes. Es el mismo flujo que la UI de Kolibri: +// primero los metadatos (MB), luego la selección del contenido (GB). +apiRouter.get('/kolibri/tree/:channelId', async (req: Request, res: Response): Promise => { + try { + const nodeId = req.query.nodeId ? String(req.query.nodeId) : undefined; + res.json(await browseChannelTree(String(req.params.channelId), nodeId)); + } catch (e: any) { + res.status(authStatus(e)).json({ error: e?.message || 'tree fetch failed' }); + } +}); + +// Tamaño exacto de una selección + espacio libre, para el paso de consentimiento. +// Body: { channelId, nodeIds?, excludeNodeIds? } +apiRouter.post('/kolibri/estimate', async (req: Request, res: Response): Promise => { + const body = req.body as { channelId?: unknown; nodeIds?: unknown; excludeNodeIds?: unknown }; + const channelId = String(body?.channelId ?? '').trim(); + if (!channelId) { res.status(400).json({ error: 'channelId required' }); return; } + try { + res.json(await estimateSelection( + channelId, + Array.isArray(body.nodeIds) ? body.nodeIds.map(String) : undefined, + Array.isArray(body.excludeNodeIds) ? body.excludeNodeIds.map(String) : undefined, + )); + } catch (e: any) { + res.status(authStatus(e)).json({ error: e?.message || 'estimate failed' }); + } +}); + +// Borrar un canal. Devuelve el id del job de Kolibri, no del motor local: es una +// operación corta y no merece un job durable. +apiRouter.post('/kolibri/delete', async (req: Request, res: Response): Promise => { + const body = req.body as { channelId?: unknown; channelName?: unknown }; + const channelId = String(body?.channelId ?? '').trim(); + if (!channelId) { res.status(400).json({ error: 'channelId required' }); return; } + try { + const jobId = await deleteChannel(channelId, + body.channelName ? String(body.channelName) : undefined); + res.json({ ok: true, kolibriJobId: jobId }); + } catch (e: any) { + res.status(authStatus(e)).json({ error: e?.message || 'delete failed' }); + } +}); + +// --- Credenciales de servicios (ADFA-4949) --------------------------------------- +// Permite al webview actualizar usuario/contraseña sin recompilar. La contraseña +// NUNCA se devuelve: el GET solo dice qué usuario hay y de dónde sale. + +apiRouter.get('/credentials/:service', (req: Request, res: Response): void => { + const service = String(req.params.service); + if (!isServiceName(service)) { res.status(404).json({ error: 'unknown service' }); return; } + try { + res.json(describeCredential(service)); + } catch (e: any) { + res.status(500).json({ error: e?.message || 'read failed' }); + } +}); + +// Valida ANTES de persistir: así el error aparece en el formulario donde se cometió, +// no media hora después en una descarga fallida. +// 401 → credenciales rechazadas (no se guarda nada) +// 403 → autentica pero no puede gestionar contenido (no se guarda nada) +// 503 → Kolibri no responde; la capa de arranque debe resolverlo primero +apiRouter.post('/credentials/:service', async (req: Request, res: Response): Promise => { + const service = String(req.params.service); + if (!isServiceName(service)) { res.status(404).json({ error: 'unknown service' }); return; } + + const body = req.body as { username?: unknown; password?: unknown }; + const username = String(body?.username ?? '').trim(); + const password = String(body?.password ?? ''); + if (!username || !password) { + res.status(400).json({ error: 'username and password required' }); + return; + } + + // Por ahora solo Kolibri se valida en vivo. Para otros servicios se guarda tal + // cual (calibre sigue con sus constantes hasta que se migre en su propio PR). + if (service !== 'kolibri') { + try { + setCredential(service, { username, password }); + res.json({ ok: true, verified: false, service }); + } catch (e: any) { + res.status(500).json({ error: e?.message || 'save failed' }); + } + return; + } + + try { + const check = await verifyCredentials(username, password); + if (!check.canManageContent) { + // Distinguir esto de "contraseña mala" ahorra horas de diagnóstico: el + // usuario existe y la clave es correcta, pero no puede importar contenido. + res.status(403).json({ + error: `'${username}' autentica pero no tiene permiso para gestionar contenido`, + saved: false, + }); + return; + } + setCredential('kolibri', { username, password }); + res.json({ ok: true, verified: true, service, username: check.username }); + } catch (e: any) { + const status = authStatus(e); + res.status(status).json({ + error: status === 401 + ? 'Kolibri rechazó estas credenciales' + : (e?.message || 'verification failed'), + saved: false, + }); + } +}); + +// Volver al valor de fábrica (o a la variable de entorno, si está puesta). +apiRouter.delete('/credentials/:service', (req: Request, res: Response): void => { + const service = String(req.params.service); + if (!isServiceName(service)) { res.status(404).json({ error: 'unknown service' }); return; } + try { + clearCredential(service); + res.json({ ok: true, ...describeCredential(service) }); + } catch (e: any) { + res.status(500).json({ error: e?.message || 'reset failed' }); + } +}); + // Start a content job → 202 { ...job } apiRouter.post('/:type/download', (req: Request, res: Response): void => { const type = String(req.params.type); diff --git a/static/dashboard/server.ts b/static/dashboard/server.ts index 3e02a564a..4be3b614e 100644 --- a/static/dashboard/server.ts +++ b/static/dashboard/server.ts @@ -8,6 +8,7 @@ import { jobs } from './sockets/jobs'; import './sockets/kiwix.exec'; import './sockets/maps.exec'; import './sockets/books.exec'; +import './sockets/kolibri.exec'; import { apiRouter } from './routes'; const app = express(); diff --git a/static/dashboard/sockets/credentials.ts b/static/dashboard/sockets/credentials.ts new file mode 100644 index 000000000..4d4e1f4bd --- /dev/null +++ b/static/dashboard/sockets/credentials.ts @@ -0,0 +1,143 @@ +// sockets/credentials.ts — almacén de credenciales de servicios del box +// +// Motivación: las credenciales de los servicios locales estaban embebidas en el +// código (books.exec.ts:15-16, books.query.ts:22, con el comentario "a credential +// override can be added later if needed"). Este módulo es ese override: si el +// operador cambia la contraseña de Kolibri en el dispositivo, se actualiza aquí y +// el mecanismo sigue funcionando sin recompilar ni redeployar. +// +// Precedencia (gana el primero que exista): +// 1. variable de entorno K2GO__USER / K2GO__PASS +// 2. override persistido /library/dashboard/credentials.json +// 3. default de fábrica Admin / changeme (lo que provisiona Ansible en IIAB) +// +// El fichero se escribe con 0600 y de forma atómica (write + rename), para que un +// corte a media escritura no deje un JSON truncado que impida autenticarse. +// +// Nota de alcance: por ahora solo Kolibri lo consume. Los runners de books siguen +// con sus constantes; migrarlos es un cambio aparte porque toca código que ya +// funciona en producción. +import fs from 'fs'; +import path from 'path'; + +export type ServiceName = 'kolibri' | 'calibre'; + +export interface Credential { + username: string; + password: string; +} + +/** De dónde salió la credencial que se está usando. Útil para diagnóstico. */ +export type CredentialOrigin = 'env' | 'override' | 'default'; + +export interface ResolvedCredential extends Credential { + origin: CredentialOrigin; +} + +const STORE_PATH = process.env.K2GO_CREDENTIALS_FILE + || '/library/dashboard/credentials.json'; + +/** Lo que provisiona el rol de Ansible de IIAB en el build del rootfs. */ +const DEFAULTS: Record = { + kolibri: { username: 'Admin', password: 'changeme' }, + calibre: { username: 'Admin', password: 'changeme' }, +}; + +const ENV_PREFIX: Record = { + kolibri: 'K2GO_KOLIBRI', + calibre: 'K2GO_CALIBRE', +}; + +const SERVICES: ServiceName[] = ['kolibri', 'calibre']; + +export function isServiceName(s: string): s is ServiceName { + return (SERVICES as string[]).includes(s); +} + +type Store = Partial>; + +/** Lectura tolerante: un fichero ausente o corrupto degrada a los defaults, no + * rompe el arranque del dashboard. */ +function readStore(): Store { + try { + const raw = fs.readFileSync(STORE_PATH, 'utf8'); + const parsed = JSON.parse(raw) as unknown; + if (!parsed || typeof parsed !== 'object') return {}; + const out: Store = {}; + for (const svc of SERVICES) { + const entry = (parsed as Record)[svc]; + if (entry && typeof entry === 'object') { + const { username, password } = entry as Record; + if (typeof username === 'string' && typeof password === 'string') { + out[svc] = { username, password }; + } + } + } + return out; + } catch { + return {}; + } +} + +function writeStore(store: Store): void { + const dir = path.dirname(STORE_PATH); + fs.mkdirSync(dir, { recursive: true }); + // Escritura atómica: si el proceso muere a medias, el fichero antiguo sigue + // siendo válido en lugar de quedar un JSON a medio escribir. + const tmp = `${STORE_PATH}.tmp-${process.pid}`; + fs.writeFileSync(tmp, JSON.stringify(store, null, 2) + '\n', { mode: 0o600 }); + fs.renameSync(tmp, STORE_PATH); + try { fs.chmodSync(STORE_PATH, 0o600); } catch { /* best effort */ } +} + +/** La credencial efectiva de un servicio, con su procedencia. */ +export function getCredential(service: ServiceName): ResolvedCredential { + const envUser = process.env[`${ENV_PREFIX[service]}_USER`]; + const envPass = process.env[`${ENV_PREFIX[service]}_PASS`]; + if (envUser && envPass) { + return { username: envUser, password: envPass, origin: 'env' }; + } + const stored = readStore()[service]; + if (stored) return { ...stored, origin: 'override' }; + return { ...DEFAULTS[service], origin: 'default' }; +} + +/** Persiste un override. NO valida contra el servicio: eso lo hace la ruta REST, + * que solo llama aquí después de un login correcto. */ +export function setCredential(service: ServiceName, cred: Credential): void { + const username = cred.username.trim(); + if (!username) throw new Error('username required'); + if (!cred.password) throw new Error('password required'); + const store = readStore(); + store[service] = { username, password: cred.password }; + writeStore(store); +} + +/** Vuelve al default de fábrica (o a la variable de entorno, si está puesta). */ +export function clearCredential(service: ServiceName): void { + const store = readStore(); + delete store[service]; + writeStore(store); +} + +/** Vista segura para la UI: nunca devuelve la contraseña, solo si hay una y de + * dónde viene. Es lo que el webview necesita para pintar el formulario. */ +export function describeCredential(service: ServiceName): { + service: ServiceName; + username: string; + origin: CredentialOrigin; + isDefault: boolean; +} { + const c = getCredential(service); + return { + service, + username: c.username, + origin: c.origin, + // Señal para que la UI pueda avisar "sigues con la contraseña de fábrica". + isDefault: c.origin === 'default' + || (c.username === DEFAULTS[service].username + && c.password === DEFAULTS[service].password), + }; +} + +export const CREDENTIALS_STORE_PATH = STORE_PATH; diff --git a/static/dashboard/sockets/jobs.ts b/static/dashboard/sockets/jobs.ts index 524ed4a70..b8ed24bf9 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'; +export type JobType = 'kiwix' | 'maps' | 'books' | 'kolibri'; export type JobPhase = | 'queued' | 'downloading' | 'indexing' | 'processing' | 'done' | 'error' | 'canceled'; diff --git a/static/dashboard/sockets/kolibri.exec.ts b/static/dashboard/sockets/kolibri.exec.ts new file mode 100644 index 000000000..c9bb228a5 --- /dev/null +++ b/static/dashboard/sockets/kolibri.exec.ts @@ -0,0 +1,403 @@ +// sockets/kolibri.exec.ts — runner de Kolibri para el motor de jobs durable +// +// Siembra contenido en Kolibri encolando tareas en SU API REST y haciendo polling. +// A diferencia de kiwix/maps, aquí no se hace spawn de ningún binario: el trabajo +// lo ejecuta el propio Kolibri, que ya está corriendo dentro del proot. +// +// Ventaja concreta de esta vía sobre invocar la CLI: Kolibri reporta progreso +// estructurado (percentage, transferred_file_size, total_resources). Su CLI no +// reporta nada parseable — usa click.progressbar sin etiqueta, y en modo no-TTY la +// salida de un import completo es literalmente una línea vacía. +// +// Un item del job es: +// { channelId, channelName?, nodeIds?, excludeNodeIds?, allThumbnails? } +// Se procesan en SECUENCIA: dos imports simultáneos solo generan contención sobre +// la misma db.sqlite3. +// +// PRECONDICIÓN: la capa de arranque garantiza que Kolibri está vivo y sus workers +// activos. El runner lo verifica igualmente y falla con un mensaje accionable en +// lugar de colgarse indefinidamente. +import { jobs, RunnerContext, CanceledError, JobUpdate } from './jobs'; +import { + loginForContent, apiJson, apiFetch, ensureContentOrigin, + KolibriSession, KolibriAuthError, KolibriApiError, STUDIO_URL, +} from './kolibri.session'; +import { + buildTaskPayload, mapPercent, mapPhase, normalizeUuid, overallPercent, + sampleSpeed, PRE_RUN_STATES, TERMINAL_STATES, +} from './kolibri.map'; + +/** Enteros positivos desde el entorno, con default. Ajustables en operación + * (redes muy lentas) y en tests. */ +function envMs(name: string, def: number): number { + const raw = process.env[name]; + if (!raw) return def; + const n = Number(raw); + return Number.isFinite(n) && n > 0 ? n : def; +} + +const POLL_MS = envMs('K2GO_KOLIBRI_POLL_MS', 2000); + +/** Si un job sigue sin ser tomado tras esto, casi seguro los workers no están + * vivos: encolar solo escribe una fila en job_storage.sqlite3; sin un + * WorkerSupervisor nadie la ejecuta y el job queda en QUEUED para siempre. */ +const QUEUED_GRACE_MS = envMs('K2GO_KOLIBRI_QUEUED_GRACE_MS', 90_000); + +/** Sin avance de bytes durante este tiempo, el transporte de Kolibri está en su + * bucle de reintentos —que NO tiene límite: espera 30 s y reintenta ante + * ConnectionError, Timeout y HTTP 502/503/504/521-524—. El estado seguiría en + * RUNNING eternamente, así que cortamos. Reintentar es seguro y barato: las + * descargas se reanudan por HTTP Range. */ +const STALL_TIMEOUT_MS = envMs('K2GO_KOLIBRI_STALL_MS', 15 * 60_000); + +/** Reintentos de login por job. Acotado para que una credencial revocada a mitad + * del import no genere un bucle de logins fallidos. */ +const MAX_REAUTH = 3; + +interface KolibriItem { + channelId?: string; + channelName?: string; + nodeIds?: string[]; + excludeNodeIds?: string[]; + allThumbnails?: boolean; +} + +interface ParsedItem { + channelId: string; + channelName?: string; + nodeIds: string[]; + excludeNodeIds: string[]; + allThumbnails?: boolean; +} + +interface KolibriJob { + id: string; + status: string; + percentage: number | null; + exception: string | null; + traceback: string | null; + extra_metadata?: { + channel_name?: string; + database_ready?: boolean; + file_size?: number; + total_resources?: number; + transferred_file_size?: number; + transferred_resources?: number; + }; +} + +function sleep(ms: number): Promise { + return new Promise((r) => setTimeout(r, ms)); +} + +/** Duración legible: evita "0 min" cuando el umbral se baja para pruebas. */ +function humanMs(ms: number): string { + return ms < 60_000 + ? `${Math.round(ms / 1000)} s` + : `${Math.round(ms / 60_000)} min`; +} + +/** Valida y normaliza los items del job. Falla ruidosamente: es mejor rechazar en + * el encolado que descargar cero bytes con éxito aparente. */ +export function parseItems(rawItems: unknown[]): ParsedItem[] { + const parsed: ParsedItem[] = []; + for (const raw of rawItems) { + // Por comodidad se acepta también un channelId suelto, como hace kiwix. + const item: KolibriItem = typeof raw === 'string' + ? { channelId: raw } + : ((raw ?? {}) as KolibriItem); + + const channelId = normalizeUuid(item.channelId); + if (!channelId) { + throw new Error(`channelId inválido: ${String(item.channelId)} — se espera ` + + 'un UUID hex de 32; resuelve los tokens antes de encolar'); + } + + const requestedNodes = item.nodeIds ?? []; + const nodeIds = requestedNodes + .map(normalizeUuid) + .filter((x): x is string => x !== null); + // Si se pidió una selección y ningún id es válido, la tarea terminaría con + // éxito sin descargar nada. Preferimos fallar aquí. + if (requestedNodes.length > 0 && nodeIds.length === 0) { + throw new Error(`ningún nodeId válido para el canal ${channelId}`); + } + + const excludeNodeIds = (item.excludeNodeIds ?? []) + .map(normalizeUuid) + .filter((x): x is string => x !== null); + + parsed.push({ + channelId, + channelName: item.channelName, + nodeIds, + excludeNodeIds, + allThumbnails: item.allThumbnails, + }); + } + if (parsed.length === 0) throw new Error('no channels requested'); + return parsed; +} + +/** Nombre del canal según el propio dispositivo (proxy a Studio, cacheado 5 min). + * Devuelve null si no se puede resolver; el llamador usará el id como nombre. */ +async function resolveChannelName( + session: KolibriSession, channelId: string, +): Promise { + try { + // Devuelve 503 {"status":"offline"} sin red; apiJson lanza y caemos a null. + const data = await apiJson | Array>>( + session, `/api/content/remotechannel/${channelId}/`, {}, 20000); + const row = Array.isArray(data) ? data[0] : data; + const name = row?.name; + return typeof name === 'string' && name ? name : null; + } catch { + return null; + } +} + +/** Traduce un fallo de autenticación en un mensaje que dice qué hacer. */ +function authErrorMessage(e: unknown): string { + if (!(e instanceof KolibriAuthError)) { + return `No se pudo autenticar contra Kolibri: ${e instanceof Error ? e.message : String(e)}`; + } + switch (e.reason) { + case 'unreachable': + return 'Kolibri no está disponible; reintenta cuando el servicio esté listo'; + case 'credentials': + return 'Credenciales de Kolibri incorrectas: actualízalas en /credentials/kolibri'; + case 'permission': + return e.message; + default: + return `No se pudo autenticar contra Kolibri: ${e.message}`; + } +} + +/** Contenedor mutable de la sesión: un import puede durar horas y sobrevivir a la + * caducidad de la sesión de Django, así que el poll necesita poder reemplazarla. */ +interface SessionHolder { current: KolibriSession } + +/** Reautentica in situ. Devuelve false si tampoco se puede ahora. */ +async function reauthenticate(ctx: RunnerContext, holder: SessionHolder): Promise { + try { + holder.current = await loginForContent(); + ctx.log('sesión caducada: reautenticado'); + return true; + } catch (e) { + ctx.log(`no se pudo reautenticar: ${authErrorMessage(e)}`); + return false; + } +} + +const kolibriRunner: (ctx: RunnerContext) => Promise = async (ctx) => { + const parsed = parseItems(ctx.items); + + ctx.update({ phase: 'queued', percent: 0 }); + + let holder: SessionHolder; + try { + holder = { current: await loginForContent() }; + } catch (e) { + throw new Error(authErrorMessage(e)); + } + + // Prerrequisito de proot: 'importcontent' llama SIEMPRE a + // lookup_channel_listing_status() → NetworkClient.discover_from_address(). Sin + // una NetworkLocation cuyo base_url coincida con el origen, ese camino cae al + // fallback que invoca ifaddr.get_adapters(), y netlink está bloqueado bajo proot. + // + // No abortamos si falla: puede que IIAB ya sembrara la fila 'reserved' y solo + // fallara nuestra comprobación. + const origin = await ensureContentOrigin(holder.current, STUDIO_URL); + ctx.log(`origen de contenido (${STUDIO_URL}): ${origin}`); + if (origin === 'failed') { + ctx.log('AVISO: no se pudo garantizar la NetworkLocation del origen. Si el ' + + 'import falla al resolver el origen, ésta es la causa probable.'); + } + + let index = 0; + for (const item of parsed) { + ctx.throwIfCanceled(); + index++; + + const channelName = item.channelName + || await resolveChannelName(holder.current, item.channelId) + || item.channelId; + + const label = parsed.length > 1 + ? `${channelName} (${index}/${parsed.length})` + : channelName; + + ctx.update({ phase: 'queued', detail: label }); + ctx.log(`encolando import de ${item.channelId} — ${channelName}`); + + const payload = buildTaskPayload({ + channelId: item.channelId, + channelName, + nodeIds: item.nodeIds, + excludeNodeIds: item.excludeNodeIds, + // Solo cuando hay selección parcial: ahí las miniaturas de los topics no + // seleccionados no vendrían y la navegación quedaría con huecos. En un + // canal completo ya vienen, así que pedirlas solo añade descarga. + allThumbnails: item.allThumbnails ?? item.nodeIds.length > 0, + }); + + const created = await apiJson( + holder.current, '/api/tasks/tasks/', + { method: 'POST', body: JSON.stringify(payload) }, 30000); + const kolibriJob = Array.isArray(created) ? created[0] : created; + if (!kolibriJob?.id) throw new Error('Kolibri no devolvió un id de job'); + ctx.log(`job de Kolibri: ${kolibriJob.id}`); + + await pollKolibriJob(ctx, holder, kolibriJob.id, label, index, parsed.length); + } + + ctx.update({ phase: 'done', percent: 100, detail: null }); +}; + +/** Sigue un job de Kolibri hasta su estado terminal, reflejando el progreso. */ +async function pollKolibriJob( + ctx: RunnerContext, + holder: SessionHolder, + kolibriJobId: string, + label: string, + index: number, + total: number, +): Promise { + const started = Date.now(); + let lastBytes = 0; + let lastSampleAt = Date.now(); + let lastProgressAt = Date.now(); + let taken = false; + let reauths = 0; + + const cancelInKolibri = async (): Promise => { + try { + await apiFetch(holder.current, `/api/tasks/tasks/${kolibriJobId}/cancel/`, + { method: 'POST', body: '{}' }); + } catch { /* mejor esfuerzo */ } + }; + + const clearInKolibri = async (): Promise => { + // OJO: DELETE /api/tasks/tasks// devuelve 405 — el viewset define + // delete() pero no destroy(), así que el router no lo enruta. + try { + await apiFetch(holder.current, `/api/tasks/tasks/${kolibriJobId}/clear/`, + { method: 'POST', body: '{}' }); + } catch { /* mejor esfuerzo */ } + }; + + for (;;) { + if (ctx.isCanceled()) { + // Cancelar también en Kolibri: si no, seguiría descargando en segundo + // plano aunque nuestro job ya figure como cancelado. + await cancelInKolibri(); + ctx.log(`job ${kolibriJobId} cancelado en Kolibri`); + throw new CanceledError(); + } + + let job: KolibriJob; + try { + job = await apiJson(holder.current, `/api/tasks/tasks/${kolibriJobId}/`); + } catch (e) { + // Sesión caducada: un import puede durar horas y sobrevivir a la sesión + // de Django. Reautenticar y seguir, en lugar de perder un job que + // Kolibri probablemente esté completando. + if (e instanceof KolibriApiError && e.isAuthExpired && reauths < MAX_REAUTH) { + reauths++; + if (await reauthenticate(ctx, holder)) { continue; } + } + // Un fallo puntual de polling no debe matar el job: Kolibri sigue + // trabajando. Solo abortamos si persiste más allá del stall timeout. + if (Date.now() - lastProgressAt > STALL_TIMEOUT_MS) { + throw new Error(`el polling de ${kolibriJobId} falló de forma sostenida: ` + + (e instanceof Error ? e.message : String(e))); + } + await sleep(POLL_MS); + continue; + } + + const meta = job.extra_metadata ?? {}; + const now = Date.now(); + + const patch: JobUpdate = { + phase: mapPhase(job.status), + detail: total > 1 ? label : (meta.channel_name || label), + }; + const local = mapPercent(job.percentage); + if (local >= 0) patch.percent = overallPercent(index, total, local); + + const bytes = meta.transferred_file_size ?? 0; + const speed = sampleSpeed(lastBytes, bytes, lastSampleAt, now); + if (speed !== null) { + patch.speed = speed; + lastBytes = bytes; + lastSampleAt = now; + lastProgressAt = now; + } + ctx.update(patch); + + // La gracia de cola solo aplica ANTES de que un worker tome el job. Si ya + // corrió y volvió a QUEUED, es el reintento propio de Kolibri + // (enqueue_args.max_retries) y es legítimo: no lo confundimos con workers + // caídos. + if (PRE_RUN_STATES.has(job.status) && !taken) { + if (now - started > QUEUED_GRACE_MS) { + throw new Error( + `El job ${kolibriJobId} sigue en ${job.status} tras ` + + `${Math.round((now - started) / 1000)} s: los workers de Kolibri no ` + + 'parecen estar activos (kolibri start los incluye; kolibri services ' + + 'los arranca sin HTTP).'); + } + } else if (!taken) { + // Acaba de pasar a RUNNING: reiniciamos el reloj de estancamiento para + // no contar el tiempo que estuvo en cola. + taken = true; + lastProgressAt = now; + } + + if (job.status === 'RUNNING' && now - lastProgressAt > STALL_TIMEOUT_MS) { + await cancelInKolibri(); + throw new Error( + `Sin avance durante ${humanMs(STALL_TIMEOUT_MS)}: Kolibri está ` + + 'reintentando la descarga en bucle (red inestable). Job cancelado; ' + + 'al reintentar se reanuda donde quedó.'); + } + + if (TERMINAL_STATES.has(job.status)) { + // Se limpia en TODOS los caminos terminales, no solo en el éxito: si no, + // los jobs fallidos se acumulan en la cola de Kolibri. + if (job.status === 'FAILED') { + const detail = job.exception || 'sin detalle'; + ctx.log(`FALLO en Kolibri: ${detail}`); + if (job.traceback) ctx.log(job.traceback.split('\n').slice(-6).join('\n')); + await clearInKolibri(); + throw new Error(`Kolibri falló importando ${label}: ${detail}`); + } + if (job.status === 'CANCELED') { + await clearInKolibri(); + throw new CanceledError(); + } + + // COMPLETED no garantiza que se haya descargado algo: con node_ids + // inexistentes la tarea termina bien sin transferir un byte. + const expected = meta.total_resources ?? 0; + const got = meta.transferred_resources ?? 0; + const mb = Math.round((meta.transferred_file_size ?? 0) / 1048576); + ctx.log(`completado: ${got}/${expected} recursos, ${mb} MB`); + await clearInKolibri(); + if (expected > 0 && got === 0) { + throw new Error( + `Kolibri terminó sin transferir nada de ${label}: revisa los nodeIds. ` + + 'Una selección vacía termina con éxito y sin contenido.'); + } + return; + } + + await sleep(POLL_MS); + } +} + +jobs.registerRunner('kolibri', kolibriRunner); + +export { kolibriRunner }; diff --git a/static/dashboard/sockets/kolibri.map.ts b/static/dashboard/sockets/kolibri.map.ts new file mode 100644 index 000000000..56ff24530 --- /dev/null +++ b/static/dashboard/sockets/kolibri.map.ts @@ -0,0 +1,135 @@ +// sockets/kolibri.map.ts — helpers puros de traducción Kolibri ↔ motor de jobs +// +// Separado de kolibri.exec.ts por la misma razón que maps.socket.ts está separado +// de maps.exec.ts: aquí no hay red, ni SQLite, ni dependencias nativas, así que se +// puede testear con `node --test` sin compilar better-sqlite3 — que es justo lo que +// hace el CI con `npm ci --ignore-scripts`. +// +// Todo lo que vive aquí encapsula una trampa concreta de la API de Kolibri. + +/** Tarea que importa metadatos + archivos en un solo job. + * Los nombres antiguos (startremotechannelimport, startchannelupdate…) son de una + * API anterior a la 0.15 y ya no existen en el backend: solo sobreviven en tests + * del frontend de Kolibri. */ +export const TASK_REMOTE_IMPORT = 'kolibri.core.content.tasks.remoteimport'; +export const TASK_DELETE_CHANNEL = 'kolibri.core.content.tasks.deletechannel'; + +/** Estados terminales de Kolibri (kolibri/core/tasks/job.py, class State). */ +export const TERMINAL_STATES = new Set(['COMPLETED', 'FAILED', 'CANCELED']); + +/** Estados en los que el job todavía no ha sido tomado por un worker. */ +export const PRE_RUN_STATES = new Set(['PENDING', 'SCHEDULED', 'QUEUED']); + +/** Fases del motor de jobs de K2Go. Se replica el tipo en lugar de importarlo de + * jobs.ts para no arrastrar better-sqlite3 a este módulo puro. */ +export type Phase = + | 'queued' | 'downloading' | 'indexing' | 'processing' + | 'done' | 'error' | 'canceled'; + +const HEX32 = /^[0-9a-f]{32}$/; + +/** + * Normaliza un identificador de canal o nodo a hex de 32 minúsculas. + * + * Kolibri acepta UUID con o sin guiones y los normaliza (HexOnlyUUIDField), pero + * validar aquí evita encolar basura y da el error en el sitio correcto. Devuelve + * null para tokens proquint: no son channel_id, y pasarlos tal cual acabaría en un + * 404 del descargador sin mensaje claro. + */ +export function normalizeUuid(raw: unknown): string | null { + if (typeof raw !== 'string') return null; + const v = raw.trim().replace(/-/g, '').toLowerCase(); + return HEX32.test(v) ? v : null; +} + +/** Traduce el estado de Kolibri a la fase del motor de jobs. */ +export function mapPhase(kolibriStatus: string): Phase { + switch (kolibriStatus) { + case 'PENDING': + case 'SCHEDULED': + case 'QUEUED': + case 'SELECTED': + return 'queued'; + case 'RUNNING': + return 'downloading'; + case 'COMPLETED': + return 'done'; + case 'FAILED': + return 'error'; + case 'CANCELING': + case 'CANCELED': + return 'canceled'; + default: + // Estado nuevo en una versión futura: no romper, seguir mostrando avance. + return 'processing'; + } +} + +/** + * Kolibri devuelve `percentage` como float 0–1; el motor de jobs usa entero 0–100. + * Confundirlos es el error más fácil de cometer con esta API. + * Devuelve -1 (indeterminado, la convención de jobs.ts) si no hay dato. + */ +export function mapPercent(percentage: number | null | undefined): number { + if (typeof percentage !== 'number' || Number.isNaN(percentage)) return -1; + return Math.max(0, Math.min(100, Math.round(percentage * 100))); +} + +/** Progreso global cuando un job de K2Go abarca varios canales: cada canal ocupa + * su franja, de modo que la barra sube 0→100 una sola vez en lugar de reiniciarse. + * Se acota a 99 para que el 100 lo ponga el final del runner. */ +export function overallPercent(index: number, total: number, localPercent: number): number { + if (total <= 1) return localPercent; + if (localPercent < 0) return -1; + return Math.min(99, Math.round(((index - 1) * 100 + localPercent) / total)); +} + +export interface TaskPayloadInput { + channelId: string; + channelName: string; + nodeIds?: string[]; + excludeNodeIds?: string[]; + allThumbnails?: boolean; +} + +/** + * Construye el cuerpo del POST a /api/tasks/tasks/. + * + * Encapsula tres trampas verificadas en el código de Kolibri: + * + * 1. `channel_name` es OBLIGATORIO (serializers.CharField sin required=False). + * Omitirlo da 400 aunque el campo solo se use para metadatos de presentación. + * 2. `peer` NO admite null (PrimaryKeyRelatedField sin allow_null=True): mandar + * `"peer": null` da 400 "This field may not be null". Hay que OMITIR la clave. + * 3. `node_ids: []` significa CERO NODOS, no "todo el canal". Ausente significa + * todo. Una lista vacía descargaría nada terminando con éxito. + */ +export function buildTaskPayload(item: TaskPayloadInput): Record { + const payload: Record = { + type: TASK_REMOTE_IMPORT, + channel_id: item.channelId, + channel_name: item.channelName, + // Sin esto los errores 404 / ENOENT / nombre inválido se cuentan como + // "skipped" y la tarea termina como COMPLETED. + fail_on_error: true, + renderable_only: true, + }; + if (item.nodeIds && item.nodeIds.length > 0) payload.node_ids = item.nodeIds; + if (item.excludeNodeIds && item.excludeNodeIds.length > 0) { + payload.exclude_node_ids = item.excludeNodeIds; + } + // Con selección parcial, sin esto la navegación por temas queda con huecos: + // las miniaturas de los topics no seleccionados no se descargan. + if (item.allThumbnails) payload.all_thumbnails = true; + return payload; +} + +/** Bytes por segundo a partir de dos muestras de `transferred_file_size`. + * Devuelve null si no hubo avance, para no pisar la velocidad anterior con un 0. */ +export function sampleSpeed( + prevBytes: number, nextBytes: number, prevAtMs: number, nextAtMs: number, +): number | null { + if (nextBytes <= prevBytes) return null; + const dtSec = Math.max(0.001, (nextAtMs - prevAtMs) / 1000); + return Math.max(0, Math.round((nextBytes - prevBytes) / dtSec)); +} diff --git a/static/dashboard/sockets/kolibri.query.ts b/static/dashboard/sockets/kolibri.query.ts new file mode 100644 index 000000000..0a2d8e29b --- /dev/null +++ b/static/dashboard/sockets/kolibri.query.ts @@ -0,0 +1,333 @@ +// sockets/kolibri.query.ts — consultas directas (no-job) de Kolibri +// +// Mismo papel que books.query.ts: lo que la UI necesita para decidir QUÉ descargar, +// separado del job que lo descarga. +// +// listInstalledChannels() qué hay ya en el dispositivo, con bytes disponibles +// browseRemoteChannels() catálogo remoto para el selector del wizard +// resolveIdentifier() token o UUID → canal (los tokens los pide el usuario, +// la CLI y las tareas exigen UUID) +// browseChannelTree() árbol granular para elegir subárboles +// estimateSelection() bytes exactos de una selección, antes de bajarla +// deleteChannel() quitar un canal +// +// Los totales locales se leen de SQLite en readonly (patrón de books.query.ts) en +// lugar de por HTTP: es más barato y no necesita sesión. OJO con una trampa: la +// columna 'available' vive en db.sqlite3, NO en el .sqlite3 del canal, y se marca +// de golpe al FINAL del import — así que sirve para "¿está completo?" pero no como +// fuente de progreso en vivo. +import Database from 'better-sqlite3'; +import fs from 'fs'; +import path from 'path'; +import { + loginForContent, login, apiJson, apiFetch, checkReadiness, + KolibriSession, STUDIO_URL, +} from './kolibri.session'; + +const KOLIBRI_HOME = process.env.KOLIBRI_HOME || '/library/kolibri'; +const MAIN_DB = path.join(KOLIBRI_HOME, 'db.sqlite3'); +const CONTENT_DIR = process.env.KOLIBRI_CONTENT_DIR + || path.join(KOLIBRI_HOME, 'content'); + +export interface InstalledChannel { + id: string; + name: string; + version: number; + filesTotal: number; + filesAvailable: number; + bytesTotal: number; + bytesAvailable: number; + complete: boolean; +} + +/** + * Canales presentes en el dispositivo y cuánto de cada uno está disponible. + * + * Un solo recorrido: la CTE reduce content_file × content_contentnode a pares + * DISTINCT (channel_id, local_file_id) y luego se agrega una vez. El DISTINCT no es + * cosmético — un LocalFile puede colgar de varios ContentNode del mismo canal, y un + * JOIN plano contaría sus bytes tantas veces como nodos lo referencien. + * + * El LEFT JOIN es deliberado: un canal cuyos metadatos están importados pero sin + * contenido debe aparecer con ceros, no desaparecer del listado. + */ +export function listInstalledChannels(): InstalledChannel[] { + if (!fs.existsSync(MAIN_DB)) return []; + const db = new Database(MAIN_DB, { readonly: true }); + try { + const rows = db.prepare(` + WITH channel_files AS ( + SELECT DISTINCT cn.channel_id AS channel_id, + f.local_file_id AS local_file_id + FROM content_file f + JOIN content_contentnode cn ON cn.id = f.contentnode_id + ) + SELECT cm.id AS id, + cm.name AS name, + cm.version AS version, + COUNT(lf.id) AS filesTotal, + COALESCE(SUM(CASE WHEN lf.available = 1 THEN 1 ELSE 0 END), 0) AS filesAvailable, + COALESCE(SUM(lf.file_size), 0) AS bytesTotal, + COALESCE(SUM(CASE WHEN lf.available = 1 + THEN lf.file_size ELSE 0 END), 0) AS bytesAvailable + FROM content_channelmetadata cm + LEFT JOIN channel_files p ON p.channel_id = cm.id + LEFT JOIN content_localfile lf ON lf.id = p.local_file_id + GROUP BY cm.id, cm.name, cm.version + ORDER BY cm.name + `).all() as Array>; + return rows.map((r) => ({ + ...r, + complete: r.filesTotal > 0 && r.filesAvailable >= r.filesTotal, + })); + } finally { + db.close(); + } +} + +/** + * Bytes ya materializados en disco, excluyendo transferencias en curso. + * + * NO LLAMAR DESDE UN HANDLER REST. Es un recorrido sincrónico del árbol de + * contenido: en un dispositivo poblado son decenas de miles de ficheros, y Node es + * monohilo, así que bloquearía todos los demás endpoints —incluidos los jobs de + * kiwix/maps/books— durante el recorrido. + * + * Se conserva porque es la única fuente de progreso que no depende de la API de + * Kolibri (su columna `available` se marca de golpe al final del import). Si algún + * día se necesita en vivo, hay que pasarlo a fs.promises y cachearlo. + */ +export function contentBytesOnDisk(): number { + const storage = path.join(CONTENT_DIR, 'storage'); + let total = 0; + const walk = (dir: string): void => { + let entries: fs.Dirent[]; + try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } + for (const e of entries) { + const p = path.join(dir, e.name); + if (e.isDirectory()) { walk(p); continue; } + // .transfer y .chunks son descargas a medias; no cuentan como presentes. + if (e.name.endsWith('.transfer') || e.name.endsWith('.chunks')) continue; + try { total += fs.statSync(p).size; } catch { /* desapareció */ } + } + }; + walk(storage); + return total; +} + +export interface RemoteChannel { + id: string; + name: string; + description: string; + version: number | null; + language: string | null; + totalResources: number | null; + publishedSize: number | null; +} + +function toRemoteChannel(row: Record): RemoteChannel { + const num = (v: unknown): number | null => + typeof v === 'number' ? v : (typeof v === 'string' && v.trim() !== '' ? Number(v) : null); + return { + id: String(row.id ?? ''), + name: String(row.name ?? ''), + description: String(row.description ?? ''), + version: num(row.version), + language: typeof row.lang_code === 'string' ? row.lang_code + : (typeof row.language === 'string' ? row.language : null), + totalResources: num(row.total_resource_count), + publishedSize: num(row.published_size), + }; +} + +/** + * Catálogo remoto para el selector del wizard, vía el proxy del propio dispositivo. + * + * Se usa /api/content/remotechannel/ en lugar de ir directo a Studio para que el + * origen y la caché sean los de Kolibri (cachea 5 min) y para no duplicar la + * política de red. Devuelve 503 {"status":"offline"} si no hay conectividad, que + * aquí se traduce en una excepción legible. + */ +export async function browseRemoteChannels( + opts: { keyword?: string; language?: string } = {}, +): Promise { + const session = await loginForContent(); + const qs = new URLSearchParams(); + if (opts.keyword) qs.set('keyword', opts.keyword); + if (opts.language) qs.set('language', opts.language); + const suffix = qs.toString() ? `?${qs.toString()}` : ''; + const data = await apiJson( + session, `/api/content/remotechannel/${suffix}`, {}, 30000); + const list = Array.isArray(data) + ? data + : ((data as { results?: unknown[] })?.results ?? []); + return (list as Array>).map(toRemoteChannel); +} + +/** + * Resuelve un token (xxxxx-xxxxx o xxxxxxxxxx) o un UUID a su canal. + * + * Necesario porque el usuario copia tokens de Studio, pero las tareas y la CLI + * exigen el hex de 32. Los guiones son puramente presentacionales: Studio guarda + * el proquint sin guion. + */ +export async function resolveIdentifier(identifier: string): Promise { + const session = await loginForContent(); + const normalized = identifier.trim().replace(/-/g, '').toLowerCase(); + const data = await apiJson( + session, `/api/content/remotechannel/${encodeURIComponent(normalized)}/`, {}, 30000); + const row = Array.isArray(data) ? data[0] : data; + if (!row || typeof row !== 'object') throw new Error(`no se encontró el canal '${identifier}'`); + const channel = toRemoteChannel(row as Record); + if (!channel.id) throw new Error(`no se encontró el canal '${identifier}'`); + return channel; +} + +export interface TreeNode { + id: string; + title: string; + kind: string; + isLeaf: boolean; + totalResources: number; + onDeviceResources: number; + importable: boolean; + children?: TreeNode[]; +} + +function toTreeNode(row: Record): TreeNode { + const kids = Array.isArray(row.children) + ? (row.children as Array>).map(toTreeNode) + : undefined; + return { + id: String(row.id ?? ''), + title: String(row.title ?? ''), + kind: String(row.kind ?? ''), + isLeaf: row.is_leaf === true, + totalResources: typeof row.total_resources === 'number' ? row.total_resources : 0, + onDeviceResources: typeof row.on_device_resources === 'number' ? row.on_device_resources : 0, + importable: row.importable !== false, + ...(kids ? { children: kids } : {}), + }; +} + +/** + * Un nivel del árbol del canal, para que el wizard permita elegir subárboles. + * + * PRECONDICIÓN: los metadatos del canal ya tienen que estar en la base local, o + * sea que hay que haber corrido un import de canal antes. Es el mismo flujo que la + * UI de Kolibri: primero baja los metadatos (MB), luego deja elegir el contenido (GB). + * + * Si no se pasa nodeId, se usa la raíz del canal. + */ +export async function browseChannelTree( + channelId: string, nodeId?: string, +): Promise { + const session = await loginForContent(); + let target = nodeId; + if (!target) { + const channel = await apiJson>( + session, `/api/content/channel/${channelId}/`); + const root = channel?.root; + if (typeof root !== 'string') { + throw new Error(`el canal ${channelId} no está en la base local: ` + + 'importa primero sus metadatos'); + } + target = root; + } + const node = await apiJson>( + session, `/api/content/contentnode_granular/${target}/`, {}, 30000); + return toTreeNode(node); +} + +export interface SelectionSize { + resourceCount: number; + fileSize: number; + freeSpace: number | null; + fitsOnDevice: boolean | null; +} + +/** + * Tamaño exacto de una selección antes de comprometer bytes, más el espacio libre. + * + * OJO con el prefijo: este endpoint NO está bajo /api/ sino bajo /device/api/, + * porque lo publica el plugin 'device'. + */ +export async function estimateSelection( + channelId: string, nodeIds?: string[], excludeNodeIds?: string[], +): Promise { + const session = await loginForContent(); + const body: Record = { channel_id: channelId }; + if (nodeIds && nodeIds.length) body.node_ids = nodeIds; + if (excludeNodeIds && excludeNodeIds.length) body.exclude_node_ids = excludeNodeIds; + + const size = await apiJson<{ resource_count?: number; file_size?: number }>( + session, '/device/api/importexportsizeview', + { method: 'POST', body: JSON.stringify(body) }, 60000); + + let freeSpace: number | null = null; + try { + const fs2 = await apiJson<{ freespace?: number }>(session, '/api/device/freespace/'); + freeSpace = typeof fs2.freespace === 'number' ? fs2.freespace : null; + } catch { /* no bloqueante */ } + + const fileSize = size.file_size ?? 0; + return { + resourceCount: size.resource_count ?? 0, + fileSize, + freeSpace, + // Kolibri ya resta su colchón (MINIMUM_DISK_SPACE, 250 MB) al calcular + // freespace, así que comparar directo es correcto. + fitsOnDevice: freeSpace === null ? null : freeSpace > fileSize, + }; +} + +/** Borra un canal completo (metadatos + archivos) vía la tarea de Kolibri. */ +export async function deleteChannel(channelId: string, channelName?: string): Promise { + const session = await loginForContent(); + const job = await apiJson<{ id?: string }>(session, '/api/tasks/tasks/', { + method: 'POST', + body: JSON.stringify({ + type: 'kolibri.core.content.tasks.deletechannel', + channel_id: channelId, + channel_name: channelName || channelId, + }), + }, 30000); + if (!job?.id) throw new Error('Kolibri no devolvió un id de job'); + return job.id; +} + +/** Diagnóstico ampliado: readiness + estado local. Lo consume /kolibri/preflight. + * checkReadiness() no lanza: siempre devuelve un diagnóstico, así que un Kolibri + * caído se refleja en los campos en lugar de romper la respuesta. + * + * Los bytes salen de SQLite, no del disco: sumar bytesAvailable da el mismo dato + * que recorrer content/storage y no bloquea el event loop. */ +export async function preflight(): Promise> { + const readiness = await checkReadiness(); + let installed: InstalledChannel[] = []; + try { installed = listInstalledChannels(); } catch { /* base ausente */ } + return { + ...readiness, + studioUrl: STUDIO_URL, + kolibriHome: KOLIBRI_HOME, + contentDir: CONTENT_DIR, + installedChannels: installed.length, + channels: installed, + bytesAvailable: installed.reduce((sum, c) => sum + c.bytesAvailable, 0), + bytesTotal: installed.reduce((sum, c) => sum + c.bytesTotal, 0), + }; +} + +/** Comprueba unas credenciales sin persistirlas. Lo usa POST /credentials/kolibri. */ +export async function verifyCredentials( + username: string, password: string, +): Promise<{ ok: boolean; canManageContent: boolean; username: string }> { + const session: KolibriSession = await login({ username, password }); + return { + ok: true, + canManageContent: session.canManageContent, + username: session.username, + }; +} + +export { apiFetch }; diff --git a/static/dashboard/sockets/kolibri.session.test.ts b/static/dashboard/sockets/kolibri.session.test.ts new file mode 100644 index 000000000..bc86127bc --- /dev/null +++ b/static/dashboard/sockets/kolibri.session.test.ts @@ -0,0 +1,279 @@ +// sockets/kolibri.session.test.ts +// +// Tests de los helpers PUROS del camino de Kolibri, en la línea de +// maps.socket.test.ts y rolling-log.test.ts: sin red, sin SQLite, sin Kolibri. +// Cubren justamente las trampas que hacen fallar el primer intento — nombres de +// cookie no estándar, rotación del token CSRF, percentage 0-1 vs 0-100, y el +// payload que Kolibri rechaza si se manda 'peer': null. +// +// Ejecutar: npm test (añade este fichero al script "test" de package.json) +// +// Importa SOLO de kolibri.session.ts y kolibri.map.ts. Ninguno de los dos arrastra +// jobs.ts, así que no se necesita el binario nativo de better-sqlite3 — el CI +// instala con `npm ci --ignore-scripts` y no lo compila. +/// +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { cookieValue, mergeCookies, matchesOrigin, KolibriApiError } from './kolibri.session'; +import { + mapPhase, mapPercent, normalizeUuid, buildTaskPayload, overallPercent, sampleSpeed, +} from './kolibri.map'; + +// ─── cookieValue ───────────────────────────────────────────────────────────── + +test('cookieValue encuentra la cookie CSRF de Kolibri, que no se llama csrftoken', () => { + const setCookies = [ + 'kolibri_csrftoken=abc123; expires=Fri, 01 Jan 2027 00:00:00 GMT; Path=/; SameSite=Lax', + 'kolibri=sess789; expires=Fri, 01 Jan 2027 00:00:00 GMT; HttpOnly; Path=/', + ]; + assert.equal(cookieValue(setCookies, 'kolibri_csrftoken'), 'abc123'); + assert.equal(cookieValue(setCookies, 'kolibri'), 'sess789'); + // Los nombres de Django estándar NO existen en Kolibri: si alguien los busca, + // debe obtener null en lugar de un falso positivo. + assert.equal(cookieValue(setCookies, 'csrftoken'), null); + assert.equal(cookieValue(setCookies, 'sessionid'), null); +}); + +test('cookieValue tolera cabeceras raras', () => { + assert.equal(cookieValue([], 'kolibri'), null); + assert.equal(cookieValue(['sin-signo-igual'], 'kolibri'), null); + // Un valor con '=' dentro (base64) debe conservarse completo. + assert.equal(cookieValue(['kolibri=a=b=c; Path=/'], 'kolibri'), 'a=b=c'); +}); + +// ─── mergeCookies ──────────────────────────────────────────────────────────── + +test('mergeCookies aplica la rotación del token CSRF tras el login', () => { + // Django rota el token al autenticar: el valor nuevo debe ganar, o el primer + // POST posterior fallaría con 403. + const before = 'kolibri_csrftoken=viejo'; + const afterLogin = ['kolibri_csrftoken=nuevo; Path=/', 'kolibri=sesion; Path=/']; + const merged = mergeCookies(before, afterLogin); + assert.match(merged, /kolibri_csrftoken=nuevo/); + assert.doesNotMatch(merged, /viejo/); + assert.match(merged, /kolibri=sesion/); +}); + +test('mergeCookies conserva cookies previas no reemplazadas', () => { + const merged = mergeCookies('otra=conservada; kolibri_csrftoken=v1', ['kolibri_csrftoken=v2']); + assert.match(merged, /otra=conservada/); + assert.match(merged, /kolibri_csrftoken=v2/); +}); + +test('mergeCookies parte de vacío sin generar basura', () => { + const merged = mergeCookies('', ['kolibri=s; HttpOnly']); + assert.equal(merged, 'kolibri=s'); +}); + +// ─── mapPhase ──────────────────────────────────────────────────────────────── + +test('mapPhase cubre los nueve estados de Kolibri', () => { + assert.equal(mapPhase('PENDING'), 'queued'); + assert.equal(mapPhase('SCHEDULED'), 'queued'); + assert.equal(mapPhase('QUEUED'), 'queued'); + assert.equal(mapPhase('SELECTED'), 'queued'); + assert.equal(mapPhase('RUNNING'), 'downloading'); + assert.equal(mapPhase('COMPLETED'), 'done'); + assert.equal(mapPhase('FAILED'), 'error'); + assert.equal(mapPhase('CANCELING'), 'canceled'); + assert.equal(mapPhase('CANCELED'), 'canceled'); +}); + +test('mapPhase degrada un estado desconocido sin romper', () => { + assert.equal(mapPhase('ALGO_NUEVO'), 'processing'); +}); + +// ─── mapPercent ────────────────────────────────────────────────────────────── + +test('mapPercent convierte el float 0-1 de Kolibri a 0-100 entero', () => { + // Es la confusión más fácil de cometer: percentage NO es 0-100. + assert.equal(mapPercent(0), 0); + assert.equal(mapPercent(0.5), 50); + assert.equal(mapPercent(0.333), 33); + assert.equal(mapPercent(1), 100); +}); + +test('mapPercent devuelve -1 (indeterminado) cuando no hay dato', () => { + assert.equal(mapPercent(null), -1); + assert.equal(mapPercent(undefined), -1); + assert.equal(mapPercent(NaN), -1); +}); + +test('mapPercent acota valores fuera de rango', () => { + assert.equal(mapPercent(1.5), 100); + assert.equal(mapPercent(-0.2), 0); +}); + +// ─── normalizeUuid ─────────────────────────────────────────────────────────── + +test('normalizeUuid acepta hex de 32 y también con guiones', () => { + const hex = '95a52b386f2c485cb97dd60901674a98'; + assert.equal(normalizeUuid(hex), hex); + assert.equal(normalizeUuid('95A52B386F2C485CB97DD60901674A98'), hex); + assert.equal(normalizeUuid('95a52b38-6f2c-485c-b97d-d60901674a98'), hex); + assert.equal(normalizeUuid(` ${hex} `), hex); +}); + +test('normalizeUuid rechaza tokens: hay que resolverlos antes de encolar', () => { + // Un token proquint no es un channel_id. Pasarlo tal cual acabaría en un 404 + // del descargador sin mensaje claro. + assert.equal(normalizeUuid('bisan-sukod'), null); + assert.equal(normalizeUuid('bisansukod'), null); + assert.equal(normalizeUuid(''), null); + assert.equal(normalizeUuid('zz'.repeat(16)), null); + assert.equal(normalizeUuid(undefined), null); + assert.equal(normalizeUuid(42), null); +}); + +// ─── buildTaskPayload ──────────────────────────────────────────────────────── + +const CH = '95a52b386f2c485cb97dd60901674a98'; + +test('buildTaskPayload usa remoteimport y siempre manda channel_name', () => { + const p = buildTaskPayload({ channelId: CH, channelName: 'Khan Academy' }); + assert.equal(p.type, 'kolibri.core.content.tasks.remoteimport'); + assert.equal(p.channel_id, CH); + // Obligatorio: sin él, Kolibri responde 400 aunque solo sea decorativo. + assert.equal(p.channel_name, 'Khan Academy'); + assert.equal(p.fail_on_error, true); +}); + +test('buildTaskPayload NUNCA incluye peer', () => { + // 'peer' es PrimaryKeyRelatedField sin allow_null: mandar null da 400 + // "This field may not be null". Hay que omitir la clave. + const p = buildTaskPayload({ channelId: CH, channelName: 'x' }); + assert.equal('peer' in p, false); +}); + +test('buildTaskPayload omite node_ids cuando no hay selección', () => { + // Distinción crítica de Kolibri: node_ids=[] significa CERO NODOS, mientras que + // ausente significa TODO EL CANAL. Mandar una lista vacía descargaría nada con + // éxito aparente. + const p = buildTaskPayload({ channelId: CH, channelName: 'x', nodeIds: [] }); + assert.equal('node_ids' in p, false); + + const q = buildTaskPayload({ channelId: CH, channelName: 'x', nodeIds: undefined }); + assert.equal('node_ids' in q, false); +}); + +test('buildTaskPayload incluye la selección cuando existe', () => { + const nodes = ['aaaa1111bbbb2222cccc3333dddd4444']; + const p = buildTaskPayload({ channelId: CH, channelName: 'x', nodeIds: nodes }); + assert.deepEqual(p.node_ids, nodes); +}); + +test('buildTaskPayload solo manda all_thumbnails si se pide', () => { + const sin = buildTaskPayload({ channelId: CH, channelName: 'x' }); + assert.equal('all_thumbnails' in sin, false); + + const con = buildTaskPayload({ channelId: CH, channelName: 'x', allThumbnails: true }); + assert.equal(con.all_thumbnails, true); +}); + +test('buildTaskPayload omite exclude_node_ids vacío', () => { + const p = buildTaskPayload({ channelId: CH, channelName: 'x', excludeNodeIds: [] }); + assert.equal('exclude_node_ids' in p, false); +}); + +// ─── overallPercent ────────────────────────────────────────────────────────── + +test('overallPercent no toca el valor cuando hay un solo canal', () => { + assert.equal(overallPercent(1, 1, 42), 42); + assert.equal(overallPercent(1, 1, -1), -1); +}); + +test('overallPercent reparte la barra en franjas por canal', () => { + // Con 3 canales, el primero al 0% es 0 global y al 100% es 33 global; así la + // barra sube una sola vez en lugar de reiniciarse tres veces. + assert.equal(overallPercent(1, 3, 0), 0); + assert.equal(overallPercent(1, 3, 100), 33); + assert.equal(overallPercent(2, 3, 0), 33); + assert.equal(overallPercent(3, 3, 50), 83); +}); + +test('overallPercent se acota a 99: el 100 lo pone el final del runner', () => { + assert.equal(overallPercent(3, 3, 100), 99); +}); + +test('overallPercent propaga el indeterminado', () => { + assert.equal(overallPercent(2, 3, -1), -1); +}); + +// ─── sampleSpeed ───────────────────────────────────────────────────────────── + +test('sampleSpeed calcula bytes por segundo entre dos muestras', () => { + // 1 MiB en 2 s → ~524 288 B/s + assert.equal(sampleSpeed(0, 1048576, 1000, 3000), 524288); +}); + +test('sampleSpeed devuelve null sin avance, para no pisar la velocidad anterior', () => { + // Devolver 0 haría parpadear la UI a "0 B/s" en cada poll sin progreso. + assert.equal(sampleSpeed(1000, 1000, 0, 2000), null); + assert.equal(sampleSpeed(1000, 500, 0, 2000), null); +}); + +test('sampleSpeed no divide por cero con dos muestras simultáneas', () => { + const v = sampleSpeed(0, 100, 5000, 5000); + assert.ok(v !== null && Number.isFinite(v) && v > 0); +}); + +// ─── matchesOrigin ─────────────────────────────────────────────────────────── +// Decide si importcontent podrá resolver el origen: si no hay coincidencia se cae +// al fallback que llama a ifaddr, bloqueado por netlink bajo proot. + +const STUDIO = 'https://studio.learningequality.org'; + +test('matchesOrigin acepta la fila con y sin barra final', () => { + assert.equal(matchesOrigin([{ base_url: STUDIO }], STUDIO), true); + assert.equal(matchesOrigin([{ base_url: `${STUDIO}/` }], STUDIO), true); + // Y también si lo buscado trae la barra y lo almacenado no. + assert.equal(matchesOrigin([{ base_url: STUDIO }], `${STUDIO}/`), true); +}); + +test('matchesOrigin no depende del location_type: cualquier fila vale', () => { + // known_location_for_address() tampoco filtra por tipo, así que una 'static' + // creada por nosotros sirve igual que las 'reserved' que siembra IIAB. + assert.equal(matchesOrigin([{ base_url: STUDIO, nickname: 'K2Go content origin' }], STUDIO), true); +}); + +test('matchesOrigin encuentra la coincidencia entre varias filas', () => { + const rows = [ + { base_url: 'http://192.168.1.50:8080' }, + { base_url: 'https://kolibridataportal.learningequality.org' }, + { base_url: `${STUDIO}/` }, + ]; + assert.equal(matchesOrigin(rows, STUDIO), true); +}); + +test('matchesOrigin rechaza cuando no hay ninguna fila del origen', () => { + assert.equal(matchesOrigin([], STUDIO), false); + assert.equal(matchesOrigin([{ base_url: 'http://192.168.1.50:8080' }], STUDIO), false); + // Un prefijo no es una coincidencia. + assert.equal(matchesOrigin([{ base_url: 'https://studio.learningequality.org.evil.test' }], STUDIO), false); +}); + +test('matchesOrigin tolera filas sin base_url', () => { + assert.equal(matchesOrigin([{}, { base_url: undefined }, { base_url: STUDIO }], STUDIO), true); + assert.equal(matchesOrigin([{}, { base_url: undefined }], STUDIO), false); +}); + +// ─── KolibriApiError ───────────────────────────────────────────────────────── + +test('KolibriApiError distingue sesión caducada de otros fallos', () => { + // Django responde 403 (no 401) cuando la sesión murió y el CSRF ya no vale; + // ambos deben disparar el re-login del poll. + assert.equal(new KolibriApiError(401, 'x').isAuthExpired, true); + assert.equal(new KolibriApiError(403, 'x').isAuthExpired, true); + assert.equal(new KolibriApiError(404, 'x').isAuthExpired, false); + assert.equal(new KolibriApiError(500, 'x').isAuthExpired, false); + assert.equal(new KolibriApiError(503, 'x').isAuthExpired, false); +}); + +test('KolibriApiError conserva el status y es un Error', () => { + const e = new KolibriApiError(418, 'soy una tetera'); + assert.ok(e instanceof Error); + assert.equal(e.status, 418); + assert.equal(e.name, 'KolibriApiError'); + assert.match(e.message, /tetera/); +}); diff --git a/static/dashboard/sockets/kolibri.session.ts b/static/dashboard/sockets/kolibri.session.ts new file mode 100644 index 000000000..f84510a82 --- /dev/null +++ b/static/dashboard/sockets/kolibri.session.ts @@ -0,0 +1,426 @@ +// sockets/kolibri.session.ts — sesión autenticada contra la API de Kolibri +// +// Mismo patrón que getCalibreSession() en books.exec.ts: nos autenticamos contra un +// servicio local por HTTP y conservamos cookie + CSRF. Kolibri difiere de +// Calibre-Web en cuatro cosas que hacen fallar el primer intento si no se saben: +// +// 1. Las cookies NO son las estándar de Django: +// sesión → 'kolibri' (no 'sessionid') +// CSRF → 'kolibri_csrftoken' (no 'csrftoken') +// 2. Django ROTA el token CSRF al hacer login. Hay que releerlo después. +// 3. El login es JSON (no form-urlencoded como Calibre-Web) y devuelve +// 'can_manage_content', que es el permiso que de verdad hace falta para +// importar contenido: un usuario puede autenticarse y NO poder importar. +// 4. El viewset exige 'Referer' del mismo origen (csrf_protect). +// +// Además aquí vive el requisito de proot que no es obvio: 'importcontent' llama +// SIEMPRE a lookup_channel_listing_status(), que pasa por +// NetworkClient.discover_from_address(). Si no existe una NetworkLocation cuyo +// base_url coincida con el origen del contenido, ese camino cae al fallback de +// variaciones de URL, que invoca ifaddr.get_adapters() — y netlink está bloqueado +// bajo proot en Android >= 13, así que revienta tras decenas de segundos. +// +// En IIAB eso se resuelve sembrando filas 'reserved' con `kolibri manage shell`. +// No lo necesitamos: known_location_for_address() es +// NetworkLocation.objects.filter(base_url__in=candidates).first() +// y NO filtra por location_type. Una NetworkLocation 'static' creada por REST +// satisface el lookup igual, y StaticNetworkLocationViewSet es un ModelViewSet +// completo. Por eso ensureContentOrigin() puede hacerlo sin salir de HTTP. +import { getCredential } from './credentials'; + +export const KOLIBRI_BASE = process.env.K2GO_KOLIBRI_URL || 'http://127.0.0.1:8009'; +export const STUDIO_URL = process.env.K2GO_STUDIO_URL + || 'https://studio.learningequality.org'; + +const SESSION_COOKIE = 'kolibri'; +const CSRF_COOKIE = 'kolibri_csrftoken'; +const CSRF_HEADER = 'X-CSRFToken'; + +/** Loopback: generoso para el arranque de Django, corto para no colgar la UI. */ +const DEFAULT_TIMEOUT_MS = 8000; + +export interface KolibriSession { + /** Cabecera Cookie ya montada para reusar en cada petición. */ + cookie: string; + csrfToken: string; + username: string; + canManageContent: boolean; +} + +/** Error con la causa distinguible, para que las rutas devuelvan el status correcto: + * 'unreachable' → 503 (el servicio no está listo; problema de la capa de arranque) + * 'credentials' → 401 (usuario o contraseña incorrectos) + * 'permission' → 403 (autentica, pero no puede gestionar contenido) */ +export type KolibriAuthReason = 'unreachable' | 'credentials' | 'permission' | 'protocol'; + +export class KolibriAuthError extends Error { + readonly reason: KolibriAuthReason; + constructor(reason: KolibriAuthReason, message: string) { + super(message); + this.name = 'KolibriAuthError'; + this.reason = reason; + } +} + +/** Extrae el valor de una cookie de las cabeceras Set-Cookie de una respuesta. */ +export function cookieValue(setCookies: string[], name: string): string | null { + for (const raw of setCookies) { + const first = raw.split(';')[0]; + const eq = first.indexOf('='); + if (eq < 0) continue; + if (first.slice(0, eq).trim() === name) return first.slice(eq + 1).trim(); + } + return null; +} + +/** Fusiona pares nombre=valor en una sola cabecera Cookie, con el último ganando. + * Exportada porque es lógica pura y se testea sin red. */ +export function mergeCookies(existing: string, setCookies: string[]): string { + const jar = new Map(); + for (const part of existing.split(';')) { + const p = part.trim(); + if (!p) continue; + const eq = p.indexOf('='); + if (eq > 0) jar.set(p.slice(0, eq).trim(), p.slice(eq + 1).trim()); + } + for (const raw of setCookies) { + const first = raw.split(';')[0]; + const eq = first.indexOf('='); + if (eq > 0) jar.set(first.slice(0, eq).trim(), first.slice(eq + 1).trim()); + } + return [...jar.entries()].map(([k, v]) => `${k}=${v}`).join('; '); +} + +async function fetchWithTimeout( + url: string, + init: RequestInit = {}, + timeoutMs = DEFAULT_TIMEOUT_MS, +): Promise { + // AbortSignal.timeout existe en Node 18+; el rootfs corre Node 22. + return fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }); +} + +/** + * Autentica contra Kolibri y devuelve una sesión reutilizable. + * + * @param override credenciales explícitas (las usa el endpoint de validación antes + * de persistirlas); si se omite, se toman del almacén. + */ +export async function login( + override?: { username: string; password: string }, +): Promise { + const cred = override ?? getCredential('kolibri'); + + // 1. Sembrar la cookie CSRF. El viewset de sesión lleva @ensure_csrf_cookie, + // así que un GET basta. + let cookie = ''; + let csrfToken: string | null = null; + try { + const seed = await fetchWithTimeout(`${KOLIBRI_BASE}/api/auth/session/current/`); + const setCookies = seed.headers.getSetCookie(); + cookie = mergeCookies('', setCookies); + csrfToken = cookieValue(setCookies, CSRF_COOKIE); + } catch (e) { + throw new KolibriAuthError('unreachable', + `Kolibri no respondió en ${KOLIBRI_BASE}: ${e instanceof Error ? e.message : String(e)}`); + } + if (!csrfToken) { + throw new KolibriAuthError('protocol', + `Kolibri no devolvió la cookie ${CSRF_COOKIE}`); + } + + // 2. Login. JSON, con Referer del mismo origen (csrf_protect lo exige). + let res: Response; + try { + res = await fetchWithTimeout(`${KOLIBRI_BASE}/api/auth/session/`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Cookie: cookie, + [CSRF_HEADER]: csrfToken, + Referer: `${KOLIBRI_BASE}/`, + }, + body: JSON.stringify({ username: cred.username, password: cred.password }), + }); + } catch (e) { + throw new KolibriAuthError('unreachable', + `Kolibri cortó la conexión durante el login: ${e instanceof Error ? e.message : String(e)}`); + } + + if (res.status === 401 || res.status === 400) { + // 401 también aparece en "app mode" si allow_other_browsers_to_connect=False + // y no hay cookie de app-key. En un box servido por nginx no aplica, pero el + // mensaje lo menciona para que el diagnóstico no lleve horas. + throw new KolibriAuthError('credentials', + `Kolibri rechazó las credenciales de '${cred.username}' (HTTP ${res.status}). ` + + 'Si el dispositivo está en modo aplicación, revisa allow_other_browsers_to_connect.'); + } + if (!res.ok) { + throw new KolibriAuthError('protocol', `Login devolvió HTTP ${res.status}`); + } + + // 3. Django rota el token CSRF al hacer login: hay que releerlo o el primer + // POST posterior fallará con 403. + const loginCookies = res.headers.getSetCookie(); + cookie = mergeCookies(cookie, loginCookies); + csrfToken = cookieValue(loginCookies, CSRF_COOKIE) ?? csrfToken; + + if (!cookie.includes(`${SESSION_COOKIE}=`)) { + throw new KolibriAuthError('protocol', + `El login no devolvió la cookie de sesión '${SESSION_COOKIE}'`); + } + + let canManageContent = false; + let username = cred.username; + try { + const data = await res.json() as Record; + canManageContent = data.can_manage_content === true; + if (typeof data.username === 'string') username = data.username; + } catch { + // Cuerpo inesperado: no invalidamos la sesión, pero el permiso queda en false + // y el llamador decidirá. Mejor eso que asumir que sí puede. + } + + return { cookie, csrfToken, username, canManageContent }; +} + +/** Igual que login(), pero exige además el permiso de gestión de contenido. + * Es lo que usa el runner: sin can_manage_content, /api/tasks/ rechazará el job. */ +export async function loginForContent( + override?: { username: string; password: string }, +): Promise { + const session = await login(override); + if (!session.canManageContent) { + throw new KolibriAuthError('permission', + `El usuario '${session.username}' autentica pero no tiene can_manage_content, ` + + 'así que no puede importar contenido.'); + } + return session; +} + +/** Petición autenticada. Reinyecta cookie + CSRF + Referer en cada llamada. */ +export async function apiFetch( + session: KolibriSession, + pathname: string, + init: RequestInit = {}, + timeoutMs = DEFAULT_TIMEOUT_MS, +): Promise { + const headers: Record = { + Cookie: session.cookie, + Referer: `${KOLIBRI_BASE}/`, + Accept: 'application/json', + ...(init.headers as Record | undefined), + }; + const method = (init.method ?? 'GET').toUpperCase(); + if (method !== 'GET' && method !== 'HEAD') { + headers[CSRF_HEADER] = session.csrfToken; + if (init.body !== undefined && !headers['Content-Type']) { + headers['Content-Type'] = 'application/json'; + } + } + return fetchWithTimeout(`${KOLIBRI_BASE}${pathname}`, { ...init, headers }, timeoutMs); +} + +/** Error de una llamada a la API que llegó a recibir respuesta. Lleva el status para + * que el llamador distinga "sesión caducada" (401/403) de un fallo cualquiera. */ +export class KolibriApiError extends Error { + readonly status: number; + constructor(status: number, message: string) { + super(message); + this.name = 'KolibriApiError'; + this.status = status; + } + /** Django responde 403 (no 401) a una sesión caducada con CSRF ya inválido. */ + get isAuthExpired(): boolean { + return this.status === 401 || this.status === 403; + } +} + +/** apiFetch + parseo JSON + error legible. */ +export async function apiJson( + session: KolibriSession, + pathname: string, + init: RequestInit = {}, + timeoutMs = DEFAULT_TIMEOUT_MS, +): Promise { + const res = await apiFetch(session, pathname, init, timeoutMs); + const text = await res.text(); + if (!res.ok) { + throw new KolibriApiError(res.status, + `${init.method ?? 'GET'} ${pathname} → HTTP ${res.status}: ${text.slice(0, 400)}`); + } + if (!text.trim()) return undefined as unknown as T; + try { + return JSON.parse(text) as T; + } catch { + throw new Error(`${pathname} devolvió algo que no es JSON: ${text.slice(0, 200)}`); + } +} + +// ─── Origen de contenido (el prerrequisito de proot) ──────────────────────────── + +interface NetworkLocationRow { + id?: string; + base_url?: string; + nickname?: string; +} + +/** Variaciones que Kolibri considera equivalentes: con y sin barra final. */ +function urlVariants(url: string): string[] { + const trimmed = url.replace(/\/+$/, ''); + return [trimmed, `${trimmed}/`]; +} + +/** ¿Coincide alguna de las filas con el origen buscado? Pura, testeable sin red. */ +export function matchesOrigin(rows: NetworkLocationRow[], baseUrl: string): boolean { + const wanted = new Set(urlVariants(baseUrl)); + return rows.some((row) => { + if (!row.base_url) return false; + return wanted.has(row.base_url) || wanted.has(row.base_url.replace(/\/+$/, '')); + }); +} + +/** + * ¿Existe ya una NetworkLocation para el origen de contenido? SOLO LECTURA. + * + * Cuenta cualquier location_type, incluidas las 'reserved' que siembra IIAB: el + * lookup de Kolibri (known_location_for_address) tampoco filtra por tipo. + * + * @returns null si no se pudo determinar (Kolibri no respondió al listado). + */ +export async function hasContentOrigin( + session: KolibriSession, + baseUrl: string = STUDIO_URL, +): Promise { + try { + const rows = await apiJson( + session, '/api/discovery/networklocation/'); + const list = Array.isArray(rows) ? rows : (rows.results ?? []); + return matchesOrigin(list, baseUrl); + } catch { + return null; + } +} + +/** + * Garantiza que exista una NetworkLocation para el origen de contenido. ESCRIBE. + * + * Sin esto, 'importcontent' cae al fallback que llama a ifaddr y falla bajo proot. + * Lo llama el runner, no los endpoints de diagnóstico: un GET no debe mutar estado. + * + * @returns 'present' si ya existía, 'created' si la creó, 'failed' si no pudo + * (no lanza: el import puede funcionar igual si IIAB ya sembró y solo + * falló nuestra comprobación). + */ +export async function ensureContentOrigin( + session: KolibriSession, + baseUrl: string = STUDIO_URL, +): Promise<'present' | 'created' | 'failed'> { + // null (no se pudo listar) cae al POST: crear es idempotente en la práctica, + // porque un duplicado no rompe el lookup. + if (await hasContentOrigin(session, baseUrl) === true) return 'present'; + + try { + const res = await apiFetch(session, '/api/discovery/staticnetworklocation/', { + method: 'POST', + body: JSON.stringify({ + base_url: baseUrl, + nickname: 'K2Go content origin', + }), + }, 15000); + if (res.ok) return 'created'; + // 400 suele significar "ya existe" (unique) o validación del serializer. + return 'failed'; + } catch { + return 'failed'; + } +} + +// ─── Readiness ──────────────────────────────────────────────────────────────── + +export interface KolibriReadiness { + ready: boolean; + reachable: boolean; + authenticated: boolean; + canManageContent: boolean; + provisioned: boolean | null; + /** true presente, false ausente, null indeterminado. Solo se consulta, nunca + * se crea desde aquí: el runner es quien lo garantiza antes de importar. */ + contentOrigin: boolean | null; + version: string | null; + /** Motivos por los que ready es false, en lenguaje accionable. */ + blockers: string[]; + credentialOrigin: string; +} + +/** + * El "gate" que la capa de arranque puede sondear: mientras no devuelva + * ready=true, no tiene sentido lanzar jobs de contenido. + * + * No lanza excepciones y NO MUTA NADA: siempre devuelve un diagnóstico. Se puede + * sondear en bucle sin efectos secundarios. + */ +export async function checkReadiness(): Promise { + const out: KolibriReadiness = { + ready: false, + reachable: false, + authenticated: false, + canManageContent: false, + provisioned: null, + contentOrigin: null, + version: null, + blockers: [], + credentialOrigin: getCredential('kolibri').origin, + }; + + // 1. ¿Responde? /api/public/info no requiere autenticación y es barato. + try { + const info = await fetchWithTimeout(`${KOLIBRI_BASE}/api/public/info`, {}, 5000); + out.reachable = info.ok; + if (info.ok) { + const body = await info.json() as Record; + if (typeof body.kolibri_version === 'string') out.version = body.kolibri_version; + } else { + out.blockers.push(`Kolibri respondió HTTP ${info.status} en /api/public/info`); + } + } catch (e) { + out.blockers.push(`Kolibri no responde en ${KOLIBRI_BASE}`); + return out; // sin servicio no hay nada más que comprobar + } + + // 2. ¿Autentica y puede gestionar contenido? + let session: KolibriSession; + try { + session = await login(); + out.authenticated = true; + out.canManageContent = session.canManageContent; + if (!session.canManageContent) { + out.blockers.push( + `'${session.username}' autentica pero no tiene can_manage_content`); + } + } catch (e) { + const reason = e instanceof KolibriAuthError ? e.reason : 'protocol'; + out.blockers.push(reason === 'credentials' + ? 'Credenciales de Kolibri incorrectas (actualízalas en /credentials/kolibri)' + : `Login contra Kolibri falló: ${e instanceof Error ? e.message : String(e)}`); + return out; + } + + // 3. ¿Está provisionado el dispositivo? Sin esto la UI mostraría el asistente. + try { + const dev = await apiJson>(session, '/api/device/deviceinfo/'); + // El endpoint solo responde en un dispositivo provisionado; que conteste ya + // es la señal. Guardamos el nombre si viene, por diagnóstico. + out.provisioned = !!dev; + } catch { + out.provisioned = null; // no concluyente: no lo marcamos como bloqueador + } + + // 4. El prerrequisito de proot, en modo consulta. No es un bloqueador: el runner + // crea la fila si falta (ensureContentOrigin) antes de encolar, así que su + // ausencia aquí no impide arrancar. Se reporta para diagnóstico. + out.contentOrigin = await hasContentOrigin(session); + + out.ready = out.blockers.length === 0; + return out; +} diff --git a/tools/kolibri-preflight.sh b/tools/kolibri-preflight.sh new file mode 100644 index 000000000..c857395fb --- /dev/null +++ b/tools/kolibri-preflight.sh @@ -0,0 +1,473 @@ +#!/bin/sh +# kolibri-preflight.sh — diagnóstico de viabilidad para sembrar contenido de Kolibri +# dentro del proot de K2Go. +# +# Ejecútalo DENTRO del proot, en el dispositivo, antes de escribir o desplegar código. +# Solo lee: no importa contenido ni modifica estado, salvo que pases --seed-locations +# o --probe-import de forma explícita. +# +# Uso: +# sh kolibri-preflight.sh diagnóstico completo, salida legible +# sh kolibri-preflight.sh --json salida JSON en stdout (para automatizar) +# sh kolibri-preflight.sh --seed-locations además, siembra las NetworkLocations +# 'reserved' si faltan (escribe) +# sh kolibri-preflight.sh --probe-import ID además, mide el rendimiento real +# importando los metadatos de un canal +# +# Códigos de salida: +# 0 todo listo para sembrar contenido +# 1 hay bloqueadores (revisa las líneas FAIL) +# 2 error de uso o Kolibri no está instalado +# +# POSIX sh a propósito: el rootfs mínimo puede no traer bash en el PATH del servicio. + +set -u + +# ── Constantes del entorno IIAB/proot ──────────────────────────────────────── +KOLIBRI_HOME="${KOLIBRI_HOME:-/library/kolibri}" +KOLIBRI_BIN="$(command -v kolibri 2>/dev/null || echo /usr/bin/kolibri)" +STUDIO_URL="${STUDIO_URL:-https://studio.learningequality.org}" +KOLIBRI_PORT="${KOLIBRI_PORT:-8009}" +NGINX_PORT="${NGINX_PORT:-8085}" +DASH_PORT="${DASH_PORT:-4000}" + +JSON=0 +SEED=0 +PROBE="" + +while [ $# -gt 0 ]; do + case "$1" in + --json) JSON=1; shift ;; + --seed-locations) SEED=1; shift ;; + --probe-import) + [ $# -ge 2 ] || { echo "--probe-import requiere un channel_id" >&2; exit 2; } + PROBE="$2"; shift 2 ;; + -h|--help) sed -n '2,25p' "$0" | sed 's/^# \?//'; exit 0 ;; + *) echo "Argumento no reconocido: $1" >&2; exit 2 ;; + esac +done + +# ── Acumuladores ───────────────────────────────────────────────────────────── +FAILURES=0 +WARNINGS=0 +JSON_KV="" + +emit() { # emit NIVEL "mensaje" + [ "$JSON" -eq 1 ] && return 0 + case "$1" in + OK) printf ' \033[32mOK\033[0m %s\n' "$2" ;; + WARN) printf ' \033[33mWARN\033[0m %s\n' "$2" ;; + FAIL) printf ' \033[31mFAIL\033[0m %s\n' "$2" ;; + INFO) printf ' %s\n' "$2" ;; + esac +} +ok() { emit OK "$1"; } +warn() { emit WARN "$1"; WARNINGS=$((WARNINGS + 1)); } +fail() { emit FAIL "$1"; FAILURES=$((FAILURES + 1)); } +info() { emit INFO "$1"; } + +section() { + [ "$JSON" -eq 1 ] && return 0 + printf '\n\033[1m%s\033[0m\n' "$1" +} + +kv() { # kv clave valor_json — acumula pares para la salida JSON + if [ -z "$JSON_KV" ]; then JSON_KV="\"$1\":$2"; else JSON_KV="$JSON_KV,\"$1\":$2"; fi +} +kvs() { kv "$1" "\"$(printf '%s' "$2" | sed 's/\\/\\\\/g; s/"/\\"/g')\""; } + +have() { command -v "$1" >/dev/null 2>&1; } + +# Compara versiones semánticas: vge 0.19.5 0.19.4 → 0 (cierto) +vge() { + [ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -1)" = "$2" ] +} + +[ "$JSON" -eq 0 ] && cat </dev/null | tr -d '\r' | awk '{print $NF}')" +if [ -z "$KVER" ]; then + warn "No se pudo leer la versión de Kolibri" + KVER="unknown" +else + ok "Versión $KVER" +fi +kvs "version" "$KVER" + +if have dpkg; then + DEBVER="$(dpkg-query -W -f='${Version}' kolibri 2>/dev/null || echo '')" + [ -n "$DEBVER" ] && info "Paquete .deb: $DEBVER" && kvs "deb_version" "$DEBVER" +fi + +# Gate de versión: la resolución de TOKENS en importchannel llegó en 0.19.4. +# En versiones anteriores el token se pasa tal cual como channel_id y muere en un +# 404 sin mensaje claro. +if [ "$KVER" != "unknown" ]; then + if vge "$KVER" "0.19.4"; then + ok "Acepta tokens en 'importchannel network' (>= 0.19.4)" + kv "supports_tokens" "true" + else + warn "NO acepta tokens en 'importchannel network' (< 0.19.4): resuelve el UUID antes" + info "Resolución manual: $STUDIO_URL/api/public/v1/channels/lookup/" + kv "supports_tokens" "false" + fi +fi + +# ═════════════════════════════════════════════════════════════════════════════ +section "3. Flags de la CLI realmente disponibles" +# ═════════════════════════════════════════════════════════════════════════════ +# Se comprueban contra el --help real, no contra la versión: es la única prueba +# que no se puede equivocar. +IC_HELP="$(KOLIBRI_HOME="$KOLIBRI_HOME" "$KOLIBRI_BIN" manage importcontent --help 2>&1 || true)" +FLAGS_OK=1 +for flag in --fail-on-error --all-thumbnails --node_ids --exclude_node_ids --manifest; do + if printf '%s' "$IC_HELP" | grep -q -- "$flag"; then + ok "importcontent $flag" + else + fail "importcontent $flag NO existe en esta versión" + FLAGS_OK=0 + fi +done +kv "importcontent_flags_ok" "$([ "$FLAGS_OK" -eq 1 ] && echo true || echo false)" + +# --no_detect_manifest solo existe en el subparser 'disk', no en 'network'. +if printf '%s' "$IC_HELP" | grep -q -- '--no_detect_manifest'; then + info "--no_detect_manifest presente (solo aplica al subcomando 'disk')" +fi + +if KOLIBRI_HOME="$KOLIBRI_HOME" "$KOLIBRI_BIN" manage scanforcontent --help 2>&1 \ + | grep -q -- '--channel-import-mode'; then + ok "scanforcontent --channel-import-mode" +else + warn "scanforcontent --channel-import-mode no existe (solo afecta a la siembra desde disco)" +fi + +# ═════════════════════════════════════════════════════════════════════════════ +section "4. KOLIBRI_HOME y estado del dispositivo" +# ═════════════════════════════════════════════════════════════════════════════ +kvs "kolibri_home" "$KOLIBRI_HOME" +if [ -d "$KOLIBRI_HOME" ]; then + ok "$KOLIBRI_HOME existe" +else + fail "$KOLIBRI_HOME no existe" +fi + +DB="$KOLIBRI_HOME/db.sqlite3" +if [ -f "$DB" ]; then + ok "db.sqlite3 presente" +else + fail "No hay db.sqlite3 — el dispositivo no está provisionado" + info "IIAB provisiona en tiempo de instalación (facility 'Kolibri-in-a-Box')." +fi + +# Provisioning: IIAB ya corrió 'provisiondevice' en el build del rootfs. Si no, +# la UI de Kolibri redirige al asistente y la siembra no tiene sentido todavía. +if [ -f "$DB" ] && have sqlite3; then + PROV="$(sqlite3 "file:$DB?mode=ro" \ + "SELECT is_provisioned FROM device_devicesettings LIMIT 1;" 2>/dev/null || echo '')" + FACS="$(sqlite3 "file:$DB?mode=ro" \ + "SELECT COUNT(*) FROM kolibriauth_facility;" 2>/dev/null || echo '?')" + SUPER="$(sqlite3 "file:$DB?mode=ro" \ + "SELECT COUNT(*) FROM device_devicepermissions WHERE is_superuser=1;" 2>/dev/null || echo '?')" + case "$PROV" in + 1) ok "Dispositivo provisionado · facilities=$FACS · superusuarios=$SUPER" ;; + 0) fail "Dispositivo NO provisionado: la app mostraría el asistente inicial" ;; + *) warn "No se pudo leer is_provisioned (¿esquema distinto?)" ;; + esac + [ "$SUPER" = "0" ] && warn "No hay superusuario: crea uno con 'kolibri manage createsuperuser'" + kv "provisioned" "$([ "$PROV" = "1" ] && echo true || echo false)" + kv "facilities" "${FACS:-0}" + kv "superusers" "${SUPER:-0}" +fi + +# ═════════════════════════════════════════════════════════════════════════════ +section "5. options.ini bajo proot" +# ═════════════════════════════════════════════════════════════════════════════ +OPTS="$KOLIBRI_HOME/options.ini" +if [ -f "$OPTS" ]; then + ok "options.ini presente" + PORT_CFG="$(awk -F= '/^[[:space:]]*HTTP_PORT/ {gsub(/ /,"",$2); print $2}' "$OPTS" | head -1)" + ZC="$(awk -F= '/^[[:space:]]*ZEROCONF_ENABLED/ {gsub(/ /,"",$2); print $2}' "$OPTS" | head -1)" + [ -n "$PORT_CFG" ] && info "HTTP_PORT=$PORT_CFG" && kvs "http_port" "$PORT_CFG" + case "$ZC" in + False|false|0) + ok "ZEROCONF_ENABLED=False — esperado bajo proot (netlink bloqueado)" + info "Implica: sin descubrimiento de pares en LAN. La siembra es por red." + kv "zeroconf" "false" ;; + "") warn "ZEROCONF_ENABLED no está fijado; bajo proot debería ser False" + kv "zeroconf" "null" ;; + *) warn "ZEROCONF_ENABLED=$ZC — bajo proot puede provocar errores de ifaddr" + kv "zeroconf" "true" ;; + esac +else + warn "No hay options.ini en $KOLIBRI_HOME" +fi + +# ═════════════════════════════════════════════════════════════════════════════ +section "6. NetworkLocations 'reserved' — el bloqueador silencioso" +# ═════════════════════════════════════════════════════════════════════════════ +# 'importcontent network' llama SIEMPRE a lookup_channel_listing_status(), que pasa +# por NetworkClient.discover_from_address(). Sin las filas 'reserved' (Studio y KDP) +# eso cae al fallback de variaciones de URL, que invoca ifaddr.get_adapters() — el +# que falla en Android 15. Resultado: traceback sin envolver tras decenas de +# segundos de timeouts. +# +# Solo 'importchannel network ' es inmune (no toca NetworkClient). +NLDB="$KOLIBRI_HOME/networklocation.sqlite3" +RESERVED="?" +if [ ! -f "$NLDB" ]; then + warn "No existe networklocation.sqlite3 (¿Kolibri nunca arrancó?)" +elif ! have sqlite3; then + warn "Sin sqlite3 no se puede comprobar" +else + RESERVED="$(sqlite3 "file:$NLDB?mode=ro" \ + "SELECT COUNT(*) FROM discovery_networklocation WHERE location_type='reserved';" \ + 2>/dev/null || echo 0)" + if [ "${RESERVED:-0}" -gt 0 ]; then + ok "$RESERVED NetworkLocation(s) 'reserved' presentes" + sqlite3 "file:$NLDB?mode=ro" \ + "SELECT ' · '||base_url FROM discovery_networklocation WHERE location_type='reserved';" \ + 2>/dev/null | while IFS= read -r l; do info "$l"; done + elif [ "$SEED" -eq 1 ]; then + warn "Faltan; sembrando (--seed-locations)" + if KOLIBRI_HOME="$KOLIBRI_HOME" "$KOLIBRI_BIN" manage --skip-update --no-input shell -c \ + "from kolibri.core.discovery.tasks import _refresh_reserved_locations; _refresh_reserved_locations()" \ + >/dev/null 2>&1; then + RESERVED="$(sqlite3 "file:$NLDB?mode=ro" \ + "SELECT COUNT(*) FROM discovery_networklocation WHERE location_type='reserved';" 2>/dev/null || echo 0)" + if [ "${RESERVED:-0}" -gt 0 ]; then ok "Sembradas: $RESERVED"; else fail "La siembra no creó filas"; fi + else + fail "Falló la siembra de NetworkLocations" + fi + else + fail "NO hay NetworkLocations 'reserved' — 'importcontent network' fallará" + info "Siémbralas con: sh $0 --seed-locations" + info "O manualmente:" + info " KOLIBRI_HOME=$KOLIBRI_HOME $KOLIBRI_BIN manage --no-input shell -c \\" + info " \"from kolibri.core.discovery.tasks import _refresh_reserved_locations; _refresh_reserved_locations()\"" + fi +fi +kv "reserved_locations" "${RESERVED:-0}" + +# ═════════════════════════════════════════════════════════════════════════════ +section "7. Parche de ifaddr (Android 15)" +# ═════════════════════════════════════════════════════════════════════════════ +# Red de seguridad del punto 6: si el seed falla o se apunta a un --baseurl no +# sembrado, el fallback llama a ifaddr.get_adapters(), que en Android >= 13/15 +# lanza PermissionError porque netlink está bloqueado. +SRV_PY="/usr/lib/python3/dist-packages/kolibri/utils/server/__init__.py" +if [ ! -f "$SRV_PY" ]; then + warn "No se encontró $SRV_PY (¿instalación no-deb?)" + kv "ifaddr_patch" "null" +elif grep -q "try" "$SRV_PY" && grep -B3 "ifaddr.get_adapters()" "$SRV_PY" 2>/dev/null | grep -q "try:"; then + ok "ifaddr.get_adapters() está protegido por try/except" + kv "ifaddr_patch" "true" +else + warn "ifaddr.get_adapters() parece sin proteger — riesgo en Android 15" + info "Parche: roles/proot_services/files/kolibri-00-prevent_ip_error_out_due_A15_restrictions.patch" + kv "ifaddr_patch" "false" +fi + +# ═════════════════════════════════════════════════════════════════════════════ +section "8. Servicios y puertos" +# ═════════════════════════════════════════════════════════════════════════════ +probe() { # probe URL etiqueta + if have curl; then + code="$(curl -s -o /dev/null -w '%{http_code}' -m 8 "$1" 2>/dev/null || echo 000)" + elif have wget; then + code="$(wget -q -S -O /dev/null -T 8 "$1" 2>&1 | awk '/HTTP\//{c=$2} END{print c+0}')" + else + warn "Sin curl ni wget: no se puede probar $2"; return 1 + fi + case "$code" in + 2*|3*) ok "$2 responde ($code)"; return 0 ;; + 000) fail "$2 no responde"; return 1 ;; + *) warn "$2 responde $code"; return 0 ;; + esac +} + +if KOLIBRI_HOME="$KOLIBRI_HOME" "$KOLIBRI_BIN" status >/dev/null 2>&1; then + ok "Kolibri está corriendo" + kv "kolibri_running" "true" + info "Nota: importcontent escribe en db.sqlite3 durante la fase de anotación." + info "El lock de SQLite es un spin-loop; para canales grandes considera pdsm stop kolibri." +else + warn "Kolibri no está corriendo (la siembra funciona igual: la CLI no lo necesita)" + kv "kolibri_running" "false" +fi + +probe "http://127.0.0.1:$KOLIBRI_PORT/api/public/info" "Kolibri :$KOLIBRI_PORT" +probe "http://127.0.0.1:$NGINX_PORT/kolibri/" "nginx :$NGINX_PORT/kolibri/" +probe "http://127.0.0.1:$DASH_PORT/api/kiwix/jobs" "dash-node :$DASH_PORT" + +# ═════════════════════════════════════════════════════════════════════════════ +section "9. Conectividad con Kolibri Studio" +# ═════════════════════════════════════════════════════════════════════════════ +if probe "$STUDIO_URL/api/public/info" "Studio ($STUDIO_URL)"; then + kv "studio_reachable" "true" +else + kv "studio_reachable" "false" + info "Sin Studio no hay siembra online. Alternativa: importar desde disco/USB." +fi + +# ═════════════════════════════════════════════════════════════════════════════ +section "10. Espacio en disco" +# ═════════════════════════════════════════════════════════════════════════════ +CONTENT_DIR="$KOLIBRI_HOME/content" +MEASURE="$CONTENT_DIR" +while [ -n "$MEASURE" ] && [ ! -d "$MEASURE" ]; do MEASURE="$(dirname "$MEASURE")"; done +AVAIL_KB="$(df -Pk "$MEASURE" 2>/dev/null | awk 'NR==2{print $4}')" +if [ -n "${AVAIL_KB:-}" ]; then + AVAIL_MB=$((AVAIL_KB / 1024)) + if [ "$AVAIL_MB" -lt 500 ]; then fail "Solo ${AVAIL_MB} MB libres" + elif [ "$AVAIL_MB" -lt 2048 ]; then warn "${AVAIL_MB} MB libres — suficiente solo para selecciones pequeñas" + else ok "${AVAIL_MB} MB libres" + fi + kv "free_mb" "$AVAIL_MB" + info "Referencia: African Storybook Library completo son ~8.300 MB." + info "Para un teléfono, selecciona subárboles con --node_ids." +else + warn "No se pudo medir el espacio libre" +fi + +if [ -d "$CONTENT_DIR/storage" ]; then + USED_KB="$(du -sk "$CONTENT_DIR/storage" 2>/dev/null | awk '{print $1}')" + info "Contenido ya presente: $((${USED_KB:-0} / 1024)) MB" + kv "content_used_mb" "$((${USED_KB:-0} / 1024))" +fi + +# ═════════════════════════════════════════════════════════════════════════════ +section "11. Canales ya instalados" +# ═════════════════════════════════════════════════════════════════════════════ +if [ -f "$DB" ] && have sqlite3; then + CH_COUNT="$(sqlite3 "file:$DB?mode=ro" \ + "SELECT COUNT(*) FROM content_channelmetadata;" 2>/dev/null || echo 0)" + if [ "${CH_COUNT:-0}" -eq 0 ]; then + info "Ningún canal instalado — es el estado que quieres cambiar" + else + ok "$CH_COUNT canal(es) instalado(s)" + # available se marca de golpe al final del import, así que aquí sí es fiable. + sqlite3 "file:$DB?mode=ro" <<'SQL' 2>/dev/null | while IFS='|' read -r n avail tot; do +.mode list +.separator | +SELECT cm.name, + (SELECT COUNT(*) FROM content_localfile lf WHERE lf.available=1 AND lf.id IN ( + SELECT DISTINCT f.local_file_id FROM content_file f + JOIN content_contentnode cn ON cn.id=f.contentnode_id + WHERE cn.channel_id=cm.id)), + (SELECT COUNT(*) FROM content_localfile lf WHERE lf.id IN ( + SELECT DISTINCT f.local_file_id FROM content_file f + JOIN content_contentnode cn ON cn.id=f.contentnode_id + WHERE cn.channel_id=cm.id)) +FROM content_channelmetadata cm; +SQL + info "· $n — $avail/$tot ficheros disponibles" + done + fi + kv "channels_installed" "${CH_COUNT:-0}" +fi + +# ═════════════════════════════════════════════════════════════════════════════ +if [ -n "$PROBE" ]; then +section "12. Prueba real: importar metadatos de $PROBE" +# ═════════════════════════════════════════════════════════════════════════════ +# Solo los metadatos (importchannel), que son 1-50 MB. Mide latencia real de red +# y confirma que el camino completo funciona sin comprometer GB de descarga. + case "$PROBE" in + [0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]) ;; + *) fail "'$PROBE' no es un UUID hex de 32 sin guiones"; PROBE="" ;; + esac + if [ -n "$PROBE" ]; then + T0="$(date +%s)" + if KOLIBRI_HOME="$KOLIBRI_HOME" timeout 600 "$KOLIBRI_BIN" manage \ + --skip-update --no-input importchannel network "$PROBE" \ + --baseurl "$STUDIO_URL" >/tmp/kpf_probe.log 2>&1; then + T1="$(date +%s)" + ok "importchannel completado en $((T1 - T0))s" + kv "probe_seconds" "$((T1 - T0))" + CHDB="$CONTENT_DIR/databases/$PROBE.sqlite3" + if [ -f "$CHDB" ] && have sqlite3; then + BYTES="$(sqlite3 "file:$CHDB?mode=ro" \ + "SELECT COALESCE(SUM(lf.file_size),0) FROM content_localfile lf WHERE lf.id IN ( + SELECT DISTINCT f.local_file_id FROM content_file f + JOIN content_contentnode cn ON cn.id=f.contentnode_id + WHERE cn.channel_id='$PROBE');" 2>/dev/null || echo 0)" + info "El contenido completo de este canal pesa $((BYTES / 1048576)) MB" + kv "probe_channel_mb" "$((BYTES / 1048576))" + fi + else + fail "importchannel falló (código $?) — revisa /tmp/kpf_probe.log" + tail -5 /tmp/kpf_probe.log 2>/dev/null | while IFS= read -r l; do info "$l"; done + fi + fi +fi + +# ═════════════════════════════════════════════════════════════════════════════ +# Veredicto +# ═════════════════════════════════════════════════════════════════════════════ +kv "failures" "$FAILURES" +kv "warnings" "$WARNINGS" +kv "ready" "$([ "$FAILURES" -eq 0 ] && echo true || echo false)" + +if [ "$JSON" -eq 1 ]; then + printf '{%s}\n' "$JSON_KV" +else + printf '\n═══════════════════════════════════════════════════════════════════\n' + if [ "$FAILURES" -eq 0 ]; then + printf ' \033[32mLISTO\033[0m — %s advertencia(s), ningún bloqueador.\n' "$WARNINGS" + printf ' Comando canónico de siembra:\n\n' + printf ' env KOLIBRI_HOME=%s \\\n' "$KOLIBRI_HOME" + printf ' %s manage --skip-update --no-input \\\n' "$KOLIBRI_BIN" + printf ' importchannel network --baseurl %s\n\n' "$STUDIO_URL" + printf ' env KOLIBRI_HOME=%s \\\n' "$KOLIBRI_HOME" + printf ' %s manage --skip-update --no-input \\\n' "$KOLIBRI_BIN" + printf ' importcontent --fail-on-error --all-thumbnails \\\n' + printf ' --node_ids network --timeout 30\n' + else + printf ' \033[31mBLOQUEADO\033[0m — %s fallo(s), %s advertencia(s).\n' "$FAILURES" "$WARNINGS" + printf ' Resuelve las líneas FAIL antes de desplegar el runner.\n' + fi + printf '═══════════════════════════════════════════════════════════════════\n' +fi + +[ "$FAILURES" -eq 0 ] || exit 1 +exit 0