feat: household recording destinations and verified Baidu segment archive
This commit is contained in:
@@ -43,6 +43,8 @@ import baidu
|
||||
import journal
|
||||
import ptz
|
||||
import displays
|
||||
import family_locations
|
||||
import recording_archive
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
os.umask(0o077)
|
||||
@@ -74,7 +76,7 @@ SCAN = {'running': False, 'items': [], 'error': '', 'network': '', 'at': None}
|
||||
ATTEMPTS = {}
|
||||
API_PORT, HLS_PORT, PLAYBACK_PORT = 19997, 18888, 19996
|
||||
MEDIA_AUTH = None
|
||||
DEFAULT_STORAGE = {'retentionDays': 30, 'maxGB': 40, 'reserveGB': 8}
|
||||
DEFAULT_STORAGE = {'retentionDays': 30, 'maxGB': 40, 'reserveGB': 8, 'segmentMinutes': 5}
|
||||
|
||||
|
||||
class Problem(Exception):
|
||||
@@ -95,6 +97,8 @@ BAIDU = baidu.Baidu(sys.modules[__name__])
|
||||
JOURNAL = journal.Journal(sys.modules[__name__])
|
||||
CLOUD_IMAGES = cloud_images.CloudImages(sys.modules[__name__])
|
||||
DISPLAYS = displays.Displays(sys.modules[__name__])
|
||||
LOCATIONS = family_locations.Locations(sys.modules[__name__])
|
||||
ARCHIVE = recording_archive.Archive(sys.modules[__name__])
|
||||
|
||||
|
||||
def setting(key, default=None):
|
||||
@@ -250,6 +254,10 @@ def save_camera(body, actor=None):
|
||||
if not isinstance(body.get(k, False), bool):
|
||||
raise Problem('开关值不正确')
|
||||
item[k] = body.get(k, False)
|
||||
if item['archiveSource'] == 'recorder':
|
||||
if not item['archiveRecorderId']:
|
||||
raise Problem('选择录像机存储时,请绑定本家庭的录像机')
|
||||
item['record'] = False
|
||||
if not old and len(objects('cameras')) >= 32:
|
||||
raise Problem('此版本最多配置 32 台设备')
|
||||
save_object('cameras', item)
|
||||
@@ -332,15 +340,18 @@ def source(c, quality):
|
||||
def write_media_config():
|
||||
with LOCK:
|
||||
paths = {}
|
||||
policy = setting('storage', DEFAULT_STORAGE)
|
||||
policy = {**DEFAULT_STORAGE, **setting('storage', {})}
|
||||
for c in objects('cameras'):
|
||||
for quality in ('main', 'sub'):
|
||||
paths[stream_name(c, quality)] = {
|
||||
'source': source(c, quality) if c['enabled'] else 'publisher',
|
||||
'rtspTransport': 'tcp',
|
||||
'sourceOnDemand': quality == 'sub' and c['enabled'],
|
||||
'record': bool(c['enabled'] and c['record'] and quality == 'main' and not STORAGE['paused']),
|
||||
'recordDeleteAfter': str(policy['retentionDays'] * 24) + 'h',
|
||||
'record': bool(c['enabled'] and c['record'] and c.get('archiveSource') != 'recorder' and quality == 'main' and not STORAGE['paused']),
|
||||
'recordDeleteAfter': '0s',
|
||||
'recordPath': str(RECORDINGS / HOUSEHOLDS.family_of(c) / '%path' / '%Y-%m-%d_%H-%M-%S-%f'),
|
||||
'recordSegmentDuration': str(policy['segmentMinutes'])+'m',
|
||||
'runOnRecordSegmentComplete': shlex.join([sys.executable,str(ROOT/'recording_hook.py'),str(DATA),str(RECORDINGS),HOUSEHOLDS.family_of(c),c['id']]),
|
||||
}
|
||||
for quality in ('compat', 'hd'):
|
||||
paths[stream_name(c, quality)] = {
|
||||
@@ -364,7 +375,7 @@ def write_media_config():
|
||||
'permissions': [{'action': a} for a in ('read', 'api', 'playback')]
|
||||
+ [{'action': 'publish', 'path': '~^cam_[a-f0-9]{16}_(compat|hd)$'}]}],
|
||||
'pathDefaults': {'recordFormat': 'fmp4', 'recordPath': str(RECORDINGS / '%path' / '%Y-%m-%d_%H-%M-%S-%f'),
|
||||
'recordSegmentDuration': '5m', 'recordPartDuration': '1s'},
|
||||
'recordSegmentDuration': str(policy['segmentMinutes'])+'m', 'recordPartDuration': '1s', 'recordMaxPartSize':'10M'},
|
||||
'paths': paths,
|
||||
}
|
||||
raw = json.dumps(config, ensure_ascii=False, indent=2)
|
||||
@@ -429,6 +440,8 @@ def media_config_watch():
|
||||
|
||||
|
||||
def recording_state(camera, ready, media_online):
|
||||
if camera.get('archiveSource') == 'recorder':
|
||||
return 'recorder'
|
||||
if not camera.get('record'):
|
||||
return 'off'
|
||||
if not camera.get('enabled'):
|
||||
@@ -461,35 +474,44 @@ def status():
|
||||
main = ready.get(stream_name(c), {})
|
||||
recording = recording_state(c, main.get('ready', False), media)
|
||||
cameras.append({**public_camera(c), 'ready': main.get('ready', False), 'tracks': main.get('tracks', []),
|
||||
'recordingRequested': c['enabled'] and c['record'] and not STORAGE['paused'],
|
||||
'recordingRequested': c['enabled'] and c['record'] and c.get('archiveSource') != 'recorder' and not STORAGE['paused'],
|
||||
'recordingState': recording, 'recordingActive': recording == 'recording'})
|
||||
with LOCK:
|
||||
storage = dict(STORAGE)
|
||||
scan = dict(SCAN)
|
||||
return {'cameras': cameras, 'assets': objects('assets'), 'recorders': [public_camera(r) for r in objects('recorders')],
|
||||
'sites': objects('sites'), 'devices': objects('devices'), 'mediaOnline': media,
|
||||
'storage': {**setting('storage'), **storage}, 'scan': scan,
|
||||
'storage': {**DEFAULT_STORAGE, **setting('storage'), **storage, 'archive':ARCHIVE.status()}, 'scan': scan,
|
||||
'version': (ROOT / 'VERSION').read_text().strip(), 'uptime': round(time.time() - STARTED)}
|
||||
|
||||
|
||||
def storage_watch():
|
||||
while True:
|
||||
try:
|
||||
usage = shutil.disk_usage(RECORDINGS)
|
||||
used, recent = 0, {}
|
||||
for p in RECORDINGS.rglob('*.mp4'):
|
||||
try:
|
||||
info = p.stat()
|
||||
used += info.st_size
|
||||
recent[p.parent.name] = max(recent.get(p.parent.name, 0), info.st_mtime)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
policy = setting('storage')
|
||||
usage = shutil.disk_usage(DATA)
|
||||
used, recent, legacy_used = 0, {}, 0
|
||||
for root_key, root in ARCHIVE.roots().items():
|
||||
for p in root.rglob('*.mp4'):
|
||||
try:
|
||||
if p.is_symlink(): continue
|
||||
info = p.stat()
|
||||
used += info.st_size
|
||||
if root_key == 'legacy': legacy_used += info.st_size
|
||||
recent[p.parent.name] = max(recent.get(p.parent.name, 0), info.st_mtime)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
policy = {**DEFAULT_STORAGE, **setting('storage',{})}
|
||||
hard_ready, hard_bytes = ARCHIVE.quota(policy)
|
||||
spool_free = shutil.disk_usage(RECORDINGS).free
|
||||
free_gb, used_gb = usage.free / 1e9, used / 1e9
|
||||
reason = '录像空间已达到配额' if used_gb >= policy['maxGB'] else ('磁盘可用空间不足' if free_gb < policy['reserveGB'] else '')
|
||||
reason = ('临时录像区的硬容量限制尚未就绪' if not hard_ready else
|
||||
'旧录像正在上传,等待腾出新片段容量' if legacy_used+hard_bytes > policy['maxGB']*1e9 else
|
||||
'临时录像区接近容量上限,等待上传释放空间' if spool_free < 256*1024**2 else
|
||||
'磁盘可用空间不足' if free_gb < policy['reserveGB'] else '')
|
||||
with LOCK:
|
||||
changed = STORAGE['paused'] != bool(reason)
|
||||
STORAGE.update(freeGB=round(free_gb, 2), usedGB=round(used_gb, 2), paused=bool(reason), reason=reason)
|
||||
STORAGE.update(freeGB=round(free_gb, 2), usedGB=round(used_gb, 2), paused=bool(reason), reason=reason,
|
||||
hardQuotaReady=hard_ready, temporaryMaxGB=round(hard_bytes/1e9,2))
|
||||
RECENT_RECORDS.clear()
|
||||
RECENT_RECORDS.update(recent)
|
||||
if changed:
|
||||
@@ -502,7 +524,7 @@ def storage_watch():
|
||||
write_media_config()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(20)
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
def discover(network):
|
||||
@@ -667,6 +689,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
try:
|
||||
path = url.urlsplit(self.path).path
|
||||
if path == '/api/location/update':
|
||||
authorization=self.headers.get('Authorization','')
|
||||
self.answer(LOCATIONS.native(authorization[7:] if authorization.startswith('Bearer ') else '',self.body(4096)))
|
||||
return
|
||||
if path in ('/api/display/heartbeat','/api/display/preview'):
|
||||
authorization = self.headers.get('Authorization','')
|
||||
grant = DISPLAYS.authorize(authorization[7:] if authorization.startswith('Bearer ') else '')
|
||||
@@ -691,11 +717,13 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if path == '/api/display/pair':
|
||||
self.answer(DISPLAYS.pair(data, self.client_address[0]))
|
||||
return
|
||||
if path == '/api/location/pair':
|
||||
self.answer(LOCATIONS.pair(data,self.client_address[0]));return
|
||||
if path in ('/api/login', '/api/setup'):
|
||||
self.login(data, path == '/api/setup')
|
||||
return
|
||||
self.require_auth()
|
||||
if path not in ('/api/logout', '/api/account/password', '/api/preferences', '/api/households/layout', '/api/family/restore',
|
||||
if path not in ('/api/locations', '/api/logout', '/api/account/password', '/api/preferences', '/api/households/layout', '/api/family/restore',
|
||||
'/api/family/person', '/api/family/link', '/api/family/event', '/api/heritage', '/api/ptz', '/api/ptz/presets',
|
||||
'/api/journal', '/api/journal/action', '/api/journal/upload', '/api/journal/finish', '/api/journal/remove-upload', '/api/journal/restore-upload'):
|
||||
self.require_manager()
|
||||
@@ -704,6 +732,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
DB.execute('DELETE FROM sessions WHERE hash=?', (hashlib.sha256(self.token().encode()).hexdigest(),))
|
||||
DB.commit()
|
||||
self.answer({'ok': True}, cookie='vision=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict')
|
||||
elif path == '/api/locations':
|
||||
self.answer(LOCATIONS.manage(self.user,data))
|
||||
elif path == '/api/preferences':
|
||||
self.answer(APPEARANCE.save_preferences(data, self.user))
|
||||
elif path == '/api/households/layout':
|
||||
@@ -824,7 +854,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.require_admin()
|
||||
policy = {'retentionDays': integer(data.get('retentionDays'), 1, 365),
|
||||
'maxGB': integer(data.get('maxGB'), 5, 100000),
|
||||
'reserveGB': integer(data.get('reserveGB'), 2, 1000)}
|
||||
'reserveGB': integer(data.get('reserveGB'), 2, 1000),
|
||||
'segmentMinutes': integer(data.get('segmentMinutes',5), 1, 15)}
|
||||
if int(os.environ.get('VISION_RECORDING_QUOTA_BYTES','0')) > policy['maxGB']*1e9:
|
||||
raise Problem('容量上限不能小于已配置的临时录像分区容量')
|
||||
if policy['maxGB'] < setting('storage',DEFAULT_STORAGE)['maxGB'] and policy['maxGB'] < (STORAGE.get('usedGB') or 0):
|
||||
raise Problem('现有待上传录像超过新上限,请等待上传释放空间后再调小')
|
||||
set_setting('storage', policy)
|
||||
write_media_config()
|
||||
audit('更新录像保留策略')
|
||||
@@ -896,12 +931,13 @@ class Handler(BaseHTTPRequestHandler):
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def compatible_playback(self, path, duration):
|
||||
def compatible_playback(self, path, duration, cloud=None, offset=0):
|
||||
started = False
|
||||
old_timeout = self.connection.gettimeout()
|
||||
try:
|
||||
reserve_bytes = int(setting('storage', DEFAULT_STORAGE).get('reserveGB', 8) * 1024**3)
|
||||
with playback.stream('http://127.0.0.1:' + str(PLAYBACK_PORT) + path, MEDIA_AUTH, duration, reserve_bytes=reserve_bytes) as output:
|
||||
options = dict(response_factory=lambda: BAIDU.open_file('shared',dict(remotePath=cloud['remote'],fsId=cloud['fs_id'])), offset=offset) if cloud else {}
|
||||
with playback.stream('http://127.0.0.1:' + str(PLAYBACK_PORT) + path, MEDIA_AUTH, duration, reserve_bytes=reserve_bytes, **options) as output:
|
||||
first = output.read1(65536)
|
||||
if not first:
|
||||
raise Problem('录像转换失败,请检查录像是否完整及服务器视频驱动', 503)
|
||||
@@ -974,6 +1010,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.require_auth()
|
||||
if path == '/api/state':
|
||||
self.answer(ACCOUNTS.state(self.user, status()))
|
||||
elif path == '/api/locations':
|
||||
self.answer(LOCATIONS.snapshot(self.user))
|
||||
elif path == '/api/devices/network':
|
||||
self.require_manager(); self.answer(NETWORK.read(self.user, query))
|
||||
elif path == '/api/displays':
|
||||
@@ -1089,9 +1127,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
start, end = parse_time(query.get('start')), parse_time(query.get('end'))
|
||||
if not 0 < (end - start).total_seconds() <= 172800:
|
||||
raise Problem('每次查询最多两天')
|
||||
q = url.urlencode({'path': stream_name(c), 'start': start.isoformat(), 'end': end.isoformat()})
|
||||
raw = media_json('/list?' + q, playback=True)
|
||||
items = [{'start': r['start'], 'duration': r['duration']} for r in raw]
|
||||
if query.get('source') == 'baidu':
|
||||
items = ARCHIVE.listing(c,start.timestamp(),end.timestamp())
|
||||
else:
|
||||
q = url.urlencode({'path': stream_name(c), 'start': start.isoformat(), 'end': end.isoformat()})
|
||||
raw = media_json('/list?' + q, playback=True)
|
||||
items = [{'start': r['start'], 'duration': r['duration']} for r in raw]
|
||||
self.answer({'items': items})
|
||||
elif path.startswith('/media/live/'):
|
||||
suffix = path[len('/media/live/'):]
|
||||
@@ -1112,6 +1153,25 @@ class Handler(BaseHTTPRequestHandler):
|
||||
except ValueError:
|
||||
raise Problem('单次回放最多一小时')
|
||||
download = query.get('download') == '1'
|
||||
if query.get('cloudId'):
|
||||
cloud = ARCHIVE.authorized(self.user,query['cloudId'])
|
||||
offset = start.timestamp()-cloud['started']
|
||||
if cloud['camera'] != c['id'] or not 0 <= offset < cloud['duration']:
|
||||
raise Problem('录像时段不属于这个云端片段')
|
||||
duration = min(duration,cloud['duration']-offset,300)
|
||||
if download:
|
||||
with BAIDU.open_file('shared',dict(remotePath=cloud['remote'],fsId=cloud['fs_id']),self.headers.get('Range','')) as response:
|
||||
self.send_response(response.status)
|
||||
self.send_header('Content-Type','video/mp4')
|
||||
self.send_header('Content-Disposition','attachment; filename="recording.mp4"')
|
||||
self.send_header('Cache-Control','no-store')
|
||||
for header in ('Content-Length','Content-Range','Accept-Ranges'):
|
||||
if response.headers.get(header): self.send_header(header,response.headers[header])
|
||||
self.end_headers()
|
||||
while chunk := response.read(65536): self.wfile.write(chunk)
|
||||
else:
|
||||
self.compatible_playback('',duration,cloud=cloud,offset=offset)
|
||||
return
|
||||
q = url.urlencode({'path': stream_name(c), 'start': start.isoformat(), 'duration': duration,
|
||||
'format': 'mp4' if download else 'fmp4'})
|
||||
if download:
|
||||
@@ -1170,6 +1230,8 @@ def initialize():
|
||||
ACCOUNTS.initialize()
|
||||
HOUSEHOLDS.initialize()
|
||||
DISPLAYS.initialize()
|
||||
LOCATIONS.initialize()
|
||||
ARCHIVE.initialize()
|
||||
HERITAGE.initialize()
|
||||
JOURNAL.initialize()
|
||||
if not setting('storage'):
|
||||
@@ -1180,6 +1242,8 @@ def initialize():
|
||||
if not objects('users') and not (DATA / 'setup-code.txt').exists():
|
||||
(DATA / 'setup-code.txt').write_text(secrets.token_hex(12), encoding='utf8')
|
||||
os.chmod(DATA / 'setup-code.txt', 0o600)
|
||||
# Recording cannot start before the hard-limit volume and space guard run.
|
||||
STORAGE.update(paused=True,reason='正在检查录像容量限制')
|
||||
write_media_config()
|
||||
|
||||
|
||||
@@ -1189,6 +1253,7 @@ if __name__ == '__main__':
|
||||
threading.Thread(target=media_config_watch, daemon=True).start()
|
||||
threading.Thread(target=BACKUPS.watch, daemon=True).start()
|
||||
threading.Thread(target=DISPLAYS.watch, daemon=True).start()
|
||||
threading.Thread(target=ARCHIVE.watch, daemon=True).start()
|
||||
bindings = [h.strip() for h in os.environ.get('VISION_BIND', '127.0.0.1').split(',') if h.strip()]
|
||||
port = int(os.environ.get('VISION_PORT', '8790'))
|
||||
servers = []
|
||||
|
||||
Reference in New Issue
Block a user