feat: V0.1.53 location timeline and durable device conversations
This commit is contained in:
+29
-15
@@ -1,25 +1,30 @@
|
||||
"""Explicitly permitted, short household announcements. Audio is RAM-only with a TTL."""
|
||||
"""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.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)
|
||||
with self.a.LOCK:self.sweep()
|
||||
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()
|
||||
@@ -28,12 +33,12 @@ class Voice:
|
||||
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']+'的手机')
|
||||
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'])
|
||||
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):
|
||||
@@ -70,6 +75,7 @@ class Voice:
|
||||
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')
|
||||
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}
|
||||
@@ -115,14 +121,17 @@ class Voice:
|
||||
|
||||
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'
|
||||
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
|
||||
@@ -130,17 +139,13 @@ class Voice:
|
||||
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)
|
||||
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 self.permitted(actor,target):raise a.Problem('对方尚未允许你喊话,或已关闭接收',403)
|
||||
if now-self.online.get(target['id'],0)>=20:raise a.Problem('对方不在线,请等对方打开 App',409)
|
||||
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=me+':'+message_id
|
||||
if key in self.receipts:return dict(ok=True,id=key,status=self.receipts[key]['status'])
|
||||
at,count=self.rates.get(me,(now,0))
|
||||
if count>=10:raise a.Problem('喊话过于频繁,请稍后再试',429)
|
||||
key=actor['archiveKey']+':'+message_id
|
||||
encoded=body.get('audio','')
|
||||
if not isinstance(encoded,str) or not 0<len(encoded)<=200000:raise a.Problem('语音大小超出限制')
|
||||
try:
|
||||
@@ -148,11 +153,19 @@ class Voice:
|
||||
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')
|
||||
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)
|
||||
@@ -160,9 +173,10 @@ class Voice:
|
||||
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']='received'
|
||||
self.history.delivery(key,'received')
|
||||
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']!='received':raise a.Problem('喊话回执不存在',404)
|
||||
if body.get('status') not in ('played','rejected'):raise a.Problem('回执不正确')
|
||||
receipt['status']=body['status'];return dict(ok=True)
|
||||
receipt['status']=body['status'];self.history.delivery(key,body['status']);return dict(ok=True)
|
||||
raise a.Problem('喊话操作不正确')
|
||||
|
||||
Reference in New Issue
Block a user