Skip to content

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

Connect the app to a self-hosted server

InlitXf50d6d25c91a
diff --git a/lib/services/host.dart b/lib/services/host.dart
new file mode 100644
index 0000000..45d2dc1
--- /dev/null
+++ b/lib/services/host.dart
@@ -0,0 +1,9 @@
+import 'dart:io' show Platform;
+
+import 'package:flutter/foundation.dart';
+
+bool get onAndroid => !kIsWeb && Platform.isAndroid;
+
+bool get onIOS => !kIsWeb && Platform.isIOS;
+
+bool get onMobile => onAndroid || onIOS;
diff --git a/lib/services/server/server_link.dart b/lib/services/server/server_link.dart
new file mode 100644
index 0000000..734eef9
--- /dev/null
+++ b/lib/services/server/server_link.dart
@@ -0,0 +1,167 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/foundation.dart';
+
+import 'transport_stub.dart' if (dart.library.js_interop) 'transport_web.dart' as net;
+
+class ServerLink extends ChangeNotifier {
+ ServerLink._();
+ static final ServerLink instance = ServerLink._();
+
+ bool available = false;
+ bool online = true;
+ int rev = 0;
+ String? remoteText;
+ DateTime? savedAt;
+
+ String? _pending;
+ bool _sending = false;
+ Timer? _poll;
+ bool _started = false;
+
+ void Function(String text, {required bool conflict, required bool fromPhone})? onRemote;
+
+ bool get busy => _sending || _pending != null;
+
+ Future<void> connect() async {
+ if (!kIsWeb || !net.transportAvailable) return;
+ final r = await net.send('GET', 'api/state');
+ if (r.status == 204 || (r.ok && (r.headers['content-type'] ?? '').contains('json'))) {
+ available = true;
+ rev = int.tryParse(r.headers['x-gymmane-rev'] ?? '') ?? 0;
+ remoteText = r.status == 204 ? null : utf8.decode(r.bytes ?? Uint8List(0));
+ }
+ }
+
+ void start() {
+ if (!available || _started) return;
+ _started = true;
+ _poll = Timer.periodic(const Duration(seconds: 20), (_) => check());
+ net.onPageVisible(check);
+ }
+
+ @override
+ void dispose() {
+ _poll?.cancel();
+ super.dispose();
+ }
+
+ void push(String text) {
+ if (!available || text == remoteText) return;
+ _pending = text;
+ if (!_sending) unawaited(_drain());
+ }
+
+ void _setOnline(bool v) {
+ if (online == v) return;
+ online = v;
+ notifyListeners();
+ }
+
+ Future<void> _drain() async {
+ _sending = true;
+ var wait = 2;
+ try {
+ while (_pending != null) {
+ final text = _pending!;
+ _pending = null;
+ final r = await net.send('PUT', 'api/state',
+ body: Uint8List.fromList(utf8.encode(text)),
+ headers: {'content-type': 'application/json', 'x-gymmane-base-rev': '$rev'});
+ if (r.ok) {
+ _setOnline(true);
+ wait = 2;
+ try {
+ rev = (jsonDecode(utf8.decode(r.bytes!))['rev'] as num).toInt();
+ } catch (_) {}
+ remoteText = text;
+ savedAt = DateTime.now();
+ continue;
+ }
+ if (r.status == 409) {
+ _setOnline(true);
+ _pending = null;
+ await _pull(conflict: true);
+ break;
+ }
+ _setOnline(false);
+ _pending ??= text;
+ await Future<void>.delayed(Duration(seconds: wait));
+ wait = wait >= 30 ? 30 : wait * 2;
+ }
+ } finally {
+ _sending = false;
+ }
+ }
+
+ Future<void> check() async {
+ if (!available || busy) return;
+ final r = await net.send('GET', 'api/rev');
+ if (!r.ok) {
+ _setOnline(false);
+ return;
+ }
+ _setOnline(true);
+ try {
+ final remote = (jsonDecode(utf8.decode(r.bytes!))['rev'] as num).toInt();
+ if (remote > rev) await _pull();
+ } catch (_) {}
+ }
+
+ Future<void> _pull({bool conflict = false}) async {
+ final r = await net.send('GET', 'api/state');
+ if (!r.ok || r.bytes == null) return;
+ rev = int.tryParse(r.headers['x-gymmane-rev'] ?? '') ?? rev;
+ final text = utf8.decode(r.bytes!);
+ remoteText = text;
+ onRemote?.call(text, conflict: conflict, fromPhone: r.headers['x-gymmane-source'] == 'phone');
+ }
+
+ Future<Map<String, dynamic>?> _json(String method, String path) async {
+ final r = await net.send(method, path);
+ if (!r.ok || r.bytes == null) return null;
+ try {
+ final v = jsonDecode(utf8.decode(r.bytes!));
+ return v is Map<String, dynamic> ? v : null;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ Future<Map<String, dynamic>?> info() => available ? _json('GET', 'api/info') : Future.value(null);
+
+ Future<Map<String, dynamic>?> scanPhone() async {
+ if (!available) return null;
+ final r = await _json('POST', 'api/sync/scan');
+ if (r?['imported'] == true) await check();
+ return r;
+ }
+
+ Future<Map<String, dynamic>?> exportForPhone() => available ? _json('POST', 'api/sync/export') : Future.value(null);
+
+ String mediaUrl(String name) => net.mediaUrl(name);
+
+ Future<bool> putMedia(String name, Uint8List bytes) async {
+ if (!available) return false;
+ final r = await net.send('PUT', 'api/media/${Uri.encodeComponent(name)}',
+ body: bytes, headers: {'content-type': 'application/octet-stream'});
+ return r.ok;
+ }
+
+ Future<Uint8List?> getMedia(String name) async {
+ if (!available) return null;
+ final r = await net.send('GET', 'api/media/${Uri.encodeComponent(name)}');
+ return r.ok ? r.bytes : null;
+ }
+
+ Future<Uint8List?> fetchBytes(String url) async {
+ final r = await net.send('GET', url);
+ return r.ok ? r.bytes : null;
+ }
+
+ Future<void> deleteMedia(String name) async {
+ if (!available) return;
+ await net.send('DELETE', 'api/media/${Uri.encodeComponent(name)}');
+ }
+}
diff --git a/lib/services/server/transport.dart b/lib/services/server/transport.dart
new file mode 100644
index 0000000..4770daf
--- /dev/null
+++ b/lib/services/server/transport.dart
@@ -0,0 +1,13 @@
+import 'dart:typed_data';
+
+class Reply {
+ const Reply(this.status, this.bytes, this.headers);
+
+ const Reply.failed() : status = 0, bytes = null, headers = const {};
+
+ final int status;
+ final Uint8List? bytes;
+ final Map<String, String> headers;
+
+ bool get ok => status >= 200 && status < 300;
+}
diff --git a/lib/services/server/transport_stub.dart b/lib/services/server/transport_stub.dart
new file mode 100644
index 0000000..c92e2e2
--- /dev/null
+++ b/lib/services/server/transport_stub.dart
@@ -0,0 +1,16 @@
+import 'dart:typed_data';
+
+import 'transport.dart';
+
+bool get transportAvailable => false;
+
+Future<Reply> send(String method, String path, {Uint8List? body, Map<String, String> headers = const {}}) async =>
+ const Reply.failed();
+
+String mediaUrl(String name) => '';
+
+void onPageVisible(void Function() callback) {}
+
+void beforeLeave(void Function() callback) {}
+
+void download(String name, Uint8List bytes, String mime) {}
diff --git a/lib/services/server/transport_web.dart b/lib/services/server/transport_web.dart
new file mode 100644
index 0000000..082628b
--- /dev/null
+++ b/lib/services/server/transport_web.dart
@@ -0,0 +1,65 @@
+import 'dart:js_interop';
+import 'dart:typed_data';
+
+import 'package:web/web.dart' as web;
+
+import 'transport.dart';
+
+bool get transportAvailable => true;
+
+String _url(String path) => Uri.base.resolve(path).toString();
+
+String mediaUrl(String name) => _url('api/media/${Uri.encodeComponent(name)}');
+
+Future<Reply> send(String method, String path, {Uint8List? body, Map<String, String> headers = const {}}) async {
+ try {
+ final h = web.Headers();
+ headers.forEach((k, v) => h.append(k, v));
+ final res = await web.window
+ .fetch(
+ _url(path).toJS,
+ web.RequestInit(
+ method: method,
+ headers: h,
+ body: body?.toJS,
+ credentials: 'same-origin',
+ cache: 'no-store',
+ ),
+ )
+ .toDart;
+ final buffer = await res.arrayBuffer().toDart;
+ return Reply(res.status, buffer.toDart.asUint8List(), {
+ 'x-gymmane-rev': res.headers.get('x-gymmane-rev') ?? '',
+ 'x-gymmane-source': res.headers.get('x-gymmane-source') ?? '',
+ 'content-type': res.headers.get('content-type') ?? '',
+ });
+ } catch (_) {
+ return const Reply.failed();
+ }
+}
+
+void onPageVisible(void Function() callback) {
+ web.document.addEventListener(
+ 'visibilitychange',
+ ((web.Event _) {
+ if (web.document.visibilityState == 'visible') callback();
+ }).toJS,
+ );
+}
+
+void beforeLeave(void Function() callback) {
+ web.window.addEventListener('pagehide', ((web.Event _) => callback()).toJS);
+}
+
+void download(String name, Uint8List bytes, String mime) {
+ final blob = web.Blob([bytes.toJS].toJS, web.BlobPropertyBag(type: mime));
+ final url = web.URL.createObjectURL(blob);
+ final a = web.HTMLAnchorElement()
+ ..href = url
+ ..download = name
+ ..style.display = 'none';
+ web.document.body?.append(a);
+ a.click();
+ a.remove();
+ Future<void>.delayed(const Duration(seconds: 30), () => web.URL.revokeObjectURL(url));
+}
diff --git a/lib/widgets/server_card.dart b/lib/widgets/server_card.dart
new file mode 100644
index 0000000..3995b23
--- /dev/null
+++ b/lib/widgets/server_card.dart
@@ -0,0 +1,229 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../l10n/l10n.dart';
+import '../services/server/server_link.dart';
+import '../theme/app_colors.dart';
+import '../theme/app_theme.dart';
+import 'liquid_notch.dart';
+import 'ui_kit.dart';
+
+const _guideUrl = 'https://github.com/InlitX/GymMane/blob/main/SELFHOST.md';
+
+class ServerCard extends StatefulWidget {
+ const ServerCard({super.key});
+
+ @override
+ State<ServerCard> createState() => _ServerCardState();
+}
+
+class _ServerCardState extends State<ServerCard> {
+ Map<String, dynamic>? _info;
+ bool _busy = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _load();
+ }
+
+ Future<void> _load() async {
+ final info = await ServerLink.instance.info();
+ if (mounted) setState(() => _info = info);
+ }
+
+ Map<String, dynamic> get _sync => (_info?['sync'] as Map?)?.cast<String, dynamic>() ?? const {};
+
+ bool get _enabled => _sync['enabled'] == true;
+
+ DateTime? get _lastImport => DateTime.tryParse(_sync['lastImport'] as String? ?? '')?.toLocal();
+
+ String get _folder => _sync['folder'] as String? ?? '';
+
+ int get _devices => (_sync['devices'] as List?)?.length ?? 0;
+
+ String get _error => _sync['error'] as String? ?? '';
+
+ Widget _folderBox(GymColors gc) => Container(
+ padding: const EdgeInsetsDirectional.fromSTEB(14, 12, 14, 12),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(children: [
+ Icon(PhosphorIconsRegular.folderSimple, size: 16, color: gc.textSecondary),
+ const SizedBox(width: 8),
+ Text(t.webPhoneFolder, style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.textSecondary)),
+ ]),
+ const SizedBox(height: 6),
+ Ltr(
+ child: SelectableText(_folder,
+ style: AppTheme.f(13.5, weight: FontWeight.w700, color: gc.text, height: 1.35)),
+ ),
+ if (_error.isNotEmpty) ...[
+ const SizedBox(height: 6),
+ Text(t.webPhoneError(_error),
+ style: AppTheme.f(12, weight: FontWeight.w600, color: gc.danger, height: 1.35)),
+ ],
+ const SizedBox(height: 6),
+ Text(t.webPhoneFolderHow,
+ style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textTertiary, height: 1.45)),
+ ]),
+ );
+
+ Future<void> _scan() async {
+ if (_busy) return;
+ setState(() => _busy = true);
+ final r = await ServerLink.instance.scanPhone();
+ if (!mounted) return;
+ setState(() => _busy = false);
+ await _load();
+ if (!mounted) return;
+ final imported = r?['imported'] == true;
+ showNotchToast(context, imported ? t.webPhoneImported : t.webPhoneNothing,
+ icon: imported ? PhosphorIconsFill.checkCircle : PhosphorIconsFill.info,
+ accent: imported ? context.gc.sage : context.gc.textSecondary);
+ }
+
+ Future<void> _export() async {
+ if (_busy) return;
+ setState(() => _busy = true);
+ final r = await ServerLink.instance.exportForPhone();
+ if (!mounted) return;
+ setState(() => _busy = false);
+ if (r?['exported'] != true) return;
+ HapticFeedback.lightImpact();
+ showNotchToast(context, t.webPhoneExportDone, icon: PhosphorIconsFill.fileZip, accent: context.gc.sage);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final link = ServerLink.instance;
+ final last = _lastImport;
+ return ListenableBuilder(
+ listenable: link,
+ builder: (context, _) => Container(
+ padding: const EdgeInsets.fromLTRB(20, 20, 20, 16),
+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(24)),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ Row(children: [
+ Container(
+ width: 40,
+ height: 40,
+ decoration: BoxDecoration(color: gc.bgRaised2, shape: BoxShape.circle),
+ child: Icon(PhosphorIconsRegular.hardDrives, size: 18, color: gc.text),
+ ),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(t.webServerTitle,
+ style: AppTheme.f(18, weight: FontWeight.w800, color: gc.text, letterSpacing: -0.3)),
+ const SizedBox(height: 3),
+ Row(children: [
+ Container(
+ width: 7,
+ height: 7,
+ decoration: BoxDecoration(color: link.online ? gc.sage : gc.warn, shape: BoxShape.circle),
+ ),
+ const SizedBox(width: 7),
+ Flexible(
+ child: Text(link.online ? t.webServerSaved : t.webServerOffline,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.textSecondary)),
+ ),
+ ]),
+ ]),
+ ),
+ ]),
+ const SizedBox(height: 18),
+ if (!_enabled && _info != null) ...[
+ Text(t.webPhoneOff, style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text, height: 1.35)),
+ const SizedBox(height: 6),
+ Text(t.webPhoneOffHow,
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.45)),
+ ] else ...[
+ Text(last == null ? t.webPhoneNone : t.webPhoneLast('${t.shortDate(last)} · ${t.clockTime(last)}'),
+ style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),
+ const SizedBox(height: 3),
+ Text(t.webPhoneDevices(_devices),
+ style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.textSecondary)),
+ const SizedBox(height: 8),
+ Text(t.webPhoneHow, style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.45)),
+ if (_folder.isNotEmpty) ...[
+ const SizedBox(height: 14),
+ _folderBox(gc),
+ ],
+ const SizedBox(height: 16),
+ Row(children: [
+ Expanded(
+ child: _Action(
+ icon: PhosphorIconsBold.arrowsClockwise,
+ label: t.webPhoneScan,
+ busy: _busy,
+ onTap: _scan,
+ ),
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: _Action(
+ icon: PhosphorIconsBold.deviceMobile,
+ label: t.webPhoneExport,
+ busy: _busy,
+ onTap: _export,
+ ),
+ ),
+ ]),
+ ],
+ const SizedBox(height: 6),
+ Align(
+ alignment: AlignmentDirectional.centerStart,
+ child: TextButton(
+ onPressed: () => launchUrl(Uri.parse(_guideUrl), mode: LaunchMode.externalApplication),
+ child: Text(t.webPhoneGuide, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.accent)),
+ ),
+ ),
+ ]),
+ ),
+ );
+ }
+}
+
+class _Action extends StatelessWidget {
+ const _Action({required this.icon, required this.label, required this.busy, required this.onTap});
+
+ final IconData icon;
+ final String label;
+ final bool busy;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ return Pressable(
+ onTap: busy ? null : onTap,
+ scale: 0.97,
+ child: AnimatedOpacity(
+ duration: const Duration(milliseconds: 180),
+ opacity: busy ? 0.5 : 1,
+ child: Container(
+ constraints: const BoxConstraints(minHeight: 44),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(icon, size: 14, color: gc.text),
+ const SizedBox(width: 8),
+ Flexible(
+ child: Text(label,
+ maxLines: 2,
+ textAlign: TextAlign.center,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.text)),
+ ),
+ ]),
+ ),
+ ),
+ );
+ }
+}