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