iobroker.agent-dvr 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.de.md +54 -8
- package/README.md +58 -24
- package/admin/assets/index-BeOyLfcC.js +685 -0
- package/admin/i18n/de.json +66 -42
- package/admin/i18n/en.json +25 -1
- package/admin/i18n/es.json +66 -42
- package/admin/i18n/fr.json +66 -42
- package/admin/i18n/it.json +66 -42
- package/admin/i18n/nl.json +66 -42
- package/admin/i18n/pl.json +66 -42
- package/admin/i18n/pt.json +66 -42
- package/admin/i18n/ru.json +66 -42
- package/admin/i18n/uk.json +66 -42
- package/admin/i18n/zh-cn.json +66 -42
- package/admin/index_m.html +1 -1
- package/build/lib/notify.js +164 -0
- package/build/lib/notify.js.map +7 -0
- package/build/lib/recording.js +206 -2
- package/build/lib/recording.js.map +2 -2
- package/build/main.js +216 -7
- package/build/main.js.map +2 -2
- package/io-package.json +359 -28
- package/package.json +1 -1
- package/admin/assets/index-Dy3EUVMO.js +0 -685
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/recording.ts"],
|
|
4
|
-
"sourcesContent": ["// Helpers for \"recordings in the ioBroker file storage\" and sendRecording/getRecording:\n// ffmpeg detection, in-memory MKV -> MP4 remux, size limits, file names, URIs and URLs.\n// Kept free of adapter state so they can be unit tested.\n\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as http from 'node:http';\nimport * as path from 'node:path';\n\n/** Telegram bots can upload at most 50 MB per file */\nexport const TELEGRAM_MAX_BYTES = 50 * 1024 * 1024;\n\nexport const MB = 1024 * 1024;\n\n/** Result of the ffmpeg detection */\nexport interface FfmpegInfo {\n\t/** true if a working ffmpeg was found */\n\tfound: boolean;\n\t/** ffmpeg version, e.g. 6.1.1 */\n\tversion: string;\n\t/** binary that answered */\n\tpath: string;\n}\n\n/**\n * Clamps a configured number into [min, max]; non-numbers fall back to the default.\n *\n * @param raw configured value\n * @param def default value\n * @param min lower bound\n * @param max upper bound\n */\nexport function clampNumber(raw: unknown, def: number, min: number, max: number): number {\n\tconst n = typeof raw === 'number' ? raw : parseFloat(typeof raw === 'string' ? raw : '');\n\tif (!Number.isFinite(n)) {\n\t\treturn def;\n\t}\n\treturn Math.max(min, Math.min(max, Math.round(n)));\n}\n\n/**\n * Number of kept recordings per camera (1..3, default 1).\n *\n * @param raw configured value\n */\nexport function recordingSlots(raw: unknown): number {\n\treturn clampNumber(raw, 1, 1, 3);\n}\n\n/**\n * Maximum recording size in bytes (configured in MB, 1..2000, default 50).\n *\n * @param rawMb configured value in MB\n */\nexport function maxRecordingBytes(rawMb: unknown): number {\n\treturn clampNumber(rawMb, 50, 1, 2000) * MB;\n}\n\n/**\n * Size check result for a recording against a byte limit.\n *\n * @param bytes size of the recording (0/NaN = unknown \u2192 allowed)\n * @param limit maximum in bytes\n */\nexport function exceedsLimit(bytes: number, limit: number): boolean {\n\treturn Number.isFinite(bytes) && bytes > 0 && bytes > limit;\n}\n\n/**\n * Human readable MB value with one decimal.\n *\n * @param bytes size in bytes\n */\nexport function fmtMb(bytes: number): string {\n\treturn `${(Math.round((bytes / MB) * 10) / 10).toFixed(1)} MB`;\n}\n\n/**\n * File name of a stored recording slot inside the camera folder.\n *\n * @param slot slot number (1 = newest)\n * @param ext 'mp4' or 'mkv'\n */\nexport function recordingFileName(slot: number, ext: string): string {\n\treturn `rec${slot}.${ext}`;\n}\n\n/**\n * Path of a stored recording inside the adapter's file storage (meta object = namespace).\n *\n * @param fid camera folder id, e.g. cam_8_Reolink\n * @param slot slot number\n * @param ext file extension\n */\nexport function recordingStoragePath(fid: string, slot: number, ext: string): string {\n\treturn `${fid}/${recordingFileName(slot, ext)}`;\n}\n\n/**\n * Fixed per-camera file used by sendRecording/getRecording for recordings that are not in a slot.\n *\n * @param fid camera folder id\n * @param ext file extension\n */\nexport function sendFileStoragePath(fid: string, ext: string): string {\n\treturn `${fid}/send.${ext}`;\n}\n\n/**\n * All recording files a camera can have in the file storage (slots and the send file).\n */\nexport function cameraRecordingFiles(): string[] {\n\tconst out: string[] = [];\n\tfor (const ext of ['mp4', 'mkv']) {\n\t\tfor (let i = 1; i <= 3; i++) {\n\t\t\tout.push(`rec${i}.${ext}`);\n\t\t}\n\t\tout.push(`send.${ext}`);\n\t}\n\treturn out;\n}\n\n/**\n * True if the current last recording should be stored on start: slot 1 empty or holding another recording.\n *\n * @param slot1Exists slot 1 file exists\n * @param name1 value of recordings.name1\n * @param lastFn file name of the newest recording in AgentDVR\n */\nexport function needsInitialFill(slot1Exists: boolean, name1: unknown, lastFn: string): boolean {\n\tif (!lastFn) {\n\t\treturn false;\n\t}\n\treturn !slot1Exists || name1 !== lastFn;\n}\n\n/**\n * ioBroker file URI resolved by telegram >= 6 (same format as the alert photos).\n *\n * @param namespace adapter namespace (meta object id), e.g. agent-dvr.0\n * @param fid camera folder id\n * @param slot slot number\n * @param ext file extension\n */\nexport function recordingUri(namespace: string, fid: string, slot: number, ext: string): string {\n\treturn `iobfile://${namespace}/${recordingStoragePath(fid, slot, ext)}`;\n}\n\n/**\n * Absolute path where a file-based objects DB keeps the file (<dataDir>/files/<metaId>/<path>).\n *\n * @param dataDir ioBroker data directory (utils.getAbsoluteDefaultDataDir())\n * @param namespace meta object id\n * @param fid camera folder id\n * @param slot slot number\n * @param ext file extension\n */\nexport function recordingAbsPath(dataDir: string, namespace: string, fid: string, slot: number, ext: string): string {\n\treturn path.join(dataDir, 'files', namespace, fid, recordingFileName(slot, ext));\n}\n\n/**\n * http(s) URL via the web extension, empty without a web instance.\n *\n * @param webBase base URL of the web instance, e.g. http://192.168.1.10:8082\n * @param namespace adapter namespace\n * @param fid camera folder id\n * @param slot slot number\n * @param ext file extension\n */\nexport function recordingUrl(webBase: string, namespace: string, fid: string, slot: number, ext: string): string {\n\treturn webBase ? `${webBase}/${namespace}/recordings/${fid}/${recordingFileName(slot, ext)}` : '';\n}\n\n/**\n * Extension of an AgentDVR recording file name ('mkv' when unknown).\n *\n * @param fn file name, e.g. 8_2026-11-12_15-55-29_931.mkv\n */\nexport function extOf(fn: string): string {\n\tconst m = /\\.([A-Za-z0-9]+)$/.exec(fn || '');\n\treturn m ? m[1].toLowerCase() : 'mkv';\n}\n\n/**\n * Mime type for a recording extension.\n *\n * @param ext file extension\n */\nexport function mimeOf(ext: string): string {\n\treturn ext === 'mp4' ? 'video/mp4' : ext === 'mkv' ? 'video/x-matroska' : 'application/octet-stream';\n}\n\n/**\n * Only plain AgentDVR recording file names are accepted (no paths).\n *\n * @param fn requested file name\n */\nexport function isValidRecordingName(fn: string): boolean {\n\treturn /^[\\w.-]{1,200}\\.(mkv|mp4)$/i.test(fn) && !fn.includes('..');\n}\n\n// ---- ffmpeg detection ----\n\n/**\n * Ordered list of ffmpeg binaries to try: configured path, PATH lookup, common locations.\n *\n * @param configPath configured path (empty = auto)\n * @param platform process.platform\n */\nexport function ffmpegCandidates(configPath: string, platform: string): string[] {\n\tconst out: string[] = [];\n\tconst add = (p: string | undefined): void => {\n\t\tconst v = (p || '').trim();\n\t\tif (v && !out.includes(v)) {\n\t\t\tout.push(v);\n\t\t}\n\t};\n\tadd(configPath);\n\tadd('ffmpeg');\n\tif (platform === 'win32') {\n\t\tadd('C:\\\\ffmpeg\\\\bin\\\\ffmpeg.exe');\n\t\tadd('C:\\\\Program Files\\\\ffmpeg\\\\bin\\\\ffmpeg.exe');\n\t} else {\n\t\tadd('/usr/bin/ffmpeg');\n\t\tadd('/usr/local/bin/ffmpeg');\n\t\tadd('/opt/homebrew/bin/ffmpeg');\n\t}\n\treturn out;\n}\n\n/**\n * Absolute path of a bare binary name (for display): looked up in the usual binary folders,\n * otherwise the name itself (it was found via the search path of the system).\n *\n * @param bin binary name or path\n * @param platform process.platform\n * @param exists file check (injectable for tests)\n */\nexport function resolveOnPath(\n\tbin: string,\n\tplatform: string,\n\texists: (p: string) => boolean = p => fs.existsSync(p),\n): string {\n\tif (/[\\\\/]/.test(bin)) {\n\t\treturn bin;\n\t}\n\tconst win = platform === 'win32';\n\tconst pathMod = win ? path.win32 : path.posix;\n\tconst dirs = win\n\t\t? ['C:\\\\ffmpeg\\\\bin', 'C:\\\\Program Files\\\\ffmpeg\\\\bin']\n\t\t: ['/usr/bin', '/usr/local/bin', '/opt/homebrew/bin', '/bin'];\n\tconst names = win && !/\\.exe$/i.test(bin) ? [`${bin}.exe`, bin] : [bin];\n\tfor (const d of dirs) {\n\t\tfor (const n of names) {\n\t\t\tconst full = pathMod.join(d, n);\n\t\t\tif (exists(full)) {\n\t\t\t\treturn full;\n\t\t\t}\n\t\t}\n\t}\n\treturn bin;\n}\n\n/**\n * Version from `ffmpeg -version` output, e.g. \"6.1.1\" from \"ffmpeg version 6.1.1-3ubuntu5 Copyright ...\".\n *\n * @param out stdout of ffmpeg -version\n */\nexport function parseFfmpegVersion(out: string): string {\n\tconst m = /ffmpeg version\\s+(\\S+)/i.exec(out || '');\n\tif (!m) {\n\t\treturn '';\n\t}\n\tconst v = /^n?(\\d+(?:\\.\\d+)*)/.exec(m[1]);\n\treturn v ? v[1] : m[1];\n}\n\n/**\n * Runs `<bin> -version` and returns the version, or '' if it is not a working ffmpeg.\n *\n * @param bin binary name or path\n * @param timeoutMs timeout\n */\nexport function probeFfmpeg(bin: string, timeoutMs = 5000): Promise<string> {\n\treturn new Promise(resolve => {\n\t\tlet out = '';\n\t\tlet done = false;\n\t\tconst timer: { id?: NodeJS.Timeout } = {};\n\t\tconst finish = (v: string): void => {\n\t\t\tif (!done) {\n\t\t\t\tdone = true;\n\t\t\t\tclearTimeout(timer.id);\n\t\t\t\tresolve(v);\n\t\t\t}\n\t\t};\n\t\tlet child: ReturnType<typeof spawn>;\n\t\ttry {\n\t\t\tchild = spawn(bin, ['-version'], { shell: false, windowsHide: true });\n\t\t} catch {\n\t\t\tresolve('');\n\t\t\treturn;\n\t\t}\n\t\ttimer.id = setTimeout(() => {\n\t\t\ttry {\n\t\t\t\tchild.kill('SIGKILL');\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t\tfinish('');\n\t\t}, timeoutMs);\n\t\tchild.stdout?.on('data', (c: Buffer) => {\n\t\t\tif (out.length < 4096) {\n\t\t\t\tout += c.toString();\n\t\t\t}\n\t\t});\n\t\tchild.on('error', () => finish(''));\n\t\tchild.on('close', code => finish(code === 0 ? parseFfmpegVersion(out) : ''));\n\t});\n}\n\n/**\n * Tries the candidates in order and returns the first working ffmpeg.\n *\n * @param candidates binaries in priority order\n * @param probe returns the version or '' (injectable for tests)\n */\nexport async function detectFfmpeg(\n\tcandidates: string[],\n\tprobe: (bin: string) => Promise<string> = b => probeFfmpeg(b),\n): Promise<FfmpegInfo> {\n\tfor (const c of candidates) {\n\t\tconst version = await probe(c);\n\t\tif (version) {\n\t\t\treturn { found: true, version, path: c };\n\t\t}\n\t}\n\treturn { found: false, version: '', path: '' };\n}\n\n/**\n * Text for info.ffmpeg.\n *\n * @param info detection result\n */\nexport function ffmpegStatusText(info: FfmpegInfo): string {\n\treturn info.found ? `${info.version} (${info.path})` : 'not found';\n}\n\n// ---- remux ----\n\n/**\n * True if the Matroska header announces an HEVC video track (needs the hvc1 tag in MP4 for Apple/Telegram).\n *\n * @param buf MKV data\n */\nexport function isHevcMkv(buf: Buffer): boolean {\n\treturn buf.subarray(0, 256 * 1024).includes('V_MPEGH/ISO/HEVC');\n}\n\n/**\n * ffmpeg arguments for a lossless MKV \u2192 fragmented MP4 remux via stdin/stdout.\n *\n * @param hevc tag the video track as hvc1\n * @param dropAudio leave out the audio track\n */\nexport function remuxArgs(hevc: boolean, dropAudio: boolean): string[] {\n\tconst args = ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0', '-map', '0:v:0'];\n\tif (!dropAudio) {\n\t\targs.push('-map', '0:a?');\n\t}\n\targs.push('-c', 'copy');\n\tif (hevc) {\n\t\targs.push('-tag:v', 'hvc1');\n\t}\n\tif (dropAudio) {\n\t\targs.push('-an');\n\t}\n\targs.push('-movflags', 'frag_keyframe+empty_moov', '-f', 'mp4', 'pipe:1');\n\treturn args;\n}\n\n/**\n * Runs ffmpeg once with the input on stdin and collects stdout.\n *\n * @param bin ffmpeg binary\n * @param input input data\n * @param args ffmpeg arguments\n * @param timeoutMs timeout\n * @param maxBytes abort when the output gets larger\n */\nexport function runFfmpeg(\n\tbin: string,\n\tinput: Buffer,\n\targs: string[],\n\ttimeoutMs: number,\n\tmaxBytes: number,\n): Promise<Buffer> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet done = false;\n\t\tconst timer: { id?: NodeJS.Timeout } = {};\n\t\tconst chunks: Buffer[] = [];\n\t\tlet size = 0;\n\t\tlet err = '';\n\t\tconst child = spawn(bin, args, { shell: false, windowsHide: true });\n\t\tconst fail = (e: Error): void => {\n\t\t\tif (!done) {\n\t\t\t\tdone = true;\n\t\t\t\tclearTimeout(timer.id);\n\t\t\t\ttry {\n\t\t\t\t\tchild.kill('SIGKILL');\n\t\t\t\t} catch {\n\t\t\t\t\t/* ignore */\n\t\t\t\t}\n\t\t\t\treject(e);\n\t\t\t}\n\t\t};\n\t\ttimer.id = setTimeout(\n\t\t\t() => fail(new Error(`ffmpeg timeout after ${Math.round(timeoutMs / 1000)} s`)),\n\t\t\ttimeoutMs,\n\t\t);\n\t\tchild.stdout.on('data', (c: Buffer) => {\n\t\t\tsize += c.length;\n\t\t\tif (size > maxBytes) {\n\t\t\t\tfail(new Error(`MP4 larger than ${fmtMb(maxBytes)}`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchunks.push(c);\n\t\t});\n\t\tchild.stderr.on('data', (c: Buffer) => {\n\t\t\tif (err.length < 2000) {\n\t\t\t\terr += c.toString();\n\t\t\t}\n\t\t});\n\t\tchild.on('error', e => fail(e));\n\t\tchild.on('close', code => {\n\t\t\tif (done) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdone = true;\n\t\t\tclearTimeout(timer.id);\n\t\t\tif (code === 0 && size > 0) {\n\t\t\t\tresolve(Buffer.concat(chunks));\n\t\t\t} else {\n\t\t\t\treject(new Error(`ffmpeg exit code ${code}: ${err.trim().split('\\n').pop() || 'no output'}`));\n\t\t\t}\n\t\t});\n\t\t// EPIPE when ffmpeg stops reading early \u2014 the close handler reports the real error\n\t\tchild.stdin.on('error', () => {});\n\t\tchild.stdin.end(input);\n\t});\n}\n\n/**\n * Remuxes MKV to MP4 without re-encoding. Retries without audio if the audio codec can't go into MP4.\n *\n * @param bin ffmpeg binary\n * @param mkv input data\n * @param timeoutMs timeout per run\n * @param maxBytes output limit\n * @param onAudioDropped called when the retry without audio was needed\n * @param run ffmpeg runner (injectable for tests)\n */\nexport async function remuxToMp4(\n\tbin: string,\n\tmkv: Buffer,\n\ttimeoutMs: number,\n\tmaxBytes: number,\n\tonAudioDropped?: (reason: string) => void,\n\trun: typeof runFfmpeg = runFfmpeg,\n): Promise<Buffer> {\n\tconst hevc = isHevcMkv(mkv);\n\ttry {\n\t\treturn await run(bin, mkv, remuxArgs(hevc, false), timeoutMs, maxBytes);\n\t} catch (e) {\n\t\tconst msg = (e as Error).message;\n\t\tif (/timeout|larger than|ENOENT|Invalid data|Error opening input/i.test(msg)) {\n\t\t\tthrow e;\n\t\t}\n\t\tconst out = await run(bin, mkv, remuxArgs(hevc, true), timeoutMs, maxBytes);\n\t\tonAudioDropped?.(msg);\n\t\treturn out;\n\t}\n}\n\n// ---- download ----\n\n/** Result of a download into memory */\nexport interface DownloadResult {\n\t/** download complete */\n\tok: boolean;\n\t/** downloaded bytes */\n\tdata?: Buffer;\n\t/** error text */\n\terror?: string;\n\t/** true when the download was stopped because of the size limit */\n\ttooLarge?: boolean;\n\t/** received or announced size in bytes */\n\tsize?: number;\n}\n\n/**\n * GET into memory with timeout and size limit (Content-Length checked first, then the received bytes).\n *\n * @param opts request options (hostname, port, path, headers)\n * @param maxBytes size limit\n * @param timeoutMs overall timeout\n */\nexport function downloadToBuffer(\n\topts: http.RequestOptions,\n\tmaxBytes: number,\n\ttimeoutMs: number,\n): Promise<DownloadResult> {\n\treturn new Promise(resolve => {\n\t\tlet done = false;\n\t\tconst timer: { id?: NodeJS.Timeout } = {};\n\t\tlet req: http.ClientRequest | undefined;\n\t\tconst finish = (r: DownloadResult): void => {\n\t\t\tif (!done) {\n\t\t\t\tdone = true;\n\t\t\t\tclearTimeout(timer.id);\n\t\t\t\tresolve(r);\n\t\t\t}\n\t\t};\n\t\ttimer.id = setTimeout(() => {\n\t\t\treq?.destroy();\n\t\t\tfinish({ ok: false, error: `timeout after ${Math.round(timeoutMs / 1000)} s` });\n\t\t}, timeoutMs);\n\t\ttry {\n\t\t\treq = http.request({ ...opts, method: 'GET' }, res => {\n\t\t\t\tif (res.statusCode && res.statusCode >= 400) {\n\t\t\t\t\tres.resume();\n\t\t\t\t\tfinish({ ok: false, error: `HTTP ${res.statusCode}` });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst len = parseInt(String(res.headers['content-length'] ?? ''), 10);\n\t\t\t\tif (exceedsLimit(len, maxBytes)) {\n\t\t\t\t\treq?.destroy();\n\t\t\t\t\tfinish({ ok: false, tooLarge: true, size: len, error: `${fmtMb(len)} > limit ${fmtMb(maxBytes)}` });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst chunks: Buffer[] = [];\n\t\t\t\tlet size = 0;\n\t\t\t\tres.on('data', (c: Buffer) => {\n\t\t\t\t\tsize += c.length;\n\t\t\t\t\tif (size > maxBytes) {\n\t\t\t\t\t\treq?.destroy();\n\t\t\t\t\t\tfinish({ ok: false, tooLarge: true, size, error: `more than ${fmtMb(maxBytes)}` });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tchunks.push(c);\n\t\t\t\t});\n\t\t\t\tres.on('end', () => finish({ ok: true, data: Buffer.concat(chunks), size }));\n\t\t\t\tres.on('error', (e: Error) => finish({ ok: false, error: e.message }));\n\t\t\t});\n\t\t\treq.on('error', (e: Error) => finish({ ok: false, error: e.message }));\n\t\t\treq.end();\n\t\t} catch (e) {\n\t\t\tfinish({ ok: false, error: (e as Error).message });\n\t\t}\n\t});\n}\n\n// ---- camera lookup for sendTo ----\n\n/** Camera reference for findCamera */\nexport interface CamRef {\n\t/** AgentDVR object id */\n\toid: number | string;\n\t/** camera name */\n\tname: string;\n\t/** folder id, e.g. cam_8_Reolink */\n\tfid: string;\n}\n\n/**\n * Finds a camera by folder id (cam_8_Reolink), oid (8 / \"8\") or name (case-insensitive).\n *\n * @param query value from the message\n * @param cams known cameras\n */\nexport function findCamera(query: unknown, cams: CamRef[]): CamRef | undefined {\n\tif (query === undefined || query === null || query === '') {\n\t\treturn undefined;\n\t}\n\tconst q = (typeof query === 'number' ? String(query) : typeof query === 'string' ? query : '').trim();\n\tconst ql = q.toLowerCase();\n\treturn (\n\t\tcams.find(c => c.fid === q) ||\n\t\tcams.find(c => String(c.oid) === q) ||\n\t\tcams.find(c => c.name.toLowerCase() === ql) ||\n\t\tcams.find(c => q.endsWith(`.${c.fid}`))\n\t);\n}\n\n// ---- message bus guard ----\n\n/** Metadata answered by sendRecording / getRecording \u2014 never the video data itself */\nexport interface ProvidedRecording {\n\t/** recording is available */\n\tok: boolean;\n\t/** error text */\n\terror?: string;\n\t/** file name for the receiver, e.g. 8_2026-11-12_15-55-29_931.mp4 */\n\tfileName?: string;\n\t/** 'mp4' or 'mkv' */\n\tformat?: string;\n\t/** mime type */\n\tmime?: string;\n\t/** size in bytes */\n\tsize?: number;\n\t/** iobfile:// URI of the file in the adapter's file storage */\n\turi?: string;\n\t/** http(s) URL via the web instance ('' without one) */\n\turl?: string;\n\t/** absolute path on the ioBroker host ('' if the file storage is not on the local disk) */\n\tfile?: string;\n}\n\n/** Largest message the adapter puts on the message bus (sendTo answers and forwards) */\nexport const MAX_MESSAGE_BYTES = 64 * 1024;\n\n/**\n * True if the value contains binary data: a Buffer, a typed array / ArrayBuffer or a\n * JSON-serialized Buffer ({ type: 'Buffer', data: [...] }).\n *\n * @param value value to check\n * @param depth recursion depth\n */\nexport function containsBinary(value: unknown, depth = 0): boolean {\n\tif (value === null || typeof value !== 'object') {\n\t\treturn false;\n\t}\n\tif (depth > 20) {\n\t\treturn true;\n\t}\n\tif (Buffer.isBuffer(value) || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n\t\treturn true;\n\t}\n\tconst o = value as Record<string, unknown>;\n\tif (o.type === 'Buffer' && Array.isArray(o.data)) {\n\t\treturn true;\n\t}\n\tconst children = Array.isArray(value) ? (value as unknown[]) : Object.values(o);\n\treturn children.some(v => containsBinary(v, depth + 1));\n}\n\n/**\n * Throws if a message for the message bus contains binary data or is too large.\n *\n * @param value message\n */\nexport function assertNoBinary(value: unknown): void {\n\tif (containsBinary(value)) {\n\t\tthrow new Error('refusing to put binary data on the ioBroker message bus');\n\t}\n\tconst len = Buffer.byteLength(JSON.stringify(value ?? null));\n\tif (len > MAX_MESSAGE_BYTES) {\n\t\tthrow new Error(`refusing to put ${len} bytes on the ioBroker message bus`);\n\t}\n}\n\n/**\n * Returns the message if it is safe for the message bus, otherwise a small error answer.\n *\n * @param value message\n */\nexport function safeMessage<T>(value: T): T | { ok: false; error: string } {\n\ttry {\n\t\tassertNoBinary(value);\n\t\treturn value;\n\t} catch (e) {\n\t\treturn { ok: false, error: (e as Error).message };\n\t}\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,gCAAsB;AACtB,SAAoB;AACpB,WAAsB;AACtB,WAAsB;AAGf,MAAM,qBAAqB,KAAK,OAAO;AAEvC,MAAM,KAAK,OAAO;A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,OAAK,OAAO,EAAE,GAAG,MAAM,CAAC,KAClC,KAAK,KAAK,OAAK,EAAE,KAAK,YAAY,MAAM,EAAE,KAC1C,KAAK,KAAK,OAAK,EAAE,SAAS,IAAI,EAAE,GAAG,EAAE,CAAC;AAExC;AA2BO,MAAM,oBAAoB,KAAK;AAS/B,SAAS,eAAe,OAAgB,QAAQ,GAAY;AAClE,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAChD,WAAO;AAAA,EACR;AACA,MAAI,QAAQ,IAAI;AACf,WAAO;AAAA,EACR;AACA,MAAI,OAAO,SAAS,KAAK,KAAK,YAAY,OAAO,KAAK,KAAK,iBAAiB,aAAa;AACxF,WAAO;AAAA,EACR;AACA,QAAM,IAAI;AACV,MAAI,EAAE,SAAS,YAAY,MAAM,QAAQ,EAAE,IAAI,GAAG;AACjD,WAAO;AAAA,EACR;AACA,QAAM,WAAW,MAAM,QAAQ,KAAK,IAAK,QAAsB,OAAO,OAAO,CAAC;AAC9E,SAAO,SAAS,KAAK,OAAK,eAAe,GAAG,QAAQ,CAAC,CAAC;AACvD;AAOO,SAAS,eAAe,OAAsB;AACpD,MAAI,eAAe,KAAK,GAAG;AAC1B,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC1E;AACA,QAAM,MAAM,OAAO,WAAW,KAAK,UAAU,wBAAS,IAAI,CAAC;AAC3D,MAAI,MAAM,mBAAmB;AAC5B,UAAM,IAAI,MAAM,mBAAmB,GAAG,oCAAoC;AAAA,EAC3E;AACD;AAOO,SAAS,YAAe,OAA4C;AAC1E,MAAI;AACH,mBAAe,KAAK;AACpB,WAAO;AAAA,EACR,SAAS,GAAG;AACX,WAAO,EAAE,IAAI,OAAO,OAAQ,EAAY,QAAQ;AAAA,EACjD;AACD;",
|
|
4
|
+
"sourcesContent": ["// Helpers for \"recordings in the ioBroker file storage\" and sendRecording/getRecording:\n// ffmpeg detection, in-memory MKV -> MP4 remux, size limits, file names, URIs and URLs.\n// Kept free of adapter state so they can be unit tested.\n\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as http from 'node:http';\nimport * as path from 'node:path';\n\n/** Telegram bots can upload at most 50 MB per file */\nexport const TELEGRAM_MAX_BYTES = 50 * 1024 * 1024;\n\nexport const MB = 1024 * 1024;\n\n/** Result of the ffmpeg detection */\nexport interface FfmpegInfo {\n\t/** true if a working ffmpeg was found */\n\tfound: boolean;\n\t/** ffmpeg version, e.g. 6.1.1 */\n\tversion: string;\n\t/** binary that answered */\n\tpath: string;\n}\n\n/**\n * Clamps a configured number into [min, max]; non-numbers fall back to the default.\n *\n * @param raw configured value\n * @param def default value\n * @param min lower bound\n * @param max upper bound\n */\nexport function clampNumber(raw: unknown, def: number, min: number, max: number): number {\n\tconst n = typeof raw === 'number' ? raw : parseFloat(typeof raw === 'string' ? raw : '');\n\tif (!Number.isFinite(n)) {\n\t\treturn def;\n\t}\n\treturn Math.max(min, Math.min(max, Math.round(n)));\n}\n\n/**\n * Number of kept recordings per camera (1..3, default 1).\n *\n * @param raw configured value\n */\nexport function recordingSlots(raw: unknown): number {\n\treturn clampNumber(raw, 1, 1, 3);\n}\n\n/**\n * Maximum recording size in bytes (configured in MB, 1..2000, default 50).\n *\n * @param rawMb configured value in MB\n */\nexport function maxRecordingBytes(rawMb: unknown): number {\n\treturn clampNumber(rawMb, 50, 1, 2000) * MB;\n}\n\n/**\n * Size check result for a recording against a byte limit.\n *\n * @param bytes size of the recording (0/NaN = unknown \u2192 allowed)\n * @param limit maximum in bytes\n */\nexport function exceedsLimit(bytes: number, limit: number): boolean {\n\treturn Number.isFinite(bytes) && bytes > 0 && bytes > limit;\n}\n\n/**\n * Human readable MB value with one decimal.\n *\n * @param bytes size in bytes\n */\nexport function fmtMb(bytes: number): string {\n\treturn `${(Math.round((bytes / MB) * 10) / 10).toFixed(1)} MB`;\n}\n\n/**\n * File name of a stored recording slot inside the camera folder.\n *\n * @param slot slot number (1 = newest)\n * @param ext 'mp4' or 'mkv'\n */\nexport function recordingFileName(slot: number, ext: string): string {\n\treturn `rec${slot}.${ext}`;\n}\n\n/**\n * Path of a stored recording inside the adapter's file storage (meta object = namespace).\n *\n * @param fid camera folder id, e.g. cam_8_Reolink\n * @param slot slot number\n * @param ext file extension\n */\nexport function recordingStoragePath(fid: string, slot: number, ext: string): string {\n\treturn `${fid}/${recordingFileName(slot, ext)}`;\n}\n\n/**\n * Fixed per-camera file used by sendRecording/getRecording for recordings that are not in a slot.\n *\n * @param fid camera folder id\n * @param ext file extension\n */\nexport function sendFileStoragePath(fid: string, ext: string): string {\n\treturn `${fid}/send.${ext}`;\n}\n\n/**\n * All recording files a camera can have in the file storage (slots and the send file).\n */\nexport function cameraRecordingFiles(): string[] {\n\tconst out: string[] = [];\n\tfor (const ext of ['mp4', 'mkv']) {\n\t\tfor (let i = 1; i <= 3; i++) {\n\t\t\tout.push(`rec${i}.${ext}`);\n\t\t}\n\t\tout.push(`send.${ext}`);\n\t}\n\treturn out;\n}\n\n/**\n * True if the current last recording should be stored on start: slot 1 empty or holding another recording.\n *\n * @param slot1Exists slot 1 file exists\n * @param name1 value of recordings.name1\n * @param lastFn file name of the newest recording in AgentDVR\n */\nexport function needsInitialFill(slot1Exists: boolean, name1: unknown, lastFn: string): boolean {\n\tif (!lastFn) {\n\t\treturn false;\n\t}\n\treturn !slot1Exists || name1 !== lastFn;\n}\n\n/**\n * ioBroker file URI resolved by telegram >= 6 (same format as the alert photos).\n *\n * @param namespace adapter namespace (meta object id), e.g. agent-dvr.0\n * @param fid camera folder id\n * @param slot slot number\n * @param ext file extension\n */\nexport function recordingUri(namespace: string, fid: string, slot: number, ext: string): string {\n\treturn `iobfile://${namespace}/${recordingStoragePath(fid, slot, ext)}`;\n}\n\n/**\n * Absolute path where a file-based objects DB keeps the file (<dataDir>/files/<metaId>/<path>).\n *\n * @param dataDir ioBroker data directory (utils.getAbsoluteDefaultDataDir())\n * @param namespace meta object id\n * @param fid camera folder id\n * @param slot slot number\n * @param ext file extension\n */\nexport function recordingAbsPath(dataDir: string, namespace: string, fid: string, slot: number, ext: string): string {\n\treturn path.join(dataDir, 'files', namespace, fid, recordingFileName(slot, ext));\n}\n\n/**\n * http(s) URL via the web extension, empty without a web instance.\n *\n * @param webBase base URL of the web instance, e.g. http://192.168.1.10:8082\n * @param namespace adapter namespace\n * @param fid camera folder id\n * @param slot slot number\n * @param ext file extension\n */\nexport function recordingUrl(webBase: string, namespace: string, fid: string, slot: number, ext: string): string {\n\treturn webBase ? `${webBase}/${namespace}/recordings/${fid}/${recordingFileName(slot, ext)}` : '';\n}\n\n/**\n * Extension of an AgentDVR recording file name ('mkv' when unknown).\n *\n * @param fn file name, e.g. 8_2026-11-12_15-55-29_931.mkv\n */\nexport function extOf(fn: string): string {\n\tconst m = /\\.([A-Za-z0-9]+)$/.exec(fn || '');\n\treturn m ? m[1].toLowerCase() : 'mkv';\n}\n\n/**\n * Mime type for a recording extension.\n *\n * @param ext file extension\n */\nexport function mimeOf(ext: string): string {\n\treturn ext === 'mp4' ? 'video/mp4' : ext === 'mkv' ? 'video/x-matroska' : 'application/octet-stream';\n}\n\n/**\n * Only plain AgentDVR recording file names are accepted (no paths).\n *\n * @param fn requested file name\n */\nexport function isValidRecordingName(fn: string): boolean {\n\treturn /^[\\w.-]{1,200}\\.(mkv|mp4)$/i.test(fn) && !fn.includes('..');\n}\n\n// ---- ffmpeg detection ----\n\n/**\n * Ordered list of ffmpeg binaries to try: configured path, PATH lookup, common locations.\n *\n * @param configPath configured path (empty = auto)\n * @param platform process.platform\n */\nexport function ffmpegCandidates(configPath: string, platform: string): string[] {\n\tconst out: string[] = [];\n\tconst add = (p: string | undefined): void => {\n\t\tconst v = (p || '').trim();\n\t\tif (v && !out.includes(v)) {\n\t\t\tout.push(v);\n\t\t}\n\t};\n\tadd(configPath);\n\tadd('ffmpeg');\n\tif (platform === 'win32') {\n\t\tadd('C:\\\\ffmpeg\\\\bin\\\\ffmpeg.exe');\n\t\tadd('C:\\\\Program Files\\\\ffmpeg\\\\bin\\\\ffmpeg.exe');\n\t} else {\n\t\tadd('/usr/bin/ffmpeg');\n\t\tadd('/usr/local/bin/ffmpeg');\n\t\tadd('/opt/homebrew/bin/ffmpeg');\n\t}\n\treturn out;\n}\n\n/**\n * Absolute path of a bare binary name (for display): looked up in the usual binary folders,\n * otherwise the name itself (it was found via the search path of the system).\n *\n * @param bin binary name or path\n * @param platform process.platform\n * @param exists file check (injectable for tests)\n */\nexport function resolveOnPath(\n\tbin: string,\n\tplatform: string,\n\texists: (p: string) => boolean = p => fs.existsSync(p),\n): string {\n\tif (/[\\\\/]/.test(bin)) {\n\t\treturn bin;\n\t}\n\tconst win = platform === 'win32';\n\tconst pathMod = win ? path.win32 : path.posix;\n\tconst dirs = win\n\t\t? ['C:\\\\ffmpeg\\\\bin', 'C:\\\\Program Files\\\\ffmpeg\\\\bin']\n\t\t: ['/usr/bin', '/usr/local/bin', '/opt/homebrew/bin', '/bin'];\n\tconst names = win && !/\\.exe$/i.test(bin) ? [`${bin}.exe`, bin] : [bin];\n\tfor (const d of dirs) {\n\t\tfor (const n of names) {\n\t\t\tconst full = pathMod.join(d, n);\n\t\t\tif (exists(full)) {\n\t\t\t\treturn full;\n\t\t\t}\n\t\t}\n\t}\n\treturn bin;\n}\n\n/**\n * Version from `ffmpeg -version` output, e.g. \"6.1.1\" from \"ffmpeg version 6.1.1-3ubuntu5 Copyright ...\".\n *\n * @param out stdout of ffmpeg -version\n */\nexport function parseFfmpegVersion(out: string): string {\n\tconst m = /ffmpeg version\\s+(\\S+)/i.exec(out || '');\n\tif (!m) {\n\t\treturn '';\n\t}\n\tconst v = /^n?(\\d+(?:\\.\\d+)*)/.exec(m[1]);\n\treturn v ? v[1] : m[1];\n}\n\n/**\n * Runs `<bin> -version` and returns the version, or '' if it is not a working ffmpeg.\n *\n * @param bin binary name or path\n * @param timeoutMs timeout\n */\nexport function probeFfmpeg(bin: string, timeoutMs = 5000): Promise<string> {\n\treturn new Promise(resolve => {\n\t\tlet out = '';\n\t\tlet done = false;\n\t\tconst timer: { id?: NodeJS.Timeout } = {};\n\t\tconst finish = (v: string): void => {\n\t\t\tif (!done) {\n\t\t\t\tdone = true;\n\t\t\t\tclearTimeout(timer.id);\n\t\t\t\tresolve(v);\n\t\t\t}\n\t\t};\n\t\tlet child: ReturnType<typeof spawn>;\n\t\ttry {\n\t\t\tchild = spawn(bin, ['-version'], { shell: false, windowsHide: true });\n\t\t} catch {\n\t\t\tresolve('');\n\t\t\treturn;\n\t\t}\n\t\ttimer.id = setTimeout(() => {\n\t\t\ttry {\n\t\t\t\tchild.kill('SIGKILL');\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t\tfinish('');\n\t\t}, timeoutMs);\n\t\tchild.stdout?.on('data', (c: Buffer) => {\n\t\t\tif (out.length < 4096) {\n\t\t\t\tout += c.toString();\n\t\t\t}\n\t\t});\n\t\tchild.on('error', () => finish(''));\n\t\tchild.on('close', code => finish(code === 0 ? parseFfmpegVersion(out) : ''));\n\t});\n}\n\n/**\n * Tries the candidates in order and returns the first working ffmpeg.\n *\n * @param candidates binaries in priority order\n * @param probe returns the version or '' (injectable for tests)\n */\nexport async function detectFfmpeg(\n\tcandidates: string[],\n\tprobe: (bin: string) => Promise<string> = b => probeFfmpeg(b),\n): Promise<FfmpegInfo> {\n\tfor (const c of candidates) {\n\t\tconst version = await probe(c);\n\t\tif (version) {\n\t\t\treturn { found: true, version, path: c };\n\t\t}\n\t}\n\treturn { found: false, version: '', path: '' };\n}\n\n/**\n * Text for info.ffmpeg.\n *\n * @param info detection result\n */\nexport function ffmpegStatusText(info: FfmpegInfo): string {\n\treturn info.found ? `${info.version} (${info.path})` : 'not found';\n}\n\n/**\n * AgentDVR lists a recording in getEvents while it is still being written. A recording counts as\n * finished when the camera no longer records and the listed size did not change since the last check.\n *\n * @param prevSize listed size at the previous check (-1 before the first check)\n * @param size listed size now\n * @param recording true while the camera records\n */\nexport function recordingFinished(prevSize: number, size: number, recording: boolean): boolean {\n\treturn !recording && size > 0 && size === prevSize;\n}\n\n/** Picture size and length of a video file */\nexport interface VideoInfo {\n\t/** width in pixels (0 = unknown) */\n\twidth: number;\n\t/** height in pixels (0 = unknown) */\n\theight: number;\n\t/** duration in whole seconds (0 = unknown) */\n\tduration: number;\n}\n\ninterface Box {\n\ttype: string;\n\tstart: number;\n\tend: number;\n}\n\nfunction* mp4Boxes(buf: Buffer, from: number, to: number): Generator<Box> {\n\tlet p = from;\n\twhile (p + 8 <= to) {\n\t\tlet size = buf.readUInt32BE(p);\n\t\tconst type = buf.toString('latin1', p + 4, p + 8);\n\t\tlet head = 8;\n\t\tif (size === 1) {\n\t\t\tif (p + 16 > to) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsize = Number(buf.readBigUInt64BE(p + 8));\n\t\t\thead = 16;\n\t\t} else if (size === 0) {\n\t\t\tsize = to - p;\n\t\t}\n\t\tif (size < head) {\n\t\t\treturn;\n\t\t}\n\t\tyield { type, start: p + head, end: Math.min(p + size, to) };\n\t\tp += size;\n\t}\n}\n\nfunction mp4Child(buf: Buffer, parent: Box, type: string): Box | undefined {\n\tfor (const b of mp4Boxes(buf, parent.start, parent.end)) {\n\t\tif (b.type === type) {\n\t\t\treturn b;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction mp4Info(buf: Buffer): VideoInfo {\n\tconst info: VideoInfo = { width: 0, height: 0, duration: 0 };\n\tconst top = [...mp4Boxes(buf, 0, buf.length)];\n\tconst moov = top.find(b => b.type === 'moov');\n\tif (!moov) {\n\t\treturn info;\n\t}\n\t// video track: tkhd width/height (16.16), mdhd timescale\n\tlet videoId = 0;\n\tlet videoScale = 0;\n\tfor (const trak of mp4Boxes(buf, moov.start, moov.end)) {\n\t\tif (trak.type !== 'trak') {\n\t\t\tcontinue;\n\t\t}\n\t\tconst tkhd = mp4Child(buf, trak, 'tkhd');\n\t\tif (!tkhd || tkhd.end - tkhd.start < 84) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst w = buf.readUInt32BE(tkhd.end - 8) / 65536;\n\t\tconst h = buf.readUInt32BE(tkhd.end - 4) / 65536;\n\t\tif (w > 0 && h > 0) {\n\t\t\tconst v1 = buf[tkhd.start] === 1;\n\t\t\tvideoId = buf.readUInt32BE(tkhd.start + (v1 ? 20 : 12));\n\t\t\tinfo.width = Math.round(w);\n\t\t\tinfo.height = Math.round(h);\n\t\t\tconst mdia = mp4Child(buf, trak, 'mdia');\n\t\t\tconst mdhd = mdia && mp4Child(buf, mdia, 'mdhd');\n\t\t\tif (mdhd) {\n\t\t\t\tvideoScale = buf.readUInt32BE(mdhd.start + (buf[mdhd.start] === 1 ? 20 : 12));\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\t// duration: mvhd (normal MP4), else mehd, else the end of the last fragment of the video track\n\tconst mvhd = mp4Child(buf, moov, 'mvhd');\n\tif (mvhd) {\n\t\tconst v1 = buf[mvhd.start] === 1;\n\t\tconst scale = buf.readUInt32BE(mvhd.start + (v1 ? 20 : 12));\n\t\tconst dur = v1 ? Number(buf.readBigUInt64BE(mvhd.start + 24)) : buf.readUInt32BE(mvhd.start + 16);\n\t\tif (scale > 0 && dur > 0) {\n\t\t\tinfo.duration = Math.round(dur / scale);\n\t\t}\n\t}\n\tif (!info.duration && videoId && videoScale) {\n\t\tlet end = 0;\n\t\tfor (const moof of top) {\n\t\t\tif (moof.type !== 'moof') {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const traf of mp4Boxes(buf, moof.start, moof.end)) {\n\t\t\t\tif (traf.type !== 'traf') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst tfhd = mp4Child(buf, traf, 'tfhd');\n\t\t\t\tif (!tfhd || buf.readUInt32BE(tfhd.start + 4) !== videoId) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst tfFlags = buf.readUInt32BE(tfhd.start) & 0xffffff;\n\t\t\t\tlet q = tfhd.start + 8;\n\t\t\t\tif (tfFlags & 0x1) {\n\t\t\t\t\tq += 8;\n\t\t\t\t}\n\t\t\t\tif (tfFlags & 0x2) {\n\t\t\t\t\tq += 4;\n\t\t\t\t}\n\t\t\t\tconst defDur = tfFlags & 0x8 ? buf.readUInt32BE(q) : 0;\n\t\t\t\tconst tfdt = mp4Child(buf, traf, 'tfdt');\n\t\t\t\tlet t = 0;\n\t\t\t\tif (tfdt) {\n\t\t\t\t\tt =\n\t\t\t\t\t\tbuf[tfdt.start] === 1\n\t\t\t\t\t\t\t? Number(buf.readBigUInt64BE(tfdt.start + 4))\n\t\t\t\t\t\t\t: buf.readUInt32BE(tfdt.start + 4);\n\t\t\t\t}\n\t\t\t\tfor (const trun of mp4Boxes(buf, traf.start, traf.end)) {\n\t\t\t\t\tif (trun.type !== 'trun') {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst flags = buf.readUInt32BE(trun.start) & 0xffffff;\n\t\t\t\t\tconst count = buf.readUInt32BE(trun.start + 4);\n\t\t\t\t\tlet r = trun.start + 8 + (flags & 0x1 ? 4 : 0) + (flags & 0x4 ? 4 : 0);\n\t\t\t\t\tconst per =\n\t\t\t\t\t\t(flags & 0x100 ? 4 : 0) +\n\t\t\t\t\t\t(flags & 0x200 ? 4 : 0) +\n\t\t\t\t\t\t(flags & 0x400 ? 4 : 0) +\n\t\t\t\t\t\t(flags & 0x800 ? 4 : 0);\n\t\t\t\t\tfor (let i = 0; i < count && r + per <= trun.end; i++) {\n\t\t\t\t\t\tt += flags & 0x100 ? buf.readUInt32BE(r) : defDur;\n\t\t\t\t\t\tr += per;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tend = Math.max(end, t);\n\t\t\t}\n\t\t}\n\t\tif (end > 0) {\n\t\t\tinfo.duration = Math.round(end / videoScale);\n\t\t}\n\t}\n\treturn info;\n}\n\nfunction ebmlVint(buf: Buffer, p: number, keepMarker: boolean): { val: number; len: number; unknown: boolean } | null {\n\tif (p >= buf.length) {\n\t\treturn null;\n\t}\n\tconst first = buf[p];\n\tlet len = 1;\n\twhile (len <= 8 && !(first & (0x80 >> (len - 1)))) {\n\t\tlen++;\n\t}\n\tif (len > 8 || p + len > buf.length) {\n\t\treturn null;\n\t}\n\tlet val = keepMarker ? first : first & (0xff >> len);\n\tlet allOnes = (first & (0xff >> len)) === 0xff >> len;\n\tfor (let i = 1; i < len; i++) {\n\t\tval = val * 256 + buf[p + i];\n\t\tif (buf[p + i] !== 0xff) {\n\t\t\tallOnes = false;\n\t\t}\n\t}\n\treturn { val, len, unknown: allOnes };\n}\n\nfunction mkvInfo(buf: Buffer): VideoInfo {\n\tconst info: VideoInfo = { width: 0, height: 0, duration: 0 };\n\tlet scale = 1000000;\n\tlet durTicks = 0;\n\tconst MASTER = new Set([0x18538067, 0x1549a966, 0x1654ae6b, 0xae, 0xe0]);\n\tconst walk = (from: number, to: number, depth: number): void => {\n\t\tlet p = from;\n\t\twhile (p < to && depth < 6) {\n\t\t\tconst id = ebmlVint(buf, p, true);\n\t\t\tconst size = id && ebmlVint(buf, p + id.len, false);\n\t\t\tif (!id || !size) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst start = p + id.len + size.len;\n\t\t\tconst end = size.unknown ? to : Math.min(start + size.val, to);\n\t\t\tif (id.val === 0x1f43b675) {\n\t\t\t\treturn; // first Cluster: all header data is before it\n\t\t\t}\n\t\t\tif (MASTER.has(id.val)) {\n\t\t\t\twalk(start, end, depth + 1);\n\t\t\t} else if (id.val === 0xb0 || id.val === 0xba || id.val === 0x2ad7b1) {\n\t\t\t\tlet v = 0;\n\t\t\t\tfor (let i = start; i < end; i++) {\n\t\t\t\t\tv = v * 256 + buf[i];\n\t\t\t\t}\n\t\t\t\tif (id.val === 0xb0 && !info.width) {\n\t\t\t\t\tinfo.width = v;\n\t\t\t\t} else if (id.val === 0xba && !info.height) {\n\t\t\t\t\tinfo.height = v;\n\t\t\t\t} else if (id.val === 0x2ad7b1) {\n\t\t\t\t\tscale = v;\n\t\t\t\t}\n\t\t\t} else if (id.val === 0x4489) {\n\t\t\t\tdurTicks = end - start === 8 ? buf.readDoubleBE(start) : end - start === 4 ? buf.readFloatBE(start) : 0;\n\t\t\t}\n\t\t\tif (size.unknown) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tp = end;\n\t\t}\n\t};\n\twalk(0, buf.length, 0);\n\tif (durTicks > 0) {\n\t\tinfo.duration = Math.round((durTicks * scale) / 1e9);\n\t}\n\treturn info;\n}\n\n/**\n * Width, height and duration from the headers of an MP4 (also fragmented) or MKV file. Unknown values are 0.\n * Telegram does not read them itself from larger bot uploads and then shows the video in a wrong\n * aspect ratio in the chat, so sendRecording passes them on.\n *\n * @param buf the whole file\n * @param format 'mp4' or 'mkv'\n */\nexport function videoInfo(buf: Buffer, format: string): VideoInfo {\n\ttry {\n\t\treturn format === 'mkv' ? mkvInfo(buf) : mp4Info(buf);\n\t} catch {\n\t\treturn { width: 0, height: 0, duration: 0 };\n\t}\n}\n\n// ---- remux ----\n\n/**\n * True if the Matroska header announces an HEVC video track (needs the hvc1 tag in MP4 for Apple/Telegram).\n *\n * @param buf MKV data\n */\nexport function isHevcMkv(buf: Buffer): boolean {\n\treturn buf.subarray(0, 256 * 1024).includes('V_MPEGH/ISO/HEVC');\n}\n\n/**\n * ffmpeg arguments for a lossless MKV \u2192 fragmented MP4 remux via stdin/stdout.\n *\n * @param hevc tag the video track as hvc1\n * @param dropAudio leave out the audio track\n */\nexport function remuxArgs(hevc: boolean, dropAudio: boolean): string[] {\n\tconst args = ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0', '-map', '0:v:0'];\n\tif (!dropAudio) {\n\t\targs.push('-map', '0:a?');\n\t}\n\targs.push('-c', 'copy');\n\tif (hevc) {\n\t\targs.push('-tag:v', 'hvc1');\n\t}\n\tif (dropAudio) {\n\t\targs.push('-an');\n\t}\n\targs.push('-movflags', 'frag_keyframe+empty_moov', '-f', 'mp4', 'pipe:1');\n\treturn args;\n}\n\n/**\n * Runs ffmpeg once with the input on stdin and collects stdout.\n *\n * @param bin ffmpeg binary\n * @param input input data\n * @param args ffmpeg arguments\n * @param timeoutMs timeout\n * @param maxBytes abort when the output gets larger\n */\nexport function runFfmpeg(\n\tbin: string,\n\tinput: Buffer,\n\targs: string[],\n\ttimeoutMs: number,\n\tmaxBytes: number,\n): Promise<Buffer> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet done = false;\n\t\tconst timer: { id?: NodeJS.Timeout } = {};\n\t\tconst chunks: Buffer[] = [];\n\t\tlet size = 0;\n\t\tlet err = '';\n\t\tconst child = spawn(bin, args, { shell: false, windowsHide: true });\n\t\tconst fail = (e: Error): void => {\n\t\t\tif (!done) {\n\t\t\t\tdone = true;\n\t\t\t\tclearTimeout(timer.id);\n\t\t\t\ttry {\n\t\t\t\t\tchild.kill('SIGKILL');\n\t\t\t\t} catch {\n\t\t\t\t\t/* ignore */\n\t\t\t\t}\n\t\t\t\treject(e);\n\t\t\t}\n\t\t};\n\t\ttimer.id = setTimeout(\n\t\t\t() => fail(new Error(`ffmpeg timeout after ${Math.round(timeoutMs / 1000)} s`)),\n\t\t\ttimeoutMs,\n\t\t);\n\t\tchild.stdout.on('data', (c: Buffer) => {\n\t\t\tsize += c.length;\n\t\t\tif (size > maxBytes) {\n\t\t\t\tfail(new Error(`MP4 larger than ${fmtMb(maxBytes)}`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchunks.push(c);\n\t\t});\n\t\tchild.stderr.on('data', (c: Buffer) => {\n\t\t\tif (err.length < 2000) {\n\t\t\t\terr += c.toString();\n\t\t\t}\n\t\t});\n\t\tchild.on('error', e => fail(e));\n\t\tchild.on('close', code => {\n\t\t\tif (done) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdone = true;\n\t\t\tclearTimeout(timer.id);\n\t\t\tif (code === 0 && size > 0) {\n\t\t\t\tresolve(Buffer.concat(chunks));\n\t\t\t} else {\n\t\t\t\treject(new Error(`ffmpeg exit code ${code}: ${err.trim().split('\\n').pop() || 'no output'}`));\n\t\t\t}\n\t\t});\n\t\t// EPIPE when ffmpeg stops reading early \u2014 the close handler reports the real error\n\t\tchild.stdin.on('error', () => {});\n\t\tchild.stdin.end(input);\n\t});\n}\n\n/**\n * Remuxes MKV to MP4 without re-encoding. Retries without audio if the audio codec can't go into MP4.\n *\n * @param bin ffmpeg binary\n * @param mkv input data\n * @param timeoutMs timeout per run\n * @param maxBytes output limit\n * @param onAudioDropped called when the retry without audio was needed\n * @param run ffmpeg runner (injectable for tests)\n */\nexport async function remuxToMp4(\n\tbin: string,\n\tmkv: Buffer,\n\ttimeoutMs: number,\n\tmaxBytes: number,\n\tonAudioDropped?: (reason: string) => void,\n\trun: typeof runFfmpeg = runFfmpeg,\n): Promise<Buffer> {\n\tconst hevc = isHevcMkv(mkv);\n\ttry {\n\t\treturn await run(bin, mkv, remuxArgs(hevc, false), timeoutMs, maxBytes);\n\t} catch (e) {\n\t\tconst msg = (e as Error).message;\n\t\tif (/timeout|larger than|ENOENT|Invalid data|Error opening input/i.test(msg)) {\n\t\t\tthrow e;\n\t\t}\n\t\tconst out = await run(bin, mkv, remuxArgs(hevc, true), timeoutMs, maxBytes);\n\t\tonAudioDropped?.(msg);\n\t\treturn out;\n\t}\n}\n\n// ---- download ----\n\n/** Result of a download into memory */\nexport interface DownloadResult {\n\t/** download complete */\n\tok: boolean;\n\t/** downloaded bytes */\n\tdata?: Buffer;\n\t/** error text */\n\terror?: string;\n\t/** true when the download was stopped because of the size limit */\n\ttooLarge?: boolean;\n\t/** received or announced size in bytes */\n\tsize?: number;\n}\n\n/**\n * GET into memory with timeout and size limit (Content-Length checked first, then the received bytes).\n *\n * @param opts request options (hostname, port, path, headers)\n * @param maxBytes size limit\n * @param timeoutMs overall timeout\n */\nexport function downloadToBuffer(\n\topts: http.RequestOptions,\n\tmaxBytes: number,\n\ttimeoutMs: number,\n): Promise<DownloadResult> {\n\treturn new Promise(resolve => {\n\t\tlet done = false;\n\t\tconst timer: { id?: NodeJS.Timeout } = {};\n\t\tlet req: http.ClientRequest | undefined;\n\t\tconst finish = (r: DownloadResult): void => {\n\t\t\tif (!done) {\n\t\t\t\tdone = true;\n\t\t\t\tclearTimeout(timer.id);\n\t\t\t\tresolve(r);\n\t\t\t}\n\t\t};\n\t\ttimer.id = setTimeout(() => {\n\t\t\treq?.destroy();\n\t\t\tfinish({ ok: false, error: `timeout after ${Math.round(timeoutMs / 1000)} s` });\n\t\t}, timeoutMs);\n\t\ttry {\n\t\t\treq = http.request({ ...opts, method: 'GET' }, res => {\n\t\t\t\tif (res.statusCode && res.statusCode >= 400) {\n\t\t\t\t\tres.resume();\n\t\t\t\t\tfinish({ ok: false, error: `HTTP ${res.statusCode}` });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst len = parseInt(String(res.headers['content-length'] ?? ''), 10);\n\t\t\t\tif (exceedsLimit(len, maxBytes)) {\n\t\t\t\t\treq?.destroy();\n\t\t\t\t\tfinish({ ok: false, tooLarge: true, size: len, error: `${fmtMb(len)} > limit ${fmtMb(maxBytes)}` });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst chunks: Buffer[] = [];\n\t\t\t\tlet size = 0;\n\t\t\t\tres.on('data', (c: Buffer) => {\n\t\t\t\t\tsize += c.length;\n\t\t\t\t\tif (size > maxBytes) {\n\t\t\t\t\t\treq?.destroy();\n\t\t\t\t\t\tfinish({ ok: false, tooLarge: true, size, error: `more than ${fmtMb(maxBytes)}` });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tchunks.push(c);\n\t\t\t\t});\n\t\t\t\tres.on('end', () => finish({ ok: true, data: Buffer.concat(chunks), size }));\n\t\t\t\tres.on('error', (e: Error) => finish({ ok: false, error: e.message }));\n\t\t\t});\n\t\t\treq.on('error', (e: Error) => finish({ ok: false, error: e.message }));\n\t\t\treq.end();\n\t\t} catch (e) {\n\t\t\tfinish({ ok: false, error: (e as Error).message });\n\t\t}\n\t});\n}\n\n// ---- camera lookup for sendTo ----\n\n/** Camera reference for findCamera */\nexport interface CamRef {\n\t/** AgentDVR object id */\n\toid: number | string;\n\t/** camera name */\n\tname: string;\n\t/** folder id, e.g. cam_8_Reolink */\n\tfid: string;\n}\n\n/**\n * Finds a camera by folder id (cam_8_Reolink), oid (8 / \"8\") or name (case-insensitive).\n *\n * @param query value from the message\n * @param cams known cameras\n */\nexport function findCamera(query: unknown, cams: CamRef[]): CamRef | undefined {\n\tif (query === undefined || query === null || query === '') {\n\t\treturn undefined;\n\t}\n\tconst q = (typeof query === 'number' ? String(query) : typeof query === 'string' ? query : '').trim();\n\tconst ql = q.toLowerCase();\n\treturn (\n\t\tcams.find(c => c.fid === q) ||\n\t\tcams.find(c => String(c.oid) === q) ||\n\t\tcams.find(c => c.name.toLowerCase() === ql) ||\n\t\tcams.find(c => q.endsWith(`.${c.fid}`))\n\t);\n}\n\n// ---- message bus guard ----\n\n/** Metadata answered by sendRecording / getRecording \u2014 never the video data itself */\nexport interface ProvidedRecording {\n\t/** recording is available */\n\tok: boolean;\n\t/** error text */\n\terror?: string;\n\t/** file name for the receiver, e.g. 8_2026-11-12_15-55-29_931.mp4 */\n\tfileName?: string;\n\t/** 'mp4' or 'mkv' */\n\tformat?: string;\n\t/** mime type */\n\tmime?: string;\n\t/** size in bytes */\n\tsize?: number;\n\t/** iobfile:// URI of the file in the adapter's file storage */\n\turi?: string;\n\t/** http(s) URL via the web instance ('' without one) */\n\turl?: string;\n\t/** absolute path on the ioBroker host ('' if the file storage is not on the local disk) */\n\tfile?: string;\n\t/** video width in pixels (0 = unknown) */\n\twidth?: number;\n\t/** video height in pixels (0 = unknown) */\n\theight?: number;\n\t/** duration in seconds (0 = unknown) */\n\tduration?: number;\n}\n\n/** Largest message the adapter puts on the message bus (sendTo answers and forwards) */\nexport const MAX_MESSAGE_BYTES = 64 * 1024;\n\n/**\n * True if the value contains binary data: a Buffer, a typed array / ArrayBuffer or a\n * JSON-serialized Buffer ({ type: 'Buffer', data: [...] }).\n *\n * @param value value to check\n * @param depth recursion depth\n */\nexport function containsBinary(value: unknown, depth = 0): boolean {\n\tif (value === null || typeof value !== 'object') {\n\t\treturn false;\n\t}\n\tif (depth > 20) {\n\t\treturn true;\n\t}\n\tif (Buffer.isBuffer(value) || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n\t\treturn true;\n\t}\n\tconst o = value as Record<string, unknown>;\n\tif (o.type === 'Buffer' && Array.isArray(o.data)) {\n\t\treturn true;\n\t}\n\tconst children = Array.isArray(value) ? (value as unknown[]) : Object.values(o);\n\treturn children.some(v => containsBinary(v, depth + 1));\n}\n\n/**\n * Throws if a message for the message bus contains binary data or is too large.\n *\n * @param value message\n */\nexport function assertNoBinary(value: unknown): void {\n\tif (containsBinary(value)) {\n\t\tthrow new Error('refusing to put binary data on the ioBroker message bus');\n\t}\n\tconst len = Buffer.byteLength(JSON.stringify(value ?? null));\n\tif (len > MAX_MESSAGE_BYTES) {\n\t\tthrow new Error(`refusing to put ${len} bytes on the ioBroker message bus`);\n\t}\n}\n\n/**\n * Returns the message if it is safe for the message bus, otherwise a small error answer.\n *\n * @param value message\n */\nexport function safeMessage<T>(value: T): T | { ok: false; error: string } {\n\ttry {\n\t\tassertNoBinary(value);\n\t\treturn value;\n\t} catch (e) {\n\t\treturn { ok: false, error: (e as Error).message };\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,gCAAsB;AACtB,SAAoB;AACpB,WAAsB;AACtB,WAAsB;AAGf,MAAM,qBAAqB,KAAK,OAAO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AAS,IAAI,EAAE,GAAG,EAAE,CAAC;AAExC;AAiCO,MAAM,oBAAoB,KAAK;AAS/B,SAAS,eAAe,OAAgB,QAAQ,GAAY;AAClE,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAChD,WAAO;AAAA,EACR;AACA,MAAI,QAAQ,IAAI;AACf,WAAO;AAAA,EACR;AACA,MAAI,OAAO,SAAS,KAAK,KAAK,YAAY,OAAO,KAAK,KAAK,iBAAiB,aAAa;AACxF,WAAO;AAAA,EACR;AACA,QAAM,IAAI;AACV,MAAI,EAAE,SAAS,YAAY,MAAM,QAAQ,EAAE,IAAI,GAAG;AACjD,WAAO;AAAA,EACR;AACA,QAAM,WAAW,MAAM,QAAQ,KAAK,IAAK,QAAsB,OAAO,OAAO,CAAC;AAC9E,SAAO,SAAS,KAAK,OAAK,eAAe,GAAG,QAAQ,CAAC,CAAC;AACvD;AAOO,SAAS,eAAe,OAAsB;AACpD,MAAI,eAAe,KAAK,GAAG;AAC1B,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC1E;AACA,QAAM,MAAM,OAAO,WAAW,KAAK,UAAU,wBAAS,IAAI,CAAC;AAC3D,MAAI,MAAM,mBAAmB;AAC5B,UAAM,IAAI,MAAM,mBAAmB,GAAG,oCAAoC;AAAA,EAC3E;AACD;AAOO,SAAS,YAAe,OAA4C;AAC1E,MAAI;AACH,mBAAe,KAAK;AACpB,WAAO;AAAA,EACR,SAAS,GAAG;AACX,WAAO,EAAE,IAAI,OAAO,OAAQ,EAAY,QAAQ;AAAA,EACjD;AACD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/build/main.js
CHANGED
|
@@ -27,6 +27,7 @@ var https = __toESM(require("node:https"));
|
|
|
27
27
|
var fs = __toESM(require("node:fs"));
|
|
28
28
|
var path = __toESM(require("node:path"));
|
|
29
29
|
var import_widget_i18n = require("./lib/widget-i18n");
|
|
30
|
+
var import_notify = require("./lib/notify");
|
|
30
31
|
var import_recording = require("./lib/recording");
|
|
31
32
|
const CAM_COMMANDS = [
|
|
32
33
|
{ id: "record", path: "/command/record", params: ["oid", "ot"], name: "Start recording" },
|
|
@@ -319,6 +320,14 @@ class AgentDvr extends utils.Adapter {
|
|
|
319
320
|
authHeader = null;
|
|
320
321
|
baseUrl = "";
|
|
321
322
|
wt = (0, import_widget_i18n.getWidgetLabels)("en");
|
|
323
|
+
/** system language for notification texts */
|
|
324
|
+
lang = "en";
|
|
325
|
+
/** connection outages of cameras and the server */
|
|
326
|
+
offline = new import_notify.OfflineTracker();
|
|
327
|
+
/** cameras whose outage state was read back after the start */
|
|
328
|
+
offlineRestored = /* @__PURE__ */ new Set();
|
|
329
|
+
/** notifications are sent one after another, so the notification-manager sends each only once */
|
|
330
|
+
notifyQueue = Promise.resolve();
|
|
322
331
|
ensuredFolders = /* @__PURE__ */ new Set();
|
|
323
332
|
registry = /* @__PURE__ */ new Map();
|
|
324
333
|
ptzActive = /* @__PURE__ */ new Map();
|
|
@@ -377,6 +386,7 @@ class AgentDvr extends utils.Adapter {
|
|
|
377
386
|
const sysConfig = await this.getForeignObjectAsync("system.config");
|
|
378
387
|
const rawLang = (_a = sysConfig == null ? void 0 : sysConfig.common) == null ? void 0 : _a.language;
|
|
379
388
|
this.wt = (0, import_widget_i18n.getWidgetLabels)(rawLang != null ? rawLang : "en");
|
|
389
|
+
this.lang = rawLang != null ? rawLang : "en";
|
|
380
390
|
const pollSeconds = Math.max(5, Math.min(3600, this.config.pollSeconds || 30));
|
|
381
391
|
this.baseUrl = `http://${this.config.serverIp}:${this.config.port || 8090}`;
|
|
382
392
|
if (this.config.user || this.config.pass) {
|
|
@@ -425,6 +435,7 @@ class AgentDvr extends utils.Adapter {
|
|
|
425
435
|
callback();
|
|
426
436
|
}
|
|
427
437
|
onMessage(obj) {
|
|
438
|
+
var _a;
|
|
428
439
|
if (!obj) {
|
|
429
440
|
return;
|
|
430
441
|
}
|
|
@@ -435,6 +446,14 @@ class AgentDvr extends utils.Adapter {
|
|
|
435
446
|
});
|
|
436
447
|
} else if (obj.command === "getAgentDvrCameras") {
|
|
437
448
|
this.sendTo(obj.from, obj.command, { cameras: this.lastCamNames }, obj.callback);
|
|
449
|
+
} else if (obj.command === "getCameras") {
|
|
450
|
+
const opts = this.lastCamNames.map((c) => ({ value: `${this.namespace}.${c.key}`, label: c.name }));
|
|
451
|
+
this.sendTo(obj.from, obj.command, opts, obj.callback);
|
|
452
|
+
} else if (obj.command === "getWidgets") {
|
|
453
|
+
const msg = (_a = obj.message) != null ? _a : {};
|
|
454
|
+
const kind = msg.kind === "live" ? "live" : "recordings";
|
|
455
|
+
const opts = this.config.enableWidget ? this.lastCamNames.map((c) => ({ value: `${this.namespace}.${c.key}.widget_${kind}`, label: c.name })) : [];
|
|
456
|
+
this.sendTo(obj.from, obj.command, opts, obj.callback);
|
|
438
457
|
} else if (obj.command === "getAvailableSources") {
|
|
439
458
|
void this.fetchAvailableSources().then((result) => {
|
|
440
459
|
this.sendTo(obj.from, obj.command, result, obj.callback);
|
|
@@ -1153,6 +1172,43 @@ class AgentDvr extends utils.Adapter {
|
|
|
1153
1172
|
this.recBusy[fid] = false;
|
|
1154
1173
|
})();
|
|
1155
1174
|
}
|
|
1175
|
+
// AgentDVR lists a recording while it is still being written: waits until the camera stops recording
|
|
1176
|
+
// and the listed size stays the same between two checks (at most 10 minutes). false = adapter stops
|
|
1177
|
+
// or the recording disappeared.
|
|
1178
|
+
async waitRecordingFinished(oid, fn) {
|
|
1179
|
+
var _a;
|
|
1180
|
+
const deadline = Date.now() + 10 * 6e4;
|
|
1181
|
+
let prev = -1;
|
|
1182
|
+
let waited = false;
|
|
1183
|
+
while (!this._pollStopped) {
|
|
1184
|
+
const res = await this.apiGet(`/q/getEvents?oid=${encodeURIComponent(String(oid))}&ot=2`);
|
|
1185
|
+
const json = asJson(res.data);
|
|
1186
|
+
const events = Array.isArray(json == null ? void 0 : json.events) ? json.events : Array.isArray(json) ? json : [];
|
|
1187
|
+
const ev = res.ok && json ? events.find((e) => e.fn === fn) : void 0;
|
|
1188
|
+
if (res.ok && json && !ev) {
|
|
1189
|
+
this.log.debug(`Recording ${fn} no longer listed`);
|
|
1190
|
+
return false;
|
|
1191
|
+
}
|
|
1192
|
+
const size = Number((_a = ev == null ? void 0 : ev.sb) != null ? _a : 0);
|
|
1193
|
+
const dev = [...this.devById.values()].find((x) => x.ot === 2 && String(x.oid) === String(oid));
|
|
1194
|
+
const data = dev == null ? void 0 : dev.raw.data;
|
|
1195
|
+
const recording = (data == null ? void 0 : data.recording) === true;
|
|
1196
|
+
if ((0, import_recording.recordingFinished)(prev, size, recording)) {
|
|
1197
|
+
if (waited) {
|
|
1198
|
+
this.log.debug(`Recording ${fn} finished (${(0, import_recording.fmtMb)(size)})`);
|
|
1199
|
+
}
|
|
1200
|
+
return true;
|
|
1201
|
+
}
|
|
1202
|
+
if (Date.now() > deadline) {
|
|
1203
|
+
this.log.info(`Recording ${fn} still growing after 10 minutes, storing the current state`);
|
|
1204
|
+
return true;
|
|
1205
|
+
}
|
|
1206
|
+
prev = size;
|
|
1207
|
+
waited = true;
|
|
1208
|
+
await this.delay(4e3);
|
|
1209
|
+
}
|
|
1210
|
+
return false;
|
|
1211
|
+
}
|
|
1156
1212
|
// Downloads a recording from AgentDVR into memory (never to disk), with size limit and timeout.
|
|
1157
1213
|
fetchRecording(oid, fn, maxBytes) {
|
|
1158
1214
|
return (0, import_recording.downloadToBuffer)(
|
|
@@ -1296,6 +1352,9 @@ class AgentDvr extends utils.Adapter {
|
|
|
1296
1352
|
this.log.info(`Recording ${fn} (${(0, import_recording.fmtMb)(listed)}) not stored: larger than ${(0, import_recording.fmtMb)(maxBytes)}`);
|
|
1297
1353
|
return;
|
|
1298
1354
|
}
|
|
1355
|
+
if (!await this.waitRecordingFinished(d.oid, fn)) {
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1299
1358
|
const dl = await this.fetchRecording(d.oid, fn, maxBytes);
|
|
1300
1359
|
if (!dl.ok || !dl.data) {
|
|
1301
1360
|
if (dl.tooLarge) {
|
|
@@ -1525,6 +1584,9 @@ class AgentDvr extends utils.Adapter {
|
|
|
1525
1584
|
if ((0, import_recording.exceedsLimit)(listedSize, limitBytes)) {
|
|
1526
1585
|
return { ok: false, size: listedSize, error: `Recording ${fn} is ${(0, import_recording.fmtMb)(listedSize)} \u2014 ${limitName}` };
|
|
1527
1586
|
}
|
|
1587
|
+
if (!await this.waitRecordingFinished(cam.oid, fn)) {
|
|
1588
|
+
return { ok: false, error: `Recording ${fn} is no longer available` };
|
|
1589
|
+
}
|
|
1528
1590
|
const dl = await this.fetchRecording(cam.oid, fn, limitBytes);
|
|
1529
1591
|
if (!dl.ok || !dl.data) {
|
|
1530
1592
|
return {
|
|
@@ -1552,7 +1614,13 @@ class AgentDvr extends utils.Adapter {
|
|
|
1552
1614
|
}
|
|
1553
1615
|
const storagePath = (0, import_recording.sendFileStoragePath)(cam.fid, out.ext);
|
|
1554
1616
|
await this.writeFileAsync(this.namespace, storagePath, out.data);
|
|
1555
|
-
return this.describeStored(
|
|
1617
|
+
return this.describeStored(
|
|
1618
|
+
storagePath,
|
|
1619
|
+
`${fn.replace(/\.[^.]+$/, "")}.${out.ext}`,
|
|
1620
|
+
out.ext,
|
|
1621
|
+
out.data.length,
|
|
1622
|
+
out.data
|
|
1623
|
+
);
|
|
1556
1624
|
}
|
|
1557
1625
|
async storedFileSize(storagePath) {
|
|
1558
1626
|
const local = this.localFilePath(storagePath);
|
|
@@ -1571,10 +1639,11 @@ class AgentDvr extends utils.Adapter {
|
|
|
1571
1639
|
const abs = path.join(utils.getAbsoluteDefaultDataDir(), "files", this.namespace, ...storagePath.split("/"));
|
|
1572
1640
|
return fs.existsSync(abs) ? abs : "";
|
|
1573
1641
|
}
|
|
1574
|
-
async describeStored(storagePath, fileName, format, size) {
|
|
1642
|
+
async describeStored(storagePath, fileName, format, size, data) {
|
|
1575
1643
|
if (this.webBaseUrl === void 0) {
|
|
1576
1644
|
this.webBaseUrl = await this.findWebBaseUrl();
|
|
1577
1645
|
}
|
|
1646
|
+
const v = (0, import_recording.videoInfo)(data != null ? data : await this.readStoredFile(storagePath), format);
|
|
1578
1647
|
return {
|
|
1579
1648
|
ok: true,
|
|
1580
1649
|
fileName,
|
|
@@ -1583,9 +1652,26 @@ class AgentDvr extends utils.Adapter {
|
|
|
1583
1652
|
size,
|
|
1584
1653
|
uri: `iobfile://${this.namespace}/${storagePath}`,
|
|
1585
1654
|
url: this.webBaseUrl ? `${this.webBaseUrl}/${this.namespace}/recordings/${storagePath}` : "",
|
|
1586
|
-
file: this.localFilePath(storagePath)
|
|
1655
|
+
file: this.localFilePath(storagePath),
|
|
1656
|
+
width: v.width,
|
|
1657
|
+
height: v.height,
|
|
1658
|
+
duration: v.duration
|
|
1587
1659
|
};
|
|
1588
1660
|
}
|
|
1661
|
+
// Reads a stored file inside the adapter process (never over the message bus); empty buffer on error.
|
|
1662
|
+
async readStoredFile(storagePath) {
|
|
1663
|
+
const local = this.localFilePath(storagePath);
|
|
1664
|
+
try {
|
|
1665
|
+
if (local) {
|
|
1666
|
+
return await fs.promises.readFile(local);
|
|
1667
|
+
}
|
|
1668
|
+
const f = await this.readFileAsync(this.namespace, storagePath);
|
|
1669
|
+
const file = f == null ? void 0 : f.file;
|
|
1670
|
+
return Buffer.isBuffer(file) ? file : Buffer.from(file != null ? file : "");
|
|
1671
|
+
} catch {
|
|
1672
|
+
return Buffer.alloc(0);
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1589
1675
|
async getRecording(msg) {
|
|
1590
1676
|
return this.provideRecording(
|
|
1591
1677
|
msg,
|
|
@@ -1622,6 +1708,13 @@ class AgentDvr extends utils.Adapter {
|
|
|
1622
1708
|
type: "video",
|
|
1623
1709
|
fileName: r.fileName
|
|
1624
1710
|
};
|
|
1711
|
+
if (telegram) {
|
|
1712
|
+
for (const k of ["width", "height", "duration"]) {
|
|
1713
|
+
if (r[k]) {
|
|
1714
|
+
payload[k] = r[k];
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1625
1718
|
for (const k of ["caption", "user", "chatId"]) {
|
|
1626
1719
|
const v = msg[k];
|
|
1627
1720
|
if (typeof v === "string" || typeof v === "number") {
|
|
@@ -1657,8 +1750,10 @@ class AgentDvr extends utils.Adapter {
|
|
|
1657
1750
|
// ---- device status data points ----
|
|
1658
1751
|
STATUS_DPS = [
|
|
1659
1752
|
{ key: "recording", role: "indicator.working", name: "Active recording" },
|
|
1660
|
-
|
|
1661
|
-
{ key: "
|
|
1753
|
+
// "online" in Agent DVR means: switched on in Agent DVR, not reachable
|
|
1754
|
+
{ key: "online", role: "indicator", name: "Switched on in Agent DVR" },
|
|
1755
|
+
// the stream connection is what tells whether the camera is reachable
|
|
1756
|
+
{ key: "connected", role: "indicator.reachable", name: "Connected (camera reachable)" },
|
|
1662
1757
|
{ key: "detected", role: "indicator", name: "Motion detected" },
|
|
1663
1758
|
{ key: "alerted", role: "indicator.alarm", name: "Alert active" }
|
|
1664
1759
|
];
|
|
@@ -1677,7 +1772,7 @@ class AgentDvr extends utils.Adapter {
|
|
|
1677
1772
|
}
|
|
1678
1773
|
const id = `${sfid}.${dp.key}`;
|
|
1679
1774
|
if (!this.ensuredFolders.has(id)) {
|
|
1680
|
-
await this.
|
|
1775
|
+
await this.extendObjectAsync(id, {
|
|
1681
1776
|
type: "state",
|
|
1682
1777
|
common: { name: dp.name, type: "boolean", role: dp.role, read: true, write: false, def: false },
|
|
1683
1778
|
native: {}
|
|
@@ -1686,6 +1781,113 @@ class AgentDvr extends utils.Adapter {
|
|
|
1686
1781
|
}
|
|
1687
1782
|
await this.setStateAsync(id, { val: !!data[dp.key], ack: true });
|
|
1688
1783
|
}
|
|
1784
|
+
if (d.ot === 2 && "connected" in data) {
|
|
1785
|
+
await this.trackCameraOffline(d, sfid, !!data.connected, data.online !== false);
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Follows the connection of a camera: offlineSince, offlineAlarm and notifications.
|
|
1790
|
+
*
|
|
1791
|
+
* @param d camera
|
|
1792
|
+
* @param sfid id of the status channel
|
|
1793
|
+
* @param connected stream connected
|
|
1794
|
+
* @param enabled camera switched on in Agent DVR
|
|
1795
|
+
*/
|
|
1796
|
+
async trackCameraOffline(d, sfid, connected, enabled) {
|
|
1797
|
+
var _a;
|
|
1798
|
+
const sinceId = `${sfid}.offlineSince`;
|
|
1799
|
+
const alarmId = `${sfid}.offlineAlarm`;
|
|
1800
|
+
if (!this.ensuredFolders.has(alarmId)) {
|
|
1801
|
+
await this.extendObjectAsync(sinceId, {
|
|
1802
|
+
type: "state",
|
|
1803
|
+
common: {
|
|
1804
|
+
name: "Not connected since",
|
|
1805
|
+
type: "number",
|
|
1806
|
+
role: "date",
|
|
1807
|
+
read: true,
|
|
1808
|
+
write: false,
|
|
1809
|
+
def: null
|
|
1810
|
+
},
|
|
1811
|
+
native: {}
|
|
1812
|
+
});
|
|
1813
|
+
await this.extendObjectAsync(alarmId, {
|
|
1814
|
+
type: "state",
|
|
1815
|
+
common: {
|
|
1816
|
+
name: "Offline longer than the set time",
|
|
1817
|
+
type: "boolean",
|
|
1818
|
+
role: "indicator.alarm",
|
|
1819
|
+
read: true,
|
|
1820
|
+
write: false,
|
|
1821
|
+
def: false
|
|
1822
|
+
},
|
|
1823
|
+
native: {}
|
|
1824
|
+
});
|
|
1825
|
+
this.ensuredFolders.add(alarmId);
|
|
1826
|
+
}
|
|
1827
|
+
const key = `cam_${d.oid}`;
|
|
1828
|
+
if (!this.offlineRestored.has(key)) {
|
|
1829
|
+
const since = await this.getStateAsync(sinceId);
|
|
1830
|
+
const alarm = await this.getStateAsync(alarmId);
|
|
1831
|
+
this.offline.restore(key, typeof (since == null ? void 0 : since.val) === "number" ? since.val : void 0, (alarm == null ? void 0 : alarm.val) === true);
|
|
1832
|
+
this.offlineRestored.add(key);
|
|
1833
|
+
}
|
|
1834
|
+
const limit = (0, import_notify.offlineMinutes)(this.config) * 6e4;
|
|
1835
|
+
const ch = this.offline.update(key, connected, enabled, Date.now(), limit);
|
|
1836
|
+
await this.setStateChangedAsync(sinceId, { val: (_a = ch.since) != null ? _a : null, ack: true });
|
|
1837
|
+
await this.setStateChangedAsync(alarmId, { val: ch.alarm, ack: true });
|
|
1838
|
+
if (ch.alarmStart) {
|
|
1839
|
+
this.log.warn(`Camera ${d.name} has not been connected for ${(0, import_notify.offlineMinutes)(this.config)} minutes`);
|
|
1840
|
+
this.notify("cameraOffline", d.oid, { name: d.name, min: (0, import_notify.offlineMinutes)(this.config) });
|
|
1841
|
+
}
|
|
1842
|
+
if (ch.alarmEnd !== void 0) {
|
|
1843
|
+
this.log.info(`Camera ${d.name} is connected again (outage about ${ch.alarmEnd} minutes)`);
|
|
1844
|
+
this.notify("cameraOnline", d.oid, { name: d.name, min: ch.alarmEnd });
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* Follows the reachability of the Agent DVR server.
|
|
1849
|
+
*
|
|
1850
|
+
* @param reachable server answered
|
|
1851
|
+
*/
|
|
1852
|
+
trackServerOffline(reachable) {
|
|
1853
|
+
const limit = (0, import_notify.offlineMinutes)(this.config) * 6e4;
|
|
1854
|
+
const ch = this.offline.update("server", reachable, true, Date.now(), limit);
|
|
1855
|
+
if (ch.alarmStart) {
|
|
1856
|
+
this.notify("serverOffline", null, { min: (0, import_notify.offlineMinutes)(this.config) });
|
|
1857
|
+
}
|
|
1858
|
+
if (ch.alarmEnd !== void 0) {
|
|
1859
|
+
this.notify("serverOnline", null, { min: ch.alarmEnd });
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* Sends a notification to the ioBroker notification system, if switched on in the settings.
|
|
1864
|
+
* The notification-manager adapter forwards it, e.g. to Telegram or e-mail.
|
|
1865
|
+
*
|
|
1866
|
+
* @param cat category
|
|
1867
|
+
* @param camera camera id in Agent DVR (null = not camera related)
|
|
1868
|
+
* @param params text placeholders
|
|
1869
|
+
* @param params.name camera name
|
|
1870
|
+
* @param params.min minutes
|
|
1871
|
+
* @param params.tag detection tag
|
|
1872
|
+
*/
|
|
1873
|
+
notify(cat, camera, params) {
|
|
1874
|
+
if (!(0, import_notify.categoryEnabled)(this.config, cat) || camera !== null && !(0, import_notify.cameraSelected)(this.config, camera)) {
|
|
1875
|
+
return;
|
|
1876
|
+
}
|
|
1877
|
+
const text = (0, import_notify.notifyText)(cat, this.lang, params);
|
|
1878
|
+
this.notifyQueue = this.notifyQueue.then(async () => {
|
|
1879
|
+
if (this._pollStopped) {
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
try {
|
|
1883
|
+
await this.registerNotification("agent-dvr", cat, text);
|
|
1884
|
+
} catch (e) {
|
|
1885
|
+
this.log.debug(`Notification ${cat}: ${e.message}`);
|
|
1886
|
+
}
|
|
1887
|
+
await new Promise((resolve) => {
|
|
1888
|
+
this.setTimeout(() => resolve(), 3e3);
|
|
1889
|
+
});
|
|
1890
|
+
});
|
|
1689
1891
|
}
|
|
1690
1892
|
// ---- build device data points ----
|
|
1691
1893
|
async buildDevice(d) {
|
|
@@ -2237,6 +2439,7 @@ class AgentDvr extends utils.Adapter {
|
|
|
2237
2439
|
this.eventTagsSeen[oid] = nextKnown;
|
|
2238
2440
|
if (newCount > 0) {
|
|
2239
2441
|
await this.pulse(`${fid}.events.new`);
|
|
2442
|
+
this.notify("newRecording", d.oid, { name: d.name });
|
|
2240
2443
|
if (this.recordingCamEnabled(fid)) {
|
|
2241
2444
|
void this.queueRecordingSave(d, fid, events[0]);
|
|
2242
2445
|
}
|
|
@@ -2249,6 +2452,10 @@ class AgentDvr extends utils.Adapter {
|
|
|
2249
2452
|
const tid = `${fid}.events.detected_${sanitize(t)}`;
|
|
2250
2453
|
await this.ensureFlag(tid, `Detected: ${t}`);
|
|
2251
2454
|
await this.pulse(tid);
|
|
2455
|
+
const cat = (0, import_notify.tagCategory)(t);
|
|
2456
|
+
if (cat) {
|
|
2457
|
+
this.notify(cat, d.oid, { name: d.name, tag: t });
|
|
2458
|
+
}
|
|
2252
2459
|
}
|
|
2253
2460
|
this.log.debug(`${newCount} new event(s), ${lateTags} late tag(s) cam ${oid} [${[...tags].join(",")}]`);
|
|
2254
2461
|
}
|
|
@@ -2337,11 +2544,13 @@ class AgentDvr extends utils.Adapter {
|
|
|
2337
2544
|
if (!res.ok || !json) {
|
|
2338
2545
|
await this.setStateAsync("info.connection", false, true);
|
|
2339
2546
|
await this.setStateAsync("system.online", { val: false, ack: true });
|
|
2547
|
+
this.trackServerOffline(false);
|
|
2340
2548
|
this.log.warn(`AgentDVR unreachable: ${res.error || "invalid response"}`);
|
|
2341
2549
|
return;
|
|
2342
2550
|
}
|
|
2343
2551
|
await this.setStateAsync("info.connection", true, true);
|
|
2344
2552
|
await this.setStateAsync("system.online", { val: true, ack: true });
|
|
2553
|
+
this.trackServerOffline(true);
|
|
2345
2554
|
if (json.settings) {
|
|
2346
2555
|
await this.flattenWrite(json.settings, "system.settings", 0);
|
|
2347
2556
|
}
|
|
@@ -2351,7 +2560,7 @@ class AgentDvr extends utils.Adapter {
|
|
|
2351
2560
|
await this.writeLeaf("system.raw_getObjects", JSON.stringify(clean).slice(0, 6e4));
|
|
2352
2561
|
}
|
|
2353
2562
|
const devices = findDevices(json);
|
|
2354
|
-
this.lastCamNames = devices.filter((d) => d.ot === 2).map((d) => ({ key: this.deviceFolder(d), name: d.name }));
|
|
2563
|
+
this.lastCamNames = devices.filter((d) => d.ot === 2).map((d) => ({ key: this.deviceFolder(d), name: d.name, oid: String(d.oid) }));
|
|
2355
2564
|
await this.setStateAsync("system.cameraCount", { val: devices.filter((d) => d.ot === 2).length, ack: true });
|
|
2356
2565
|
const activeFolders = new Set(devices.map((d) => this.deviceFolder(d)));
|
|
2357
2566
|
for (const d of devices) {
|