2026-10-19 00:00:12 +08:00
"""Member-bound sharing. Live fixes stay in RAM; history needs separate consent."""
2026-10-18 20:00:43 +08:00
import hashlib
import json
import math
import secrets
import time
2026-10-19 00:57:33 +08:00
from location_sync import Sync , interval_valid
2026-10-18 20:00:43 +08:00
class Locations :
def __init__ ( self , app ):
2026-10-19 00:57:33 +08:00
self . a = app ; self . codes = {}; self . attempts = {}; self . latest = {}; self . sync = Sync ( app )
2026-10-18 20:00:43 +08:00
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 ()
2026-10-19 00:57:33 +08:00
self . sync . initialize ()
2026-10-18 20:00:43 +08:00
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
2026-10-18 21:26:12 +08:00
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 ()
2026-10-18 20:00:43 +08:00
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 天' )
2026-10-18 21:26:12 +08:00
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 ( '请明确选择查看人,或选择仅查看家人位置' )
2026-10-18 20:00:43 +08:00
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 ,
2026-10-18 21:26:12 +08:00
** chosen , viewOnly = view_only , intervalSeconds = 300 , createdBy = user [ 'id' ],
2026-10-19 00:00:12 +08:00
historyDefault = True , consentProtocol = 3 if view_only or chosen [ 'phones' ] else 2 )
2026-10-18 21:26:12 +08:00
self . refresh_receipt ( grant )
2026-10-18 20:00:43 +08:00
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' )
2026-10-18 21:26:12 +08:00
if body . get ( 'consentProtocol' ) not in ( 2 , 3 ): raise a . Problem ( '请更新配套 App,在手机上确认具体查看人后开启共享' , 409 )
2026-10-18 20:00:43 +08:00
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 )
2026-10-18 21:26:12 +08:00
if body [ 'consentProtocol' ] < grant [ 'consentProtocol' ]: raise a . Problem ( '此配对需要新版家人位置 App' , 409 )
2026-10-18 20:00:43 +08:00
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 )
2026-10-18 21:26:12 +08:00
return dict ( token = token , ** { k : grant [ k ] for k in ( 'home' , 'memberName' , 'viewers' , 'displays' , 'phones' , 'viewOnly' , 'intervalSeconds' , 'expires' , 'receipt' , 'consentProtocol' )})
2026-10-18 20:00:43 +08:00
def native ( self , token , body ):
2026-10-19 00:57:33 +08:00
if body . get ( 'action' ) == 'history-batch' : return self . sync . batch ( token , body )
2026-10-19 00:00:12 +08:00
if body . get ( 'action' ) in ( 'history-list' , 'history-delete' ):
return self . a . HISTORY . native ( token , body )
result = self . _native ( token , body )
if body . get ( 'action' ) == 'update' and body . get ( 'position' ) and body . get ( 'signal' ) == 'available' :
with self . a . LOCK :
row = self . a . DB . execute ( 'SELECT * FROM member_location_shares WHERE token_hash=? AND enabled=1 AND expires>?' ,( hashlib . sha256 ( token . encode ()) . hexdigest (), time . time ())) . fetchone ()
if row :
fix = self . latest . get ( row [ 'id' ],{}) . get ( 'fix' ); grant = json . loads ( row [ 'grant_json' ])
if fix and fix [ 'at' ] == body [ 'position' ][ 'at' ]:
2026-10-19 00:57:33 +08:00
if not body . get ( 'bufferedHistory' ): self . a . HISTORY . record ( row , grant , fix )
2026-10-19 00:00:12 +08:00
else : fix = None
else : fix = None
if fix :
try : self . a . MAPS . archive . observe ( fix )
except Exception : pass # A public map outage cannot break real-time sharing.
return result
def _native ( self , token , body ):
2026-10-18 20:00:43 +08:00
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' ):
2026-10-19 00:57:33 +08:00
self . sync . close ( sid )
2026-10-18 20:00:43 +08:00
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 )
2026-10-18 21:26:12 +08:00
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' ],
2026-10-19 00:00:12 +08:00
intervalSeconds = grant . get ( 'intervalSeconds' , 300 ), viewOnly = grant . get ( 'viewOnly' , False ),
2026-10-19 00:57:33 +08:00
sampleIntervalSeconds = grant . get ( 'sampleIntervalSeconds' , 60 ),
2026-10-19 00:00:12 +08:00
historyEnabled = grant . get ( 'historyEnabled' , False ), historyDefault = grant . get ( 'historyDefault' , False ) and 'historyEnabled' not in grant ,
history = self . a . HISTORY . own_status ( row [ 'member_id' ]))
2026-10-18 21:26:12 +08:00
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 )
2026-10-19 00:57:33 +08:00
if not interval_valid ( interval ): raise a . Problem ( '上传周期可选 10 秒、1/5 分钟,或 1 至 720 小时(最多 30 天)' )
sample = body . get ( 'sampleIntervalSeconds' , 60 )
if type ( sample ) is not int or sample not in ( 10 , 60 , 300 ): raise a . Problem ( '采集周期可选 10 秒、1 分钟或 5 分钟' )
2026-10-18 21:26:12 +08:00
if not any ( chosen . values ()): raise a . Problem ( '至少选择一位查看人;只查看家人无需开启自己的共享' )
2026-10-19 00:00:12 +08:00
history = body . get ( 'historyEnabled' , False )
if type ( history ) is not bool or history and body . get ( 'historyConsent' ) is not True : raise a . Problem ( '长期保存轨迹需要本人单独同意' , 403 )
2026-10-19 00:57:33 +08:00
self . sync . close ( sid )
grant . update ( chosen , viewOnly = False , intervalSeconds = interval , sampleIntervalSeconds = sample , consentProtocol = 3 , historyEnabled = history )
2026-10-18 21:26:12 +08:00
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 )
2026-10-19 00:57:33 +08:00
return dict ( ok = True , receipt = grant [ 'receipt' ], intervalSeconds = interval , sampleIntervalSeconds = sample , historyEnabled = history , ** chosen )
2026-10-18 20:00:43 +08:00
if action == 'start' :
2026-10-18 21:26:12 +08:00
if grant . get ( 'viewOnly' ): raise a . Problem ( '此手机仅用于查看家人,请先由本人设置共享对象' , 403 )
2026-10-18 20:00:43 +08:00
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 ,))
2026-10-18 21:26:12 +08:00
self . latest [ sid ] = dict ( seen = 0 , started = now , fix = None , signal = 'waiting' )
2026-10-19 00:57:33 +08:00
collection = self . sync . start ( row , grant ) if body . get ( 'bufferedHistory' ) is True else {}
return dict ( ok = True , expires = row [ 'expires' ], intervalSeconds = grant . get ( 'intervalSeconds' , 300 ), sampleIntervalSeconds = grant . get ( 'sampleIntervalSeconds' , 60 ), ** collection )
2026-10-18 20:00:43 +08:00
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 )
2026-10-19 00:57:33 +08:00
self . sync . seen ( sid , old [ 'started' ], now )
2026-10-18 20:00:43 +08:00
return dict ( ok = True , expires = row [ 'expires' ])
2026-10-18 21:26:12 +08:00
def listing ( self , family , user = None , display_id = None , phone_id = None ):
2026-10-18 20:00:43 +08:00
a = self . a ; now = time . time (); items = []
2026-10-18 21:26:12 +08:00
if not user and not display_id and not phone_id : return items
2026-10-18 20:00:43 +08:00
if user and not a . HOUSEHOLDS . grant ( a . get_object ( 'users' , user . get ( 'id' )), family ): return items
with a . LOCK :
2026-10-18 21:26:12 +08:00
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
2026-10-18 20:00:43 +08:00
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
2026-10-18 21:26:12 +08:00
if phone_id and phone_id != row [ 'id' ] and phone_id not in { v [ 'id' ] for v in grant . get ( 'phones' ,[])}: continue
2026-10-19 00:57:33 +08:00
recent = self . latest . get ( row [ 'id' ]) or self . sync . timing ( row [ 'id' ]); fix = recent . get ( 'fix' ); seen = recent . get ( 'seen' , 0 )
2026-10-18 20:00:43 +08:00
age = now - ( fix [ 'at' ] if fix else recent . get ( 'started' , row [ 'created' ]))
2026-10-19 00:57:33 +08:00
scheduled = grant . get ( 'intervalSeconds' , 300 ) > 900 and now - ( seen or recent . get ( 'started' , row [ 'created' ])) <= grant [ 'intervalSeconds' ] + 900
stale = age > 900 or seen and now - seen > 900
state = 'scheduled' if stale and scheduled else 'stale' if stale else 'live' if fix else 'waiting'
2026-10-18 20:00:43 +08:00
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 ,
2026-10-19 00:57:33 +08:00
signal = recent . get ( 'signal' , 'waiting' ), lastSeen = seen or None , position = position , expires = row [ 'expires' ],
intervalSeconds = grant . get ( 'intervalSeconds' , 300 ), nextUploadAt = ( seen or recent . get ( 'started' , row [ 'created' ])) + grant . get ( 'intervalSeconds' , 300 )))
2026-10-18 20:00:43 +08:00
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 }]
2026-10-18 21:26:12 +08:00
return dict ( items = self . listing ( family , user = user ), members = manageable , viewers = users , displays = displays ,
phones = self . phones ( family ) if manageable else [], bindings = bindings )