"""Durable, consent-scoped upload batches; acknowledge only verified cloud files.""" import hashlib import json import math import re import secrets import shutil import time import datetime as dt MAX_INTERVAL = 30 * 86400 MAX_POINTS = 128 MAX_PAYLOAD = 64000 def interval_valid(value): return type(value) is int and (value in (10, 60, 300) or 3600 <= value <= MAX_INTERVAL and value % 3600 == 0) class Sync: def __init__(self, app): self.a = app def initialize(self): with self.a.LOCK, self.a.DB: self.a.DB.execute('CREATE TABLE IF NOT EXISTS location_collection_sessions ' '(id TEXT PRIMARY KEY,share_id TEXT,family TEXT,member TEXT,started REAL,ended REAL,expires REAL,grant_json TEXT)') self.a.DB.execute('CREATE INDEX IF NOT EXISTS collection_share ON location_collection_sessions(share_id)') self.a.DB.execute('CREATE TABLE IF NOT EXISTS location_upload_timing (share_id TEXT PRIMARY KEY,started REAL,last_received REAL)') def close(self, sid): self.a.DB.execute('UPDATE location_collection_sessions SET ended=? WHERE share_id=? AND ended IS NULL', (time.time(), sid)) def start(self, row, grant): self.close(row['id']) self.a.DB.execute('INSERT OR REPLACE INTO location_upload_timing VALUES (?,?,0)', (row['id'], time.time())) if not grant.get('historyEnabled'): return dict(historyEnabled=False, collectionId='') key = secrets.token_hex(16) now = time.time() self.a.DB.execute('INSERT INTO location_collection_sessions VALUES (?,?,?,?,?,NULL,?,?)', (key, row['id'], row['family_id'], row['member_id'], now, row['expires'], json.dumps(grant))) return dict(historyEnabled=True, collectionId=key, collectionStartedAt=now) def seen(self, sid, started, now): self.a.DB.execute('INSERT OR REPLACE INTO location_upload_timing VALUES (?,?,?)', (sid, started, now)) def timing(self, sid): row=self.a.DB.execute('SELECT started,last_received FROM location_upload_timing WHERE share_id=?', (sid,)).fetchone() return dict(started=row['started'],seen=row['last_received']) if row else {} def batch(self, token, body): a = self.a if not isinstance(token, str) or len(token) != 43: raise a.Problem('需要手机配对授权', 401) batch_id, digest = body.get('batchId'), body.get('sha256') if not isinstance(batch_id, str) or not re.fullmatch('[a-f0-9]{32}', batch_id) or not isinstance(digest, str) or not re.fullmatch('[a-f0-9]{64}', digest): raise a.Problem('轨迹批次标识或校验值不正确') 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 or not a.LOCATIONS.eligible(row['family_id'], row['member_id']): raise a.Problem('手机绑定已解除,未接收本地轨迹', 401) # Expiration stops new collection/viewing. A still-bound phone may finish # uploading points collected inside its previously authorized window. key = hashlib.sha256((row['id'] + ':' + batch_id).encode()).hexdigest()[:32] existing = a.DB.execute('SELECT * FROM location_history_files WHERE id=?', (key,)).fetchone() if existing: meta = json.loads(existing['body']) if meta.get('uploadDigest') != digest or meta.get('uploadShare') != row['id']: raise a.Problem('批次内容与已接收记录不一致,未清除手机记录', 409) if meta['state'] == 'deleting': raise a.Problem('此历史已由本人删除,请在手机清理相应待上传记录', 409) return self.receipt(batch_id, meta) raw = body.get('payload') if not isinstance(raw, str) or len(raw.encode('utf-8')) > MAX_PAYLOAD or hashlib.sha256(raw.encode('utf-8')).hexdigest() != digest: raise a.Problem('轨迹内容校验失败,未接收记录') try: payload = json.loads(raw) if not isinstance(payload, dict) or payload.get('version') != 1: raise ValueError() session_id, points = payload['collectionId'], payload['points'] if not isinstance(session_id, str) or not isinstance(points, list) or not 1 <= len(points) <= MAX_POINTS: raise ValueError() except (ValueError, KeyError, TypeError): raise a.Problem('轨迹批次格式不正确') from None session = a.DB.execute('SELECT * FROM location_collection_sessions WHERE id=? AND share_id=?', (session_id, row['id'])).fetchone() if not session or session['member'] != row['member_id'] or session['family'] != row['family_id']: raise a.Problem('找不到该批轨迹的本人采集授权', 403) grant = json.loads(session['grant_json']) now = time.time() upper = min(session['expires'], session['ended'] if session['ended'] is not None else now + 60) deleted = a.setting('history_deleted:' + row['member_id'], 0) values, ids = [], set() for item in points: if not isinstance(item, dict): raise a.Problem('定位点格式不正确') point_id, pos = item.get('id'), item.get('position') if not isinstance(point_id, str) or not re.fullmatch('[a-f0-9]{32}', point_id) or point_id in ids or not isinstance(pos, dict): raise a.Problem('定位点标识不正确或重复') ids.add(point_id) for name, low, high in [('latitude', -90, 90), ('longitude', -180, 180), ('accuracy', 0, 100000), ('at', session['started'] - 5, min(upper, now + 60))]: value = pos.get(name) if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high: raise a.Problem('定位点超出采集授权时间或范围:' + name) if pos['at'] <= deleted: raise a.Problem('此历史已由本人删除,不能重新上传', 409) values.append(dict(position={k:pos[k] for k in ('latitude', 'longitude', 'accuracy', 'at')}, viewers=[v['id'] for v in grant['viewers']], phones=[v['id'] for v in grant.get('phones', [])])) values.sort(key=lambda item:item['position']['at']) encrypted = [] for index, value in enumerate(values): point_key = key + ':' + str(index) encrypted.append((point_key, row['family_id'], row['member_id'], value['position']['at'], a.HISTORY.seal(value, point_key), key)) import location_history used = a.DB.execute('SELECT coalesce(sum(length(payload)),0) FROM location_history_points').fetchone()[0] if used + sum(len(item[4]) for item in encrypted) > location_history.LIMIT or shutil.disk_usage(a.DATA).free < 1024**3: raise a.Problem('服务器待上传空间不足,请保留手机记录,稍后重试', 507) stamp = dt.datetime.fromtimestamp(values[0]['position']['at'], dt.timezone(dt.timedelta(hours=8))) remote = '/apps/' + a.BAIDU.public_config()['appFolder'] + '/家庭轨迹/' + row['family_id'] + '/' + row['member_id'] + '/' + stamp.strftime('%Y/%m/%d/') + key + '.track' meta = dict(state='pending', remote=remote, attempts=0, nextTry=0, uploadBatch=batch_id, uploadShare=row['id'], uploadDigest=digest, uploadCount=len(values)) a.DB.execute('INSERT INTO location_history_files VALUES (?,?,?,?,?,?)', (key, row['family_id'], row['member_id'], values[0]['position']['at'], values[-1]['position']['at'], json.dumps(meta))) a.DB.executemany('INSERT INTO location_history_points VALUES (?,?,?,?,?,?)', encrypted) # The surrounding SQLite transaction commits before an accepted response. # Phone deletion requires a later cloud-verified response, not this one. return self.receipt(batch_id, meta) @staticmethod def receipt(batch_id, meta): return dict(ok=True, batchId=batch_id, sha256=meta['uploadDigest'], count=meta['uploadCount'], state='verified' if meta['state'] == 'cloud' else 'accepted', retryAfterSeconds=30)