Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/cameras.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// Registre local des caméras autorisées (fichier 0600 hors dépôt) fusionné avec les réglages en base.43import fs from 'node:fs';44import path from 'node:path';45import type { Config } from './config.ts';46import type { DB } from './db.ts';47import { registerSecret } from './log.ts';4849export type CameraSecret = {50 id: string;51 name: string;52 host: string;53 mac?: string;54 rtspPort: number;55 onvifPort: number;56 username: string;57 password: string;58 mainPath: string;59 subPath: string;60};6162export type Camera = CameraSecret & {63 position: number;64 recordEnabled: boolean;65 recordAudio: boolean;66 liveAudio: boolean;67 ptzEnabled: boolean;68 schedule: ScheduleRule[] | null;69 motionEnabled: boolean;70 motionSensitivity: number;71 motionCooldownS: number;72 motionIgnore: number[];73 model: string | null;74 firmware: string | null;75 capabilities: Record<string, unknown>;76 effectiveHost: string;77 /** ports du relais local (127.0.0.1) vers le RTSP et l'ONVIF de la caméra */78 relayRtspPort: number;79 relayOnvifPort: number;80};8182export type ScheduleRule = { days: number[]; from: string; to: string };8384const ID_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;8586export function loadRegistry(cfg: Config): CameraSecret[] {87 const file = path.join(cfg.configDir, 'cameras.json');88 const st = fs.statSync(file);89 if ((st.mode & 0o077) !== 0) throw new Error(`${file} doit être en mode 0600`);90 const raw = JSON.parse(fs.readFileSync(file, 'utf8'));91 const list: CameraSecret[] = [];92 for (const c of raw.cameras || []) {93 if (!ID_RE.test(c.id)) throw new Error(`identifiant de caméra invalide : ${c.id}`);94 if (!/^[A-Za-z0-9._-]+$/.test(c.host)) throw new Error(`hôte invalide pour ${c.id}`);95 for (const p of [c.mainPath, c.subPath]) if (!/^\/[A-Za-z0-9._/-]*$/.test(p)) throw new Error(`chemin RTSP invalide pour ${c.id}`);96 registerSecret(c.password);97 list.push({98 id: c.id,99 name: String(c.name || c.id),100 host: c.host,101 mac: c.mac,102 rtspPort: Number(c.rtspPort || 554),103 onvifPort: Number(c.onvifPort || 2020),104 username: String(c.username),105 password: String(c.password),106 mainPath: c.mainPath,107 subPath: c.subPath,108 });109 }110 return list;111}112113/** Crée les lignes manquantes en base (le nom du registre n'est qu'une valeur initiale). */114export function syncCameras(db: DB, registry: CameraSecret[]): void {115 const now = Date.now();116 registry.forEach((c, i) => {117 db.prepare('INSERT INTO cameras (id, name, position, created_ms, updated_ms) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO NOTHING').run(c.id, c.name, i, now, now);118 db.prepare('INSERT INTO camera_state (camera_id, updated_ms) VALUES (?, ?) ON CONFLICT(camera_id) DO NOTHING').run(c.id, now);119 });120}121122export const RELAY_BASE_PORT = 18600;123124export function listCameras(db: DB, registry: CameraSecret[]): Camera[] {125 const rows = db.prepare('SELECT * FROM cameras').all() as Record<string, any>[];126 const byId = new Map(rows.map((r) => [r.id as string, r]));127 const out: Camera[] = [];128 for (const [index, c] of registry.entries()) {129 const r = byId.get(c.id);130 if (!r) continue;131 let schedule: ScheduleRule[] | null = null;132 let capabilities: Record<string, unknown> = {};133 let motionIgnore: number[] = [];134 try {135 const m = JSON.parse(r.motion_ignore || '[]');136 if (Array.isArray(m)) motionIgnore = m.filter((x) => Number.isInteger(x) && x >= 0 && x < 144);137 } catch {138 motionIgnore = [];139 }140 try {141 schedule = r.schedule ? JSON.parse(r.schedule) : null;142 } catch {143 schedule = null;144 }145 try {146 capabilities = JSON.parse(r.capabilities || '{}');147 } catch {148 capabilities = {};149 }150 out.push({151 ...c,152 name: r.name,153 position: r.position,154 recordEnabled: !!r.record_enabled,155 recordAudio: !!r.record_audio,156 liveAudio: !!r.live_audio,157 ptzEnabled: !!r.ptz_enabled,158 schedule,159 motionEnabled: !!r.motion_enabled,160 motionSensitivity: Math.max(1, Math.min(10, Number(r.motion_sensitivity) || 5)),161 motionCooldownS: Math.max(10, Math.min(3600, Number(r.motion_cooldown_s) || 60)),162 motionIgnore,163 model: r.model,164 firmware: r.firmware,165 capabilities,166 effectiveHost: r.host_override || c.host,167 relayRtspPort: RELAY_BASE_PORT + index * 2,168 relayOnvifPort: RELAY_BASE_PORT + index * 2 + 1,169 });170 }171 out.sort((a, b) => a.position - b.position || a.id.localeCompare(b.id));172 return out;173}174175export function rtspUrl(cam: Camera, profile: 'main' | 'sub'): string {176 const p = profile === 'main' ? cam.mainPath : cam.subPath;177 return `rtsp://${encodeURIComponent(cam.username)}:${encodeURIComponent(cam.password)}@127.0.0.1:${cam.relayRtspPort}${p}`;178}179180/** Horaire : null = 24 h/24. Sinon liste de plages hebdomadaires dans le fuseau configuré. */181export function inSchedule(schedule: ScheduleRule[] | null, now: Date, timezone: string): boolean {182 if (!schedule || schedule.length === 0) return true;183 const parts = new Intl.DateTimeFormat('en-GB', { timeZone: timezone, weekday: 'short', hour: '2-digit', minute: '2-digit', hour12: false }).formatToParts(now);184 const wd = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(parts.find((p) => p.type === 'weekday')!.value);185 const hh = Number(parts.find((p) => p.type === 'hour')!.value) % 24;186 const mm = Number(parts.find((p) => p.type === 'minute')!.value);187 const cur = hh * 60 + mm;188 const toMin = (s: string) => {189 const [h, m] = s.split(':').map(Number);190 return h * 60 + m;191 };192 for (const r of schedule) {193 const from = toMin(r.from);194 const to = toMin(r.to);195 if (from <= to) {196 if (r.days.includes(wd) && cur >= from && cur < to) return true;197 } else {198 // plage qui traverse minuit199 if (r.days.includes(wd) && cur >= from) return true;200 if (r.days.includes((wd + 6) % 7) && cur < to) return true;201 }202 }203 return false;204}205206export function validateSchedule(input: unknown): ScheduleRule[] | null {207 if (input === null || input === undefined) return null;208 if (!Array.isArray(input) || input.length > 28) throw new Error('horaire invalide');209 const out: ScheduleRule[] = [];210 for (const r of input) {211 if (!r || !Array.isArray(r.days) || r.days.length === 0 || r.days.some((d: unknown) => !Number.isInteger(d) || (d as number) < 0 || (d as number) > 6)) throw new Error('jours invalides');212 for (const t of [r.from, r.to]) if (typeof t !== 'string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(t)) throw new Error('heure invalide');213 out.push({ days: [...new Set(r.days as number[])].sort(), from: r.from, to: r.to });214 }215 return out;216}217