Skip to content

Offline gym log for Android. No account, no ads, no internet.

Add self-host sync server

InlitX573c58435087
diff --git a/server/analysis_options.yaml b/server/analysis_options.yaml
new file mode 100644
index 0000000..572dd23
--- /dev/null
+++ b/server/analysis_options.yaml
@@ -0,0 +1 @@
+include: package:lints/recommended.yaml
diff --git a/server/bin/server.dart b/server/bin/server.dart
new file mode 100644
index 0000000..73333fd
--- /dev/null
+++ b/server/bin/server.dart
@@ -0,0 +1,74 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:gymmane_server/gymmane_server.dart';
+
+Future<void> main(List<String> args) async {
+ if (args.contains('--help') || args.contains('-h')) {
+ stdout.writeln('''GymMane server $serverVersion
+
+Environment:
+ GYMMANE_PORT port to listen on (default 8080)
+ GYMMANE_HOST address to bind (default 0.0.0.0)
+ GYMMANE_DATA folder for your data (default ./data next to the server)
+ GYMMANE_WEB folder with the web app (default ./web next to the server)
+ GYMMANE_PASSWORD ask for this password in the browser (optional)
+ GYMMANE_SYNC folder shared with your phone through Syncthing (default DATA/sync, "off" to disable)
+ GYMMANE_KEEP_DAYS daily copies of your data to keep (default 30)
+
+ --health exit 0 if the server answers, 1 if not''');
+ return;
+ }
+ if (args.contains('--health')) {
+ exit(await _healthy(Config.fromEnvironment()) ? 0 : 1);
+ }
+ final config = Config.fromEnvironment();
+ final server = GymManeServer(config);
+ await server.start();
+ stdout.writeln('GymMane $serverVersion is running.');
+ stdout.writeln(' Open: http://localhost:${server.port}');
+ for (final ip in await _lanAddresses()) {
+ stdout.writeln(' http://$ip:${server.port}');
+ }
+ stdout.writeln(' Data: ${Directory(config.dataDir).absolute.path}');
+ if (config.syncDir != null) stdout.writeln(' Phone: ${Directory(config.syncDir!).absolute.path}');
+ if (config.password != null) stdout.writeln(' Password required.');
+
+ for (final signal in [ProcessSignal.sigint, if (!Platform.isWindows) ProcessSignal.sigterm]) {
+ signal.watch().listen((_) async {
+ await server.stop();
+ exit(0);
+ });
+ }
+}
+
+Future<List<String>> _lanAddresses() async {
+ try {
+ final list = await NetworkInterface.list(type: InternetAddressType.IPv4);
+ return [
+ for (final i in list)
+ for (final a in i.addresses)
+ if (!a.isLoopback && !a.isLinkLocal) a.address,
+ ];
+ } catch (_) {
+ return const [];
+ }
+}
+
+Future<bool> _healthy(Config config) async {
+ final client = HttpClient()..connectionTimeout = const Duration(seconds: 3);
+ try {
+ final req = await client.getUrl(Uri.parse('http://127.0.0.1:${config.port}/api/health'));
+ final password = config.password;
+ if (password != null) {
+ req.headers.set(HttpHeaders.authorizationHeader, 'Basic ${base64.encode(utf8.encode('gymmane:$password'))}');
+ }
+ final res = await req.close();
+ await res.drain<void>();
+ return res.statusCode == 200;
+ } catch (_) {
+ return false;
+ } finally {
+ client.close(force: true);
+ }
+}
diff --git a/server/lib/gymmane_server.dart b/server/lib/gymmane_server.dart
new file mode 100644
index 0000000..9227034
--- /dev/null
+++ b/server/lib/gymmane_server.dart
@@ -0,0 +1,5 @@
+export 'src/config.dart';
+export 'src/media_store.dart';
+export 'src/phone_sync.dart';
+export 'src/server.dart';
+export 'src/state_store.dart';
diff --git a/server/lib/src/config.dart b/server/lib/src/config.dart
new file mode 100644
index 0000000..0125cea
--- /dev/null
+++ b/server/lib/src/config.dart
@@ -0,0 +1,42 @@
+import 'dart:io';
+
+class Config {
+ Config({
+ required this.port,
+ required this.host,
+ required this.dataDir,
+ required this.webDir,
+ required this.syncDir,
+ required this.password,
+ required this.keepDays,
+ });
+
+ final int port;
+ final String host;
+ final String dataDir;
+ final String webDir;
+ final String? syncDir;
+ final String? password;
+ final int keepDays;
+
+ factory Config.fromEnvironment([Map<String, String>? env]) {
+ final e = env ?? Platform.environment;
+ String? read(String key) {
+ final v = e[key]?.trim();
+ return v == null || v.isEmpty ? null : v;
+ }
+
+ final here = File(Platform.resolvedExecutable).parent.path;
+ final data = read('GYMMANE_DATA') ?? '$here${Platform.pathSeparator}data';
+ final sync = read('GYMMANE_SYNC');
+ return Config(
+ port: int.tryParse(read('GYMMANE_PORT') ?? read('PORT') ?? '') ?? 8080,
+ host: read('GYMMANE_HOST') ?? '0.0.0.0',
+ dataDir: data,
+ webDir: read('GYMMANE_WEB') ?? '$here${Platform.pathSeparator}web',
+ syncDir: sync == 'off' ? null : sync ?? '$data${Platform.pathSeparator}sync',
+ password: read('GYMMANE_PASSWORD'),
+ keepDays: int.tryParse(read('GYMMANE_KEEP_DAYS') ?? '') ?? 30,
+ );
+ }
+}
diff --git a/server/lib/src/media_store.dart b/server/lib/src/media_store.dart
new file mode 100644
index 0000000..0febd66
--- /dev/null
+++ b/server/lib/src/media_store.dart
@@ -0,0 +1,62 @@
+import 'dart:io';
+import 'dart:typed_data';
+
+class MediaFiles {
+ MediaFiles(this.dir);
+
+ final String dir;
+
+ static final _safe = RegExp(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$');
+
+ static bool validName(String name) => _safe.hasMatch(name) && !name.contains('..');
+
+ Future<void> open() => Directory(dir).create(recursive: true);
+
+ File? _file(String name) => validName(name) ? File('$dir/$name') : null;
+
+ Future<Uint8List?> read(String name) async {
+ final f = _file(name);
+ if (f == null || !await f.exists()) return null;
+ return f.readAsBytes();
+ }
+
+ Future<bool> write(String name, List<int> bytes) async {
+ final f = _file(name);
+ if (f == null) return false;
+ final tmp = File('${f.path}.part');
+ await tmp.writeAsBytes(bytes, flush: true);
+ await tmp.rename(f.path);
+ return true;
+ }
+
+ Future<bool> delete(String name) async {
+ final f = _file(name);
+ if (f == null || !await f.exists()) return false;
+ await f.delete();
+ return true;
+ }
+
+ Future<bool> exists(String name) async {
+ final f = _file(name);
+ return f != null && await f.exists();
+ }
+
+ static String typeOf(String name) {
+ final ext = name.contains('.') ? name.substring(name.lastIndexOf('.') + 1).toLowerCase() : '';
+ return switch (ext) {
+ 'jpg' || 'jpeg' => 'image/jpeg',
+ 'png' => 'image/png',
+ 'webp' => 'image/webp',
+ 'gif' => 'image/gif',
+ 'heic' => 'image/heic',
+ 'mp4' => 'video/mp4',
+ 'webm' => 'video/webm',
+ 'mov' => 'video/quicktime',
+ 'mp3' => 'audio/mpeg',
+ 'm4a' => 'audio/mp4',
+ 'ogg' => 'audio/ogg',
+ 'wav' => 'audio/wav',
+ _ => 'application/octet-stream',
+ };
+ }
+}
diff --git a/server/lib/src/phone_sync.dart b/server/lib/src/phone_sync.dart
new file mode 100644
index 0000000..d1bdfbc
--- /dev/null
+++ b/server/lib/src/phone_sync.dart
@@ -0,0 +1,287 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:archive/archive.dart';
+import 'package:gymmane_merge/gymmane_merge.dart';
+
+import 'media_store.dart';
+import 'state_store.dart';
+
+class PhoneSync {
+ PhoneSync({required this.syncDir, required this.dataDir, required this.store, required this.media});
+
+ final String syncDir;
+ final String dataDir;
+ final StateStore store;
+ final MediaFiles media;
+
+ static const device = 'server';
+ static const keep = 3;
+ static const _groups = {
+ 'noteMedia': ['notes'],
+ 'shotMedia': ['shots', 'bodyTl', 'timeline'],
+ 'momentMedia': ['moments'],
+ 'foodMedia': ['nutrition'],
+ 'passMedia': ['passes'],
+ };
+ static final _legacy = RegExp(r'^gymmane-auto-\d{4}-\d{2}-\d{2}.*\.zip$');
+
+ File get _meta => File('$dataDir/sync.meta.json');
+
+ final Map<String, int> _pulled = {};
+ DateTime? lastImport;
+ String? lastImportFile;
+ DateTime? lastExport;
+ String? lastError;
+ Timer? _poll;
+ Timer? _exportSoon;
+ bool _busy = false;
+
+ Future<void> start({Duration every = const Duration(seconds: 15)}) async {
+ await Directory(syncDir).create(recursive: true);
+ await _readMeta();
+ await scan();
+ _poll = Timer.periodic(every, (_) => scan());
+ }
+
+ void stop() {
+ _poll?.cancel();
+ _exportSoon?.cancel();
+ }
+
+ Map<String, Object?> get info => {
+ 'enabled': true,
+ 'folder': Uri.file(Directory(syncDir).absolute.path).normalizePath().toFilePath(),
+ 'devices': _pulled.keys.toList(),
+ if (lastImport != null) 'lastImport': lastImport!.toIso8601String(),
+ if (lastImportFile != null) 'lastImportFile': lastImportFile,
+ if (lastExport != null) 'lastExport': lastExport!.toIso8601String(),
+ if (lastError != null) 'error': lastError,
+ };
+
+ Future<void> _readMeta() async {
+ if (!await _meta.exists()) return;
+ try {
+ final m = jsonDecode(await _meta.readAsString()) as Map<String, dynamic>;
+ lastImport = DateTime.tryParse(m['import'] as String? ?? '');
+ lastImportFile = m['file'] as String?;
+ lastExport = DateTime.tryParse(m['export'] as String? ?? '');
+ ((m['pulled'] as Map?) ?? const {}).forEach((k, v) {
+ if (k is String && v is num) _pulled[k] = v.toInt();
+ });
+ } catch (_) {}
+ }
+
+ Future<void> _writeMeta() => _meta.writeAsString(jsonEncode({
+ if (lastImport != null) 'import': lastImport!.toIso8601String(),
+ if (lastImportFile != null) 'file': lastImportFile,
+ if (lastExport != null) 'export': lastExport!.toIso8601String(),
+ 'pulled': _pulled,
+ }));
+
+ Future<List<(String, DateTime, File)>> _candidates() async {
+ final dir = Directory(syncDir);
+ if (!await dir.exists()) return const [];
+ final names = <String, File>{};
+ final legacy = <File>[];
+ await for (final f in dir.list()) {
+ if (f is! File) continue;
+ final name = f.uri.pathSegments.last;
+ if (name.startsWith('.')) continue;
+ names[name] = f;
+ if (_legacy.hasMatch(name)) legacy.add(f);
+ }
+ final out = <(String, DateTime, File)>[
+ for (final e in newestByDevice(names.keys, self: device).entries) (e.key, e.value.at, names[e.value.name]!),
+ ];
+ File? old;
+ DateTime? oldAt;
+ for (final f in legacy) {
+ final at = (await f.stat()).modified.toUtc();
+ if (oldAt == null || at.isAfter(oldAt)) {
+ old = f;
+ oldAt = at;
+ }
+ }
+ if (old != null) out.add(('legacy', oldAt!, old));
+ return out;
+ }
+
+ Future<bool> scan() async {
+ if (_busy) return false;
+ _busy = true;
+ var merged = false;
+ try {
+ for (final (dev, at, f) in await _candidates()) {
+ if (at.millisecondsSinceEpoch <= (_pulled[dev] ?? 0)) continue;
+ final size = await f.length();
+ await Future<void>.delayed(const Duration(milliseconds: 600));
+ if (await f.length() != size) continue;
+ final last = lastExport;
+ final result = await mergeZip(await f.readAsBytes(), incomingNewer: last == null || at.isAfter(last));
+ _pulled[dev] = at.millisecondsSinceEpoch;
+ if (result == null) {
+ lastError = 'Could not read ${f.uri.pathSegments.last}';
+ continue;
+ }
+ lastError = null;
+ lastImport = DateTime.now().toUtc();
+ lastImportFile = f.uri.pathSegments.last;
+ if (result) merged = true;
+ }
+ await _writeMeta();
+ return merged;
+ } catch (e) {
+ lastError = '$e';
+ return false;
+ } finally {
+ _busy = false;
+ }
+ }
+
+ Future<bool?> mergeZip(Uint8List bytes, {required bool incomingNewer}) async {
+ final Archive archive;
+ try {
+ archive = ZipDecoder().decodeBytes(bytes);
+ } catch (_) {
+ return null;
+ }
+ ArchiveFile? json;
+ for (final f in archive.files) {
+ if (f.isFile && f.name.split('/').last == 'gymmane.json') json = f;
+ }
+ if (json == null) return null;
+ final Map<String, dynamic> incoming;
+ try {
+ final decoded = jsonDecode(utf8.decode(json.readBytes() ?? const []));
+ if (decoded is! Map<String, dynamic>) return null;
+ incoming = decoded;
+ } catch (_) {
+ return null;
+ }
+
+ Map<String, dynamic> local = const {};
+ final text = store.current.text;
+ if (text != null) {
+ try {
+ local = jsonDecode(text) as Map<String, dynamic>;
+ } catch (_) {}
+ }
+
+ final localEx = (local['media'] as Map?) ?? const {};
+ final exercise = <String, String>{};
+ final exMap = incoming['media'];
+ if (exMap is Map) {
+ for (final e in exMap.entries) {
+ final id = e.key;
+ final path = e.value;
+ if (id is! String || path is! String || localEx.containsKey(id)) continue;
+ final data = archive.findFile(path)?.readBytes();
+ if (data == null) continue;
+ final ext = path.contains('.') ? path.substring(path.lastIndexOf('.') + 1).toLowerCase() : 'dat';
+ final clean = id.replaceAll(RegExp(r'[^A-Za-z0-9_-]'), '_');
+ final name = 'ex-$clean-${data.length}.$ext';
+ if (await media.write(name, data)) exercise[id] = name;
+ }
+ }
+ incoming['media'] = exercise;
+
+ var added = exercise.isNotEmpty;
+ for (final group in _groups.keys) {
+ final map = incoming[group];
+ if (map is! Map) continue;
+ for (final e in map.entries) {
+ final name = e.key;
+ final path = e.value;
+ if (name is! String || path is! String || !MediaFiles.validName(name) || await media.exists(name)) continue;
+ final data = archive.findFile(path)?.readBytes();
+ if (data != null && await media.write(name, data)) added = true;
+ }
+ }
+
+ final merged = mergeStates(local, incoming, incomingNewer: incomingNewer);
+ if (sameState(local, merged) && !added) return false;
+ await store.write(jsonEncode(merged), source: 'phone');
+ return true;
+ }
+
+ void changed() {
+ _exportSoon?.cancel();
+ _exportSoon = Timer(const Duration(seconds: 30), () => exportZip());
+ }
+
+ Future<bool> exportZip() async {
+ final text = store.current.text;
+ if (text == null) return false;
+ try {
+ final data = jsonDecode(text) as Map<String, dynamic>;
+ final archive = Archive();
+ final added = <String>{};
+
+ Future<String?> add(String name) async {
+ final path = 'files/$name';
+ if (added.contains(name)) return path;
+ final bytes = await media.read(name);
+ if (bytes == null) return null;
+ archive.addFile(ArchiveFile.noCompress(path, bytes.length, bytes));
+ added.add(name);
+ return path;
+ }
+
+ final exercise = <String, String>{};
+ final exMap = data['media'];
+ if (exMap is Map) {
+ for (final e in exMap.entries) {
+ if (e.key is! String || e.value is! String) continue;
+ final path = await add(e.value as String);
+ if (path != null) exercise[e.key as String] = path;
+ }
+ }
+ data['media'] = exercise;
+
+ for (final entry in _groups.entries) {
+ final found = <String, String>{};
+ for (final key in entry.value) {
+ for (final name in stringsIn(data[key])) {
+ if (found.containsKey(name) || !MediaFiles.validName(name) || !await media.exists(name)) continue;
+ final path = await add(name);
+ if (path != null) found[name] = path;
+ }
+ }
+ data[entry.key] = found;
+ }
+
+ archive.addFile(ArchiveFile.string('gymmane.json', const JsonEncoder.withIndent(' ').convert(data)));
+ final zip = ZipEncoder().encodeBytes(archive);
+ final now = DateTime.now().toUtc();
+ final name = syncName(device, now);
+ final tmp = File('$syncDir/.$name.part');
+ await tmp.writeAsBytes(zip, flush: true);
+ await tmp.rename('$syncDir/$name');
+ lastExport = now;
+ await _prune();
+ await _writeMeta();
+ return true;
+ } catch (e) {
+ lastError = '$e';
+ return false;
+ }
+ }
+
+ Future<void> _prune() async {
+ final own = <SyncFile>[];
+ await for (final f in Directory(syncDir).list()) {
+ if (f is! File) continue;
+ final s = SyncFile.parse(f.uri.pathSegments.last);
+ if (s != null && s.device == device) own.add(s);
+ }
+ own.sort((a, b) => b.at.compareTo(a.at));
+ for (final s in own.skip(keep)) {
+ try {
+ await File('$syncDir/${s.name}').delete();
+ } catch (_) {}
+ }
+ }
+}
diff --git a/server/lib/src/server.dart b/server/lib/src/server.dart
new file mode 100644
index 0000000..cadade3
--- /dev/null
+++ b/server/lib/src/server.dart
@@ -0,0 +1,292 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'config.dart';
+import 'media_store.dart';
+import 'phone_sync.dart';
+import 'state_store.dart';
+
+const serverVersion = '1.0.0';
+
+class GymManeServer {
+ GymManeServer(this.config)
+ : store = StateStore(config.dataDir, keepDays: config.keepDays),
+ media = MediaFiles('${config.dataDir}/media');
+
+ final Config config;
+ final StateStore store;
+ final MediaFiles media;
+ PhoneSync? sync;
+ HttpServer? _http;
+
+ static const _maxState = 64 * 1024 * 1024;
+ static const _maxMedia = 80 * 1024 * 1024;
+
+ int get port => _http?.port ?? config.port;
+
+ Future<void> start() async {
+ await store.open();
+ await media.open();
+ final dir = config.syncDir;
+ if (dir != null) {
+ sync = PhoneSync(syncDir: dir, dataDir: config.dataDir, store: store, media: media);
+ await sync!.start();
+ }
+ final http = await HttpServer.bind(config.host, config.port, shared: true);
+ http.autoCompress = true;
+ http.idleTimeout = const Duration(seconds: 30);
+ _http = http;
+ http.listen((req) => unawaited(_handle(req)));
+ }
+
+ Future<void> stop() async {
+ sync?.stop();
+ await _http?.close(force: true);
+ }
+
+ Future<void> _handle(HttpRequest req) async {
+ final res = req.response;
+ res.headers
+ ..set('x-content-type-options', 'nosniff')
+ ..set('referrer-policy', 'no-referrer');
+ try {
+ if (!_authorized(req)) {
+ res.statusCode = HttpStatus.unauthorized;
+ res.headers.set('www-authenticate', 'Basic realm="GymMane", charset="UTF-8"');
+ res.write('Sign in to open GymMane.');
+ return;
+ }
+ final path = req.uri.path;
+ if (path.startsWith('/api/')) {
+ res.headers.set('cache-control', 'no-store');
+ await _api(req, path.substring(5));
+ } else {
+ await _static(req, path);
+ }
+ } catch (e) {
+ try {
+ res.statusCode = HttpStatus.internalServerError;
+ res.write('error');
+ } catch (_) {}
+ } finally {
+ try {
+ await res.close();
+ } catch (_) {}
+ }
+ }
+
+ bool _authorized(HttpRequest req) {
+ final password = config.password;
+ if (password == null) return true;
+ final header = req.headers.value(HttpHeaders.authorizationHeader) ?? '';
+ if (!header.toLowerCase().startsWith('basic ')) return false;
+ try {
+ final decoded = utf8.decode(base64.decode(header.substring(6).trim()));
+ final given = decoded.contains(':') ? decoded.substring(decoded.indexOf(':') + 1) : decoded;
+ return _same(given, password);
+ } catch (_) {
+ return false;
+ }
+ }
+
+ static bool _same(String a, String b) {
+ final x = utf8.encode(a);
+ final y = utf8.encode(b);
+ var diff = x.length ^ y.length;
+ for (var i = 0; i < x.length && i < y.length; i++) {
+ diff |= x[i] ^ y[i];
+ }
+ return diff == 0;
+ }
+
+ void _json(HttpResponse res, Object body, {int status = HttpStatus.ok}) {
+ res.statusCode = status;
+ res.headers.contentType = ContentType.json;
+ res.write(jsonEncode(body));
+ }
+
+ Future<List<int>?> _body(HttpRequest req, int max) async {
+ final out = BytesBuilder(copy: false);
+ await for (final chunk in req) {
+ out.add(chunk);
+ if (out.length > max) return null;
+ }
+ return out.takeBytes();
+ }
+
+ Future<void> _api(HttpRequest req, String route) async {
+ final res = req.response;
+ final method = req.method;
+ if (route == 'health') return _json(res, {'ok': true});
+ if (route == 'info' && method == 'GET') {
+ final now = store.current;
+ return _json(res, {
+ 'app': 'gymmane',
+ 'version': serverVersion,
+ 'rev': now.rev,
+ if (now.savedAt != null) 'savedAt': now.savedAt!.toIso8601String(),
+ 'source': now.source,
+ 'auth': config.password != null,
+ 'sync': sync?.info ?? {'enabled': false},
+ });
+ }
+ if (route == 'rev' && method == 'GET') return _json(res, {'rev': store.current.rev});
+ if (route == 'state') {
+ if (method == 'GET') {
+ final now = store.current;
+ res.headers
+ ..set('x-gymmane-rev', '${now.rev}')
+ ..set('x-gymmane-source', now.source);
+ if (now.text == null) {
+ res.statusCode = HttpStatus.noContent;
+ return;
+ }
+ res.headers.contentType = ContentType.json;
+ res.write(now.text);
+ return;
+ }
+ if (method == 'PUT') {
+ final bytes = await _body(req, _maxState);
+ if (bytes == null) return _json(res, {'error': 'too large'}, status: HttpStatus.requestEntityTooLarge);
+ final text = utf8.decode(bytes, allowMalformed: false);
+ if (!StateStore.isValid(text)) return _json(res, {'error': 'invalid'}, status: HttpStatus.badRequest);
+ final base = int.tryParse(req.headers.value('x-gymmane-base-rev') ?? '');
+ final result = await store.write(text, baseRev: base);
+ if (result.conflict) return _json(res, {'rev': result.rev}, status: HttpStatus.conflict);
+ sync?.changed();
+ return _json(res, {'rev': result.rev});
+ }
+ }
+ if (route.startsWith('media/')) {
+ final name = Uri.decodeComponent(route.substring(6));
+ if (!MediaFiles.validName(name)) return _json(res, {'error': 'name'}, status: HttpStatus.badRequest);
+ switch (method) {
+ case 'GET' || 'HEAD':
+ final bytes = await media.read(name);
+ if (bytes == null) return _json(res, {'error': 'missing'}, status: HttpStatus.notFound);
+ res.headers
+ ..contentType = ContentType.parse(MediaFiles.typeOf(name))
+ ..set('cache-control', 'private, max-age=31536000, immutable');
+ if (method == 'GET') res.add(bytes);
+ return;
+ case 'PUT':
+ final bytes = await _body(req, _maxMedia);
+ if (bytes == null) return _json(res, {'error': 'too large'}, status: HttpStatus.requestEntityTooLarge);
+ await media.write(name, bytes);
+ sync?.changed();
+ return _json(res, {'ok': true});
+ case 'DELETE':
+ await media.delete(name);
+ return _json(res, {'ok': true});
+ }
+ }
+ if (route == 'sync/scan' && method == 'POST') {
+ final s = sync;
+ if (s == null) return _json(res, {'enabled': false});
+ final imported = await s.scan();
+ return _json(res, {'imported': imported, 'rev': store.current.rev, ...s.info});
+ }
+ if (route == 'sync/export' && method == 'POST') {
+ final s = sync;
+ if (s == null) return _json(res, {'enabled': false});
+ return _json(res, {'exported': await s.exportZip(), ...s.info});
+ }
+ _json(res, {'error': 'not found'}, status: HttpStatus.notFound);
+ }
+
+ static const _types = {
+ 'html': 'text/html; charset=utf-8',
+ 'js': 'text/javascript; charset=utf-8',
+ 'mjs': 'text/javascript; charset=utf-8',
+ 'json': 'application/json; charset=utf-8',
+ 'css': 'text/css; charset=utf-8',
+ 'wasm': 'application/wasm',
+ 'png': 'image/png',
+ 'jpg': 'image/jpeg',
+ 'webp': 'image/webp',
+ 'svg': 'image/svg+xml',
+ 'ico': 'image/x-icon',
+ 'ttf': 'font/ttf',
+ 'otf': 'font/otf',
+ 'woff2': 'font/woff2',
+ 'txt': 'text/plain; charset=utf-8',
+ 'wav': 'audio/wav',
+ 'mp3': 'audio/mpeg',
+ 'bin': 'application/octet-stream',
+ 'frag': 'application/octet-stream',
+ };
+
+ Future<void> _static(HttpRequest req, String path) async {
+ final res = req.response;
+ if (req.method != 'GET' && req.method != 'HEAD') {
+ res.statusCode = HttpStatus.methodNotAllowed;
+ return;
+ }
+ final root = Directory(config.webDir).absolute.path;
+ var rel = Uri.decodeComponent(path);
+ if (rel.isEmpty || rel.endsWith('/')) rel = '${rel}index.html';
+ final parts = rel.split('/').where((p) => p.isNotEmpty).toList();
+ if (parts.any((p) => p == '..' || p.startsWith('.'))) {
+ res.statusCode = HttpStatus.notFound;
+ return;
+ }
+ var file = File([root, ...parts].join(Platform.pathSeparator));
+ if (!await file.exists()) {
+ final last = parts.isEmpty ? '' : parts.last;
+ if (last.contains('.')) {
+ res.statusCode = HttpStatus.notFound;
+ return;
+ }
+ file = File('$root${Platform.pathSeparator}index.html');
+ if (!await file.exists()) {
+ res.statusCode = HttpStatus.serviceUnavailable;
+ res.headers.contentType = ContentType.text;
+ res.write('The GymMane web files are missing. Set GYMMANE_WEB to the folder with index.html.');
+ return;
+ }
+ }
+ final name = file.uri.pathSegments.last;
+ final ext = name.contains('.') ? name.substring(name.lastIndexOf('.') + 1).toLowerCase() : '';
+ final stat = await file.stat();
+ final modified = stat.modified.toUtc();
+ final since = req.headers.ifModifiedSince;
+ final entry = name == 'index.html' || name == 'flutter_bootstrap.js' || name == 'flutter_service_worker.js';
+ res.headers
+ ..set('content-type', _types[ext] ?? 'application/octet-stream')
+ ..set('cache-control', entry ? 'no-cache' : 'public, max-age=3600')
+ ..set('cross-origin-opener-policy', 'same-origin')
+ ..set('cross-origin-embedder-policy', 'require-corp')
+ ..set('cross-origin-resource-policy', 'same-origin')
+ ..set(HttpHeaders.varyHeader, 'accept-encoding')
+ ..set(HttpHeaders.lastModifiedHeader, HttpDate.format(modified));
+ if (since != null && !modified.isAfter(since.add(const Duration(seconds: 1)))) {
+ res.statusCode = HttpStatus.notModified;
+ return;
+ }
+ final accepts = req.headers[HttpHeaders.acceptEncodingHeader]?.join(',').contains('gzip') ?? false;
+ if (accepts && _packable.contains(ext) && stat.size > 1024) {
+ final packed = await _packed(file, modified);
+ res.headers.set(HttpHeaders.contentEncodingHeader, 'gzip');
+ res.contentLength = packed.length;
+ if (req.method == 'HEAD') return;
+ res.add(packed);
+ return;
+ }
+ res.contentLength = stat.size;
+ if (req.method == 'HEAD') return;
+ await res.addStream(file.openRead());
+ }
+
+ static const _packable = {'html', 'js', 'mjs', 'json', 'css', 'wasm', 'svg', 'txt', 'ttf', 'otf', 'frag', 'bin'};
+ final Map<String, (DateTime, List<int>)> _gz = {};
+
+ Future<List<int>> _packed(File file, DateTime modified) async {
+ final hit = _gz[file.path];
+ if (hit != null && hit.$1 == modified) return hit.$2;
+ final bytes = gzip.encode(await file.readAsBytes());
+ _gz[file.path] = (modified, bytes);
+ return bytes;
+ }
+}
diff --git a/server/lib/src/state_store.dart b/server/lib/src/state_store.dart
new file mode 100644
index 0000000..47cbdee
--- /dev/null
+++ b/server/lib/src/state_store.dart
@@ -0,0 +1,98 @@
+import 'dart:convert';
+import 'dart:io';
+
+class Snapshot {
+ const Snapshot(this.rev, this.text, this.savedAt, this.source);
+
+ final int rev;
+ final String? text;
+ final DateTime? savedAt;
+ final String source;
+}
+
+class WriteResult {
+ const WriteResult.ok(this.rev) : conflict = false;
+ const WriteResult.conflict(this.rev) : conflict = true;
+
+ final int rev;
+ final bool conflict;
+}
+
+class StateStore {
+ StateStore(this.dir, {this.keepDays = 30});
+
+ final String dir;
+ final int keepDays;
+
+ File get _state => File('$dir/state.json');
+ File get _meta => File('$dir/state.meta.json');
+ Directory get _history => Directory('$dir/history');
+
+ Snapshot? _cache;
+
+ Future<void> open() async {
+ await Directory(dir).create(recursive: true);
+ await _history.create(recursive: true);
+ _cache = await _readDisk();
+ }
+
+ Snapshot get current => _cache ?? const Snapshot(0, null, null, 'none');
+
+ Future<Snapshot> _readDisk() async {
+ var rev = 0;
+ DateTime? at;
+ var source = 'none';
+ if (await _meta.exists()) {
+ try {
+ final m = jsonDecode(await _meta.readAsString()) as Map<String, dynamic>;
+ rev = (m['rev'] as num?)?.toInt() ?? 0;
+ at = DateTime.tryParse(m['savedAt'] as String? ?? '');
+ source = m['source'] as String? ?? 'web';
+ } catch (_) {}
+ }
+ final text = await _state.exists() ? await _state.readAsString() : null;
+ if (text != null && rev == 0) rev = 1;
+ return Snapshot(rev, text, at, text == null ? 'none' : source);
+ }
+
+ static bool isValid(String text) {
+ try {
+ return jsonDecode(text) is Map<String, dynamic>;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ Future<WriteResult> write(String text, {int? baseRev, String source = 'web'}) async {
+ final now = current;
+ if (baseRev != null && now.rev != 0 && baseRev != now.rev) return WriteResult.conflict(now.rev);
+ final rev = now.rev + 1;
+ final at = DateTime.now().toUtc();
+ await _keepHistory(now);
+ await _atomic(_state, text);
+ await _atomic(_meta, jsonEncode({'rev': rev, 'savedAt': at.toIso8601String(), 'source': source}));
+ _cache = Snapshot(rev, text, at, source);
+ return WriteResult.ok(rev);
+ }
+
+ Future<void> _atomic(File f, String text) async {
+ final tmp = File('${f.path}.tmp');
+ await tmp.writeAsString(text, flush: true);
+ await tmp.rename(f.path);
+ }
+
+ Future<void> _keepHistory(Snapshot before) async {
+ final text = before.text;
+ if (text == null) return;
+ final day = DateTime.now().toUtc().toIso8601String().substring(0, 10);
+ final f = File('${_history.path}/state-$day.json');
+ if (!await f.exists()) await f.writeAsString(text, flush: true);
+ final files = (await _history.list().toList()).whereType<File>().where((x) => x.path.endsWith('.json')).toList()
+ ..sort((a, b) => b.path.compareTo(a.path));
+ for (final old in files.skip(keepDays)) {
+ try {
+ await old.delete();
+ } catch (_) {}
+ }
+ }
+}
diff --git a/server/pubspec.lock b/server/pubspec.lock
new file mode 100644
index 0000000..31a1283
--- /dev/null
+++ b/server/pubspec.lock
@@ -0,0 +1,428 @@
+# Generated by pub
+# See https://dart.dev/tools/pub/glossary#lockfile
+packages:
+ _fe_analyzer_shared:
+ dependency: transitive
+ description:
+ name: _fe_analyzer_shared
+ sha256: "48e48f73a431eb269eec66d243a63a07ed90ef9417a74047a3b98d52338626ad"
+ url: "https://pub.dev"
+ source: hosted
+ version: "109.0.0"
+ analyzer:
+ dependency: transitive
+ description:
+ name: analyzer
+ sha256: "6d377901d198536b648172974d9d4f277910502cad92193466869cac0ff34990"
+ url: "https://pub.dev"
+ source: hosted
+ version: "14.5.0"
+ archive:
+ dependency: "direct main"
+ description:
+ name: archive
+ sha256: de5ac590b8155e4e676088d714bd41ea620449a6adc0f7950c5073874b287ddb
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.6.0"
+ args:
+ dependency: transitive
+ description:
+ name: args
+ sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.7.0"
+ async:
+ dependency: transitive
+ description:
+ name: async
+ sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.13.1"
+ boolean_selector:
+ dependency: transitive
+ description:
+ name: boolean_selector
+ sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.2"
+ cli_config:
+ dependency: transitive
+ description:
+ name: cli_config
+ sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.2.0"
+ cli_util:
+ dependency: transitive
+ description:
+ name: cli_util
+ sha256: "89b8801ba49f8b593fbf2d3e59efd0f566c46cd4ba6837ae2610c72b52a0f899"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.6.0"
+ collection:
+ dependency: transitive
+ description:
+ name: collection
+ sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.19.1"
+ convert:
+ dependency: transitive
+ description:
+ name: convert
+ sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.2"
+ coverage:
+ dependency: transitive
+ description:
+ name: coverage
+ sha256: ff89e37c19355194e279d26dafe8e4bece46c9ea63a30be4dc68214f5bc290d3
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.16.0"
+ crypto:
+ dependency: transitive
+ description:
+ name: crypto
+ sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.8"
+ ffi:
+ dependency: transitive
+ description:
+ name: ffi
+ sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.0"
+ file:
+ dependency: transitive
+ description:
+ name: file
+ sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.0.1"
+ frontend_server_client:
+ dependency: transitive
+ description:
+ name: frontend_server_client
+ sha256: "404dbf9bce29beafbe9dcb19219447b6f7d49900cd42b8d3b7af102b24508e25"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.1.0"
+ glob:
+ dependency: transitive
+ description:
+ name: glob
+ sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.0"
+ gymmane_merge:
+ dependency: "direct main"
+ description:
+ path: "../packages/gymmane_merge"
+ relative: true
+ source: path
+ version: "1.0.0"
+ http_multi_server:
+ dependency: transitive
+ description:
+ name: http_multi_server
+ sha256: "361668bdd71f0ae2dc6d17b75a593520f3c414af6534f9eed1aa72049dd71d18"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.2.3"
+ http_parser:
+ dependency: transitive
+ description:
+ name: http_parser
+ sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.1.2"
+ io:
+ dependency: transitive
+ description:
+ name: io
+ sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.0"
+ lints:
+ dependency: "direct dev"
+ description:
+ name: lints
+ sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df"
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.1.0"
+ logging:
+ dependency: transitive
+ description:
+ name: logging
+ sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.3.0"
+ matcher:
+ dependency: transitive
+ description:
+ name: matcher
+ sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.12.20"
+ meta:
+ dependency: transitive
+ description:
+ name: meta
+ sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.19.0"
+ mime:
+ dependency: transitive
+ description:
+ name: mime
+ sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.0"
+ node_preamble:
+ dependency: transitive
+ description:
+ name: node_preamble
+ sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.0.2"
+ package_config:
+ dependency: transitive
+ description:
+ name: package_config
+ sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.0"
+ path:
+ dependency: transitive
+ description:
+ name: path
+ sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.9.1"
+ pool:
+ dependency: transitive
+ description:
+ name: pool
+ sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.5.3"
+ posix:
+ dependency: transitive
+ description:
+ name: posix
+ sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63"
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.5.4"
+ pub_semver:
+ dependency: transitive
+ description:
+ name: pub_semver
+ sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.1"
+ shelf:
+ dependency: transitive
+ description:
+ name: shelf
+ sha256: e75e9cf311d7fd712048038cc17c25199c38536c20330d53e7db058b543d5a48
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.3"
+ shelf_packages_handler:
+ dependency: transitive
+ description:
+ name: shelf_packages_handler
+ sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.2"
+ shelf_static:
+ dependency: transitive
+ description:
+ name: shelf_static
+ sha256: "480504af9e5323899c5be26a4f6c2fc4437d50954d39842f0290f4ae733d57b4"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.0"
+ shelf_web_socket:
+ dependency: transitive
+ description:
+ name: shelf_web_socket
+ sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.0"
+ source_map_stack_trace:
+ dependency: transitive
+ description:
+ name: source_map_stack_trace
+ sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.2"
+ source_maps:
+ dependency: transitive
+ description:
+ name: source_maps
+ sha256: "14c2945847669b44089bb1222f66873d7ff7103c58911917f2a63c5a62327898"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.10.14"
+ source_span:
+ dependency: transitive
+ description:
+ name: source_span
+ sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.10.2"
+ stack_trace:
+ dependency: transitive
+ description:
+ name: stack_trace
+ sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.12.2"
+ stream_channel:
+ dependency: transitive
+ description:
+ name: stream_channel
+ sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.4"
+ string_scanner:
+ dependency: transitive
+ description:
+ name: string_scanner
+ sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.1"
+ term_glyph:
+ dependency: transitive
+ description:
+ name: term_glyph
+ sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.2"
+ test:
+ dependency: "direct dev"
+ description:
+ name: test
+ sha256: "44b2fccf4407bcdb5e105c064c5d6b5e2a640c87761f8b03cdce8cf532d98cfa"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.33.0"
+ test_api:
+ dependency: transitive
+ description:
+ name: test_api
+ sha256: "47481c58bb92d0b1d218f0510ff5647e768f8e1256d07077a151fb520923b51d"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.7.15"
+ test_core:
+ dependency: transitive
+ description:
+ name: test_core
+ sha256: "9dec4c178bd61493e1cd2060ffe701fcb61c43da2493e99590fb1b0cc82eb4af"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.6.21"
+ typed_data:
+ dependency: transitive
+ description:
+ name: typed_data
+ sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.0"
+ vm_service:
+ dependency: transitive
+ description:
+ name: vm_service
+ sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78"
+ url: "https://pub.dev"
+ source: hosted
+ version: "15.4.0"
+ watcher:
+ dependency: transitive
+ description:
+ name: watcher
+ sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.1"
+ web:
+ dependency: transitive
+ description:
+ name: web
+ sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.1"
+ web_socket:
+ dependency: transitive
+ description:
+ name: web_socket
+ sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.1"
+ web_socket_channel:
+ dependency: transitive
+ description:
+ name: web_socket_channel
+ sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.3"
+ webkit_inspection_protocol:
+ dependency: transitive
+ description:
+ name: webkit_inspection_protocol
+ sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.1"
+ yaml:
+ dependency: transitive
+ description:
+ name: yaml
+ sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.4"
+sdks:
+ dart: ">=3.11.0 <4.0.0"
diff --git a/server/pubspec.yaml b/server/pubspec.yaml
new file mode 100644
index 0000000..ea4a456
--- /dev/null
+++ b/server/pubspec.yaml
@@ -0,0 +1,16 @@
+name: gymmane_server
+description: "Self-hosted server for the GymMane web app."
+publish_to: 'none'
+version: 1.0.0
+
+environment:
+ sdk: ^3.11.0
+
+dependencies:
+ archive: ^4.0.9
+ gymmane_merge:
+ path: ../packages/gymmane_merge
+
+dev_dependencies:
+ lints: ^6.0.0
+ test: ^1.25.0
diff --git a/server/test/server_test.dart b/server/test/server_test.dart
new file mode 100644
index 0000000..1ab1ffe
--- /dev/null
+++ b/server/test/server_test.dart
@@ -0,0 +1,188 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:archive/archive.dart';
+import 'package:gymmane_server/gymmane_server.dart';
+import 'package:test/test.dart';
+
+void main() {
+ late Directory tmp;
+ late GymManeServer server;
+ late HttpClient client;
+
+ Future<GymManeServer> boot({String? password}) async {
+ final web = Directory('${tmp.path}/web')..createSync(recursive: true);
+ File('${web.path}/index.html').writeAsStringSync('<html>gymmane</html>');
+ File('${web.path}/main.dart.js').writeAsStringSync('console.log(1)');
+ final s = GymManeServer(Config(
+ port: 0,
+ host: '127.0.0.1',
+ dataDir: '${tmp.path}/data',
+ webDir: web.path,
+ syncDir: '${tmp.path}/sync',
+ password: password,
+ keepDays: 3,
+ ));
+ await s.start();
+ return s;
+ }
+
+ Future<(int, String, HttpHeaders)> call(String method, String path,
+ {String? body, List<int>? bytes, Map<String, String> headers = const {}}) async {
+ final req = await client.openUrl(method, Uri.parse('http://127.0.0.1:${server.port}$path'));
+ headers.forEach(req.headers.set);
+ if (body != null) req.write(body);
+ if (bytes != null) req.add(bytes);
+ final res = await req.close();
+ final text = await utf8.decoder.bind(res).join();
+ return (res.statusCode, text, res.headers);
+ }
+
+ setUp(() async {
+ tmp = Directory.systemTemp.createTempSync('gymmane-server');
+ client = HttpClient();
+ server = await boot();
+ });
+
+ tearDown(() async {
+ client.close(force: true);
+ await server.stop();
+ tmp.deleteSync(recursive: true);
+ });
+
+ test('empieza vacío y guarda el estado con su revisión', () async {
+ var (status, _, headers) = await call('GET', '/api/state');
+ expect(status, 204);
+ expect(headers.value('x-gymmane-rev'), '0');
+ final (put, putBody, _) = await call('PUT', '/api/state', body: '{"onboarded":true}');
+ expect(put, 200);
+ expect(jsonDecode(putBody)['rev'], 1);
+ final (get, text, h2) = await call('GET', '/api/state');
+ expect(get, 200);
+ expect(text, '{"onboarded":true}');
+ expect(h2.value('x-gymmane-rev'), '1');
+ });
+
+ test('rechaza un guardado hecho sobre una revisión vieja', () async {
+ await call('PUT', '/api/state', body: '{"a":1}');
+ await call('PUT', '/api/state', body: '{"a":2}', headers: {'x-gymmane-base-rev': '1'});
+ final (status, body, _) = await call('PUT', '/api/state', body: '{"a":3}', headers: {'x-gymmane-base-rev': '1'});
+ expect(status, 409);
+ expect(jsonDecode(body)['rev'], 2);
+ final (_, text, _) = await call('GET', '/api/state');
+ expect(text, '{"a":2}');
+ });
+
+ test('no acepta algo que no sea un objeto JSON', () async {
+ final (status, _, _) = await call('PUT', '/api/state', body: 'hola');
+ expect(status, 400);
+ });
+
+ test('guarda, sirve y borra fotos, y rechaza nombres raros', () async {
+ final (put, _, _) = await call('PUT', '/api/media/food-1-2.jpg', bytes: [1, 2, 3]);
+ expect(put, 200);
+ final req = await client.getUrl(Uri.parse('http://127.0.0.1:${server.port}/api/media/food-1-2.jpg'));
+ final res = await req.close();
+ expect(res.headers.contentType?.mimeType, 'image/jpeg');
+ expect(await res.fold<List<int>>([], (a, b) => a..addAll(b)), [1, 2, 3]);
+ final (bad, _, _) = await call('PUT', '/api/media/..%2Fsecret', bytes: [1]);
+ expect(bad, 400);
+ await call('DELETE', '/api/media/food-1-2.jpg');
+ final (gone, _, _) = await call('GET', '/api/media/food-1-2.jpg');
+ expect(gone, 404);
+ });
+
+ test('sirve la web y vuelve a index.html en rutas de la app', () async {
+ final (root, html, _) = await call('GET', '/');
+ expect(root, 200);
+ expect(html, contains('gymmane'));
+ final (deep, html2, _) = await call('GET', '/progress');
+ expect(deep, 200);
+ expect(html2, contains('gymmane'));
+ final (missing, _, _) = await call('GET', '/nope.js');
+ expect(missing, 404);
+ final (escape, _, _) = await call('GET', '/../data/state.json');
+ expect(escape, isNot(200));
+ });
+
+ test('con contraseña pide entrar y deja pasar con la correcta', () async {
+ await server.stop();
+ server = await boot(password: 'pesas');
+ final (closed, _, h) = await call('GET', '/api/info');
+ expect(closed, 401);
+ expect(h.value('www-authenticate'), contains('Basic'));
+ final wrong = base64.encode(utf8.encode('yo:otra'));
+ final (no, _, _) = await call('GET', '/api/info', headers: {'authorization': 'Basic $wrong'});
+ expect(no, 401);
+ final right = base64.encode(utf8.encode('yo:pesas'));
+ final (ok, _, _) = await call('GET', '/api/info', headers: {'authorization': 'Basic $right'});
+ expect(ok, 200);
+ });
+
+ test('junta la copia del móvil con lo de la web, con sus fotos, y deja la suya', () async {
+ await call('PUT', '/api/state', body: jsonEncode({
+ 'notes': [
+ {'id': 'w1', 't': 'web'},
+ ],
+ }));
+ final archive = Archive()
+ ..addFile(ArchiveFile.string(
+ 'gymmane.json',
+ jsonEncode({
+ 'onboarded': true,
+ 'media': {'EIeI8Vf': 'media/images/bench.jpg'},
+ 'notes': [
+ {'id': 'n1', 'm': ['note-1-0.jpg']},
+ ],
+ 'noteMedia': {'note-1-0.jpg': 'media/notes/first.jpg'},
+ 'nutrition': {
+ 'foods': [
+ {'id': 'f1', 'ph': 'food-9-1.png'},
+ ],
+ },
+ 'foodMedia': {'food-9-1.png': 'foods/oats.png'},
+ })))
+ ..addFile(ArchiveFile.noCompress('media/images/bench.jpg', 3, [9, 9, 9]))
+ ..addFile(ArchiveFile.noCompress('media/notes/first.jpg', 2, [7, 7]))
+ ..addFile(ArchiveFile.noCompress('foods/oats.png', 1, [5]));
+ File('${tmp.path}/sync/gymmane-auto-phone-2026-11-10-120000.zip').writeAsBytesSync(ZipEncoder().encodeBytes(archive));
+ final (status, body, _) = await call('POST', '/api/sync/scan');
+ expect(status, 200);
+ expect(jsonDecode(body)['imported'], isTrue);
+
+ final (_, text, _) = await call('GET', '/api/state');
+ final state = jsonDecode(text) as Map<String, dynamic>;
+ expect(state.containsKey('noteMedia'), isFalse);
+ expect([for (final n in state['notes'] as List) (n as Map)['id']], containsAll(['w1', 'n1']));
+ final exName = (state['media'] as Map)['EIeI8Vf'] as String;
+ expect(File('${tmp.path}/data/media/$exName').readAsBytesSync(), [9, 9, 9]);
+ expect(File('${tmp.path}/data/media/note-1-0.jpg').readAsBytesSync(), [7, 7]);
+ expect(File('${tmp.path}/data/media/food-9-1.png').readAsBytesSync(), [5]);
+
+ final (again, body2, _) = await call('POST', '/api/sync/scan');
+ expect(again, 200);
+ expect(jsonDecode(body2)['imported'], isFalse);
+
+ final (ex, _, _) = await call('POST', '/api/sync/export');
+ expect(ex, 200);
+ final mine = Directory('${tmp.path}/sync')
+ .listSync()
+ .whereType<File>()
+ .where((f) => f.uri.pathSegments.last.startsWith('gymmane-auto-server-'))
+ .toList();
+ expect(mine, hasLength(1));
+ final out = ZipDecoder().decodeBytes(mine.single.readAsBytesSync());
+ final back = jsonDecode(utf8.decode(out.findFile('gymmane.json')!.readBytes()!)) as Map<String, dynamic>;
+ expect((back['noteMedia'] as Map).keys, ['note-1-0.jpg']);
+ expect((back['foodMedia'] as Map).keys, ['food-9-1.png']);
+ expect(out.findFile((back['media'] as Map)['EIeI8Vf'] as String)!.readBytes(), [9, 9, 9]);
+ });
+
+ test('guarda una copia diaria del estado anterior', () async {
+ await call('PUT', '/api/state', body: '{"a":1}');
+ await call('PUT', '/api/state', body: '{"a":2}');
+ final history = Directory('${tmp.path}/data/history').listSync().whereType<File>().toList();
+ expect(history, hasLength(1));
+ expect(history.single.readAsStringSync(), '{"a":1}');
+ });
+}