Files
ucvl-home-vision/recording_hook.py
T

39 lines
1.5 KiB
Python

"""MediaMTX completion hook. Durable tickets contain no credentials."""
import hashlib
import json
import math
import os
from pathlib import Path
import re
import sys
import tempfile
def ticket(data, root, family, camera, segment, duration):
root = Path(root).resolve()
path = Path(segment)
if not re.fullmatch('[a-f0-9]{16}', family) or not re.fullmatch('[a-f0-9]{16}', camera):
raise ValueError('Invalid recording owner')
if path.is_symlink() or not path.is_file() or path.resolve().parent != root / family / ('cam_'+camera+'_main'):
raise ValueError('Invalid recording path')
duration = float(duration)
if not math.isfinite(duration) or not 0 < duration <= 86400:
raise ValueError('Invalid segment duration')
relative = str(path.resolve().relative_to(root))
folder = Path(data) / 'recording-tickets'
folder.mkdir(mode=0o700, exist_ok=True)
key = hashlib.sha256(relative.encode()).hexdigest()
body = dict(family=family, camera=camera, path=relative, duration=duration)
fd, temporary = tempfile.mkstemp(prefix='ticket-', dir=folder)
try:
with os.fdopen(fd, 'w', encoding='utf8') as output:
json.dump(body, output); output.flush(); os.fsync(output.fileno())
os.replace(temporary, folder/(key+'.json'))
finally:
Path(temporary).unlink(missing_ok=True)
if __name__ == '__main__':
os.umask(0o077)
ticket(*sys.argv[1:5], os.environ['MTX_SEGMENT_PATH'], os.environ['MTX_SEGMENT_DURATION'])