SPB Git

Repository Public

Settings.tsx 23.8 KB 550 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : web/src/pages/Settings.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, type ReactNode } from 'react';43import { api, type CameraDto } from '../api';44import { Link, useApp, usePoll } from '../ctx';45import { fmtAgo, fmtDateTime } from '../fmt';46import { IconLogout, IconStorage, IconSystem } from '../icons';47import { resetPrefs, setPrefs, usePrefs, type Prefs } from '../prefs';4849const DOW = ['D', 'L', 'M', 'M', 'J', 'V', 'S'];50const DOW_FULL = ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'];5152export function SettingsPage() {53  const { cameras, logout } = useApp();54  return (55    <>56      <div className="page-head">57        <h1>Réglages</h1>58      </div>59      <div className="stack">60        <div className="grid-2">61          <Link to="/storage" className="btn">62            <IconStorage />63            Stockage64          </Link>65          <Link to="/system" className="btn">66            <IconSystem />67            Système68          </Link>69        </div>70        <h2>Affichage et options avancées</h2>71        <Display />72        <h2>Caméras</h2>73        {cameras.map((c) => (74          <CameraSettings key={c.id} cam={c} />75        ))}76        <h2>Enregistrement</h2>77        <Retention />78        <h2>Accès</h2>79        <PushStatus />80        <Sessions />81        <KeyRotation />82        <h2>Confidentialité</h2>83        <div className="card pad stack">84          <ul className="muted" style={{ margin: 0, paddingLeft: 18, display: 'flex', flexDirection: 'column', gap: 6, fontSize: 14 }}>85            <li>Les flux, les enregistrements et le catalogue restent sur le cluster MacLustr ; aucune vidéo n’est envoyée à un service tiers.</li>86            <li>Le son n’est ni diffusé ni enregistré tant qu’il n’est pas activé caméra par caméra ci-dessus.</li>87            <li>Aucune reconnaissance faciale, aucun suivi, aucune statistique d’usage.</li>88            <li>Cet appareil ne conserve aucune vidéo : seule l’interface est mise en cache pour l’installation sur l’écran d’accueil.</li>89          </ul>90        </div>91        <h2>Application</h2>92        <div className="card pad stack">93          <p className="muted" style={{ fontSize: 14 }}>94            <b style={{ color: 'var(--text)' }}>iPhone / iPad :</b> dans Safari, touchez Partager puis « Sur l’écran d’accueil ». <b style={{ color: 'var(--text)' }}>Android :</b> menu de Chrome, « Installer l’application ». Sur iOS, la lecture s’arrête quand l’application passe en arrière-plan ; l’enregistrement, lui, continue sur le serveur.95          </p>96          <button className="btn danger" onClick={logout}>97            <IconLogout />98            Verrouiller cet appareil99          </button>100        </div>101      </div>102    </>103  );104}105106function CameraSettings({ cam }: { cam: CameraDto }) {107  const { refreshCameras, toast } = useApp();108  const [name, setName] = useState(cam.name);109  const [busy, setBusy] = useState(false);110  const rule = cam.settings.schedule?.[0] || null;111  const [sched, setSched] = useState<{ on: boolean; days: number[]; from: string; to: string }>({ on: !!rule, days: rule?.days || [1, 2, 3, 4, 5], from: rule?.from || '18:00', to: rule?.to || '07:00' });112  useEffect(() => setName(cam.name), [cam.name]);113114  async function patch(body: Record<string, unknown>, ok?: string) {115    setBusy(true);116    try {117      await api(`/api/cameras/${encodeURIComponent(cam.id)}/settings`, { method: 'PATCH', body });118      await refreshCameras();119      if (ok) toast(ok);120    } catch (e: any) {121      toast(e.message);122    } finally {123      setBusy(false);124    }125  }126  const sw = (label: string, hint: string, key: 'recordEnabled' | 'recordAudio' | 'liveAudio' | 'ptzEnabled', disabled = false) => (127    <label className="switch">128      <input type="checkbox" checked={!!cam.settings[key]} disabled={busy || disabled} onChange={(e) => void patch({ [key]: e.target.checked })} />129      <i />130      <span>131        {label}132        <span className="muted" style={{ display: 'block', fontSize: 13 }}>133          {hint}134        </span>135      </span>136    </label>137  );138  const saveSchedule = (next: typeof sched) => {139    setSched(next);140    void patch({ schedule: next.on && next.days.length ? [{ days: next.days, from: next.from, to: next.to }] : null }, 'Horaire enregistré');141  };142  return (143    <div className="card pad stack">144      <form145        className="row"146        onSubmit={(e) => {147          e.preventDefault();148          if (name.trim() && name.trim() !== cam.name) void patch({ name: name.trim() }, 'Nom enregistré');149        }}150      >151        <label className="field grow">152          <span>Nom · {cam.model || cam.id}</span>153          <input className="input" value={name} maxLength={60} onChange={(e) => setName(e.target.value)} />154        </label>155        <button className="btn" type="submit" style={{ alignSelf: 'flex-end' }} disabled={busy || !name.trim() || name.trim() === cam.name}>156          Enregistrer157        </button>158      </form>159      {sw('Enregistrement', 'Flux principal, sans réencodage, segments d’une minute', 'recordEnabled')}160      {sw('Enregistrer le son', 'Désactivé par défaut ; relance brève de l’enregistreur', 'recordAudio', !cam.capabilities.audio)}161      {sw('Son dans le direct', 'Autorise l’écoute en direct depuis la page de la caméra', 'liveAudio', !cam.capabilities.audio)}162      {cam.capabilities.ptz && sw('Orientation à distance (PTZ)', 'Affiche les commandes de déplacement', 'ptzEnabled')}163      <Motion cam={cam} patch={patch} busy={busy} />164      <label className="switch">165        <input type="checkbox" checked={sched.on} disabled={busy} onChange={(e) => saveSchedule({ ...sched, on: e.target.checked })} />166        <i />167        <span>168          Horaire d’enregistrement169          <span className="muted" style={{ display: 'block', fontSize: 13 }}>170            {sched.on ? 'Enregistre seulement pendant la plage ci-dessous' : 'Enregistre 24 h sur 24'}171          </span>172        </span>173      </label>174      {sched.on && (175        <div className="stack">176          <div className="days" role="group" aria-label="Jours">177            {DOW.map((d, i) => (178              <label key={i}>179                <input type="checkbox" checked={sched.days.includes(i)} aria-label={DOW_FULL[i]} onChange={(e) => saveSchedule({ ...sched, days: e.target.checked ? [...sched.days, i].sort() : sched.days.filter((x) => x !== i) })} />180                {d}181              </label>182            ))}183          </div>184          <div className="row">185            <label className="field grow">186              <span>De</span>187              <input className="input" type="time" value={sched.from} onChange={(e) => e.target.value && saveSchedule({ ...sched, from: e.target.value })} />188            </label>189            <label className="field grow">190              <span>À</span>191              <input className="input" type="time" value={sched.to} onChange={(e) => e.target.value && saveSchedule({ ...sched, to: e.target.value })} />192            </label>193          </div>194        </div>195      )}196    </div>197  );198}199200function Retention() {201  const { toast } = useApp();202  const [days, setDays] = useState('');203  const [gb, setGb] = useState('');204  const [cur, setCur] = useState<{ days: number; maxArchiveGB: number } | null>(null);205  useEffect(() => {206    void api('/api/settings').then((s) => {207      setCur(s.retention);208      setDays(String(s.retention.days));209      setGb(String(s.retention.maxArchiveGB));210    });211  }, []);212  async function save() {213    try {214      const r = await api('/api/settings', { method: 'PATCH', body: { retention: { days: Number(days), maxArchiveGB: Number(gb) } } });215      setCur(r.retention);216      toast('Rétention enregistrée');217    } catch (e: any) {218      toast(e.message);219    }220  }221  const dirty = cur && (String(cur.days) !== days || String(cur.maxArchiveGB) !== gb);222  return (223    <div className="card pad stack">224      <div className="row">225        <label className="field grow">226          <span>Rétention (jours)</span>227          <input className="input" inputMode="numeric" value={days} onChange={(e) => setDays(e.target.value.replace(/\D/g, ''))} />228        </label>229        <label className="field grow">230          <span>Quota d’archive (Go)</span>231          <input className="input" inputMode="numeric" value={gb} onChange={(e) => setGb(e.target.value.replace(/\D/g, ''))} />232        </label>233      </div>234      <p className="muted" style={{ fontSize: 13 }}>235        Les plus anciens segments non protégés sont supprimés dès que l’une des deux limites est atteinte. Les extraits protégés depuis l’Historique sont conservés.236      </p>237      <button className="btn" onClick={() => void save()} disabled={!dirty}>238        Enregistrer239      </button>240    </div>241  );242}243244function Sessions() {245  const { toast, sessionId } = useApp();246  const { data, reload } = usePoll(() => api<{ sessions: any[] }>('/api/auth/sessions'), 30000);247  async function revoke(id: string) {248    try {249      await api(`/api/auth/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' });250      toast('Session révoquée');251      reload();252    } catch (e: any) {253      toast(e.message);254    }255  }256  const device = (ua: string | null) => {257    if (!ua) return 'Appareil inconnu';258    const os = /iPhone/.test(ua) ? 'iPhone' : /iPad/.test(ua) ? 'iPad' : /Android/.test(ua) ? 'Android' : /Mac OS X/.test(ua) ? 'Mac' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : 'Appareil';259    const br = /Edg\//.test(ua) ? 'Edge' : /Chrome\//.test(ua) ? 'Chrome' : /Firefox\//.test(ua) ? 'Firefox' : /Safari\//.test(ua) ? 'Safari' : ua.split('/')[0].slice(0, 20);260    return `${os} · ${br}`;261  };262  return (263    <div className="card">264      <div style={{ padding: '14px 16px 4px' }}>265        <h2>Sessions actives</h2>266      </div>267      <div className="list">268        {(data?.sessions || []).map((s) => (269          <div key={s.id} className="list-item">270            <div className="grow">271              <div style={{ fontWeight: 550 }}>272                {device(s.userAgent)}273                {s.id === sessionId && <span className="badge" style={{ marginLeft: 8, color: 'var(--accent)' }}>Cet appareil</span>}274              </div>275              <div className="muted" style={{ fontSize: 13 }}>276                Vue {fmtAgo(s.lastSeenMs)} · expire le {fmtDateTime(s.expiresMs)}277              </div>278              <div className="faint mono" style={{ fontSize: 12 }}>279                {s.ip || '—'} · {s.trusted ? 'appareil de confiance' : 'session courte'}280              </div>281            </div>282            <button className="btn small" onClick={() => void revoke(s.id)}>283              Révoquer284            </button>285          </div>286        ))}287      </div>288    </div>289  );290}291292function KeyRotation() {293  const { toast, logout } = useApp();294  const [open, setOpen] = useState(false);295  const [cur, setCur] = useState('');296  const [busy, setBusy] = useState(false);297  const [newKey, setNewKey] = useState<string | null>(null);298  async function rotate() {299    setBusy(true);300    try {301      const r = await api<{ key: string }>('/api/auth/rotate-key', { method: 'POST', body: { currentKey: cur.trim() }, quiet401: true });302      setNewKey(r.key);303      setCur('');304    } catch (e: any) {305      toast(e.status === 401 ? 'Clé actuelle refusée' : e.message);306    } finally {307      setBusy(false);308    }309  }310  if (newKey)311    return (312      <div className="card pad stack">313        <h2>Nouvelle clé d’accès</h2>314        <div className="notice warn">Cette clé n’est affichée qu’une fois. Rangez-la maintenant dans votre gestionnaire de mots de passe : l’ancienne clé et toutes les sessions sont révoquées.</div>315        <div className="keybox" aria-label="Nouvelle clé">316          {newKey}317        </div>318        <div className="row wrap">319          <button className="btn" onClick={() => void navigator.clipboard?.writeText(newKey).then(() => toast('Clé copiée'))}>320            Copier321          </button>322          <button323            className="btn primary"324            onClick={() => {325              setNewKey(null);326              logout();327            }}328          >329            J’ai rangé la clé — me reconnecter330          </button>331        </div>332      </div>333    );334  return (335    <div className="card pad stack">336      <h2>Clé d’accès</h2>337      <p className="muted" style={{ fontSize: 14 }}>338        Une seule clé est active. La renouveler invalide immédiatement l’ancienne clé et déconnecte tous les appareils.339      </p>340      {!open ? (341        <button className="btn" onClick={() => setOpen(true)}>342          Renouveler la clé…343        </button>344      ) : (345        <form346          className="stack"347          onSubmit={(e) => {348            e.preventDefault();349            if (cur.trim() && !busy) void rotate();350          }}351        >352          <label className="field">353            <span>Clé actuelle (confirmation)</span>354            <input className="input mono" type="password" autoComplete="current-password" value={cur} onChange={(e) => setCur(e.target.value)} autoCapitalize="off" spellCheck={false} />355          </label>356          <div className="row">357            <button className="btn danger" type="submit" disabled={!cur.trim() || busy}>358              Renouveler et tout déconnecter359            </button>360            <button className="btn" type="button" onClick={() => (setOpen(false), setCur(''))}>361              Annuler362            </button>363          </div>364        </form>365      )}366    </div>367  );368}369370const ACCENTS: { id: Prefs['accent']; name: string; color: string }[] = [371  { id: 'glacier', name: 'Glacier', color: '#7cc4d8' },372  { id: 'ambre', name: 'Ambre', color: '#dcae62' },373  { id: 'signal', name: 'Signal', color: '#6fcf97' },374  { id: 'ivoire', name: 'Ivoire', color: '#e6e2d6' },375];376377function Seg<T extends string | number>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {378  return (379    <div className="seg" role="group" aria-label={label}>380      {options.map(([v, l]) => (381        <button key={String(v)} aria-pressed={value === v} onClick={() => onChange(v)}>382          {l}383        </button>384      ))}385    </div>386  );387}388function Opt({ title, hint, children }: { title: string; hint?: string; children: ReactNode }) {389  return (390    <div className="opt">391      <div>392        {title}393        {hint && <small>{hint}</small>}394      </div>395      {children}396    </div>397  );398}399function Sw({ k, title, hint }: { k: 'marks' | 'stats' | 'reduceMotion' | 'hoverPreview'; title: string; hint: string }) {400  const p = usePrefs();401  return (402    <label className="switch">403      <input type="checkbox" checked={p[k]} onChange={(e) => setPrefs({ [k]: e.target.checked })} />404      <i />405      <span>406        {title}407        <span className="muted" style={{ display: 'block', fontSize: 12.5 }}>408          {hint}409        </span>410      </span>411    </label>412  );413}414415/** Préférences propres à cet appareil : rien n'est envoyé au serveur. */416function Display() {417  const p = usePrefs();418  const { toast } = useApp();419  return (420    <div className="card pad stack">421      <Opt title="Couleur d’accent" hint="Le rouge reste réservé à l’enregistrement et aux alertes">422        <div className="swatches" role="group" aria-label="Couleur d’accent">423          {ACCENTS.map((a) => (424            <button key={a.id} aria-pressed={p.accent === a.id} aria-label={a.name} title={a.name} onClick={() => setPrefs({ accent: a.id })}>425              <i style={{ background: a.color }} />426            </button>427          ))}428        </div>429      </Opt>430      <Opt title="Densité de l’interface">431        <Seg label="Densité" value={p.density} options={[['confort', 'CONFORT'], ['compact', 'COMPACT']]} onChange={(v) => setPrefs({ density: v })} />432      </Opt>433      <Opt title="Disposition du mur de moniteurs" hint="Focus : une grande image, les autres en bande">434        <Seg label="Disposition" value={p.layout} options={[[0, 'AUTO'], [1, '1'], [2, '2'], [3, '3'], [4, '4'], [9, 'FOCUS']]} onChange={(v) => setPrefs({ layout: v })} />435      </Opt>436      <Opt title="Qualité par défaut d’une caméra" hint="Auto : 4K si le navigateur décode le HEVC, sinon 720p">437        <Seg label="Qualité" value={p.quality} options={[['auto', 'AUTO'], ['main', '4K'], ['sub', '720P']]} onChange={(v) => setPrefs({ quality: v })} />438      </Opt>439      <Opt title="Cadrage des tuiles" hint="Entière : toute l’image ; remplie : sans bandes, bords rognés">440        <Seg label="Cadrage" value={p.fit} options={[['contain', 'ENTIÈRE'], ['cover', 'REMPLIE']]} onChange={(v) => setPrefs({ fit: v })} />441      </Opt>442      <Opt title="Ronde automatique" hint={`Change de caméra toutes les ${p.patrolSeconds} secondes`}>443        <input type="range" min={4} max={60} step={1} value={p.patrolSeconds} onChange={(e) => setPrefs({ patrolSeconds: Number(e.target.value) })} aria-label="Durée de la ronde par caméra" style={{ maxWidth: 220 }} />444      </Opt>445      <Sw k="marks" title="Repères de viseur" hint="Équerres fines aux coins de chaque image" />446      <Sw k="stats" title="Statistiques techniques sur le direct" hint="Transport, codec, résolution réelle, débit reçu, retard, images perdues" />447      <Sw k="hoverPreview" title="Aperçu au survol de la frise" hint="Vignette tirée de la vidéo enregistrée à cet instant" />448      <Sw k="reduceMotion" title="Réduire les animations" hint="S’ajoute au réglage du système" />449      <div className="row wrap">450        <button className="btn small" onClick={() => (resetPrefs(), toast('Préférences d’affichage réinitialisées'))}>451          Réinitialiser l’affichage452        </button>453        <span className="faint" style={{ fontSize: 12.5 }}>454          Enregistré sur cet appareil seulement. Raccourcis clavier : touche <kbd>?</kbd> · palette de commandes : <kbd>⌘K</kbd>455        </span>456      </div>457    </div>458  );459}460461/** Détection de mouvement d'une caméra : activation, sensibilité, délai entre notifications, zones ignorées. */462function Motion({ cam, patch, busy }: { cam: CameraDto; patch: (body: Record<string, unknown>, ok?: string) => Promise<void>; busy: boolean }) {463  const s = cam.settings;464  const [sens, setSens] = useState(s.motionSensitivity ?? 5);465  const [cool, setCool] = useState(s.motionCooldownS ?? 60);466  const [zones, setZones] = useState(false);467  const [shot, setShot] = useState(0);468  useEffect(() => setSens(s.motionSensitivity ?? 5), [s.motionSensitivity]);469  useEffect(() => setCool(s.motionCooldownS ?? 60), [s.motionCooldownS]);470  if (s.motionEnabled === undefined) return null;471  const ignore = new Set(s.motionIgnore || []);472  const toggle = (i: number) => {473    const next = new Set(ignore);474    if (next.has(i)) next.delete(i);475    else next.add(i);476    void patch({ motionIgnore: [...next] });477  };478  return (479    <>480      <label className="switch">481        <input type="checkbox" checked={!!s.motionEnabled} disabled={busy} onChange={(e) => void patch({ motionEnabled: e.target.checked })} />482        <i />483        <span>484          Détection de mouvement485          <span className="muted" style={{ display: 'block', fontSize: 12.5 }}>486            Différence d’images analysée sur le serveur · {cam.status.lastMotionMs ? `dernier mouvement ${fmtAgo(cam.status.lastMotionMs)}` : 'aucun mouvement relevé'}487          </span>488        </span>489      </label>490      {s.motionEnabled && (491        <div className="stack">492          <label className="field">493            <span>494              Sensibilité · <span className="mono">{sens}/10</span>495            </span>496            <input type="range" min={1} max={10} step={1} value={sens} onChange={(e) => setSens(Number(e.target.value))} onPointerUp={() => sens !== s.motionSensitivity && void patch({ motionSensitivity: sens })} onKeyUp={() => sens !== s.motionSensitivity && void patch({ motionSensitivity: sens })} />497          </label>498          <label className="field">499            <span>500              Délai minimal entre deux notifications · <span className="mono">{cool >= 60 ? `${Math.round(cool / 60)} min` : `${cool} s`}</span>501            </span>502            <input type="range" min={10} max={900} step={10} value={cool} onChange={(e) => setCool(Number(e.target.value))} onPointerUp={() => cool !== s.motionCooldownS && void patch({ motionCooldownS: cool })} onKeyUp={() => cool !== s.motionCooldownS && void patch({ motionCooldownS: cool })} />503          </label>504          <div className="row wrap">505            <button className={`btn small ${zones ? 'on' : ''}`} onClick={() => (setZones((z) => !z), setShot(Date.now()))} aria-expanded={zones}>506              Zones ignorées ({ignore.size})507            </button>508            {ignore.size > 0 && (509              <button className="btn small" onClick={() => void patch({ motionIgnore: [] }, 'Zones ignorées effacées')}>510                Tout analyser511              </button>512            )}513          </div>514          {zones && (515            <>516              <div className="zones">517                <img alt="" src={`/api/cameras/${encodeURIComponent(cam.id)}/snapshot?profile=sub&_=${shot}`} />518                <div className="grid" role="group" aria-label="Zones ignorées par la détection">519                  {Array.from({ length: 144 }, (_, i) => (520                    <button key={i} disabled={i < 8} aria-pressed={ignore.has(i)} aria-label={`Zone ligne ${Math.floor(i / 16) + 1}, colonne ${(i % 16) + 1}`} onClick={() => toggle(i)} />521                  ))}522                </div>523              </div>524              <p className="faint" style={{ fontSize: 12.5 }}>525                Touchez les zones à ignorer (écran allumé, ventilateur, fenêtre). La bande grise en haut à gauche, où la caméra incruste l’heure, est toujours ignorée.526              </p>527            </>528          )}529        </div>530      )}531    </>532  );533}534535function PushStatus() {536  const { data } = usePoll(() => api<{ configured: boolean; devices: number }>('/api/push/status'), 60000);537  if (!data) return null;538  return (539    <div className="card pad row wrap">540      <span className={`dot ${data.configured && data.devices ? 'ok' : data.configured ? 'warn' : ''}`} />541      <div className="grow">542        Notifications sur iPhone543        <div className="muted" style={{ fontSize: 12.5 }}>544          {!data.configured ? 'Non configurées sur le serveur.' : data.devices ? `${data.devices} appareil(s) inscrit(s). Les préférences se règlent dans l’app iOS.` : 'Serveur prêt ; aucun appareil inscrit. Autorisez les notifications dans l’app iOS.'}545        </div>546      </div>547    </div>548  );549}550
Files main
Menu

Theme