"""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']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)