Files
ucvl-home-vision/family_locations.py
T

120 lines
7.4 KiB
Python
Raw Normal View History

"""Opt-in household location sharing. Coordinates are latest-only, in memory, never audited."""
import hashlib
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 location_shares '
'(user_id TEXT PRIMARY KEY,family_id TEXT,token_hash TEXT,expires REAL,enabled INTEGER DEFAULT 0,created REAL)')
def valid_user(self, row):
user=self.a.get_object('users',row['user_id'])
return user if user and not user.get('disabled') and self.a.HOUSEHOLDS.family_of(user)==row['family_id'] else None
def manage(self, user, data):
a=self.a; uid=user['id']; family=a.HOUSEHOLDS.scope(user); now=time.time()
# A superadministrator browsing another household cannot pretend to be its member.
if family!=a.HOUSEHOLDS.family_of(user): raise a.Problem('请在自己所属的家庭开启位置共享',403)
with a.LOCK,a.DB:
if data.get('action')=='stop':
a.DB.execute('DELETE FROM location_shares WHERE user_id=?',(uid,))
self.latest.pop(uid,None)
self.codes={k:v for k,v in self.codes.items() if v['user_id']!=uid}
return {'ok':True}
if data.get('action')!='pair' or data.get('consent') is not True:
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 天')
self.codes={k:v for k,v in self.codes.items() if v['until']>now and v['user_id']!=uid}
if len(self.codes)>=128: raise a.Problem('配对繁忙,请稍后再试',429)
code=''.join(secrets.choice('0123456789') for _ in range(8))
digest=hashlib.sha256(code.encode()).hexdigest()
while digest in self.codes:
code=''.join(secrets.choice('0123456789') for _ in range(8));digest=hashlib.sha256(code.encode()).hexdigest()
self.codes[digest]=dict(user_id=uid,family_id=family,until=now+600,expires=now+days*86400)
return dict(code=code,validSeconds=600,expires=now+days*86400)
def pair(self, body, ip):
a=self.a; now=time.time();code=body.get('code')
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:raise a.Problem('配对尝试过多,请稍后再试',429)
if len(self.attempts)>4096:raise a.Problem('配对服务繁忙',429)
self.attempts[ip]=(at,count+1)
key=hashlib.sha256(code.encode()).hexdigest();row=self.codes.get(key)
if not row or row['until']<now or not self.valid_user(row):raise a.Problem('配对码已失效',401)
token=secrets.token_urlsafe(32)
a.DB.execute('INSERT OR REPLACE INTO location_shares VALUES (?,?,?,?,0,?)',
(row['user_id'],row['family_id'],hashlib.sha256(token.encode()).hexdigest(),row['expires'],now))
self.latest.pop(row['user_id'],None);self.codes.pop(key);self.attempts.pop(ip,None)
home=a.get_object('households',row['family_id'])
return dict(token=token,home=home['name'],expires=row['expires'])
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 location_shares WHERE token_hash=?',(hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
if not row or row['expires']<now or not self.valid_user(row):raise a.Problem('位置共享授权已结束',401)
uid=row['user_id'];action=body.get('action')
if action=='stop':
a.DB.execute('DELETE FROM location_shares WHERE user_id=?',(uid,));self.latest.pop(uid,None)
return {'ok':True}
if action=='start':
if body.get('consent') is not True:raise a.Problem('请先在手机上同意共享')
a.DB.execute('UPDATE location_shares SET enabled=1 WHERE user_id=?',(uid,))
self.latest[uid]=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(uid,dict(started=now,fix=None))
if now-old.get('seen',0)<10:raise a.Problem('位置更新过于频繁',429)
signal=body.get('signal','waiting')
if signal not in ('waiting','available','permission_denied','location_disabled'):raise a.Problem('定位状态不正确')
fix=old.get('fix')
if body.get('position') is not None:
pos=body['position']
if 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')}
self.latest[uid]=dict(started=old['started'],seen=now,fix=fix,signal=signal)
return dict(ok=True,expires=row['expires'])
def listing(self, family):
a=self.a;now=time.time();items=[]
with a.LOCK:
rows=a.DB.execute('SELECT * FROM location_shares WHERE family_id=? AND enabled=1 AND expires>?',(family,now)).fetchall()
active={r['user_id'] for r in a.DB.execute('SELECT user_id FROM location_shares WHERE enabled=1 AND expires>?',(now,))}
self.latest={k:v for k,v in self.latest.items() if k in active}
for row in rows:
user=self.valid_user(row)
if not user:self.latest.pop(row['user_id'],None);continue
recent=self.latest.get(row['user_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'
# After 24 hours do not expose an obsolete coordinate, but keep the stale warning.
position=fix if fix and now-fix['at']<86400 else None
items.append(dict(id=user['id'],name=user.get('name') or user['username'],status=state,
signal=recent.get('signal','waiting'),lastSeen=seen or None,position=position,expires=row['expires']))
return items
def snapshot(self,user):
family=self.a.HOUSEHOLDS.scope(user)
with self.a.LOCK:
own=self.a.DB.execute('SELECT enabled,expires,family_id FROM location_shares WHERE user_id=?',(user['id'],)).fetchone()
return dict(items=self.listing(family),own=dict(own) if own and own['expires']>time.time() else None,
canShare=family==self.a.HOUSEHOLDS.family_of(user))