SPB Git

Repository Public

Events.tsx 7.9 KB 192 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : web/src/pages/Events.tsx9 * Module           : pages10 * 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 */4142import { useEffect, useState } from 'react';43import { api, type EventDto } from '../api';44import { Link, useApp } from '../ctx';45import { fmtDate, fmtTime } from '../fmt';4647const TYPES: Record<string, string> = {48  motion: 'Mouvement',49  camera_offline: 'Caméra hors ligne',50  camera_online: 'Caméra en ligne',51  camera_address_changed: 'Adresse de caméra',52  recording_gap: 'Trou d’enregistrement',53  recording_stalled: 'Enregistrement bloqué',54  recording_resumed: 'Enregistrement rétabli',55  recording_suspended: 'Enregistrement suspendu',56  recording_unsuspended: 'Enregistrement repris',57  segment_quarantined: 'Segment isolé',58  retention_purge: 'Purge',59  storage_threshold: 'Seuil de stockage',60  archive_unavailable: 'Archive indisponible',61  archive_restored: 'Archive rétablie',62  spool_full: 'Tampon plein',63  spool_ok: 'Tampon rétabli',64  catalog_reconciled: 'Catalogue réconcilié',65  gateway_restart: 'Passerelle relancée',66  export_ready: 'Export prêt',67  key_rotated: 'Clé renouvelée',68  service_start: 'Démarrage',69  service_stop: 'Arrêt',70};7172export function EventsPage() {73  const { cameras } = useApp();74  const [events, setEvents] = useState<EventDto[]>([]);75  const [cursor, setCursor] = useState<number | null>(null);76  const [cam, setCam] = useState('');77  const [sev, setSev] = useState('');78  const [kind, setKind] = useState('');79  const [loading, setLoading] = useState(true);80  const [error, setError] = useState<string | null>(null);8182  const query = (c?: number | null) => `/api/events?limit=40${cam ? `&cameraId=${encodeURIComponent(cam)}` : ''}${sev ? `&severity=${sev}` : ''}${kind ? `&type=${kind}` : ''}${c ? `&cursor=${c}` : ''}`;83  useEffect(() => {84    let alive = true;85    setLoading(true);86    const run = () =>87      api<{ events: EventDto[]; nextCursor: number | null }>(query()).then(88        (r) => {89          if (!alive) return;90          setEvents(r.events);91          setCursor(r.nextCursor);92          setLoading(false);93          setError(null);94        },95        (e) => alive && (setError(e.message), setLoading(false)),96      );97    void run();98    const t = window.setInterval(() => !document.hidden && void run(), 20000);99    return () => {100      alive = false;101      clearInterval(t);102    };103    // eslint-disable-next-line react-hooks/exhaustive-deps104  }, [cam, sev, kind]);105106  async function more() {107    if (!cursor) return;108    const r = await api<{ events: EventDto[]; nextCursor: number | null }>(query(cursor));109    setEvents((e) => [...e, ...r.events]);110    setCursor(r.nextCursor);111  }112  const names = new Map(cameras.map((c) => [c.id, c.name]));113114  return (115    <>116      <div className="page-head">117        <h1>118          Événements119          <span className="sub">Journal réel du système : état des caméras, enregistrement, stockage</span>120        </h1>121      </div>122      <div className="row wrap" style={{ marginBottom: 14 }}>123        <select className="input" style={{ width: 'auto' }} value={cam} onChange={(e) => setCam(e.target.value)} aria-label="Filtrer par caméra">124          <option value="">Toutes les caméras</option>125          {cameras.map((c) => (126            <option key={c.id} value={c.id}>127              {c.name}128            </option>129          ))}130        </select>131        <div className="seg" role="group" aria-label="Gravité">132          {[133            ['', '', 'TOUT'],134            ['', 'motion', 'MOUVEMENTS'],135            ['warning', '', 'AVERTISSEMENTS'],136            ['critical', '', 'CRITIQUES'],137          ].map(([v, k, l]) => (138            <button key={l} aria-pressed={sev === v && kind === k} onClick={() => (setSev(v), setKind(k))}>139              {l}140            </button>141          ))}142        </div>143      </div>144      {error && <div className="notice bad">{error}</div>}145      <div className="card list">146        {!loading && events.length === 0 && <div className="empty">Aucun événement pour ces filtres.</div>}147        {events.map((e) => {148          const at = e.type === 'recording_gap' && e.data?.toMs ? e.data.toMs : e.tsMs;149          const linkable = !!e.cameraId && ['motion', 'camera_offline', 'camera_online', 'recording_gap', 'recording_resumed', 'export_ready', 'segment_quarantined'].includes(e.type);150          return (151            <div key={e.id} className="list-item">152              {e.type === 'motion' && e.data?.hasImage ? <img className="thumb" loading="lazy" alt="" src={`/api/events/${e.id}/image`} /> : e.cameraId && linkable ? <Thumb cameraId={e.cameraId} t={at} /> : <span className={`dot ${e.severity === 'critical' ? 'bad' : e.severity === 'warning' ? 'warn' : 'ok'}`} style={{ margin: '0 6px' }} />}153              <div className="grow">154                <div style={{ fontWeight: 550 }}>155                  {TYPES[e.type] || e.type}156                  {e.severity !== 'info' && <span className="badge" style={{ marginLeft: 8, color: e.severity === 'critical' ? '#ff9a9d' : 'var(--warn)' }}>{e.severity === 'critical' ? 'Critique' : 'Avertissement'}</span>}157                </div>158                <div className="muted" style={{ fontSize: 14 }}>159                  {e.message}160                </div>161                <div className="faint mono" style={{ fontSize: 12, marginTop: 2 }}>162                  {fmtDate(e.tsMs)} · {fmtTime(e.tsMs)}163                  {e.cameraId ? ` · ${names.get(e.cameraId) || e.cameraId}` : ''}164                </div>165              </div>166              {linkable && (167                <Link to={`/history?camera=${encodeURIComponent(e.cameraId!)}&t=${e.type === 'motion' ? Math.max(0, at - 2000) : at}`} className="btn small">168                  Voir169                </Link>170              )}171            </div>172          );173        })}174      </div>175      {cursor && (176        <div style={{ textAlign: 'center', marginTop: 14 }}>177          <button className="btn" onClick={() => void more()}>178            Événements plus anciens179          </button>180        </div>181      )}182    </>183  );184}185186/** Vignette tirée de l'enregistrement réel à l'instant de l'événement ; rien n'est affiché s'il n'y a pas de vidéo. */187function Thumb({ cameraId, t }: { cameraId: string; t: number }) {188  const [ok, setOk] = useState(true);189  if (!ok) return <span className="thumb" aria-hidden="true" />;190  return <img className="thumb" loading="lazy" alt="" src={`/api/recordings/thumbnail?cameraId=${encodeURIComponent(cameraId)}&t=${t}`} onError={() => setOk(false)} onLoad={(e) => e.currentTarget.naturalWidth === 0 && setOk(false)} />;191}192
Files main
Menu

Theme