SPB Git

Repository Public

onvif.ts 6.1 KB 137 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : server/src/onvif.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// Client ONVIF minimal (WS-Security UsernameToken Digest) : inventaire des capacités et PTZ.43// Les destinations sont limitées au registre local des caméras : jamais d'URL fournie par le navigateur.44import crypto from 'node:crypto';45import type { Camera } from './cameras.ts';4647function esc(s: string): string {48  return s.replace(/[<>&"']/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' })[c]!);49}5051async function soap(cam: Camera, path: string, body: string, timeoutMs = 5000): Promise<string> {52  const nonce = crypto.randomBytes(16);53  const created = new Date().toISOString();54  const digest = crypto.createHash('sha1').update(Buffer.concat([nonce, Buffer.from(created), Buffer.from(cam.password)])).digest('base64');55  const header =56    `<s:Header><Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><UsernameToken>` +57    `<Username>${esc(cam.username)}</Username>` +58    `<Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">${digest}</Password>` +59    `<Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">${nonce.toString('base64')}</Nonce>` +60    `<Created xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">${created}</Created>` +61    `</UsernameToken></Security></s:Header>`;62  const envelope = `<?xml version="1.0" encoding="UTF-8"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">${header}<s:Body>${body}</s:Body></s:Envelope>`;63  const res = await fetch(`http://127.0.0.1:${cam.relayOnvifPort}${path}`, {64    method: 'POST',65    headers: { 'Content-Type': 'application/soap+xml; charset=utf-8' },66    body: envelope,67    signal: AbortSignal.timeout(timeoutMs),68    redirect: 'error',69  });70  const text = await res.text();71  if (!res.ok) throw new Error(`ONVIF HTTP ${res.status}`);72  return text;73}7475const first = (xml: string, tag: string): string | null => {76  const m = new RegExp(`<(?:\\w+:)?${tag}[^>]*>([^<]*)<`).exec(xml);77  return m ? m[1] : null;78};7980export type OnvifInfo = {81  manufacturer: string | null;82  model: string | null;83  firmware: string | null;84  profiles: { token: string; encoding: string | null; width: number | null; height: number | null; fps: number | null; bitrateKbps: number | null }[];85  ptz: boolean;86  audio: boolean;87  ptzProfileToken: string | null;88};8990export async function inspect(cam: Camera): Promise<OnvifInfo> {91  const dev = await soap(cam, '/onvif/device_service', '<GetDeviceInformation xmlns="http://www.onvif.org/ver10/device/wsdl"/>');92  const prof = await soap(cam, '/onvif/service', '<GetProfiles xmlns="http://www.onvif.org/ver10/media/wsdl"/>');93  const profiles: OnvifInfo['profiles'] = [];94  const blocks = prof.split(/<(?:\w+:)?Profiles\b/).slice(1);95  let ptzToken: string | null = null;96  for (const b of blocks) {97    const token = /token="([^"]+)"/.exec(b)?.[1] || '';98    const num = (t: string) => {99      const v = first(b, t);100      return v ? Number(v) : null;101    };102    profiles.push({ token, encoding: first(b, 'Encoding'), width: num('Width'), height: num('Height'), fps: num('FrameRateLimit'), bitrateKbps: num('BitrateLimit') });103    if (!ptzToken && /PTZConfiguration/.test(b)) ptzToken = token;104  }105  let ptz = false;106  if (ptzToken) {107    try {108      const nodes = await soap(cam, '/onvif/service', '<GetNodes xmlns="http://www.onvif.org/ver20/ptz/wsdl"/>');109      ptz = /PTZNode/.test(nodes) && /ContinuousPanTiltVelocitySpace/.test(nodes);110    } catch {111      ptz = false;112    }113  }114  return {115    manufacturer: first(dev, 'Manufacturer'),116    model: first(dev, 'Model'),117    firmware: first(dev, 'FirmwareVersion'),118    profiles,119    ptz,120    audio: /AudioEncoderConfiguration/.test(prof),121    ptzProfileToken: ptz ? ptzToken : null,122  };123}124125export async function ptzMove(cam: Camera, token: string, pan: number, tilt: number): Promise<void> {126  const clamp = (v: number) => Math.max(-1, Math.min(1, v));127  await soap(128    cam,129    '/onvif/service',130    `<ContinuousMove xmlns="http://www.onvif.org/ver20/ptz/wsdl"><ProfileToken>${esc(token)}</ProfileToken><Velocity><PanTilt xmlns="http://www.onvif.org/ver10/schema" x="${clamp(pan).toFixed(2)}" y="${clamp(tilt).toFixed(2)}"/></Velocity></ContinuousMove>`,131  );132}133134export async function ptzStop(cam: Camera, token: string): Promise<void> {135  await soap(cam, '/onvif/service', `<Stop xmlns="http://www.onvif.org/ver20/ptz/wsdl"><ProfileToken>${esc(token)}</ProfileToken><PanTilt>true</PanTilt><Zoom>true</Zoom></Stop>`);136}137
Files main
Menu

Theme