Add recording upload queue and verified local space reclamation dashboard

This commit is contained in:
Codex
2026-10-16 15:55:09 +08:00
parent 0cfda18053
commit f9be8a0a31
15 changed files with 267 additions and 25 deletions
+68 -5
View File
@@ -24,6 +24,8 @@ class Archive:
self.phase = ''
self.error = ''
self.scanned = 0
self.progress = {}
self.last_retry = 0
def initialize(self):
a = self.a
@@ -38,6 +40,10 @@ class Archive:
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);''')
columns = {r[1] for r in a.DB.execute('PRAGMA table_info(recording_archive)')}
for column, kind in [('released_bytes','INTEGER'),('released_at','REAL')]:
if column not in columns:
a.DB.execute('ALTER TABLE recording_archive ADD COLUMN '+column+' '+kind+' NOT NULL DEFAULT 0')
# 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:
@@ -153,6 +159,10 @@ class Archive:
self.update(row['id'],state='cloud',error=''); return True
if self.fingerprint(p) != row['fingerprint']:
raise self.a.Problem('片段在入队后发生变化,已保留本地文件,需核查')
def report(stage, done=0, total=0):
self.progress = dict(id=row['id'],stage=stage,done=done,total=total,
percent=round(min(100,100*done/total),1) if total else None)
report('preparing')
self.phase = '上传 '+dt.datetime.fromtimestamp(row['started'],ZONE).strftime('%m-%d %H:%M')+' · '+row['camera']
digest = hashlib.sha256()
with p.open('rb') as source:
@@ -162,18 +172,21 @@ class Archive:
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)
result = self.a.BAIDU.upload('shared',p,remote,progress=lambda n,total:report('uploading',n,total))
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)
report('verifying',0,row['size'])
self.a.BAIDU.verify_file(remote,result['fs_id'],row['size'],sha,progress=lambda n,total:report('verifying',n,total))
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)
report('verifying',0,row['size'])
self.a.BAIDU.verify_file(remote,row['fs_id'],row['size'],sha,progress=lambda n,total:report('verifying',n,total))
if self.fingerprint(p) != row['fingerprint']: raise self.a.Problem('上传期间片段发生变化,未删除本地文件')
report('cleaning')
p.unlink()
self.update(row['id'],state='cloud',retry_at=0,error='')
self.update(row['id'],state='cloud',retry_at=0,error='',released_bytes=row['size'],released_at=time.time())
self.error = ''
return True
except Exception as exc:
@@ -185,7 +198,7 @@ class Archive:
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()
self.phase = ''; self.progress = {}; self.guard.release()
def status(self):
with self.a.LOCK:
@@ -196,6 +209,56 @@ class Archive:
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 tasks(self, user, query):
"""Platform operations only; do not expose other households to managers."""
if user['role'] != 'admin': raise self.a.Problem('上传任务总览仅超级管理员可查看',403)
state = query.get('state','pending')
if state not in ('all','pending','retry','cloud','expired'): raise self.a.Problem('任务状态不正确')
try: page = int(query.get('page','1'))
except (TypeError,ValueError): raise self.a.Problem('页码不正确')
if not 1 <= page <= 1000000: raise self.a.Problem('页码不正确')
where = []; values = []
if state=='pending': where.append("state IN ('pending','verified')")
elif state=='retry': where.append("state IN ('pending','verified') AND error<>''")
elif state!='all': where.append('state=?');values.append(state)
for key in ('family','camera'):
if query.get(key):
if not re.fullmatch(ID,query[key]): raise self.a.Problem('筛选对象不正确')
where.append(key+'=?');values.append(query[key])
sql = ' WHERE '+' AND '.join(where) if where else ''
with self.a.LOCK:
count = self.a.DB.execute('SELECT count(*) FROM recording_archive'+sql,values).fetchone()[0]
page = min(page,max(1,math.ceil(count/20)))
rows = self.a.DB.execute("SELECT * FROM recording_archive"+sql+" ORDER BY CASE WHEN state IN ('pending','verified') THEN 0 ELSE 1 END, CASE WHEN state IN ('pending','verified') THEN started ELSE -started END,id LIMIT 20 OFFSET ?",(*values,(page-1)*20)).fetchall()
totals = dict(self.a.DB.execute("SELECT coalesce(sum(CASE WHEN state IN ('pending','verified') THEN size ELSE 0 END),0) pendingBytes, sum(CASE WHEN state IN ('pending','verified') THEN 1 ELSE 0 END) pendingCount, coalesce(sum(released_bytes),0) releasedBytes, coalesce(sum(CASE WHEN released_at>? THEN released_bytes ELSE 0 END),0) releasedTodayBytes, coalesce(sum(CASE WHEN state='cloud' THEN size ELSE 0 END),0) cloudBytes, sum(CASE WHEN state='cloud' THEN 1 ELSE 0 END) cloudCount FROM recording_archive",(dt.datetime.combine(dt.datetime.now(ZONE).date(),dt.time.min,tzinfo=ZONE).timestamp(),)).fetchone())
homes = {h['id']:h['name'] for h in self.a.objects('households')}
cameras = {c['id']:c['name'] for c in self.a.objects('cameras')}
scopes = self.a.DB.execute('SELECT DISTINCT family,camera FROM recording_archive ORDER BY family,camera').fetchall()
active = dict(self.progress)
items = [dict(id=r['id'],name=Path(r['path']).name,familyId=r['family'],familyName=homes.get(r['family'],'已移除家庭'),
cameraId=r['camera'],cameraName=cameras.get(r['camera'],'已移除摄像机'),started=r['started'],duration=r['duration'],
size=r['size'],state=r['state'],attempts=r['attempts'],error=r['error'],retryAt=r['retry_at'],
verifiedAt=r['verified_at'],releasedAt=r['released_at'],releasedBytes=r['released_bytes'],remotePath=r['remote']) for r in rows]
return dict(items=items,page=page,total=count,pages=max(1,math.ceil(count/20)),totals={k:v or 0 for k,v in totals.items()},
active=active,updatedAt=time.time(),status=self.status(),
families=[dict(id=k,name=homes.get(k,'已移除家庭')) for k in sorted({r['family'] for r in scopes})],
cameras=[dict(id=r['camera'],familyId=r['family'],name=cameras.get(r['camera'],'已移除摄像机')) for r in scopes])
def retry(self, user):
if user['role'] != 'admin': raise self.a.Problem('仅超级管理员可重试上传队列',403)
if not self.guard.acquire(blocking=False): raise self.a.Problem('当前片段正在处理,请等待完成',409)
try:
now=time.time()
if now-self.last_retry<10: raise self.a.Problem('请稍等后再重试',429)
with self.a.LOCK,self.a.DB:
row=self.a.DB.execute("SELECT id FROM recording_archive WHERE state IN ('pending','verified') ORDER BY started,id LIMIT 1").fetchone()
if not row: return dict(ok=True)
self.a.DB.execute('UPDATE recording_archive SET retry_at=0 WHERE id=?',(row['id'],))
self.last_retry=now
self.a.audit('重试最早待上传录像',user['username'])
return dict(ok=True)
finally: self.guard.release()
def listing(self, camera, start, end):
family = self.a.HOUSEHOLDS.family_of(camera)
with self.a.LOCK: