dashPi: a self-hosted home dashboard, its sync server and phone app

The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-10-24 09:35:12 +02:00
commit fb3c01cdd7
333 changed files with 45151 additions and 0 deletions

122
app/lib/sync/client.dart Normal file
View file

@ -0,0 +1,122 @@
// Talking to the dash-sync mailbox (PROTOCOL.md "HTTP"): join with a device token + the
// passphrase, then pull everyone else's batches and push ours — what the dashboard's
// sync.py does every 5 minutes. The token and the data key live in Android's secure storage
// (Keystore-backed); the rest (clock, how far we've read) in the store.
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
import 'crypto.dart';
import 'store.dart';
const chunk = 2000; // changes per batch, like sync.py
class SyncSettings {
SyncSettings({required this.server, required this.token, required this.account, required this.name,
required this.device, required this.key});
final String server, token, account, name, device;
final Uint8List key;
static const _storage = FlutterSecureStorage();
static Future<SyncSettings?> load() async {
final j = await _storage.read(key: 'sync');
if (j == null) return null;
final m = jsonDecode(j) as Map<String, dynamic>;
return SyncSettings(server: m['server'], token: m['token'], account: m['account'], name: m['name'],
device: m['device'], key: base64Decode(m['key']));
}
Future<void> save() => _storage.write(
key: 'sync',
value: jsonEncode({'server': server, 'token': token, 'account': account, 'name': name,
'device': device, 'key': base64Encode(key)}));
static Future<void> forget() => _storage.delete(key: 'sync');
}
class SyncError implements Exception {
SyncError(this.message);
final String message;
@override
String toString() => message;
}
Future<Map<String, dynamic>> _call(String server, String token, String method, String path,
{Uint8List? body}) async {
final uri = Uri.parse(server.replaceAll(RegExp(r'/+$'), '') + path);
final headers = {'Authorization': 'Bearer $token', 'Accept': 'application/json'};
late http.Response r;
try {
r = method == 'POST'
? await http.post(uri, headers: {...headers, 'Content-Type': 'application/octet-stream'}, body: body)
: await http.get(uri, headers: headers);
} catch (e) {
throw SyncError("Can't reach the server ($e)");
}
final j = r.body.isEmpty ? <String, dynamic>{} : jsonDecode(r.body) as Map<String, dynamic>;
if (r.statusCode >= 400) throw SyncError('Server: ${r.statusCode} ${j['error'] ?? r.body}');
return j;
}
/// First start: check the token, fetch the wrapped key, unlock it with the passphrase (or take
/// the recovery key). The server must already have a key — the dashboard makes it (sync.py setup).
Future<SyncSettings> join(String server, String token, {String? passphrase, String? recovery}) async {
final hello = await _call(server, token, 'GET', '/v1/hello');
final Uint8List key;
if (recovery != null && recovery.trim().isNotEmpty) {
key = SyncCrypto.fromRecovery(recovery);
} else {
final Map<String, dynamic> wrapped;
try {
wrapped = await _call(server, token, 'GET', '/v1/key');
} on SyncError catch (e) {
if (e.message.contains('404')) throw SyncError('No key on the server yet — set up the dashboard first.');
rethrow;
}
key = await SyncCrypto.unwrap(wrapped, passphrase ?? '');
}
return SyncSettings(server: server, token: token, account: hello['account'], name: hello['device'],
device: SyncStore.randomId().substring(0, 12), key: key);
}
class SyncResult {
int batches = 0, applied = 0, skipped = 0, pushed = 0;
@override
String toString() => '$batches batches in ($applied applied, $skipped skipped), $pushed changes out';
}
/// Pull everyone else's batches since the last one read, then push ours.
Future<SyncResult> runSync(SyncSettings s, SyncStore store, SyncCrypto crypto) async {
final res = SyncResult();
while (true) {
final j = await _call(s.server, s.token, 'GET', '/v1/batches?after=${store.meta('pulled')}&limit=50');
final batches = (j['batches'] as List).cast<Map<String, dynamic>>();
if (batches.isEmpty) break;
for (final b in batches) {
if (b['device'] != s.name) {
final batch = crypto.openBatch(s.key, base64Decode(b['blob'] as String), s.account);
if (batch['dev'] != s.device) {
final st = store.apply(batch['changes'] as List);
res.applied += st['applied']!;
res.skipped += st['skipped']!;
}
res.batches++;
}
store.setMeta('pulled', b['seq'] as int); // only after the batch is in (applying again is harmless)
}
}
final (items, mark) = store.changes();
for (var i = 0; i < items.length; i += chunk) {
final part = items.sublist(i, i + chunk > items.length ? items.length : i + chunk);
final blob = crypto.sealBatch(s.key,
{'v': 1, 'dev': s.device, 'made': DateTime.now().millisecondsSinceEpoch, 'changes': part}, s.account);
await _call(s.server, s.token, 'POST', '/v1/batches', body: blob);
res.pushed += part.length;
}
if (items.isNotEmpty) store.markPushed(mark);
return res;
}

117
app/lib/sync/crypto.dart Normal file
View file

@ -0,0 +1,117 @@
// Encryption for dash-sync (PROTOCOL.md "Keys" + "A batch"), byte for byte what the dashboard's
// sync.py does with PyNaCl: a batch = "DS1\0" + 24-byte nonce + XChaCha20-Poly1305-IETF(data key,
// nonce, zlib(JSON), ad = "dash-sync/1/<account>"); the data key sits on the server wrapped with
// Argon2id(passphrase). Argon2id with 64 MB takes a second or two, so it runs in its own isolate.
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:sodium/sodium_sumo.dart';
const _magic = [0x44, 0x53, 0x31, 0x00]; // "DS1\0"
const _keyAd = 'dash-sync/key/1';
class SyncCrypto {
SyncCrypto._(this._sodium);
static Future<SyncCrypto> create() async => SyncCrypto._(await SodiumSumoInit.init());
final SodiumSumo _sodium;
Aead get _aead => _sodium.crypto.aeadXChaCha20Poly1305IETF;
Uint8List _ad(String account) => utf8.encode('dash-sync/1/$account');
/// JSON → zlib → sealed batch, ready to POST.
Uint8List sealBatch(Uint8List key, Map<String, dynamic> batch, String account) {
final plain = Uint8List.fromList(ZLibCodec(level: 6).encode(utf8.encode(jsonEncode(batch))));
final nonce = _sodium.randombytes.buf(24);
final k = SecureKey.fromList(_sodium, key);
try {
final box = _aead.encrypt(message: plain, nonce: nonce, key: k, additionalData: _ad(account));
return Uint8List.fromList([..._magic, ...nonce, ...box]);
} finally {
k.dispose();
}
}
/// A sealed batch → its JSON. Throws on a wrong key / account or a damaged batch.
Map<String, dynamic> openBatch(Uint8List key, Uint8List blob, String account) {
if (blob.length < 28 + 16 || !_listEq(blob.sublist(0, 4), _magic)) {
throw const FormatException('not a sync batch');
}
final k = SecureKey.fromList(_sodium, key);
try {
final plain = _aead.decrypt(
cipherText: blob.sublist(28), nonce: blob.sublist(4, 28), key: k, additionalData: _ad(account));
return jsonDecode(utf8.decode(ZLibCodec().decode(plain))) as Map<String, dynamic>;
} finally {
k.dispose();
}
}
/// The data key from the server's wrapped key + the passphrase (in a background isolate).
/// Throws [WrongPassphrase].
static Future<Uint8List> unwrap(Map<String, dynamic> w, String passphrase) =>
Isolate.run(() async => _unwrap(await SodiumSumoInit.init(), w, passphrase));
static Uint8List _unwrap(SodiumSumo s, Map<String, dynamic> w, String passphrase) {
if (w['kdf'] != 'argon2id13') throw FormatException('unknown kdf ${w['kdf']}');
final kek = s.crypto.pwhash(
outLen: 32,
password: Int8List.fromList(utf8.encode(passphrase)),
salt: base64Decode(w['salt'] as String),
opsLimit: w['ops'] as int,
memLimit: w['mem'] as int,
alg: CryptoPwhashAlgorithm.argon2id13,
);
try {
// a copy: what libsodium returns is a view on native memory that's freed with the isolate
return Uint8List.fromList(s.crypto.aeadXChaCha20Poly1305IETF.decrypt(
cipherText: base64Decode(w['box'] as String),
nonce: base64Decode(w['nonce'] as String),
key: kek,
additionalData: utf8.encode(_keyAd),
));
} on SodiumException {
throw const WrongPassphrase();
} finally {
kek.dispose();
}
}
/// The recovery key ("ABCD-EFGH-…", base32 of the data key) → the data key.
static Uint8List fromRecovery(String code) {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
final s = code.replaceAll(RegExp(r'[\s-]'), '').toUpperCase();
final out = <int>[];
var buf = 0, bits = 0;
for (final ch in s.split('')) {
final v = alphabet.indexOf(ch);
if (v < 0) throw const FormatException("that's not a recovery key");
buf = (buf << 5) | v;
bits += 5;
if (bits >= 8) {
bits -= 8;
out.add((buf >> bits) & 0xff);
}
}
if (out.length != 32) throw const FormatException("that's not a recovery key");
return Uint8List.fromList(out);
}
static bool _listEq(List<int> a, List<int> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
}
class WrongPassphrase implements Exception {
const WrongPassphrase();
@override
String toString() => 'Wrong passphrase';
}

145
app/lib/sync/gb_relay.dart Normal file
View file

@ -0,0 +1,145 @@
// The band's data from Gadgetbridge to the dashboard, through the sync (no Syncthing): Gadgetbridge's
// database export on this phone (Gadgetbridge ▸ Settings ▸ Automations ▸ Auto export), picked once,
// is read at every sync (the app's and the background task's, background.dart) when it changed; the new rows of the six tables the dashboard's gb.py reads
// (only those columns) go into the store as health.<TABLE> rows — ids = the band's timestamps, as
// gb.RELAY_SYNC — and travel like any change. The Pi imports them (gb.import_relay).
//
// Incremental like gb.py: rows from the newest relayed minute minus OVERLAP (the band hands over
// sleep and late minutes after the fact); an unchanged row isn't put again. Rows older than KEEP
// days that were sent are dropped here without a delete marker — the Pi keeps them.
// With them goes the phone's time zone (health.RELAY_INFO "tz"): the dashboard reads the band's times in it
// unless Settings ▸ Health sets one.
import 'dart:io';
import 'package:gb_export/gb_export.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqlite3/sqlite3.dart';
import 'store.dart';
const overlapS = 2 * 86400;
const keepDays = 14;
/// table → (id prefix, timestamp column, timestamp in ms?, columns sent) — gb.RELAY_SCHEMA / RELAY_SYNC
const relayTables = {
'XIAOMI_ACTIVITY_SAMPLE': ('a', 'TIMESTAMP', false, ['TIMESTAMP', 'HEART_RATE', 'STEPS', 'DISTANCE_CM']),
'XIAOMI_DAILY_SUMMARY_SAMPLE': ('d', 'TIMESTAMP', true, ['TIMESTAMP', 'HR_RESTING']),
'XIAOMI_SLEEP_STAGE_SAMPLE': ('s', 'TIMESTAMP', true, ['TIMESTAMP', 'STAGE']),
'XIAOMI_SLEEP_TIME_SAMPLE': ('t', 'TIMESTAMP', true, ['TIMESTAMP', 'WAKEUP_TIME']),
'BASE_ACTIVITY_SUMMARY': ('w', 'START_TIME', true, ['START_TIME', 'END_TIME', 'ACTIVITY_KIND', 'OVERRIDE_ACTIVITY_KIND']),
'XIAOMI_MANUAL_SAMPLE': ('m', 'TIMESTAMP', true, ['TIMESTAMP', 'TYPE', 'VALUE']),
};
class GbRelay {
GbRelay(this.store);
final SyncStore store;
String? get uri => store.metaText('gb_uri');
String? get lastResult => store.metaText('gb_result');
int get lastRun => store.meta('gb_run'); // ms
/// The system file picker → remember the export (null = cancelled).
Future<bool> pick() async {
final u = await pickExport();
if (u == null) return false;
store.setMetaText('gb_uri', u);
store.setMetaText('gb_stamp', null); // read it at the next sync
return true;
}
void forget() {
store.setMetaText('gb_uri', null);
store.setMetaText('gb_stamp', null);
}
/// Read the export if it changed → rows put (0 = nothing new; null = no export picked).
Future<int?> run() async {
final u = uri;
if (u == null) return null;
final info = await exportInfo(u);
if (info == null) {
_done('can\'t open the export — choose it again');
return 0;
}
await _zone();
final stamp = '${info['size']}:${info['modified']}';
var put = 0;
if (stamp != store.metaText('gb_stamp')) {
final tmp = '${(await getTemporaryDirectory()).path}/gb_export.db';
if (!await copyExport(u, tmp)) {
_done('can\'t read the export');
return 0;
}
try {
put = _read(tmp);
store.setMetaText('gb_stamp', stamp);
_done('$put new or changed rows from the export of ${_when(info['modified']!)}');
} catch (e) {
_done('the export couldn\'t be read: $e');
} finally {
for (final f in [tmp, '$tmp-wal', '$tmp-shm', '$tmp-journal']) {
final x = File(f);
if (x.existsSync()) x.deleteSync();
}
}
}
_trim();
return put;
}
int _read(String path) {
final gb = sqlite3.open(path, mode: OpenMode.readOnly);
var put = 0, newest = store.meta('gb_last');
final since = newest == 0 ? 0 : newest - overlapS;
try {
store.db.execute('BEGIN');
for (final MapEntry(key: t, value: (prefix, ts, ms, cols)) in relayTables.entries) {
final have = gb.select("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", [t]);
if (have.isEmpty) continue;
for (final r in gb.select('SELECT ${cols.join(', ')} FROM $t WHERE $ts >= ? ORDER BY $ts', [ms ? since * 1000 : since])) {
final data = {for (final c in cols) c: r[c]};
final id = t == 'XIAOMI_MANUAL_SAMPLE' ? '$prefix:${r['TIMESTAMP']}:${r['TYPE']}' : '$prefix:${r[ts]}';
final old = store.row('health.$t', id);
if (old != null && cols.every((c) => old[c] == data[c])) continue;
store.put('health.$t', id, data);
put++;
if (t == 'XIAOMI_ACTIVITY_SAMPLE' && (r[ts] as int) > newest) newest = r[ts] as int;
}
}
store.setMeta('gb_last', newest);
store.db.execute('COMMIT');
} catch (_) {
store.db.execute('ROLLBACK');
rethrow;
} finally {
gb.close();
}
return put;
}
/// The phone's time zone → health.RELAY_INFO (only when it changed: a trip abroad, the clocks moved by hand).
Future<void> _zone() async {
final z = await timeZone();
if (z == null || z.isEmpty || store.row('health.RELAY_INFO', 'i:tz')?['v'] == z) return;
store.put('health.RELAY_INFO', 'i:tz', {'k': 'tz', 'v': z});
}
/// Drop rows older than keepDays that were already sent — here only (no delete marker).
void _trim() {
final cut = DateTime.now().millisecondsSinceEpoch ~/ 1000 - keepDays * 86400, pushed = store.meta('pushed');
for (final MapEntry(key: t, value: (_, ts, ms, _)) in relayTables.entries) {
store.db.execute("DELETE FROM rec WHERE t = ? AND h <= ? AND json_extract(data, '\$.$ts') < ?",
['health.$t', pushed, ms ? cut * 1000 : cut]);
}
}
void _done(String result) {
store.setMetaText('gb_result', result);
store.setMeta('gb_run', DateTime.now().millisecondsSinceEpoch);
}
static String _when(int ms) {
final d = DateTime.fromMillisecondsSinceEpoch(ms);
return '${d.day}.${d.month}. ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
}
}

39
app/lib/sync/kick.dart Normal file
View file

@ -0,0 +1,39 @@
// "Sync now" to the dashboard over the home network (the dashboard's sync.kick): right after the
// band's rows went out, the Pi pulls them, imports them, rewrites the Health summaries and pushes
// them at once — then the app pulls again. Away from home the Pi doesn't answer and nothing changes
// (the usual 5-minute / hourly rhythm). The message is sealed with the data key, so only a device
// of this account can send one.
import 'dart:convert';
import 'dart:io';
import 'package:http/io_client.dart';
import 'client.dart';
import 'crypto.dart';
import 'store.dart';
/// The dashboard on the home network, e.g. http://192.168.1.50:8080: the Sync page (store meta pi_url),
/// else the build's --dart-define=PI_URL=… (tool/publish.env); empty = no "sync now", the usual rhythm only.
String piUrl(SyncStore store) =>
(store.metaText('pi_url') ?? const String.fromEnvironment('PI_URL')).trim().replaceAll(RegExp(r'/+$'), '');
const _connect = Duration(seconds: 3); // not home → give up quickly
const _answer = Duration(minutes: 3); // the Pi 3: import + summaries ≈ 1 min
/// → true when the Pi sent something back (pull now).
Future<bool> kickPi(SyncSettings s, SyncStore store, SyncCrypto crypto) async {
final pi = piUrl(store);
if (pi.isEmpty) return false;
final blob = crypto.sealBatch(s.key, {'kick': DateTime.now().millisecondsSinceEpoch}, s.account);
final client = IOClient(HttpClient()..connectionTimeout = _connect);
try {
final r = await client
.post(Uri.parse('$pi/api/sync/kick'), headers: {'Content-Type': 'application/octet-stream'}, body: blob)
.timeout(_answer);
if (r.statusCode != 200) return false;
return ((jsonDecode(r.body) as Map<String, dynamic>)['pushed'] ?? 0) > 0;
} catch (_) {
return false;
} finally {
client.close();
}
}

225
app/lib/sync/store.dart Normal file
View file

@ -0,0 +1,225 @@
// The phone's copy of the synced data, kept in the wire format of PROTOCOL.md: one row per
// (table, id) with its stamp, device and the columns as JSON — references are already ids there,
// so nothing is translated (the dashboard's syncdb.py turns them into its integer keys; we don't
// need to). The merge rules are syncdb.apply's: the later (stamp, device) wins per row, deletes
// leave a marker, a change older than a marker is skipped, the clock only moves forward.
//
// rec (t "food.entry", u id, h stamp, d device, data JSON)
// tomb (t, u, h, d) a delete marker
// meta (k, v) clock, pushed (my newest stamp sent), pulled (server seq)
import 'dart:convert';
import 'dart:math';
import 'package:sqlite3/sqlite3.dart';
class SyncStore {
SyncStore(String path, this.device) : db = sqlite3.open(path) {
db.execute('PRAGMA journal_mode = WAL');
db.execute('PRAGMA busy_timeout = 10000'); // the app and the background sync share the file
db.execute('''
CREATE TABLE IF NOT EXISTS rec (t TEXT NOT NULL, u TEXT NOT NULL, h INTEGER NOT NULL, d TEXT NOT NULL,
data TEXT NOT NULL, PRIMARY KEY (t, u)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS tomb (t TEXT NOT NULL, u TEXT NOT NULL, h INTEGER NOT NULL, d TEXT NOT NULL,
PRIMARY KEY (t, u)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS rec_mine ON rec (d, h);
CREATE INDEX IF NOT EXISTS tomb_mine ON tomb (d, h);
''');
}
final Database db;
final String device; // this device's id (12 hex), in every change it makes
int meta(String k) => (db.select('SELECT v FROM meta WHERE k = ?', [k]).firstOrNull?['v'] as int?) ?? 0;
void setMeta(String k, int v) => db.execute('INSERT OR REPLACE INTO meta VALUES (?, ?)', [k, v]);
String? metaText(String k) => db.select('SELECT v FROM meta WHERE k = ?', [k]).firstOrNull?['v'] as String?;
void setMetaText(String k, String? v) =>
v == null ? db.execute('DELETE FROM meta WHERE k = ?', [k]) : db.execute('INSERT OR REPLACE INTO meta VALUES (?, ?)', [k, v]);
/// Tables whose rows are documents (syncdb.py "fork"): their text columns, versioned by rev / revs.
/// Two versions written at the same time are both kept — the loser as "copy:" + its rev.
static const forks = {'notes.note': ['body', 'updated']};
/// Tables the phone never reads — the dashboards' raw ActivityWatch data (every window, every minute of
/// typing): not kept. What the app shows of it comes as the Pi's blocks (workload.act).
static const skip = ['activity.'];
static bool newer(int h, String d, int? lh, String? ld) =>
h != (lh ?? 0) ? h > (lh ?? 0) : d.compareTo(ld ?? '') > 0;
/// A new local stamp: never below the last one + 1 (PROTOCOL.md "Stamps").
int _tick() {
final h = max(meta('clock') + 1, DateTime.now().millisecondsSinceEpoch);
setMeta('clock', h);
return h;
}
// ---- reading -----------------------------------------------------------------------------
/// Every live row of a table ("food.entry") as {_u, _h (its change stamp), …columns}.
List<Map<String, dynamic>> rows(String t, {String? where, List<Object?> args = const []}) => [
for (final r in db.select(
'SELECT u, h, data FROM rec WHERE t = ?${where == null ? '' : ' AND ($where)'}', [t, ...args]))
{'_u': r['u'], '_h': r['h'], ...jsonDecode(r['data'] as String) as Map<String, dynamic>}
];
Map<String, dynamic>? row(String t, String u) {
final r = db.select('SELECT data FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull;
return r == null ? null : {'_u': u, ...jsonDecode(r['data'] as String) as Map<String, dynamic>};
}
Map<String, int> counts() => {
for (final r in db.select('SELECT t, count(*) AS n FROM rec GROUP BY t ORDER BY t'))
r['t'] as String: r['n'] as int
};
// ---- writing here ------------------------------------------------------------------------
/// Save a row made / changed on this device (the whole row: columns we don't show are kept
/// by passing the row as read). `u` = its id: a natural one ("day:2026-10-20") or random.
void put(String t, String u, Map<String, dynamic> data) {
final clean = Map<String, dynamic>.of(data)
..remove('_u')
..remove('_h');
db.execute('INSERT OR REPLACE INTO rec VALUES (?, ?, ?, ?, ?)', [t, u, _tick(), device, jsonEncode(clean)]);
}
/// Has another device seen this row as it is (it came from one, or went out)?
bool known(String t, String u) {
final r = db.select('SELECT h, d FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull;
return r == null || r['d'] != device || (r['h'] as int) <= meta('pushed');
}
void delete(String t, String u) {
final h = _tick();
db.execute('DELETE FROM rec WHERE t = ? AND u = ?', [t, u]);
db.execute('INSERT OR REPLACE INTO tomb VALUES (?, ?, ?, ?)', [t, u, h, device]);
}
/// Drop rows of [t] whose JSON [field] is below [before] — here only, no delete marker (the other side
/// keeps them): only rows another device made, or ours already sent.
void dropOld(String t, String field, num before) => db.execute(
"DELETE FROM rec WHERE t = ? AND json_extract(data, '\$.$field') < ? AND (d != ? OR h <= ?)",
[t, before, device, meta('pushed')]);
static String randomId() {
final r = Random.secure();
return List.generate(16, (_) => r.nextInt(256).toRadixString(16).padLeft(2, '0')).join();
}
// ---- sync ---------------------------------------------------------------------------------
/// This device's changes since the last push: (changes, mark) — markPushed(mark) once sent.
(List<Map<String, dynamic>>, int) changes() {
final since = meta('pushed');
var mark = since;
final out = <Map<String, dynamic>>[];
final items = <(int, Map<String, dynamic>)>[];
for (final r in db.select('SELECT t, u, h, d, data FROM rec WHERE d = ? AND h > ?', [device, since])) {
items.add((r['h'] as int,
{'t': r['t'], 'u': r['u'], 'h': r['h'], 'd': r['d'], 'row': jsonDecode(r['data'] as String)}));
}
for (final r in db.select('SELECT t, u, h, d FROM tomb WHERE d = ? AND h > ?', [device, since])) {
items.add((r['h'] as int, {'t': r['t'], 'u': r['u'], 'h': r['h'], 'd': r['d'], 'del': true}));
}
items.sort((a, b) => a.$1.compareTo(b.$1));
for (final (h, c) in items) {
out.add(c);
mark = max(mark, h);
}
return (out, mark);
}
void markPushed(int mark) => setMeta('pushed', max(meta('pushed'), mark));
/// Another device's changes → {applied, skipped}. Rows first, then the deletes (like syncdb).
Map<String, int> apply(List<dynamic> changes) {
final stats = {'applied': 0, 'skipped': 0};
if (changes.isEmpty) return stats;
db.execute('BEGIN IMMEDIATE');
try {
var top = meta('clock');
for (final c in changes.cast<Map<String, dynamic>>()) {
top = max(top, c['h'] as int);
}
setMeta('clock', top); // the clock moves past what arrives
for (final pass in [false, true]) {
for (final c in changes.cast<Map<String, dynamic>>()) {
if ((c['del'] == true) != pass) continue;
final t = c['t'] as String, u = c['u'] as String, h = c['h'] as int, d = c['d'] as String;
if (skip.any(t.startsWith)) {
stats['skipped'] = stats['skipped']! + 1;
continue;
}
final cur = db.select('SELECT h, d, data FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull;
final tomb = db.select('SELECT h, d FROM tomb WHERE t = ? AND u = ?', [t, u]).firstOrNull;
if (pass) {
if (tomb == null || newer(h, d, tomb['h'] as int, tomb['d'] as String)) {
db.execute('INSERT OR REPLACE INTO tomb VALUES (?, ?, ?, ?)', [t, u, h, d]);
}
if (cur != null && newer(h, d, cur['h'] as int, cur['d'] as String)) {
db.execute('DELETE FROM rec WHERE t = ? AND u = ?', [t, u]);
stats['applied'] = stats['applied']! + 1;
} else {
stats['skipped'] = stats['skipped']! + 1;
}
} else {
if (cur != null && forks.containsKey(t) &&
(tomb == null || newer(h, d, tomb['h'] as int, tomb['d'] as String)) &&
_fork(t, u, h, d, (c['row'] as Map).cast<String, dynamic>(), cur)) {
stats['applied'] = stats['applied']! + 1;
continue;
}
final beaten = (tomb != null && !newer(h, d, tomb['h'] as int, tomb['d'] as String)) ||
(cur != null && !newer(h, d, cur['h'] as int, cur['d'] as String));
if (beaten) {
stats['skipped'] = stats['skipped']! + 1;
} else {
db.execute('INSERT OR REPLACE INTO rec VALUES (?, ?, ?, ?, ?)', [t, u, h, d, jsonEncode(c['row'])]);
stats['applied'] = stats['applied']! + 1;
}
}
}
}
db.execute('COMMIT');
} catch (_) {
db.execute('ROLLBACK');
rethrow;
}
return stats;
}
/// syncdb._fork: a document row meeting another version of itself → true when settled here,
/// false = go on with the plain last-change-wins (after keeping the loser as a copy).
bool _fork(String t, String u, int h, String d, Map<String, dynamic> row, Row cur) {
final loc = jsonDecode(cur['data'] as String) as Map<String, dynamic>;
final mine = loc['rev'] as String?, theirs = row['rev'] as String?;
if (mine == null || theirs == null || mine == theirs) return false; // the same text: only the rest differs
final win = newer(h, d, cur['h'] as int, cur['d'] as String);
final text = [...forks[t]!, 'rev', 'revs'];
List<String> revs(Map<String, dynamic> m) => ((m['revs'] as String?) ?? '').split(' ');
if (revs(row).contains(mine)) { // written on top of ours: its text
if (win) return false;
final merged = {...loc, for (final k in text) if (row.containsKey(k)) k: row[k]};
db.execute('UPDATE rec SET data = ? WHERE t = ? AND u = ?', [jsonEncode(merged), t, u]);
return true;
}
if (revs(loc).contains(theirs)) { // ours was written on top of it: our text, their pin / folder —
if (!win) return false; // stamped here, so it goes out (with their stamp our text never would)
final merged = {...row, for (final k in text) if (loc.containsKey(k)) k: loc[k]};
db.execute('UPDATE rec SET h = ?, d = ?, data = ? WHERE t = ? AND u = ?', [_tick(), device, jsonEncode(merged), t, u]);
return true;
}
// both written at the same time: the later one stays, the other becomes a copy (the same one on every device)
final (lost, lh, ld) = win ? (loc, cur['h'] as int, cur['d'] as String) : (row, h, d);
final cu = 'copy:${lost['rev']}';
if (db.select('SELECT 1 FROM rec WHERE t = ? AND u = ?', [t, cu]).isEmpty &&
db.select('SELECT 1 FROM tomb WHERE t = ? AND u = ?', [t, cu]).isEmpty) {
db.execute('INSERT INTO rec VALUES (?, ?, ?, ?, ?)', [t, cu, lh, ld, jsonEncode({...lost, 'origin': lost['rev']})]);
}
return false;
}
}