Release 0.1.49: self-hosted maps and consented cloud location history

This commit is contained in:
Codex
2026-10-19 00:00:12 +08:00
parent d0b3db7f82
commit a5d2399d2e
58 changed files with 2586 additions and 223 deletions
+215
View File
@@ -0,0 +1,215 @@
"""Explicit opt-in, encrypted cloud history. Real-time sharing stays RAM-only.
SQLite holds bounded encrypted pending points and a small cloud index. The random
encryption key is a DB setting, so the existing database backup recovers the key
and index together. Cloud files are never public or exposed as direct links.
"""
import base64,datetime as dt,gzip,hashlib,json,os,secrets,shutil,threading,time
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
LIMIT=32*1024*1024
MAX_READ=2*1024*1024
READ_SLOTS=threading.BoundedSemaphore(2)
class History:
def __init__(self,app):self.a=app;self.worker=threading.Lock();self.last_error=''
def initialize(self):
a=self.a
with a.LOCK,a.DB:
a.DB.execute('CREATE TABLE IF NOT EXISTS location_history_points (id TEXT PRIMARY KEY, family TEXT, member TEXT, at REAL, payload BLOB, batch TEXT)')
a.DB.execute('CREATE INDEX IF NOT EXISTS history_points_member ON location_history_points(member,at)')
a.DB.execute('CREATE TABLE IF NOT EXISTS location_history_files (id TEXT PRIMARY KEY,family TEXT,member TEXT,start REAL,end REAL,body TEXT)')
a.DB.execute('CREATE INDEX IF NOT EXISTS history_files_member ON location_history_files(member,start)')
if not a.setting('location_history_key'):a.set_setting('location_history_key',base64.b64encode(secrets.token_bytes(32)).decode())
def seal(self,value,aad):
nonce=secrets.token_bytes(12);key=base64.b64decode(self.a.setting('location_history_key'))
return nonce+AESGCM(key).encrypt(nonce,gzip.compress(json.dumps(value,separators=(',',':')).encode()),aad.encode())
def unseal(self,value,aad):
key=base64.b64decode(self.a.setting('location_history_key'))
return json.loads(gzip.decompress(AESGCM(key).decrypt(value[:12],value[12:],aad.encode())))
def record(self,row,grant,fix):
if grant.get('historyEnabled') is not True:return
a=self.a
with a.LOCK,a.DB:
used=a.DB.execute('SELECT coalesce(sum(length(payload)),0) FROM location_history_points').fetchone()[0]
if used>=LIMIT or shutil.disk_usage(a.DATA).free<1024**3:
self.last_error='轨迹待上传空间已满,新增历史暂停;实时共享继续';return
if a.DB.execute('SELECT 1 FROM location_history_points WHERE member=? AND at=?',(row['member_id'],fix['at'])).fetchone():return
key=secrets.token_hex(16)
payload=self.seal(dict(position=fix,viewers=[v['id'] for v in grant['viewers']],phones=[v['id'] for v in grant.get('phones',[])]),key)
a.DB.execute('INSERT INTO location_history_points VALUES (?,?,?,?,?,NULL)',(key,row['family_id'],row['member_id'],fix['at'],payload))
self.last_error=''
def own_status(self,member):
a=self.a
with a.LOCK:
pending=a.DB.execute('SELECT count(*) FROM location_history_points WHERE member=?',(member,)).fetchone()[0]
rows=a.DB.execute('SELECT body FROM location_history_files WHERE member=?',(member,)).fetchall()
files=[json.loads(r[0]) for r in rows]
return dict(pending=pending,archived=sum(f.get('state')=='cloud' for f in files),deleting=sum(f.get('state')=='deleting' for f in files),
error=next((f.get('error') for f in files if f.get('error')),self.last_error),retention='forever')
def access(self,family,member,*,user=None,phone=None,delete=False):
a=self.a
with a.LOCK:
if phone:
current=a.DB.execute('SELECT * FROM member_location_shares WHERE id=? AND expires>?',(phone['id'],time.time())).fetchone()
if not current or current['family_id']!=family or not a.LOCATIONS.eligible(family,current['member_id']):raise a.Problem('手机授权已失效',401)
valid=a.LOCATIONS.eligible(family,member)
if not valid:raise a.Problem('家庭成员不存在',404)
own=bool(phone and phone['member_id']==member or user and user.get('personId')==valid[1]['id'])
if user and (user.get('disabled') or not a.HOUSEHOLDS.grant(a.get_object('users',user['id']),family)):raise a.Problem('家庭授权已失效',403)
if own:return ('owner',None)
if delete:raise a.Problem('只有本人可以删除自己的历史轨迹',403)
row=a.DB.execute('SELECT * FROM member_location_shares WHERE member_id=? AND family_id=? AND enabled=1 AND expires>?',(member,family,time.time())).fetchone()
grant=json.loads(row['grant_json']) if row else {}
kind='viewers' if user else 'phones';actor=user['id'] if user else phone['id'] if phone else ''
if not grant.get('historyEnabled') or actor not in {v['id'] for v in grant.get(kind,[])}:raise a.Problem('本人未授权查看历史轨迹,或共享已关闭',403)
return kind,actor
@staticmethod
def day_range(date,period='day',until=None):
try:
day=dt.datetime.strptime(date,'%Y-%m-%d').replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
if period=='life':return 0,time.time()+86400
if period=='week':day-=dt.timedelta(days=day.weekday());end=day+dt.timedelta(days=7)
elif period=='month':day=day.replace(day=1);end=(day.replace(day=28)+dt.timedelta(days=4)).replace(day=1)
elif period=='year':day=day.replace(month=1,day=1);end=day.replace(year=day.year+1)
elif period=='custom':
end=dt.datetime.strptime(until,'%Y-%m-%d').replace(tzinfo=day.tzinfo)+dt.timedelta(days=1)
if end<=day:raise ValueError()
elif period=='day':end=day+dt.timedelta(days=1)
else:raise ValueError()
return day.timestamp(),end.timestamp()
except (ValueError,TypeError):raise ValueError('请选择有效日期') from None
def query(self,*args,**kwargs):
if not READ_SLOTS.acquire(False):raise self.a.Problem('历史读取任务较多,请稍后重试',429)
try:return self._query(*args,**kwargs)
finally:READ_SLOTS.release()
def _query(self,family,member,date,*,user=None,phone=None,period='day',until=None,cursor=0):
a=self.a;kind,actor=self.access(family,member,user=user,phone=phone)
try:
start,end=self.day_range(date,period,until);cursor=int(cursor)
if not 0<=cursor<=1000000:raise ValueError()
except ValueError:raise a.Problem('请选择有效日期') from None
with a.LOCK:
generation=a.setting('history_deleted:'+member,0)
# Pending ciphertext is globally capped at 32 MiB. Sample after access
# filtering, across the whole interval, rather than dropping its tail.
pending=a.DB.execute('SELECT id,payload FROM location_history_points WHERE family=? AND member=? AND at>=? AND at<? ORDER BY at',(family,member,start,end)).fetchall() if cursor==0 else []
files=a.DB.execute('SELECT * FROM location_history_files WHERE family=? AND member=? AND end>=? AND start<? ORDER BY start,id LIMIT 9 OFFSET ?',(family,member,start,end,cursor)).fetchall()
total=a.DB.execute('SELECT count(*) FROM location_history_files WHERE family=? AND member=? AND end>=? AND start<?',(family,member,start,end)).fetchone()[0]
more=len(files)>8;files=files[:8]
values=[self.unseal(r['payload'],r['id']) for r in pending]
for row in files:
meta=json.loads(row['body'])
if meta.get('state')!='cloud':continue
with a.BAIDU.open_file('shared',dict(remotePath=meta['remote'],fsId=meta['fsId'])) as response:raw=response.read(MAX_READ+1)
if len(raw)>MAX_READ or hashlib.sha256(raw).hexdigest()!=meta['sha256']:raise a.Problem('历史轨迹校验失败,未显示数据',502)
values.extend(self.unseal(raw,row['id']))
# Recheck after slow cloud reads: revocation or deletion takes effect immediately.
kind,actor=self.access(family,member,user=user,phone=phone)
with a.LOCK:
if generation!=a.setting('history_deleted:'+member,0):raise a.Problem('历史已删除,请重新读取',409)
current={r[0] for r in a.DB.execute('SELECT id FROM location_history_files WHERE family=? AND member=?',(family,member))}
if any(r['id'] not in current for r in files):raise a.Problem('轨迹已变更,请重新读取',409)
if any(json.loads(r[0]).get('state')=='deleting' for r in a.DB.execute('SELECT body FROM location_history_files WHERE family=? AND member=?',(family,member))):raise a.Problem('轨迹正在删除',409)
points={v['position']['at']:v['position'] for v in values if start<=v['position']['at']<end and (kind=='owner' or actor in v.get(kind,[]))}
values=[points[k] for k in sorted(points)]
if values:
for point in (values[0],values[-1]):
try:a.MAPS.archive.for_point(point)
except Exception:pass
if len(values)>4000:values=[values[round(i*(len(values)-1)/3999)] for i in range(4000)]
return dict(points=values,date=date,period=period,retention='forever',totalFiles=total,loadedFiles=cursor+len(files),nextCursor=cursor+8 if more else None,sampled=len(points)>4000)
def delete(self,family,member,*,user=None,phone=None):
self.access(family,member,user=user,phone=phone,delete=True);a=self.a
with a.LOCK,a.DB:
a.set_setting('history_deleted:'+member,time.time())
a.DB.execute('DELETE FROM location_history_points WHERE family=? AND member=?',(family,member))
for row in a.DB.execute('SELECT id,body FROM location_history_files WHERE family=? AND member=?',(family,member)).fetchall():
meta=json.loads(row['body']);meta.update(state='deleting',nextTry=0,error='')
a.DB.execute('UPDATE location_history_files SET body=? WHERE id=?',(json.dumps(meta),row['id']))
return dict(ok=True,message='历史已隐藏,云端删除任务会继续重试直至完成')
def native(self,token,body):
a=self.a
with a.LOCK:
row=a.DB.execute('SELECT * FROM member_location_shares WHERE token_hash=? AND expires>?',(hashlib.sha256(token.encode()).hexdigest(),time.time())).fetchone()
if not row or not a.LOCATIONS.eligible(row['family_id'],row['member_id']):raise a.Problem('手机配对已失效',401)
row=dict(row)
member=body.get('memberId') or row['member_id']
if body['action']=='history-delete':
if body.get('confirm') is not True:raise a.Problem('请确认删除历史轨迹')
return self.delete(row['family_id'],member,phone=row)
return self.query(row['family_id'],member,body.get('date'),phone=row,period=body.get('period','day'),until=body.get('until'),cursor=body.get('cursor',0))
def package(self):
a=self.a
with a.LOCK,a.DB:
seed=a.DB.execute('SELECT * FROM location_history_points WHERE batch IS NULL AND at<? ORDER BY at LIMIT 1',(time.time()-3600,)).fetchone()
if not seed:return
rows=a.DB.execute('SELECT * FROM location_history_points WHERE batch IS NULL AND family=? AND member=? AND at<? ORDER BY at LIMIT 1000',(seed['family'],seed['member'],seed['at']+3600)).fetchall()
key=secrets.token_hex(16);date=dt.datetime.fromtimestamp(seed['at'],dt.timezone(dt.timedelta(hours=8)))
remote='/apps/'+a.BAIDU.public_config()['appFolder']+'/家庭轨迹/'+seed['family']+'/'+seed['member']+'/'+date.strftime('%Y/%m/%d/')+key+'.track'
meta=dict(state='pending',remote=remote,attempts=0,nextTry=0)
a.DB.execute('INSERT INTO location_history_files VALUES (?,?,?,?,?,?)',(key,seed['family'],seed['member'],rows[0]['at'],rows[-1]['at'],json.dumps(meta)))
a.DB.executemany('UPDATE location_history_points SET batch=? WHERE id=?',[(key,r['id']) for r in rows])
def process(self,row):
a=self.a;meta=json.loads(row['body']);file=a.DATA/('history-'+row['id']+'.partial')
try:
if meta['state']=='deleting':
# Even an interrupted upload has a deterministic path to clean up.
a.BAIDU.delete_history_file(meta['remote'])
with a.LOCK,a.DB:a.DB.execute('DELETE FROM location_history_files WHERE id=?',(row['id'],))
return
with a.LOCK:points=a.DB.execute('SELECT id,payload FROM location_history_points WHERE batch=? ORDER BY at',(row['id'],)).fetchall()
if not points:return
raw=self.seal([self.unseal(p['payload'],p['id']) for p in points],row['id'])
# Persist stable ciphertext before upload: retries must use exactly the same bytes.
with a.LOCK,a.DB:
current=json.loads(a.DB.execute('SELECT body FROM location_history_files WHERE id=?',(row['id'],)).fetchone()[0])
if current['state']=='deleting':return
if current.get('payload'):raw=base64.b64decode(current['payload'])
else:current['payload']=base64.b64encode(raw).decode();a.DB.execute('UPDATE location_history_files SET body=? WHERE id=?',(json.dumps(current),row['id']))
file.write_bytes(raw)
result=a.BAIDU.upload('shared',file,meta['remote']);digest=hashlib.sha256(raw).hexdigest()
a.BAIDU.verify_file(meta['remote'],str(result['fs_id']),len(raw),digest)
with a.LOCK,a.DB:
current=json.loads(a.DB.execute('SELECT body FROM location_history_files WHERE id=?',(row['id'],)).fetchone()[0])
if current['state']!='deleting':current.update(state='cloud',fsId=str(result['fs_id']),sha256=digest,bytes=len(raw),error='')
current.pop('payload',None)
a.DB.execute('UPDATE location_history_files SET body=? WHERE id=?',(json.dumps(current),row['id']))
a.DB.execute('DELETE FROM location_history_points WHERE batch=?',(row['id'],))
except Exception:
with a.LOCK,a.DB:
current=a.DB.execute('SELECT body FROM location_history_files WHERE id=?',(row['id'],)).fetchone()
if current:
current=json.loads(current[0]);attempt=current.get('attempts',0)+1
current.update(attempts=attempt,nextTry=time.time()+min(21600,60*2**min(attempt,8)),error='网盘任务未完成,将自动重试;本地待上传资料保留')
a.DB.execute('UPDATE location_history_files SET body=? WHERE id=?',(json.dumps(current),row['id']))
finally:file.unlink(missing_ok=True)
def tick(self):
if not self.worker.acquire(False):return
try:
self.package()
with self.a.LOCK:rows=self.a.DB.execute('SELECT * FROM location_history_files ORDER BY start').fetchall()
for row in rows:
meta=json.loads(row['body'])
if meta['state']!='cloud' and meta.get('nextTry',0)<=time.time():self.process(dict(row));break
finally:self.worker.release()
def watch(self):
while True:
try:self.tick()
except Exception:self.last_error='历史归档暂未完成,将自动重试'
time.sleep(30)