Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/core.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// vision-core : service permanent (passerelle go2rtc + NVR + rétention + supervision).43// Indépendant de l'API et de tout navigateur : l'enregistrement continue quoi qu'il arrive côté interface.44import crypto from 'node:crypto';45import fs from 'node:fs';46import http from 'node:http';47import path from 'node:path';48import { inSchedule, listCameras, loadRegistry, syncCameras, type Camera } from './cameras.ts';49import { reconcile } from './catalog.ts';50import { ensureDirs, gitCommit, loadConfig } from './config.ts';51import { addEvent, getSetting, openAndMigrate, setSetting } from './db.ts';52import { Go2rtc } from './go2rtc.ts';53import { logger } from './log.ts';54import { checkCameras, sampleMetrics } from './monitor.ts';55import { inspect, ptzMove, ptzStop } from './onvif.ts';56import { controlToken } from './control.ts';57import { MotionDetector, saveMotionImage, type MotionHit } from './motion.ts';58import { apnsConfigured, sendPush } from './push.ts';59import { CameraRecorder } from './recorder.ts';60import { startRelay } from './relay.ts';61import { housekeeping, runRetention } from './retention.ts';62import { dirSizeBytes, verifyVolume } from './storage.ts';6364const log = logger('core');65const cfg = loadConfig();66ensureDirs(cfg);67const db = openAndMigrate(cfg);68const registry = loadRegistry(cfg);69syncCameras(db, registry);7071let cams: Camera[] = listCameras(db, registry);72const go2rtc = new Go2rtc(cfg, () => cams);73const recorders = new Map<string, CameraRecorder>();74const detectors = new Map<string, MotionDetector>();75let shuttingDown = false;76let archiveOk = true;77let spoolFull = false;78const GB = 1024 ** 3;7980async function discoverCapabilities(): Promise<void> {81 for (const cam of cams) {82 try {83 const info = await inspect(cam);84 db.prepare('UPDATE cameras SET model = ?, firmware = ?, capabilities = ?, updated_ms = ? WHERE id = ?').run(85 [info.manufacturer, info.model].filter(Boolean).join(' ') || null,86 info.firmware,87 JSON.stringify({ ptz: info.ptz, audio: info.audio, ptzProfileToken: info.ptzProfileToken, profiles: info.profiles }),88 Date.now(),89 cam.id,90 );91 log.info('capacités ONVIF relevées', { cam: cam.id, model: info.model, ptz: info.ptz, audio: info.audio });92 } catch (e: any) {93 log.warn('ONVIF indisponible', { cam: cam.id, err: String(e?.message || e) });94 }95 }96}9798function heartbeat(): void {99 setSetting(db, 'core_heartbeat', {100 tsMs: Date.now(),101 pid: process.pid,102 startedMs: startedMs,103 version: cfg.version,104 commit: gitCommit(),105 go2rtc: { running: go2rtc.running, restarts: go2rtc.restartCount, startedMs: go2rtc.startedAt },106 archiveOk,107 spoolFull,108 });109}110const startedMs = Date.now();111112async function reconcileRecorders(): Promise<void> {113 cams = listCameras(db, registry);114 const suspended = getSetting(db, 'recording_suspended', false) || spoolFull;115 const now = new Date();116 for (const cam of cams) {117 let rec = recorders.get(cam.id);118 if (!rec) {119 rec = new CameraRecorder(cfg, db, cam);120 recorders.set(cam.id, rec);121 }122 rec.cam = cam;123 const want = cam.recordEnabled && !suspended && inSchedule(cam.schedule, now, cfg.timezone);124 const st = rec.currentState;125 if (want) {126 if ((st === 'recording' || st === 'starting') && rec.audio !== cam.recordAudio) await rec.restart('changement du réglage audio');127 else if (st === 'stopped' || st === 'suspended') {128 rec.markStartReference();129 rec.start();130 }131 } else if (st !== 'stopped' && st !== 'suspended') {132 await rec.stop(suspended ? 'enregistrement suspendu' : 'désactivé ou hors horaire');133 if (suspended) db.prepare("UPDATE camera_state SET recorder_state = 'suspended', updated_ms = ? WHERE camera_id = ?").run(Date.now(), cam.id);134 }135 rec.tick();136 }137}138139const clock = (ms: number) => new Intl.DateTimeFormat('fr-CA', { timeZone: cfg.timezone, hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' }).format(ms).replace(/ h | min /g, ':').replace(/ s$/, '');140141function onMotion(hit: MotionHit, notify: boolean): void {142 void saveMotionImage(cfg, db, hit);143 if (!notify) return;144 const cam = cams.find((c) => c.id === hit.cameraId);145 void sendPush(cfg, db, { kind: 'motion', title: `Mouvement — ${cam?.name || hit.cameraId}`, body: clock(hit.tsMs), cameraId: hit.cameraId, tsMs: hit.tsMs, eventId: hit.eventId }).catch((e) => log.warn('notification', { err: String(e?.message || e) }));146}147148/** Un analyseur par caméra dont la détection est activée et qui est joignable. */149function reconcileDetectors(): void {150 for (const cam of cams) {151 let det = detectors.get(cam.id);152 if (!det) {153 det = new MotionDetector(cfg, db, cam, onMotion);154 detectors.set(cam.id, det);155 }156 det.configure(cam);157 if (cam.motionEnabled) det.start();158 else if (det.running) det.stop();159 det.tick();160 }161}162163/** Alertes système (caméra hors ligne, événements critiques) relayées aux appareils qui les demandent. */164const SYSTEM_PUSH_TYPES = new Set(['camera_offline', 'camera_online', 'recording_stalled', 'recording_suspended', 'archive_unavailable', 'spool_full', 'key_rotated']);165function pushSystemEvents(): void {166 if (!apnsConfigured(cfg)) return;167 const last = getSetting<number>(db, 'push_last_event_id', -1);168 const maxRow = db.prepare('SELECT COALESCE(MAX(id), 0) AS m FROM events').get() as { m: number };169 if (last < 0) return setSetting(db, 'push_last_event_id', maxRow.m); // premier passage : ne pas rejouer l'historique170 const rows = db.prepare("SELECT id, ts_ms, camera_id, type, severity, message FROM events WHERE id > ? AND type != 'motion' ORDER BY id LIMIT 20").all(last) as Record<string, any>[];171 if (maxRow.m !== last) setSetting(db, 'push_last_event_id', maxRow.m);172 for (const e of rows) {173 if (!SYSTEM_PUSH_TYPES.has(e.type) && e.severity !== 'critical') continue;174 if (Date.now() - e.ts_ms > 10 * 60000) continue;175 const cam = cams.find((c) => c.id === e.camera_id);176 void sendPush(cfg, db, { kind: 'system', title: cam ? `${cam.name}` : 'MacLustr Vision', body: e.message, cameraId: e.camera_id, tsMs: e.ts_ms, eventId: e.id }).catch(() => {});177 }178}179180async function slowLoop(): Promise<void> {181 // identité et disponibilité de l'archive182 const vol = verifyVolume(cfg);183 if (!vol.ok && archiveOk) {184 archiveOk = false;185 addEvent(db, { type: 'archive_unavailable', severity: 'critical', message: `Archive indisponible (${vol.reason}) : les segments restent dans le tampon local borné` });186 } else if (vol.ok && !archiveOk) {187 archiveOk = true;188 addEvent(db, { type: 'archive_restored', severity: 'info', message: 'Archive de nouveau disponible : archivage du tampon repris' });189 }190 // tampon borné191 const spool = dirSizeBytes(cfg.spoolDir);192 if (!spoolFull && spool > cfg.retention.spoolMaxGB * GB) {193 spoolFull = true;194 addEvent(db, { type: 'spool_full', severity: 'critical', message: `Tampon local plein (${(spool / GB).toFixed(1)} Go) : enregistrement arrêté pour ne pas remplir le disque système` });195 } else if (spoolFull && spool < cfg.retention.spoolMaxGB * GB * 0.5) {196 spoolFull = false;197 addEvent(db, { type: 'spool_ok', severity: 'info', message: 'Tampon local revenu sous le seuil : enregistrement repris' });198 }199 try {200 runRetention(cfg, db);201 } catch (e: any) {202 log.error('rétention', { err: String(e?.message || e) });203 }204 const api = getSetting<{ pid?: number; tsMs?: number }>(db, 'api_heartbeat', {});205 await sampleMetrics(cfg, db, api.pid && api.tsMs && Date.now() - api.tsMs < 120000 ? [api.pid] : []);206 if (!(await go2rtc.healthy()) && go2rtc.running && Date.now() - go2rtc.startedAt > 30000) {207 log.error('go2rtc ne répond plus, relance');208 addEvent(db, { type: 'gateway_restart', severity: 'warning', message: 'Passerelle vidéo sans réponse : relance' });209 await go2rtc.restart();210 }211}212213async function main(): Promise<void> {214 log.info('démarrage', { version: cfg.version, commit: gitCommit(), cameras: cams.map((c) => c.id) });215 addEvent(db, { type: 'service_start', message: `vision-core démarré (version ${cfg.version})` });216 // relais locaux vers les caméras (la cible suit l'adresse courante de la caméra, même après un changement DHCP)217 for (const c of cams) {218 const cur = () => cams.find((x) => x.id === c.id) || null;219 startRelay(c.relayRtspPort, () => {220 const x = cur();221 return x ? { host: x.effectiveHost, port: x.rtspPort } : null;222 });223 startRelay(c.relayOnvifPort, () => {224 const x = cur();225 return x ? { host: x.effectiveHost, port: x.onvifPort } : null;226 });227 }228 await go2rtc.start();229 for (let i = 0; i < 40 && !(await go2rtc.healthy()); i++) await new Promise((r) => setTimeout(r, 250));230 const rec = await reconcile(cfg, db, cams.map((c) => c.id));231 log.info('catalogue réconcilié', rec);232 void discoverCapabilities();233 startControl();234 fs.writeFileSync(path.join(cfg.dataDir, 'core.pid'), String(process.pid));235 heartbeat();236237 const guard = (name: string, fn: () => Promise<unknown> | unknown) => async () => {238 if (shuttingDown) return;239 try {240 await fn();241 } catch (e: any) {242 log.error(`boucle ${name}`, { err: String(e?.stack || e) });243 }244 };245 let busyFast = false;246 setInterval(247 guard('enregistreurs', async () => {248 if (busyFast) return;249 busyFast = true;250 try {251 await reconcileRecorders();252 reconcileDetectors();253 pushSystemEvents();254 heartbeat();255 } finally {256 busyFast = false;257 }258 }),259 5000,260 );261 setInterval(262 guard('caméras', async () => {263 const changed = await checkCameras(db, cams);264 if (changed.length) {265 cams = listCameras(db, registry);266 await go2rtc.restart();267 }268 }),269 15000,270 );271 setInterval(guard('lente', slowLoop), 60000);272 setInterval(guard('ménage', () => housekeeping(cfg, db)), 10 * 60000);273 setInterval(guard('onvif', discoverCapabilities), 6 * 3600000);274 await guard('caméras', () => checkCameras(db, cams))();275 await guard('enregistreurs', reconcileRecorders)();276 await guard('lente', slowLoop)();277 housekeeping(cfg, db);278}279280/**281 * Canal de commande local (127.0.0.1) : l'API tourne sous PM2, où macOS bloque l'accès au réseau local ;282 * les commandes PTZ sont donc exécutées ici. Jeton dérivé du secret serveur, destinations limitées au registre.283 */284const ptzTimers = new Map<string, NodeJS.Timeout>();285function startControl(): void {286 const token = Buffer.from(controlToken(cfg));287 const server = http.createServer(async (req, res) => {288 const reply = (status: number, body: unknown) => {289 res.writeHead(status, { 'Content-Type': 'application/json' });290 res.end(JSON.stringify(body));291 };292 try {293 const got = Buffer.from(String(req.headers.authorization || '').replace(/^Bearer /, ''));294 if (got.length !== token.length || !crypto.timingSafeEqual(got, token)) return reply(401, { error: 'unauthorized' });295 if (req.method !== 'POST' || req.url !== '/ptz') return reply(404, { error: 'not_found' });296 const chunks: Buffer[] = [];297 let size = 0;298 for await (const c of req) {299 size += c.length;300 if (size > 2048) return reply(413, { error: 'too_large' });301 chunks.push(c);302 }303 const b = JSON.parse(Buffer.concat(chunks).toString('utf8'));304 const cam = cams.find((c) => c.id === b.cameraId);305 const caps = (cam?.capabilities || {}) as any;306 if (!cam || !caps.ptz || !caps.ptzProfileToken) return reply(409, { error: 'ptz_unsupported' });307 const prev = ptzTimers.get(cam.id);308 if (prev) clearTimeout(prev);309 detectors.get(cam.id)?.suppress(8000);310 if (b.action === 'stop') await ptzStop(cam, caps.ptzProfileToken);311 else if (b.action === 'move') {312 const pan = Math.max(-1, Math.min(1, Number(b.pan) || 0));313 const tilt = Math.max(-1, Math.min(1, Number(b.tilt) || 0));314 const dur = Math.max(100, Math.min(3000, Number(b.durationMs) || 600));315 await ptzMove(cam, caps.ptzProfileToken, pan, tilt);316 // arrêt garanti côté serveur, même si le navigateur ou l'API disparaît317 ptzTimers.set(cam.id, setTimeout(() => void ptzStop(cam, caps.ptzProfileToken).catch(() => {}), dur));318 } else return reply(400, { error: 'invalid_action' });319 reply(200, { ok: true });320 } catch (e: any) {321 log.warn('commande PTZ', { err: String(e?.message || e) });322 reply(502, { error: 'ptz_failed' });323 }324 });325 server.on('error', (e) => log.error('canal de commande', { err: String(e) }));326 server.listen(cfg.go2rtc.controlPort, '127.0.0.1', () => log.info('canal de commande', { port: cfg.go2rtc.controlPort }));327}328329async function shutdown(signal: string): Promise<void> {330 if (shuttingDown) return;331 shuttingDown = true;332 log.info('arrêt', { signal });333 try {334 for (const d of detectors.values()) d.stop();335 await Promise.all([...recorders.values()].map((r) => r.stop('arrêt du service')));336 await go2rtc.stop();337 addEvent(db, { type: 'service_stop', message: 'vision-core arrêté proprement' });338 db.close();339 } catch (e: any) {340 log.error('arrêt', { err: String(e?.message || e) });341 }342 process.exit(0);343}344process.on('SIGTERM', () => void shutdown('SIGTERM'));345process.on('SIGINT', () => void shutdown('SIGINT'));346process.on('uncaughtException', (e) => {347 log.error('exception non interceptée', { err: String(e?.stack || e) });348});349process.on('unhandledRejection', (e: any) => {350 log.error('rejet non intercepté', { err: String(e?.stack || e) });351});352353// garde : refuser de démarrer si la base est sur un volume réseau (WAL incompatible)354try {355 fs.accessSync(cfg.dataDir, fs.constants.W_OK);356} catch {357 log.error('dossier de données inaccessible', { dir: cfg.dataDir });358 process.exit(1);359}360void main();361