249 lines
14 KiB
Python
249 lines
14 KiB
Python
"""Ordered, durable Baidu recording archive; delete local bytes only after readback."""
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import secrets
|
|
import shutil
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
|
|
ID = r'[a-f0-9]{16}'
|
|
NAME = re.compile(r'\d{4}-\d\d-\d\d_\d\d-\d\d-\d\d-\d{6}\.mp4')
|
|
ZONE = dt.timezone(dt.timedelta(hours=8))
|
|
|
|
|
|
class Archive:
|
|
def __init__(self, app):
|
|
self.a = app
|
|
self.guard = threading.Lock()
|
|
self.phase = ''
|
|
self.error = ''
|
|
self.scanned = 0
|
|
|
|
def initialize(self):
|
|
a = self.a
|
|
with a.LOCK, a.DB:
|
|
a.DB.executescript('''CREATE TABLE IF NOT EXISTS recording_archive (
|
|
id TEXT PRIMARY KEY, family TEXT NOT NULL, camera TEXT NOT NULL,
|
|
root TEXT NOT NULL, path TEXT NOT NULL, started REAL NOT NULL,
|
|
duration REAL NOT NULL, size INTEGER NOT NULL, fingerprint TEXT NOT NULL,
|
|
sha256 TEXT NOT NULL DEFAULT '', remote TEXT NOT NULL DEFAULT '', fs_id TEXT NOT NULL DEFAULT '',
|
|
state TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
|
|
retry_at REAL NOT NULL DEFAULT 0, error TEXT NOT NULL DEFAULT '',
|
|
verified_at REAL NOT NULL DEFAULT 0, UNIQUE(root,path));
|
|
CREATE INDEX IF NOT EXISTS recording_archive_time ON recording_archive(state,started);
|
|
CREATE INDEX IF NOT EXISTS recording_archive_scope ON recording_archive(family,camera,started);''')
|
|
# Snapshot legacy ownership once. A later device transfer must not
|
|
# reassign historic footage to the receiving household.
|
|
if a.setting('recording_legacy_owners') is None:
|
|
a.set_setting('recording_legacy_owners', {c['id']:a.HOUSEHOLDS.family_of(c) for c in a.objects('cameras')})
|
|
if not a.setting('recording_instance'):
|
|
a.set_setting('recording_instance', secrets.token_hex(8))
|
|
|
|
def roots(self):
|
|
roots = {'current':self.a.RECORDINGS.resolve()}
|
|
legacy = os.environ.get('VISION_LEGACY_RECORDINGS', '')
|
|
if legacy and Path(legacy).resolve() != self.a.RECORDINGS.resolve():
|
|
roots['legacy'] = Path(legacy).resolve()
|
|
return roots
|
|
|
|
@staticmethod
|
|
def fingerprint(path):
|
|
s = path.stat()
|
|
return json.dumps([s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns])
|
|
|
|
def local(self, row):
|
|
root = self.roots().get(row['root'])
|
|
if root is None: raise self.a.Problem('录像目录已变化,保留队列等待管理员检查', 409)
|
|
p = root / row['path']
|
|
if p.is_symlink() or p.resolve() != p.absolute() or not p.resolve().is_relative_to(root.resolve()):
|
|
raise self.a.Problem('录像路径不安全,未操作文件', 409)
|
|
return p
|
|
|
|
def enqueue(self, root_key, relative, family, camera, duration):
|
|
if not re.fullmatch(ID, family) or not re.fullmatch(ID, camera): return
|
|
p = self.local(dict(root=root_key, path=relative))
|
|
root = self.roots()[root_key]
|
|
allowed = [root/family/('cam_'+camera+'_main')]
|
|
if root_key == 'legacy' or self.a.setting('recording_legacy_owners',{}).get(camera)==family:
|
|
allowed.append(root/('cam_'+camera+'_main'))
|
|
if p.parent not in allowed or not NAME.fullmatch(p.name) or not p.is_file(): return
|
|
if not math.isfinite(duration) or not 0 < duration <= 86400 or p.stat().st_size <= 0: return
|
|
# MediaMTX uses the host local timezone in its default strftime path.
|
|
started = dt.datetime.strptime(p.stem, '%Y-%m-%d_%H-%M-%S-%f').timestamp()
|
|
key = hashlib.sha256((root_key+'/'+relative).encode()).hexdigest()[:32]
|
|
with self.a.LOCK, self.a.DB:
|
|
self.a.DB.execute('INSERT OR IGNORE INTO recording_archive (id,family,camera,root,path,started,duration,size,fingerprint) VALUES (?,?,?,?,?,?,?,?,?)',
|
|
(key,family,camera,root_key,relative,started,duration,p.stat().st_size,self.fingerprint(p)))
|
|
|
|
def consume(self):
|
|
folder = self.a.DATA/'recording-tickets'
|
|
if not folder.exists(): return
|
|
for p in sorted(folder.glob('*.json'))[:256]:
|
|
if p.is_symlink() or p.stat().st_size > 4096: continue
|
|
try:
|
|
body = json.loads(p.read_text(encoding='utf8'))
|
|
self.enqueue('current',body['path'],body['family'],body['camera'],float(body['duration']))
|
|
p.unlink()
|
|
except (OSError, ValueError, KeyError, TypeError):
|
|
self.error = '部分录像完成通知无法读取,原文件已保留'
|
|
|
|
def recover(self):
|
|
"""Crash/upgrade recovery: never infer closure from age alone."""
|
|
if os.name != 'posix' or not Path('/proc').is_dir(): return
|
|
# Require visibility of the media writer's descriptors. Fail closed if
|
|
# it exists but /proc permissions prevent inspecting its open files.
|
|
opened = set()
|
|
try:
|
|
for proc in Path('/proc').iterdir():
|
|
if not proc.name.isdigit(): continue
|
|
try:
|
|
if proc.joinpath('comm').read_text().strip() != 'mediamtx': continue
|
|
for fd in proc.joinpath('fd').iterdir():
|
|
try: opened.add(os.readlink(fd))
|
|
except FileNotFoundError: pass
|
|
except FileNotFoundError: pass
|
|
except (PermissionError, OSError):
|
|
self.error = '无法核对录制中文件,暂缓恢复旧片段'; return
|
|
owners = self.a.setting('recording_legacy_owners',{})
|
|
recovered = 0
|
|
for root_key, root in self.roots().items():
|
|
for p in sorted(root.rglob('*.mp4')):
|
|
if recovered >= 100: return
|
|
if p.is_symlink() or not NAME.fullmatch(p.name): continue
|
|
relative = str(p.relative_to(root))
|
|
with self.a.LOCK:
|
|
if self.a.DB.execute('SELECT 1 FROM recording_archive WHERE root=? AND path=?',(root_key,relative)).fetchone(): continue
|
|
try:
|
|
if str(p) in opened or time.time()-p.stat().st_mtime < 60: continue
|
|
match = re.fullmatch('cam_('+ID+')_main',p.parent.name)
|
|
if not match: continue
|
|
camera = match[1]
|
|
family = p.parent.parent.name if re.fullmatch(ID,p.parent.parent.name) else owners.get(camera,'')
|
|
before = self.fingerprint(p)
|
|
result = subprocess.run(['ffprobe','-v','error','-show_entries','format=duration','-of','json',str(p)],capture_output=True,timeout=15,check=True)
|
|
duration = float(json.loads(result.stdout)['format']['duration'])
|
|
if self.fingerprint(p) != before: continue
|
|
self.enqueue(root_key,relative,family,camera,duration); recovered += 1
|
|
except (OSError,ValueError,KeyError,subprocess.SubprocessError): continue
|
|
|
|
def update(self, key, **values):
|
|
with self.a.LOCK, self.a.DB:
|
|
self.a.DB.execute('UPDATE recording_archive SET '+','.join(k+'=?' for k in values)+' WHERE id=?',(*values.values(),key))
|
|
|
|
def row(self, key):
|
|
with self.a.LOCK:
|
|
r = self.a.DB.execute('SELECT * FROM recording_archive WHERE id=?',(key,)).fetchone()
|
|
return dict(r) if r else None
|
|
|
|
def process_one(self):
|
|
if not self.guard.acquire(blocking=False): return False
|
|
row = None
|
|
try:
|
|
with self.a.LOCK:
|
|
r = self.a.DB.execute("SELECT * FROM recording_archive WHERE state IN ('pending','verified') ORDER BY started,id LIMIT 1").fetchone()
|
|
if not r: return False
|
|
row = dict(r)
|
|
if row['retry_at'] > time.time(): return False
|
|
p = self.local(row)
|
|
if row['state']=='verified' and not p.exists():
|
|
self.update(row['id'],state='cloud',error=''); return True
|
|
if self.fingerprint(p) != row['fingerprint']:
|
|
raise self.a.Problem('片段在入队后发生变化,已保留本地文件,需核查')
|
|
self.phase = '上传 '+dt.datetime.fromtimestamp(row['started'],ZONE).strftime('%m-%d %H:%M')+' · '+row['camera']
|
|
digest = hashlib.sha256()
|
|
with p.open('rb') as source:
|
|
while block := source.read(1024*1024): digest.update(block)
|
|
sha = digest.hexdigest()
|
|
if row['sha256'] and row['sha256'] != sha: raise self.a.Problem('本地片段校验不一致,未删除')
|
|
remote = row['remote'] or ('/apps/'+self.a.BAIDU.public_config()['appFolder']+'/监控录像/'+self.a.setting('recording_instance')+'/'+row['family']+'/'+row['camera']+'/'+dt.datetime.fromtimestamp(row['started'],ZONE).strftime('%Y-%m-%d')+'/'+p.name)
|
|
self.update(row['id'],sha256=sha,remote=remote)
|
|
if row['state'] != 'verified':
|
|
result = self.a.BAIDU.upload('shared',p,remote)
|
|
if result.get('path') != remote or result.get('size') != row['size'] or not result.get('fs_id'):
|
|
raise self.a.Problem('网盘上传结果不完整,本地录像已保留')
|
|
self.phase = '校验云端片段 · '+row['camera']
|
|
self.a.BAIDU.verify_file(remote,result['fs_id'],row['size'],sha)
|
|
self.update(row['id'],state='verified',fs_id=str(result['fs_id']),verified_at=time.time(),error='')
|
|
else:
|
|
# Recheck cloud after a crash before retrying the local deletion.
|
|
self.a.BAIDU.verify_file(remote,row['fs_id'],row['size'],sha)
|
|
if self.fingerprint(p) != row['fingerprint']: raise self.a.Problem('上传期间片段发生变化,未删除本地文件')
|
|
p.unlink()
|
|
self.update(row['id'],state='cloud',retry_at=0,error='')
|
|
self.error = ''
|
|
return True
|
|
except Exception as exc:
|
|
# Never expose credential-bearing HTTP/transport exception details.
|
|
message = str(exc) if isinstance(exc,self.a.Problem) else '上传或校验未完成,本地片段已保留,将自动重试'
|
|
self.error = message
|
|
if row:
|
|
attempts = row['attempts']+1
|
|
self.update(row['id'],attempts=attempts,retry_at=time.time()+min(1800,15*2**min(attempts,7)),error=message)
|
|
return False
|
|
finally:
|
|
self.phase = ''; self.guard.release()
|
|
|
|
def status(self):
|
|
with self.a.LOCK:
|
|
rows = list(self.a.DB.execute('SELECT state,count(*) AS n,coalesce(sum(size),0) AS bytes FROM recording_archive GROUP BY state'))
|
|
oldest = self.a.DB.execute("SELECT started,error,retry_at FROM recording_archive WHERE state IN ('pending','verified') ORDER BY started LIMIT 1").fetchone()
|
|
counts = {r['state']:r['n'] for r in rows}
|
|
return dict(pending=counts.get('pending',0)+counts.get('verified',0),uploaded=counts.get('cloud',0),
|
|
pendingGB=round(sum(r['bytes'] for r in rows if r['state'] in ('pending','verified'))/1e9,2),
|
|
phase=self.phase,error=self.error or (oldest['error'] if oldest else ''),retryAt=oldest['retry_at'] if oldest else 0)
|
|
|
|
def listing(self, camera, start, end):
|
|
family = self.a.HOUSEHOLDS.family_of(camera)
|
|
with self.a.LOCK:
|
|
rows = self.a.DB.execute("SELECT id,started,duration,state FROM recording_archive WHERE camera=? AND family=? AND state IN ('cloud','verified') AND started<? AND started+duration>? ORDER BY started LIMIT 3000",(camera['id'],family,end,start)).fetchall()
|
|
return [dict(id=r['id'],start=dt.datetime.fromtimestamp(r['started'],dt.timezone.utc).isoformat(),duration=r['duration'],source='baidu') for r in rows]
|
|
|
|
def authorized(self, user, key):
|
|
row = self.row(key)
|
|
if not row or row['state'] not in ('cloud','verified'): raise self.a.Problem('云端录像不存在',404)
|
|
camera = self.a.ACCOUNTS.camera(user,self.a.get_object('cameras',row['camera']))
|
|
if self.a.HOUSEHOLDS.family_of(camera) != row['family']: raise self.a.Problem('历史录像属于设备转移前的家庭,未授权访问',403)
|
|
return row
|
|
|
|
def watch(self):
|
|
while True:
|
|
try:
|
|
self.consume()
|
|
if time.time()-self.scanned > 60:
|
|
self.recover(); self.scanned = time.time()
|
|
if self.process_one():
|
|
self.prune()
|
|
continue
|
|
except Exception:
|
|
self.error = '录像队列暂不可用,原文件已保留'
|
|
time.sleep(5)
|
|
|
|
def prune(self):
|
|
# Only this instance's indexed, verified cloud recordings are eligible.
|
|
# Pending files never expire, including during a long cloud outage.
|
|
days = self.a.setting('storage',{}).get('retentionDays',30)
|
|
cutoff = time.time()-days*86400
|
|
with self.a.LOCK:
|
|
rows = [dict(r) for r in self.a.DB.execute("SELECT * FROM recording_archive WHERE state='cloud' AND started+duration<? ORDER BY started LIMIT 10",(cutoff,))]
|
|
root = '/apps/'+self.a.BAIDU.public_config()['appFolder']+'/监控录像/'+self.a.setting('recording_instance')+'/'
|
|
for row in rows:
|
|
expected = root+row['family']+'/'+row['camera']+'/'+dt.datetime.fromtimestamp(row['started'],ZONE).strftime('%Y-%m-%d')+'/'+Path(row['path']).name
|
|
if row['remote'] != expected: continue
|
|
self.a.BAIDU.delete_recording_file(expected)
|
|
self.update(row['id'],state='expired')
|
|
|
|
def quota(self, policy):
|
|
"""A dedicated filesystem enforces the limit even if Python stops."""
|
|
root = self.a.RECORDINGS
|
|
configured = int(os.environ.get('VISION_RECORDING_QUOTA_BYTES','0'))
|
|
ready = (os.name=='posix' and configured>0 and root.is_mount()
|
|
and root.stat().st_dev != self.a.DATA.stat().st_dev
|
|
and shutil.disk_usage(root).total <= configured <= policy['maxGB']*1e9)
|
|
return ready, configured
|