Files
ucvl-home-vision/voice_history.py
T

195 lines
11 KiB
Python
Raw Permalink Normal View History

"""Participant-only voice conversations. SQLite indexes; bounded encrypted cloud outbox.
The logical phone is the household member's paired phone (currently one per member).
Displays use the household + inventory device, never a temporary pairing token.
Audio is retained indefinitely in Baidu after checksum verification, not in SQLite.
"""
import base64
import datetime as dt
import hashlib
import os
import re
import secrets
import shutil
import threading
import time
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
LIMIT = 16 * 1024 * 1024
MAX_FILE = 150028
READ_SLOTS = threading.BoundedSemaphore(2)
class VoiceHistory:
def __init__(self, app):
self.a = app
self.worker = threading.Lock()
@property
def folder(self):
return self.a.DATA / 'voice-outbox'
def initialize(self):
a = self.a
with a.LOCK, a.DB:
a.DB.execute('''CREATE TABLE IF NOT EXISTS voice_history (
seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL,
family TEXT NOT NULL, sender TEXT NOT NULL, target TEXT NOT NULL,
sender_name TEXT, target_name TEXT, sender_kind TEXT, target_kind TEXT,
at REAL NOT NULL, seconds REAL NOT NULL, digest TEXT NOT NULL,
delivery TEXT NOT NULL, remote TEXT NOT NULL, state TEXT NOT NULL,
fs_id TEXT DEFAULT '', cipher_sha TEXT NOT NULL, size INTEGER NOT NULL,
attempts INTEGER DEFAULT 0, next_try REAL DEFAULT 0)''')
a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_sender ON voice_history(family,sender,seq)')
a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_target ON voice_history(family,target,seq)')
a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_pair ON voice_history(family,sender,target,seq)')
a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_pending ON voice_history(state,next_try,seq)')
if not a.setting('voice_history_key'):
a.set_setting('voice_history_key', base64.b64encode(secrets.token_bytes(32)).decode())
# A restart ends live playback, but never removes the conversation.
a.DB.execute("UPDATE voice_history SET delivery='expired' WHERE delivery IN ('queued','transferring','received')")
a.DB.execute("UPDATE voice_history SET state='retry' WHERE state='uploading'")
self.folder.mkdir(parents=True, exist_ok=True)
os.chmod(self.folder, 0o700)
with a.LOCK:
pending = {self.filename(r['id']) for r in a.DB.execute("SELECT id FROM voice_history WHERE state!='cloud'")}
for file in self.folder.iterdir():
if re.fullmatch(r'[a-f0-9]{64}\.(voice|partial)', file.name) and file.name not in pending:
file.unlink(missing_ok=True)
@staticmethod
def identity(family, kind, key):
return hashlib.sha256((family + '|' + kind + '|' + key).encode()).hexdigest()
@staticmethod
def filename(key):
return hashlib.sha256(key.encode()).hexdigest() + '.voice'
def existing(self, key):
return self.a.DB.execute('SELECT * FROM voice_history WHERE id=?', (key,)).fetchone()
def accept(self, key, actor, target, raw, seconds):
"""Called under the app transaction, before acknowledging the accepted send."""
a = self.a
previous = self.existing(key)
digest = hashlib.sha256(raw).hexdigest()
if previous:
if previous['sender'] != actor['archiveKey'] or previous['target'] != target['archiveKey'] or previous['digest'] != digest:
raise a.Problem('语音编号已用于另一条内容,请重新录制', 409)
return previous
used = max(a.DB.execute("SELECT coalesce(sum(size),0) FROM voice_history WHERE state!='cloud'").fetchone()[0],
sum(p.stat().st_size for p in self.folder.iterdir() if p.suffix in ('.voice','.partial')))
if used + len(raw) + 28 > LIMIT or shutil.disk_usage(a.DATA).free < 256 * 1024 * 1024:
raise a.Problem('语音归档等待空间不足,请稍后再发;已有记录保留', 507)
now = time.time()
nonce = secrets.token_bytes(12)
cipher = nonce + AESGCM(base64.b64decode(a.setting('voice_history_key'))).encrypt(nonce, raw, key.encode())
local = self.folder / self.filename(key)
temporary = local.with_suffix('.partial')
with temporary.open('wb') as stream:
os.chmod(temporary, 0o600)
stream.write(cipher)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, local)
if os.name != 'nt':
fd = os.open(self.folder, os.O_RDONLY)
try: os.fsync(fd)
finally: os.close(fd)
date = dt.datetime.fromtimestamp(now, dt.timezone(dt.timedelta(hours=8)))
conversation = hashlib.sha256('|'.join(sorted([actor['archiveKey'], target['archiveKey']])).encode()).hexdigest()
remote = '/apps/' + a.BAIDU.public_config()['appFolder'] + '/家庭沟通/' + actor['familyId'] + '/' + conversation + '/' + date.strftime('%Y/%m/%d/') + local.name
a.DB.execute('''INSERT INTO voice_history
(id,family,sender,target,sender_name,target_name,sender_kind,target_kind,at,seconds,digest,delivery,remote,state,cipher_sha,size)
VALUES (?,?,?,?,?,?,?,?,?,?,?,'queued',?,'pending',?,?)''',
(key, actor['familyId'], actor['archiveKey'], target['archiveKey'], actor['name'], target['name'], actor['kind'], target['kind'], now, seconds, digest, remote, hashlib.sha256(cipher).hexdigest(), len(cipher)))
return None
def delivery(self, key, state):
self.a.DB.execute('UPDATE voice_history SET delivery=? WHERE id=?', (state, key))
def conversations(self, actor):
me = actor['archiveKey']
rows = self.a.DB.execute('''SELECT * FROM voice_history WHERE seq IN (
SELECT max(seq) FROM voice_history WHERE family=? AND (sender=? OR target=?)
GROUP BY CASE WHEN sender=? THEN target ELSE sender END) ORDER BY seq DESC LIMIT 200''',
(actor['familyId'], me, me, me)).fetchall()
return [dict(archiveKey=r['target'] if r['sender']==me else r['sender'],
name=r['target_name'] if r['sender']==me else r['sender_name'],
kind=r['target_kind'] if r['sender']==me else r['sender_kind'],
lastAt=r['at']) for r in rows]
def listing(self, actor, body):
peer = body.get('peer', '')
before = body.get('before', 0)
if not isinstance(peer, str) or not re.fullmatch(r'[a-f0-9]{64}', peer) or type(before) is not int or before < 0 or before > 2**63-1:
raise self.a.Problem('请选择有效的沟通对象和记录页')
me = actor['archiveKey']
# Two bounded index scans; do not sort a lifetime of messages to fetch ten rows.
cutoff=before or 2**63-1
rows = self.a.DB.execute('''SELECT * FROM (SELECT * FROM voice_history
WHERE family=? AND sender=? AND target=? AND seq<? ORDER BY seq DESC LIMIT 11)
UNION ALL SELECT * FROM (SELECT * FROM voice_history
WHERE family=? AND sender=? AND target=? AND seq<? ORDER BY seq DESC LIMIT 11)
ORDER BY seq DESC LIMIT 11''',
(actor['familyId'],me,peer,cutoff,actor['familyId'],peer,me,cutoff)).fetchall()
more = len(rows) > 10
rows = rows[:10]
return dict(items=[dict(id=r['id'], seq=r['seq'], mine=r['sender']==me,
senderName=r['sender_name'], targetName=r['target_name'], at=r['at'],
seconds=r['seconds'], delivery=r['delivery'], archive=r['state']) for r in reversed(rows)],
before=rows[-1]['seq'] if more else 0)
def permitted_row(self, actor, key):
row = self.existing(key) if isinstance(key,str) else None
if not row or row['family'] != actor['familyId'] or actor['archiveKey'] not in (row['sender'], row['target']):
raise self.a.Problem('聊天记录不存在或不属于此设备', 404)
return dict(row)
def replay(self, token, body, authorize):
if not READ_SLOTS.acquire(False): raise self.a.Problem('语音正在读取,请稍后再试', 429)
try:
with self.a.LOCK:
actor = authorize(token, body.get('kind'))
row = self.permitted_row(actor, body.get('id'))
if row['state'] == 'cloud':
with self.a.BAIDU.open_file('shared', dict(remotePath=row['remote'], fsId=row['fs_id'])) as stream:
cipher = stream.read(MAX_FILE + 1)
else:
try:
with (self.folder / self.filename(row['id'])).open('rb') as stream: cipher = stream.read(MAX_FILE + 1)
except FileNotFoundError: raise self.a.Problem('语音归档状态刚更新,请重试', 409)
if len(cipher)!=row['size'] or len(cipher)>MAX_FILE or hashlib.sha256(cipher).hexdigest()!=row['cipher_sha']:
raise self.a.Problem('语音校验未通过,未播放', 502)
with self.a.LOCK:
# Authorization can change during the cloud request.
self.permitted_row(authorize(token,body.get('kind')),row['id'])
secret=base64.b64decode(self.a.setting('voice_history_key'))
raw = AESGCM(secret).decrypt(cipher[:12], cipher[12:], row['id'].encode())
if hashlib.sha256(raw).hexdigest()!=row['digest']: raise self.a.Problem('语音内容校验未通过',502)
return dict(id=row['id'], senderName=row['sender_name'], seconds=row['seconds'], audio=base64.b64encode(raw).decode())
finally: READ_SLOTS.release()
def tick(self):
if not self.worker.acquire(False): return
a=self.a
try:
with a.LOCK:
row=a.DB.execute("SELECT * FROM voice_history WHERE state!='cloud' AND next_try<=? ORDER BY seq LIMIT 1", (time.time(),)).fetchone()
if not row:return
row=dict(row)
with a.DB:a.DB.execute("UPDATE voice_history SET state='uploading' WHERE id=?",(row['id'],))
local=self.folder/self.filename(row['id'])
try:
with local.open('rb') as stream: cipher=stream.read(MAX_FILE+1)
if len(cipher)!=row['size'] or hashlib.sha256(cipher).hexdigest()!=row['cipher_sha']:raise ValueError('outbox integrity')
result=a.BAIDU.upload('shared',local,row['remote'])
a.BAIDU.verify_file(row['remote'],str(result['fs_id']),row['size'],row['cipher_sha'])
with a.LOCK,a.DB:
a.DB.execute("UPDATE voice_history SET state='cloud',fs_id=?,next_try=0 WHERE id=?",(str(result['fs_id']),row['id']))
local.unlink(missing_ok=True)
except Exception:
with a.LOCK,a.DB:
a.DB.execute("UPDATE voice_history SET state='retry',attempts=attempts+1,next_try=? WHERE id=? AND state!='cloud'",(time.time()+min(21600,30*2**min(row['attempts'],9)),row['id']))
finally:self.worker.release()