Files

186 lines
11 KiB
Python

"""Explicitly permitted announcements plus durable, device-bound conversations."""
import base64
import hashlib
import json
import re
import time
from voice_history import VoiceHistory
class Voice:
def __init__(self, app):
self.a=app; self.online={}; self.messages={}; self.receipts={}; self.rates={}; self.history=VoiceHistory(app)
def initialize(self):
with self.a.LOCK,self.a.DB:
self.a.DB.execute('CREATE TABLE IF NOT EXISTS voice_receivers '
'(endpoint TEXT PRIMARY KEY, family_id TEXT, enabled INTEGER, allowed TEXT)')
self.online.clear(); self.messages.clear(); self.receipts.clear(); self.rates.clear()
self.history.initialize()
def watch(self):
while True:
time.sleep(10)
try:
with self.a.LOCK,self.a.DB:self.sweep()
self.history.tick()
except Exception:pass # Pending cloud work stays durable for a later retry.
def endpoint(self, key):
a=self.a;now=time.time()
if not isinstance(key,str):return None
kind,_,sid=key.partition(':')
if kind=='phone':
row=a.DB.execute('SELECT * FROM member_location_shares WHERE id=? AND expires>?',(sid,now)).fetchone()
valid=a.LOCATIONS.eligible(row['family_id'],row['member_id']) if row else None
if valid:return dict(id=key,kind=kind,familyId=row['family_id'],name=valid[1]['name']+'的手机',archiveKey=self.history.identity(row['family_id'],kind,row['member_id']))
elif kind=='display':
row=a.DB.execute('SELECT * FROM household_displays WHERE id=? AND revoked=0 AND expires_at>?',(sid,now)).fetchone()
device=a.get_object('devices',row['device_id']) if row else None
if device and a.HOUSEHOLDS.family_of(device)==row['family_id']:
return dict(id=key,kind=kind,familyId=row['family_id'],name=device['name'],archiveKey=self.history.identity(row['family_id'],kind,row['device_id']))
return None
def authorize(self, token, kind):
a=self.a
if not isinstance(token,str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}',token):raise a.Problem('请先完成设备配对',401)
if kind=='phone':
row=a.DB.execute('SELECT id FROM member_location_shares WHERE token_hash=?',(hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
actor=self.endpoint('phone:'+row['id']) if row else None
elif kind=='display':
grant=a.DISPLAYS.authorize_native(token)
actor=self.endpoint('display:'+grant['id'])
else:actor=None
if not actor:raise a.Problem('设备配对已失效,请重新配对',401)
return actor
def settings(self, actor):
row=self.a.DB.execute('SELECT * FROM voice_receivers WHERE endpoint=? AND family_id=?',(actor['id'],actor['familyId'])).fetchone()
return dict(enabled=bool(row['enabled']),allowed=json.loads(row['allowed'])) if row else dict(enabled=False,allowed=[])
def candidates(self, actor):
a=self.a;family=actor['familyId'];keys=[]
keys+=['phone:'+r['id'] for r in a.DB.execute('SELECT id FROM member_location_shares WHERE family_id=?',(family,))]
keys+=['display:'+r['id'] for r in a.DB.execute('SELECT id FROM household_displays WHERE family_id=? AND revoked=0',(family,))]
return [ep for key in keys if key!=actor['id'] and (ep:=self.endpoint(key))]
def permitted(self, sender, receiver):
if not sender or not receiver or sender['id']==receiver['id'] or sender['familyId']!=receiver['familyId']:return False
settings=self.settings(receiver)
return settings['enabled'] and sender['id'] in settings['allowed']
def sweep(self):
now=time.time()
for key,message in list(self.messages.items()):
if message['expires']<=now or not self.permitted(self.endpoint(message['sender']),self.endpoint(message['target'])):
self.messages.pop(key,None)
if key in self.receipts:self.receipts[key]['status']='expired'
self.history.delivery(key,'expired')
for key,receipt in self.receipts.items():
if receipt['expires']<=now and receipt['status'] in ('queued','transferring','received'):
self.history.delivery(key,'expired')
self.receipts={k:v for k,v in self.receipts.items() if v['expires']>now}
self.online={k:v for k,v in self.online.items() if now-v<60}
self.rates={k:v for k,v in self.rates.items() if now-v[0]<60}
def configure(self, actor, body):
enabled=body.get('enabled');allowed=body.get('allowed',[])
choices={r['id'] for r in self.candidates(actor)}
if type(enabled) is not bool or not isinstance(allowed,list) or len(allowed)>100 or any(not isinstance(k,str) for k in allowed) or len(set(allowed))!=len(allowed) or not set(allowed)<=choices:
raise self.a.Problem('请选择本家庭有效的喊话人')
if enabled and (body.get('consent') is not True or not allowed):raise self.a.Problem('请确认接收喊话并选择允许的家人或终端')
self.a.DB.execute('INSERT OR REPLACE INTO voice_receivers VALUES (?,?,?,?)',
(actor['id'],actor['familyId'],int(enabled),json.dumps(allowed)))
self.sweep()
return dict(ok=True,enabled=enabled,allowed=allowed)
def manage_display(self, user, body):
a=self.a;device=a.DISPLAYS.device(user,body.get('deviceId'))
with a.LOCK,a.DB:
row=a.DB.execute('SELECT id FROM household_displays WHERE device_id=? AND family_id=? AND revoked=0 AND expires_at>?',
(device['id'],a.HOUSEHOLDS.scope(user),time.time())).fetchone()
if not row:raise a.Problem('请先配对显示终端',409)
actor=self.endpoint('display:'+row['id'])
if body.get('action')=='configure':return self.configure(actor,body)
if body.get('action')!='settings':raise a.Problem('喊话设置操作不正确')
return dict(**self.settings(actor),candidates=self.candidates(actor))
@staticmethod
def duration(raw):
# Bound actual ADTS frame duration, rather than trusting client-supplied metadata.
rates=(96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350)
cursor=0;seconds=0
while cursor<len(raw):
h=raw[cursor:cursor+7]
if len(h)<7 or h[0]!=255 or h[1]&0xf6!=0xf0:raise ValueError()
rate=(h[2]>>2)&15
length=((h[3]&3)<<11)|(h[4]<<3)|(h[5]>>5)
header=7 if h[1]&1 else 9
if rate>=len(rates) or length<=header or cursor+length>len(raw):raise ValueError()
seconds+=1024*((h[6]&3)+1)/rates[rate];cursor+=length
if seconds>31:raise ValueError()
if seconds<.3:raise ValueError()
return round(seconds,2)
def native(self, token, body):
a=self.a;now=time.time()
if body.get('action')=='replay':return self.history.replay(token,body,self.authorize)
with a.LOCK,a.DB:
actor=self.authorize(token,body.get('kind'));self.sweep()
action=body.get('action');me=actor['id']
if action=='configure':return self.configure(actor,body)
if action=='history':return self.history.listing(actor,body)
if action=='offline':
self.online.pop(me,None)
for key,m in list(self.messages.items()):
if m['target']==me:
self.messages.pop(key);self.receipts[key]['status']='rejected';self.history.delivery(key,'rejected')
return dict(ok=True)
if action=='status':
self.online[me]=now
candidates=self.candidates(actor)
targets=[dict(ep,online=now-self.online.get(ep['id'],0)<20) for ep in candidates if self.permitted(actor,ep)]
inbox=[dict(id=k,senderName=m['senderName'],seconds=m['seconds']) for k,m in self.messages.items() if m['target']==me]
sent=[dict(id=k,status=r['status']) for k,r in self.receipts.items() if r['sender']==me]
return dict(me=actor,**self.settings(actor),candidates=candidates,targets=targets,inbox=inbox,sent=sent,conversations=self.history.conversations(actor))
if action=='send':
target=self.endpoint(body.get('target'))
if not target:raise a.Problem('接收设备配对已失效',403)
message_id=body.get('id','')
if not isinstance(message_id,str) or not re.fullmatch(r'[a-f0-9]{32}',message_id):raise a.Problem('喊话编号不正确')
key=actor['archiveKey']+':'+message_id
encoded=body.get('audio','')
if not isinstance(encoded,str) or not 0<len(encoded)<=200000:raise a.Problem('语音大小超出限制')
try:
raw=base64.b64decode(encoded,validate=True)
if len(raw)>150000:raise ValueError()
seconds=self.duration(raw)
except (ValueError,TypeError):raise a.Problem('请上传 0.3 至 30 秒的 AAC 语音')
if self.history.existing(key):
previous=self.history.accept(key,actor,target,raw,seconds)
return dict(ok=True,id=key,status=previous['delivery'],archive=previous['state'])
if not self.permitted(actor,target):raise a.Problem('对方尚未允许你喊话,或已关闭接收',403)
if now-self.online.get(target['id'],0)>=20:raise a.Problem('对方不在线,请等对方打开 App',409)
at,count=self.rates.get(me,(now,0))
if count>=10:raise a.Problem('喊话过于频繁,请稍后再试',429)
if len(self.messages)>=48 or len(self.receipts)>=2048 or sum(m['target']==target['id'] for m in self.messages.values())>=3:raise a.Problem('对方还有待播放的喊话,请稍候',429)
self.rates[me]=(at,count+1)
self.history.accept(key,actor,target,raw,seconds)
self.messages[key]=dict(sender=me,target=target['id'],senderName=actor['name'],audio=raw,seconds=seconds,expires=now+90)
self.receipts[key]=dict(sender=me,target=target['id'],status='queued',expires=now+180)
return dict(ok=True,id=key,status='queued',archive='pending')
key=body.get('id','')
if not isinstance(key,str):raise a.Problem('喊话编号不正确')
receipt=self.receipts.get(key)
if action=='take':
m=self.messages.get(key)
if not m or m['target']!=me or not self.permitted(self.endpoint(m['sender']),actor):raise a.Problem('语音已过期或没有接收权限',404)
del self.messages[key];receipt['status']='transferring'
self.history.delivery(key,'transferring')
return dict(id=key,senderName=m['senderName'],seconds=m['seconds'],audio=base64.b64encode(m['audio']).decode())
if action=='ack':
if not receipt or receipt['target']!=me or receipt['status'] not in ('transferring','received'):raise a.Problem('喊话回执不存在',404)
if body.get('status') not in ('received','played','rejected'):raise a.Problem('回执不正确')
receipt['status']=body['status'];self.history.delivery(key,body['status']);return dict(ok=True)
raise a.Problem('喊话操作不正确')