Files
ucvl-home-vision/member_locations.py
T

166 lines
12 KiB
Python

"""Member-bound location sharing. Pairing is not consent; coordinates are RAM-only."""
import hashlib
import json
import math
import secrets
import time
class Locations:
def __init__(self, app):
self.a=app; self.codes={}; self.attempts={}; self.latest={}
def initialize(self):
with self.a.LOCK,self.a.DB:
self.a.DB.execute('CREATE TABLE IF NOT EXISTS member_location_shares '
'(id TEXT PRIMARY KEY,member_id TEXT UNIQUE,family_id TEXT,token_hash TEXT UNIQUE,'
'expires REAL,enabled INTEGER DEFAULT 0,created REAL,grant_json TEXT)')
# Old all-household consent must not become consent for a new contract.
if self.a.DB.execute("SELECT name FROM sqlite_master WHERE name='location_shares'").fetchone():
self.a.DB.execute('UPDATE location_shares SET enabled=0')
self.codes.clear(); self.latest.clear(); self.attempts.clear()
def eligible(self, family, key):
try: return self.a.MEMBERS.member(family,key,active=True)
except self.a.Problem: return None
def can_manage(self, user, person):
return self.a.HOUSEHOLDS.manager(user) or user.get('personId') == person['id']
def recipients(self, family):
a=self.a
users=[dict(id=u['id'],name=u.get('name') or u['username'],username=u['username'])
for u in a.objects('users') if a.HOUSEHOLDS.grant(u,family)]
displays=[]
for row in a.DB.execute('SELECT id,device_id FROM household_displays WHERE family_id=? AND revoked=0 AND expires_at>?', (family,time.time())):
device=a.get_object('devices',row['device_id'])
if device and a.HOUSEHOLDS.family_of(device)==family:displays.append(dict(id=row['id'],name=device['name']))
return users,displays
def manage(self, user, data):
a=self.a; family=a.HOUSEHOLDS.scope(user); now=time.time()
with a.LOCK,a.DB:
member,person=a.MEMBERS.member(family,data.get('memberId'))
if not self.can_manage(user,person): raise a.Problem('协助家人配对需要家庭管理权限',403)
if data.get('action')=='stop':
row=a.DB.execute('SELECT id FROM member_location_shares WHERE member_id=?',(member['id'],)).fetchone()
a.DB.execute('DELETE FROM member_location_shares WHERE member_id=?',(member['id'],))
if row:self.latest.pop(row['id'],None)
self.codes={k:v for k,v in self.codes.items() if v['memberId']!=member['id']}
return {'ok':True}
if data.get('action')!='pair' or not self.eligible(family,member['id']): raise a.Problem('请选择当前家庭的在世成员')
days=data.get('days',7)
if type(days) is not int or days not in (1,7,30): raise a.Problem('请选择 1、7 或 30 天')
users,displays=self.recipients(family);chosen={}
for key,options in [('viewerIds',users),('displayIds',displays)]:
ids=data.get(key,[])
if not isinstance(ids,list) or len(ids)>100 or any(not isinstance(i,str) for i in ids) or len(ids)!=len(set(ids)) or not set(ids)<={r['id'] for r in options}:
raise a.Problem('请选择仍有本家庭访问权限的账号或显示终端')
chosen[key]=[r for r in options if r['id'] in ids]
if not chosen['viewerIds'] and not chosen['displayIds']: raise a.Problem('请明确选择至少一位查看人或一台显示终端')
self.codes={k:v for k,v in self.codes.items() if v['until']>now and v['memberId']!=member['id']}
if len(self.codes)>=128: raise a.Problem('配对繁忙,请稍后再试',429)
while True:
code=f'{secrets.randbelow(100000000):08d}';digest=hashlib.sha256(code.encode()).hexdigest()
if digest not in self.codes:break
grant=dict(memberId=member['id'],personId=person['id'],memberName=person['name'],familyId=family,
home=a.get_object('households',family)['name'],until=now+600,expires=now+days*86400,
viewers=chosen['viewerIds'],displays=chosen['displayIds'],createdBy=user['id'],consentProtocol=2)
grant['receipt']=hashlib.sha256(json.dumps(grant,sort_keys=True).encode()).hexdigest()
self.codes[digest]=grant
return dict(code=code,validSeconds=600,expires=grant['expires'])
def pair(self, body, ip):
a=self.a;now=time.time();code=body.get('code')
if body.get('consentProtocol')!=2:raise a.Problem('请更新配套 App,在手机上确认具体查看人后开启共享',409)
if not isinstance(code,str) or len(code)!=8 or not code.isascii() or not code.isdigit():raise a.Problem('请输入八位配对码')
with a.LOCK,a.DB:
self.attempts={k:v for k,v in self.attempts.items() if now-v[0]<600}
at,count=self.attempts.get(ip,(now,0))
if count>=5 or len(self.attempts)>4096:raise a.Problem('配对尝试过多,请稍后再试',429)
self.attempts[ip]=(at,count+1)
key=hashlib.sha256(code.encode()).hexdigest();grant=self.codes.get(key)
if not grant or grant['until']<now or not self.eligible(grant['familyId'],grant['memberId']):raise a.Problem('配对码已失效',401)
issuer=a.get_object('users',grant['createdBy'])
try:issuer=a.HOUSEHOLDS.context(issuer,grant['familyId']) if issuer else None
except a.Problem:issuer=None
if not issuer or issuer.get('disabled') or not self.can_manage(issuer,self.eligible(grant['familyId'],grant['memberId'])[1]):raise a.Problem('配对授权已失效',401)
token=secrets.token_urlsafe(32);sid=secrets.token_hex(16)
old=a.DB.execute('SELECT id FROM member_location_shares WHERE member_id=?',(grant['memberId'],)).fetchone()
if old:self.latest.pop(old['id'],None)
a.DB.execute('INSERT OR REPLACE INTO member_location_shares VALUES (?,?,?,?,?,0,?,?)',
(sid,grant['memberId'],grant['familyId'],hashlib.sha256(token.encode()).hexdigest(),grant['expires'],now,json.dumps(grant)))
self.codes.pop(key);self.attempts.pop(ip,None)
return dict(token=token,**{k:grant[k] for k in ('home','memberName','viewers','displays','expires','receipt','consentProtocol')})
def native(self, token, body):
a=self.a;now=time.time()
if not isinstance(token,str) or len(token)!=43:raise a.Problem('需要手机配对授权',401)
with a.LOCK,a.DB:
row=a.DB.execute('SELECT * FROM member_location_shares WHERE token_hash=?',(hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
if not row:raise a.Problem('手机绑定已解除,请重新配对',401)
sid=row['id'];action=body.get('action');grant=json.loads(row['grant_json'])
if action in ('stop','revoke'):
if action=='revoke':a.DB.execute('DELETE FROM member_location_shares WHERE id=?',(sid,))
else:a.DB.execute('UPDATE member_location_shares SET enabled=0 WHERE id=?',(sid,))
self.latest.pop(sid,None);return {'ok':True}
if row['expires']<now or not self.eligible(row['family_id'],row['member_id']):
self.latest.pop(sid,None);raise a.Problem('位置共享授权已结束',401)
if action=='start':
if body.get('consent') is not True or body.get('receipt')!=grant['receipt']:raise a.Problem('请本人核对姓名及查看人,并同意开启共享',403)
a.DB.execute('UPDATE member_location_shares SET enabled=1 WHERE id=?',(sid,))
self.latest[sid]=dict(seen=now,started=now,fix=None,signal='waiting')
return dict(ok=True,expires=row['expires'])
if action!='update' or not row['enabled']:raise a.Problem('位置共享尚未开启',403)
old=self.latest.get(sid,dict(started=now,fix=None))
if now-old.get('seen',0)<10:raise a.Problem('位置更新过于频繁',429)
signal=body.get('signal','waiting');fix=old.get('fix')
if signal not in ('waiting','available','permission_denied','location_disabled'):raise a.Problem('定位状态不正确')
if body.get('position') is not None:
pos=body['position']
if signal!='available' or not isinstance(pos,dict):raise a.Problem('位置数据与手机定位状态不一致')
for key,lo,hi in [('latitude',-90,90),('longitude',-180,180),('accuracy',0,100000),('at',now-900,now+60)]:
v=pos.get(key)
if type(v) not in (int,float) or not math.isfinite(v) or not lo<=v<=hi:raise a.Problem('位置数据不正确:'+key)
if not fix or pos['at']>fix['at']:fix={k:pos[k] for k in ('latitude','longitude','accuracy','at')}
if signal in ('permission_denied','location_disabled'):fix=None
self.latest[sid]=dict(started=old['started'],seen=now,fix=fix,signal=signal)
return dict(ok=True,expires=row['expires'])
def listing(self, family, user=None, display_id=None):
a=self.a;now=time.time();items=[]
if not user and not display_id:return items
if user and not a.HOUSEHOLDS.grant(a.get_object('users',user.get('id')),family):return items
with a.LOCK:
if display_id:
d=a.DB.execute('SELECT device_id FROM household_displays WHERE id=? AND family_id=? AND revoked=0 AND expires_at>?',(display_id,family,now)).fetchone()
obj=a.get_object('devices',d['device_id']) if d else None
if not obj or a.HOUSEHOLDS.family_of(obj)!=family:return items
rows=a.DB.execute('SELECT * FROM member_location_shares WHERE enabled=1 AND expires>?',(now,)).fetchall()
active={r['id'] for r in rows};self.latest={k:v for k,v in self.latest.items() if k in active}
for row in rows:
if row['family_id']!=family:continue
valid=self.eligible(family,row['member_id'])
if not valid:self.latest.pop(row['id'],None);continue
grant=json.loads(row['grant_json'])
if user and user['id'] not in {v['id'] for v in grant['viewers']}:continue
if display_id and display_id not in {v['id'] for v in grant['displays']}:continue
recent=self.latest.get(row['id'],{});fix=recent.get('fix');seen=recent.get('seen',0)
age=now-(fix['at'] if fix else recent.get('started',row['created']))
state='stale' if age>900 or seen and now-seen>900 else 'live' if fix else 'waiting'
position=fix if fix and state=='live' else None
items.append(dict(id=row['member_id'],personId=valid[1]['id'],name=valid[1]['name'],status=state,
signal=recent.get('signal','waiting'),lastSeen=seen or None,position=position,expires=row['expires']))
return items
def snapshot(self,user):
a=self.a;family=a.HOUSEHOLDS.scope(user)
with a.LOCK:
members=a.MEMBERS.snapshot(user)['items']
manageable=[m for m in members if a.HOUSEHOLDS.manager(user) or m['personId']==user.get('personId')]
users,displays=self.recipients(family) if manageable else ([],[])
bindings=[dict(memberId=r['member_id'],enabled=bool(r['enabled']),expires=r['expires'])
for r in a.DB.execute('SELECT * FROM member_location_shares WHERE family_id=? AND expires>?',(family,time.time()))
if r['member_id'] in {m['id'] for m in manageable}]
return dict(items=self.listing(family,user=user),members=manageable,viewers=users,displays=displays,bindings=bindings)