Separate system accounts and household people, add generation directory and consented member location sharing

This commit is contained in:
Codex
2026-10-18 20:00:43 +08:00
parent 67bc5a1ba9
commit 3b2c046060
52 changed files with 1497 additions and 311 deletions
+55 -16
View File
@@ -11,6 +11,7 @@ import shutil
import subprocess
import threading
import time
import recording_format
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')
@@ -44,6 +45,10 @@ class 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')
if 'metadata' not in columns:
a.DB.execute("ALTER TABLE recording_archive ADD COLUMN metadata TEXT NOT NULL DEFAULT ''")
if 'archive_size' not in columns:
a.DB.execute('ALTER TABLE recording_archive ADD COLUMN archive_size INTEGER 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:
@@ -145,6 +150,37 @@ class Archive:
r = self.a.DB.execute('SELECT * FROM recording_archive WHERE id=?',(key,)).fetchone()
return dict(r) if r else None
def prepared_file(self, row):
return self.a.DATA/'recording-prepared'/(row['id']+'.mp4')
def prepare(self, row, source):
# An already assigned old path stays immutable across retries/upgrades.
if row['remote'] and not row['metadata']: return source,row
target = self.prepared_file(row)
target.parent.mkdir(mode=0o700,exist_ok=True)
if target.is_symlink(): raise self.a.Problem('录像准备路径异常,原文件已保留')
family=self.a.get_object('households',row['family']) or {}
camera=self.a.get_object('cameras',row['camera']) or {}
saved=json.loads(row['metadata']) if row['metadata'] else {}
family_name=saved.get('familyName',family.get('name','家庭')); camera_name=saved.get('cameraName',camera.get('name','摄像头'))
if not target.exists() or not row['metadata']:
if shutil.disk_usage(target.parent).free < max(row['size']*2,512*1024*1024):
raise self.a.Problem('写入录像时间属性所需临时空间不足,原片段已保留')
temp=target.with_suffix('.partial.mp4')
try:
meta=recording_format.prepare(source,temp,row,family_name,camera_name)
temp.replace(target)
finally: temp.unlink(missing_ok=True)
if self.fingerprint(source)!=row['fingerprint']:
target.unlink(missing_ok=True)
raise self.a.Problem('录像准备期间原片段发生变化,已暂停上传')
# Persist path with metadata before a cloud request, for retry safety.
remote=row['remote'] or recording_format.remote_path(self.a.BAIDU.public_config()['appFolder'],
self.a.setting('recording_instance'),row,family_name,camera_name)
self.update(row['id'],metadata=json.dumps(meta,ensure_ascii=False),archive_size=target.stat().st_size,remote=remote)
row=self.row(row['id'])
return target,row
def process_one(self):
if not self.guard.acquire(blocking=False): return False
row = None
@@ -156,36 +192,40 @@ class Archive:
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
self.prepared_file(row).unlink(missing_ok=True)
self.update(row['id'],state='cloud',error='',released_bytes=row['size'],released_at=row['released_at'] or time.time()); 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')
upload_file,row=self.prepare(row,p)
archive_size=row['archive_size'] or row['size']
self.phase = '上传 '+dt.datetime.fromtimestamp(row['started'],ZONE).strftime('%m-%d %H:%M')+' · '+row['camera']
digest = hashlib.sha256()
with p.open('rb') as source:
with upload_file.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)
remote = row['remote']
self.update(row['id'],sha256=sha,remote=remote)
if row['state'] != 'verified':
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'):
result = self.a.BAIDU.upload('shared',upload_file,remote,progress=lambda n,total:report('uploading',n,total))
if result.get('path') != remote or result.get('size') != archive_size or not result.get('fs_id'):
raise self.a.Problem('网盘上传结果不完整,本地录像已保留')
self.phase = '校验云端片段 · '+row['camera']
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))
report('verifying',0,archive_size)
self.a.BAIDU.verify_file(remote,result['fs_id'],archive_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.
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))
report('verifying',0,archive_size)
self.a.BAIDU.verify_file(remote,row['fs_id'],archive_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.prepared_file(row).unlink(missing_ok=True)
self.update(row['id'],state='cloud',retry_at=0,error='',released_bytes=row['size'],released_at=time.time())
self.error = ''
return True
@@ -230,14 +270,15 @@ class Archive:
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())
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 CASE WHEN archive_size>0 THEN archive_size ELSE size END 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'],'已移除家庭'),
items = [dict(id=r['id'],name=Path(r['remote'] or 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'],
ended=r['started']+r['duration'],metadata=json.loads(r['metadata']) if r['metadata'] else {},
archiveSize=r['archive_size'] or r['size'],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(),
@@ -292,11 +333,9 @@ class Archive:
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)
if not recording_format.valid_path(row['remote'],self.a.BAIDU.public_config()['appFolder'],self.a.setting('recording_instance'),row): continue
self.a.BAIDU.delete_recording_file(row['remote'])
self.update(row['id'],state='expired')
def quota(self, policy):