Release 0.1.45: member phone locations and people-first family navigation

This commit is contained in:
Codex
2026-10-18 21:26:12 +08:00
parent 3b2c046060
commit fdb239b3ed
47 changed files with 914 additions and 287 deletions
+63 -16
View File
@@ -37,6 +37,28 @@ class Locations:
if device and a.HOUSEHOLDS.family_of(device)==family:displays.append(dict(id=row['id'],name=device['name']))
return users,displays
def phones(self, family):
items=[]
for row in self.a.DB.execute('SELECT id,member_id FROM member_location_shares WHERE family_id=? AND expires>?',(family,time.time())):
valid=self.eligible(family,row['member_id'])
if valid:items.append(dict(id=row['id'],memberId=row['member_id'],name=valid[1]['name']))
return items
def select_recipients(self, family, data, own_id=None):
users,displays=self.recipients(family)
phones=[p for p in self.phones(family) if p['id']!=own_id]
chosen={}
for key,options,name in [('viewerIds',users,'viewers'),('displayIds',displays,'displays'),('phoneIds',phones,'phones')]:
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 self.a.Problem('请选择本家庭仍有效的查看账号、家人手机或显示终端')
chosen[name]=[r for r in options if r['id'] in ids]
return chosen
@staticmethod
def refresh_receipt(grant):
grant['receipt']=hashlib.sha256(json.dumps({k:v for k,v in grant.items() if k!='receipt'},sort_keys=True).encode()).hexdigest()
def manage(self, user, data):
a=self.a; family=a.HOUSEHOLDS.scope(user); now=time.time()
with a.LOCK,a.DB:
@@ -51,13 +73,11 @@ class Locations:
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('请明确选择至少一位查看人或一台显示终端')
chosen=self.select_recipients(family,data)
view_only=data.get('viewOnly',False)
if type(view_only) is not bool:raise a.Problem('配对用途不正确')
if view_only:chosen=dict(viewers=[],displays=[],phones=[])
elif not any(chosen.values()):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:
@@ -65,14 +85,15 @@ class Locations:
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()
**chosen,viewOnly=view_only,intervalSeconds=300,createdBy=user['id'],
consentProtocol=3 if view_only or chosen['phones'] else 2)
self.refresh_receipt(grant)
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 body.get('consentProtocol') not in (2,3):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}
@@ -81,6 +102,7 @@ class Locations:
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)
if body['consentProtocol']<grant['consentProtocol']:raise a.Problem('此配对需要新版家人位置 App',409)
issuer=a.get_object('users',grant['createdBy'])
try:issuer=a.HOUSEHOLDS.context(issuer,grant['familyId']) if issuer else None
except a.Problem:issuer=None
@@ -91,7 +113,7 @@ class Locations:
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')})
return dict(token=token,**{k:grant[k] for k in ('home','memberName','viewers','displays','phones','viewOnly','intervalSeconds','expires','receipt','consentProtocol')})
def native(self, token, body):
a=self.a;now=time.time()
@@ -106,11 +128,31 @@ class Locations:
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=='list':
return dict(items=self.listing(row['family_id'],phone_id=sid),memberName=grant['memberName'],home=grant['home'],expires=row['expires'])
if action=='settings':
users,displays=self.recipients(row['family_id'])
return dict(viewers=users,displays=displays,phones=[p for p in self.phones(row['family_id']) if p['id']!=sid],
viewerIds=[v['id'] for v in grant['viewers']],displayIds=[v['id'] for v in grant['displays']],
phoneIds=[v['id'] for v in grant.get('phones',[])],receipt=grant['receipt'],
intervalSeconds=grant.get('intervalSeconds',300),viewOnly=grant.get('viewOnly',False))
if action=='configure':
if body.get('consent') is not True or body.get('receipt')!=grant['receipt']:raise a.Problem('请本人确认新的共享设置',403)
chosen=self.select_recipients(row['family_id'],body,own_id=sid)
interval=body.get('intervalSeconds',300)
if type(interval) is not int or interval not in (10,60,300):raise a.Problem('请选择实时、1 分钟或 5 分钟')
if not any(chosen.values()):raise a.Problem('至少选择一位查看人;只查看家人无需开启自己的共享')
grant.update(chosen,viewOnly=False,intervalSeconds=interval,consentProtocol=3)
self.refresh_receipt(grant)
a.DB.execute('UPDATE member_location_shares SET enabled=0,grant_json=? WHERE id=?',(json.dumps(grant),sid))
self.latest.pop(sid,None)
return dict(ok=True,receipt=grant['receipt'],intervalSeconds=interval,**chosen)
if action=='start':
if grant.get('viewOnly'):raise a.Problem('此手机仅用于查看家人,请先由本人设置共享对象',403)
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'])
self.latest[sid]=dict(seen=0,started=now,fix=None,signal='waiting')
return dict(ok=True,expires=row['expires'],intervalSeconds=grant.get('intervalSeconds',300))
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)
@@ -127,11 +169,14 @@ class Locations:
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):
def listing(self, family, user=None, display_id=None, phone_id=None):
a=self.a;now=time.time();items=[]
if not user and not display_id:return items
if not user and not display_id and not phone_id:return items
if user and not a.HOUSEHOLDS.grant(a.get_object('users',user.get('id')),family):return items
with a.LOCK:
if phone_id:
phone=a.DB.execute('SELECT member_id FROM member_location_shares WHERE id=? AND family_id=? AND expires>?',(phone_id,family,now)).fetchone()
if not phone or not self.eligible(family,phone['member_id']):return items
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
@@ -145,6 +190,7 @@ class Locations:
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
if phone_id and phone_id!=row['id'] and phone_id not in {v['id'] for v in grant.get('phones',[])}: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'
@@ -162,4 +208,5 @@ class Locations:
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)
return dict(items=self.listing(family,user=user),members=manageable,viewers=users,displays=displays,
phones=self.phones(family) if manageable else [],bindings=bindings)