Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/catalog.ts9 * Module : server10 * Repository : https://git.spboucher.ai/maclustr-vision11 * Project Website : https://camera.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Catalogue : réconciliation fichiers ↔ base au démarrage, plages enregistrées et trous.43import fs from 'node:fs';44import path from 'node:path';45import type { Config } from './config.ts';46import { addEvent, type DB } from './db.ts';47import { logger } from './log.ts';48import { probe, sha256File } from './media.ts';49import { parseStamp, verifyVolume } from './storage.ts';5051const log = logger('catalog');5253function walk(dir: string, out: string[], root: string): void {54 let entries: fs.Dirent[] = [];55 try {56 entries = fs.readdirSync(dir, { withFileTypes: true });57 } catch {58 return;59 }60 for (const e of entries) {61 const p = path.join(dir, e.name);62 if (e.isDirectory()) walk(p, out, root);63 else if (e.isFile() && e.name.endsWith('.mkv')) out.push(path.relative(root, p));64 }65}6667/** Au démarrage : segments catalogués sans fichier → « missing » ; fichiers orphelins → inscrits ; restes de copie supprimés. */68export async function reconcile(cfg: Config, db: DB, cameraIds: string[]): Promise<{ missing: number; adopted: number }> {69 if (!verifyVolume(cfg).ok) return { missing: 0, adopted: 0 };70 let missing = 0;71 let adopted = 0;72 for (const cam of cameraIds) {73 const onDisk: string[] = [];74 walk(path.join(cfg.archiveDir, cam), onDisk, cfg.archiveDir);75 const diskSet = new Set(onDisk);76 const rows = db.prepare("SELECT id, rel_path, state FROM segments WHERE camera_id = ?").all(cam) as { id: number; rel_path: string; state: string }[];77 const known = new Set(rows.map((r) => r.rel_path));78 for (const r of rows) {79 if (!diskSet.has(r.rel_path) && r.state !== 'missing') {80 db.prepare("UPDATE segments SET state = 'missing' WHERE id = ?").run(r.id);81 missing++;82 }83 }84 for (const rel of onDisk) {85 if (known.has(rel)) continue;86 const abs = path.join(cfg.archiveDir, rel);87 const startMs = parseStamp(path.basename(rel));88 const p = startMs !== null ? await probe(cfg, abs) : null;89 if (!p || startMs === null || p.durationMs < 500) continue;90 db.prepare(91 "INSERT INTO segments (camera_id, start_ms, end_ms, duration_ms, codec, width, height, has_audio, size_bytes, rel_path, state, sha256, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'recovered', ?, ?) ON CONFLICT(rel_path) DO NOTHING",92 ).run(cam, startMs, startMs + p.durationMs, p.durationMs, p.codec, p.width, p.height, p.hasAudio ? 1 : 0, p.sizeBytes, rel, await sha256File(abs), Date.now());93 adopted++;94 }95 }96 if (missing || adopted) {97 log.warn('réconciliation', { missing, adopted });98 addEvent(db, { type: 'catalog_reconciled', severity: missing ? 'warning' : 'info', message: `Réconciliation du catalogue : ${missing} segment(s) manquant(s), ${adopted} fichier(s) réinscrit(s)`, data: { missing, adopted } });99 }100 return { missing, adopted };101}102103export type Range = { startMs: number; endMs: number };104105/** Fusionne les segments en plages continues (tolérance 2,5 s) et en déduit les trous. */106export function coverage(db: DB, cameraId: string, fromMs: number, toMs: number, toleranceMs = 2500): { ranges: Range[]; gaps: Range[]; segments: number; bytes: number } {107 const rows = db108 .prepare("SELECT start_ms, end_ms, size_bytes FROM segments WHERE camera_id = ? AND end_ms > ? AND start_ms < ? AND state IN ('archived','recovered') ORDER BY start_ms")109 .all(cameraId, fromMs, toMs) as { start_ms: number; end_ms: number; size_bytes: number }[];110 const ranges: Range[] = [];111 let bytes = 0;112 for (const r of rows) {113 bytes += r.size_bytes;114 const last = ranges[ranges.length - 1];115 if (last && r.start_ms - last.endMs <= toleranceMs) last.endMs = Math.max(last.endMs, r.end_ms);116 else ranges.push({ startMs: r.start_ms, endMs: r.end_ms });117 }118 const gaps: Range[] = [];119 for (let i = 1; i < ranges.length; i++) gaps.push({ startMs: ranges[i - 1].endMs, endMs: ranges[i].startMs });120 return { ranges, gaps, segments: rows.length, bytes };121}122