Compare commits

..

No commits in common. "c12faa3920335a53e2dc67f5cdf557cbb3f44bab" and "10364dc1ffb8f427a23efd80898f901bef458d8a" have entirely different histories.

98 changed files with 1016 additions and 2823 deletions

View File

@ -113,40 +113,6 @@ silently does **not** reach the running service.
private `kuhyx/syncs` GitHub repo (see "Cross-device sync" above)
and `~/.config/diet_guard/sync_token`.
## The companion app's desktop target is a web build
`app/` builds for two platforms, and only two: **Android** (the phone) and
**web** (the Linux desktop). There is no `app/linux/` — Flutter's GTK embedder
manages only ~20fps at 3840x2160 (measured on a stock `flutter create` app, so
it is the toolkit, not this code), where the same Dart in Chrome sustains
~144fps; see `~/todo/docs/desktop-performance-findings.md`. On the desktop the
app is the web build served by `bin/diet_guard_desktop.dart` and shown in a
Chrome `--app` window.
Consequences worth knowing before touching `app/`:
- **`dart:io` does not fail a web *compile*** — it becomes a stub that throws
at runtime, so the symptom is a blank white window, not a build error. Every
platform-specific edge goes behind a conditional export
(`document_store*.dart`, `blob_store*.dart`, `background_tasks*.dart`,
`notification_backend*.dart`, `token_vault*.dart`,
`github_client_factory*.dart`, `attached_image*.dart`). Branch on `kIsWeb`
*before* any `Platform.is…`, which itself throws on web.
- **The port and the Chrome `--user-data-dir` are fixed on purpose**
(`lib/services/desktop_wrapper.dart`). IndexedDB is keyed by origin and
lives in that profile: changing either hides the entire local food log.
- **The wrapper holds the GitHub token**, not the browser, and proxies
`api.github.com` plus the CORS-less device flow (`lib/desktop/github_proxy.dart`).
- **The desktop pushes as device id `desktop`**, the phone as `phone`, the
Python side as `pc`. Sharing an id means two devices overwrite each other's
pushed log every tick.
- **Desktop reminders only exist while the window is open.** A browser has no
WorkManager equivalent; the PC's real backstop is `diet-guard-gate.timer`,
which locks the screen. Don't "fix" this with a background service without
deciding you want a new daemon.
- `flutter create --platforms linux` would silently restore the slow path.
Don't run it in `app/`.
## Commands
- Run tests: `python -m pytest diet_guard/tests/ --cov=diet_guard --cov-branch --cov-fail-under=100`
@ -154,11 +120,6 @@ Consequences worth knowing before touching `app/`:
- Test the lock manually (safe, closeable): `python -m diet_guard gate --demo`
- Run one sync tick manually: `python -m diet_guard sync`
- Install for production: `bash install.sh`
- App tests: `cd app && flutter test`
- Run the desktop app from the repo: `cd app && bash run.sh`
- Install the desktop app (Arch package + .desktop entry):
`cd app && bash install_arch.sh`
- Build the phone app: `cd app && flutter build apk --release`
## Do NOT
@ -170,9 +131,6 @@ Consequences worth knowing before touching `app/`:
- Don't reintroduce a seal/lock/`chattr +i` on the budget file as a "fix" —
it was deliberately removed so the budget is freely editable and synced
between devices; see "Operational gotchas" above.
- Don't re-add a Linux embedder target to `app/`, and don't change the
wrapper's fixed port or Chrome profile path — see "The companion app's
desktop target is a web build" above.
## Flutter/Dart AI rules

View File

@ -4,7 +4,7 @@
# This file should be version controlled and should not be manually edited.
version:
revision: "ee80f08bbf97172ec030b8751ceab557177a34a6"
revision: "c9a6c484230f8b5e408ec57be1ef71dee1e77020"
channel: "stable"
project_type: app
@ -13,11 +13,11 @@ project_type: app
migration:
platforms:
- platform: root
create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
- platform: web
create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
create_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
base_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
- platform: linux
create_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
base_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
# User provided section

View File

@ -1,133 +0,0 @@
// coverage:ignore-file
// Entry point for the desktop wrapper: resolves real paths, starts the
// server, and launches the browser. The serving logic it delegates to is
// covered by test/desktop/wrapper_server_test.dart.
import 'dart:io';
import 'package:diet_guard_app/desktop/github_proxy.dart';
import 'package:diet_guard_app/desktop/wrapper_server.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:path/path.dart' as p;
Future<void> main(List<String> args) async {
final home = Platform.environment['HOME'];
if (home == null) {
stderr.writeln('HOME is not set; cannot resolve the data directory.');
exit(1);
}
// `dart build cli` emits bundle/bin/<exe> alongside bundle/lib/, so the
// installed layout is /opt/diet-guard/bin/diet_guard_desktop with the web
// assets one level up at /opt/diet-guard/web. --web-root overrides for
// development runs straight out of the repo.
final webRoot =
_argValue(args, '--web-root') ??
p.normalize(p.join(p.dirname(Platform.resolvedExecutable), '..', 'web'));
if (!Directory(webRoot).existsSync()) {
stderr.writeln('web assets not found at $webRoot');
exit(1);
}
// Overridable so a verification run cannot touch the real data or the real
// sync token.
final dataDir =
_argValue(args, '--data-dir') ??
p.join(home, '.local', 'share', 'diet-guard-desktop');
final proxy = GitHubProxy(
tokenPath:
_argValue(args, '--token-path') ??
p.join(home, '.config', 'diet_guard_app', 'sync_token'),
// The PC's Python gate already keeps a token for `diet-guard-sync.timer`;
// reusing it means the desktop app needs no second setup on this machine.
// Read-only: a token obtained here is written to our own path.
fallbackTokenPath:
_argValue(args, '--fallback-token-path') ??
p.join(home, '.config', 'diet_guard', 'sync_token'),
);
final server = WrapperServer(
webRoot: webRoot,
dataDir: dataDir,
gitHubProxy: proxy,
);
final port =
int.tryParse(_argValue(args, '--port') ?? '') ?? desktopWrapperPort;
await server.start(port);
stdout.writeln('diet_guard desktop serving on http://localhost:$port');
// A bare flag, not a valued option: requiring a dummy value meant passing a
// stray positional, which the AOT runtime tries to interpret as a snapshot.
if (!args.contains('--no-browser')) {
final ranLongEnough = await _launchBrowser(home, port);
if (!ranLongEnough) {
// Chrome exits immediately when it hands the URL to an instance that
// already owns the profile directory (or when a stale SingletonLock is
// left behind). Shutting down here would pull the server out from under
// a window that is still open, so keep serving instead.
stdout.writeln(
'Browser returned immediately (handed off to an existing window). '
'Still serving on http://localhost:$port -- Ctrl-C to stop.',
);
return;
}
// Otherwise the browser owned the session: its window closed, so we exit.
await server.stop();
}
}
/// Launches the app in a Chrome-family browser with a **stable** profile
/// directory, since the food log, photos and settings live in that profile.
/// Returns true when the browser ran long enough to have owned the session.
Future<bool> _launchBrowser(String home, int port) async {
// Ordered by preference, and deliberately broad: this machine runs Thorium
// behind /opt/google/chrome, and has a policy that uninstalls the `chromium`
// package, so assuming any single browser is wrong. DIET_GUARD_BROWSER
// overrides.
final candidates = [
Platform.environment['DIET_GUARD_BROWSER'] ?? '',
'/opt/google/chrome/chrome',
'/opt/thorium-browser/thorium-browser',
'/usr/bin/google-chrome-stable',
'/usr/bin/chromium',
'/usr/bin/brave',
];
final browser = candidates.firstWhere(
(path) => path.isNotEmpty && File(path).existsSync(),
orElse: () => '',
);
if (browser.isEmpty) {
stderr.writeln(
'No Chrome-family browser found; open http://localhost:$port manually.',
);
return false;
}
// The profile directory must stay as stable as the port: IndexedDB is keyed
// by origin and lives inside this profile, so a changing path silently
// hides the entire food log.
final profile = p.join(
home,
'.local',
'share',
'diet-guard-desktop',
'profile',
);
final process = await Process.start(browser, [
'--app=http://localhost:$port',
'--user-data-dir=$profile',
// Sets WM_CLASS, which the .desktop entry matches on via StartupWMClass.
// Without it the window inherits the browser's class and the taskbar shows
// a browser icon instead of diet_guard's.
'--class=diet_guard_app',
'--no-first-run',
]);
final started = DateTime.now();
await process.exitCode;
return DateTime.now().difference(started) > const Duration(seconds: 5);
}
String? _argValue(List<String> args, String name) {
final index = args.indexOf(name);
if (index == -1 || index + 1 >= args.length) return null;
return args[index + 1];
}

View File

@ -1,86 +0,0 @@
#!/bin/bash
# Builds the diet_guard companion app's desktop target and installs it as an
# Arch Linux package via pacman.
# Run from anywhere -- uses the directory of this script as the repo root.
# Requires: flutter, base-devel (provides makepkg), sudo for pacman.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# The desktop app is a Flutter *web* build served by a small local wrapper:
# Flutter's Linux embedder only reaches ~20fps at 4K, while the same Dart code
# in Chrome sustains ~144fps.
WEB_DIR="$SCRIPT_DIR/build/web"
WRAPPER_BUNDLE="$SCRIPT_DIR/build/cli/bundle"
WORK_DIR="$(mktemp -d)"
cleanup() { rm -rf "$WORK_DIR"; }
trap cleanup EXIT
# Parse version from pubspec.yaml (strip build number: 1.0.0+1 -> 1.0.0)
PKGVER="$(grep '^version:' "$SCRIPT_DIR/pubspec.yaml" \
| sed 's/^version:[[:space:]]*//' | sed 's/+.*//')"
echo "==> Building diet_guard_app $PKGVER (Flutter web release)..."
cd "$SCRIPT_DIR"
flutter build web --release
echo "==> Compiling the desktop wrapper..."
# `dart build cli`, not `dart compile exe`: the package pulls in dependencies
# with native build hooks, which `dart compile` refuses to handle even though
# the wrapper itself uses none of them.
rm -rf "$SCRIPT_DIR/build/cli"
dart build cli -o "$SCRIPT_DIR/build/cli"
echo "==> Generating PKGBUILD..."
cat > "$WORK_DIR/PKGBUILD" <<EOF
pkgname=diet-guard-app
pkgver=$PKGVER
pkgrel=1
pkgdesc='Diet logging and budget companion for diet_guard'
arch=('x86_64')
url='https://github.com/kuhyx/diet-guard'
license=('custom')
# No hard browser dependency: naming one means makepkg installs it, and this
# system has a policy that immediately removes 'chromium' again, which then
# fails dependency resolution. The wrapper discovers whatever is present.
depends=()
optdepends=('google-chrome: renders the app window'
'chromium: renders the app window')
# !strip is load-bearing: the wrapper is a Dart AOT executable with its
# snapshot embedded in the ELF, and stripping discards it. The stripped binary
# still runs, but is just the bare Dart VM printing a usage message.
options=('!strip' '!debug')
package() {
# Preserve the bundle's bin/ + lib/ layout: the executable loads its native
# libraries from ../lib and resolves the web assets from ../web.
install -dm755 "\$pkgdir/opt/diet-guard-app"
cp -r "$WRAPPER_BUNDLE/bin" "\$pkgdir/opt/diet-guard-app/bin"
# lib/ only exists when a dependency ships native code; copying it
# unconditionally would fail on a bundle that has none.
if [[ -d "$WRAPPER_BUNDLE/lib" ]]; then
cp -r "$WRAPPER_BUNDLE/lib" "\$pkgdir/opt/diet-guard-app/lib"
fi
chmod 755 "\$pkgdir/opt/diet-guard-app/bin/diet_guard_desktop"
install -dm755 "\$pkgdir/opt/diet-guard-app/web"
cp -r "$WEB_DIR/." "\$pkgdir/opt/diet-guard-app/web/"
install -dm755 "\$pkgdir/usr/bin"
cat > "\$pkgdir/usr/bin/diet-guard-app" <<'WRAPPER'
#!/bin/bash
exec /opt/diet-guard-app/bin/diet_guard_desktop "\$@"
WRAPPER
chmod 755 "\$pkgdir/usr/bin/diet-guard-app"
}
EOF
echo "==> Installing package via makepkg..."
cd "$WORK_DIR"
makepkg -sif --noconfirm
echo "==> Installing the desktop entry..."
"$SCRIPT_DIR/desktop/install_desktop_entry.sh"
echo "==> Done. 'diet-guard-app' now runs version $PKGVER installed via pacman."

View File

@ -1,194 +0,0 @@
/// The desktop wrapper's GitHub half: token storage, device flow, API proxy.
///
/// The desktop app runs in a browser, and a browser cannot do either half of
/// GitHub sync safely on its own:
///
/// * GitHub's **device-flow** endpoints (`github.com/login/device/code` and
/// the token poll) send no CORS headers, so a page cannot call them at all.
/// * A token held by the page would live in `localStorage` inside the Chrome
/// profile -- `flutter_secure_storage` on web is WebCrypto-wrapped
/// `localStorage` with the wrap key sitting beside the ciphertext, which is
/// obfuscation rather than encryption at rest.
///
/// This wrapper is a local process with neither limitation, so it owns the
/// token file and performs every authenticated call itself. The page never
/// sees the token: it asks for *status*, and its API requests are proxied
/// with the `Authorization` header attached here.
library;
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
/// GitHub's REST API base, which [GitHubProxy] fronts.
const githubApiBase = 'https://api.github.com';
/// GitHub's device-flow base (a different host, and CORS-less on purpose).
const githubDeviceBase = 'https://github.com';
/// Serves `/github/*` for the wrapper.
class GitHubProxy {
/// Creates a proxy storing its token at [tokenPath], optionally seeding
/// from [fallbackTokenPath] (the PC's own `diet_guard` sync token) when it
/// has none of its own.
GitHubProxy({
required this.tokenPath,
this.fallbackTokenPath,
http.Client? httpClient,
}) : _http = httpClient ?? http.Client();
/// File this wrapper writes tokens to (mode 600).
final String tokenPath;
/// Optional pre-existing token to fall back to, so a PC that already
/// configured `python -m diet_guard sync` needs no second setup.
final String? fallbackTokenPath;
final http.Client _http;
/// Reads the stored token, or the empty string when there is none.
Future<String> readToken() async {
for (final path in [tokenPath, ?fallbackTokenPath]) {
final file = File(path);
if (!file.existsSync()) continue;
try {
final token = (await file.readAsString()).trim();
if (token.isNotEmpty) return token;
} on FileSystemException {
continue;
}
}
return '';
}
/// Writes [token] (mode 600), or deletes the file when it is empty.
Future<void> writeToken(String token) async {
final file = File(tokenPath);
if (token.isEmpty) {
if (file.existsSync()) await file.delete();
return;
}
await file.parent.create(recursive: true);
await file.writeAsString(token);
// The token is a repo-scoped credential; keep it off other users' eyes
// the same way the Python side's sync_token is stored.
await Process.run('chmod', ['600', tokenPath]);
}
/// Handles a `/github/...` [request], with [rest] the path after `/github/`.
///
/// Returns false when [rest] matches nothing, so the caller can 404.
Future<bool> handle(HttpRequest request, String rest) async {
switch (rest) {
case 'auth/status':
final token = await readToken();
_json(request, {'configured': token.isNotEmpty});
return true;
case 'auth/token':
await writeToken((await utf8.decoder.bind(request).join()).trim());
request.response.statusCode = HttpStatus.noContent;
return true;
case 'auth/device/start':
await _deviceStart(request);
return true;
case 'auth/device/poll':
await _devicePoll(request);
return true;
}
if (rest.startsWith('api/')) {
await _proxyApi(request, rest.substring('api/'.length));
return true;
}
return false;
}
Future<void> _deviceStart(HttpRequest request) async {
final body = await _jsonBody(request);
final response = await _http.post(
Uri.parse('$githubDeviceBase/login/device/code'),
headers: const {'Accept': 'application/json'},
body: {'client_id': '${body['client_id']}', 'scope': 'repo'},
);
_passThrough(request, response);
}
Future<void> _devicePoll(HttpRequest request) async {
final body = await _jsonBody(request);
final response = await _http.post(
Uri.parse('$githubDeviceBase/login/oauth/access_token'),
headers: const {'Accept': 'application/json'},
body: {
'client_id': '${body['client_id']}',
'device_code': '${body['device_code']}',
'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',
},
);
Map<String, dynamic> decoded;
try {
decoded = jsonDecode(response.body) as Map<String, dynamic>;
} on FormatException {
_passThrough(request, response);
return;
}
final token = decoded['access_token'];
if (token is String && token.isNotEmpty) {
await writeToken(token);
// Deliberately does not echo the token back: the whole point of the
// proxy is that the browser never holds it.
_json(request, {'status': 'ok'});
return;
}
// Still pending / denied / expired: the page drives the poll loop, so it
// needs GitHub's own `error` value verbatim.
_json(request, decoded..remove('access_token'));
}
Future<void> _proxyApi(HttpRequest request, String path) async {
final token = await readToken();
final uri = Uri.parse(
'$githubApiBase/$path',
).replace(query: request.uri.query.isEmpty ? null : request.uri.query);
final proxied = http.Request(request.method, uri)
..headers.addAll({
'Authorization': 'Bearer $token',
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
})
..bodyBytes = await _bodyBytes(request);
final response = await http.Response.fromStream(await _http.send(proxied));
_passThrough(request, response);
}
Future<Map<String, dynamic>> _jsonBody(HttpRequest request) async {
final raw = await utf8.decoder.bind(request).join();
if (raw.isEmpty) return {};
try {
final decoded = jsonDecode(raw);
return decoded is Map<String, dynamic> ? decoded : {};
} on FormatException {
return {};
}
}
Future<List<int>> _bodyBytes(HttpRequest request) async {
final chunks = await request.toList();
return [for (final chunk in chunks) ...chunk];
}
void _passThrough(HttpRequest request, http.Response response) {
request.response
..statusCode = response.statusCode
..headers.contentType = ContentType.json
..add(response.bodyBytes);
}
void _json(HttpRequest request, Map<String, dynamic> body) {
request.response
..headers.contentType = ContentType.json
..write(jsonEncode(body));
}
/// Releases the outbound HTTP client.
void close() => _http.close();
}

View File

@ -1,200 +0,0 @@
/// Local HTTP server backing the desktop app.
///
/// The desktop app is a Flutter **web** build (Flutter's Linux embedder
/// manages only ~20fps at 4K, where the same Dart code in Chrome sustains
/// ~144fps -- see `~/todo/docs/desktop-performance-findings.md`), so it runs
/// in a browser and cannot touch the filesystem. This process is the other
/// half of the desktop app:
///
/// * it serves the built web assets;
/// * it owns an on-disk copy of every document and photo the app stores, so a
/// wiped Chrome profile is not a total-loss event (photos in particular
/// never sync, so nothing else could restore them);
/// * it fronts GitHub, holding the sync token and running the CORS-less
/// device flow the page cannot (see `github_proxy.dart`).
///
/// Binds to loopback only. The endpoints overwrite files in the user's home
/// directory with no authentication, so exposing them on a routable address
/// would let anything on the network rewrite the food log.
library;
import 'dart:async';
import 'dart:io';
import 'package:diet_guard_app/desktop/github_proxy.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:path/path.dart' as p;
/// Serves the desktop app's web build plus its disk-backed endpoints.
class WrapperServer {
/// Creates a server serving [webRoot], mirroring the app's storage under
/// [dataDir], and proxying GitHub through [gitHubProxy].
WrapperServer({
required this.webRoot,
required this.dataDir,
required this.gitHubProxy,
});
/// Directory holding the built Flutter web assets.
final String webRoot;
/// Directory holding the on-disk copies of documents and photo blobs.
final String dataDir;
/// GitHub half of the wrapper.
final GitHubProxy gitHubProxy;
HttpServer? _server;
/// Port the server is listening on, once [start] has completed.
int get port => _server!.port;
/// Binds to loopback on [requestedPort] and begins serving.
///
/// Pass 0 to let the OS choose a port (tests do this); the desktop launcher
/// passes [desktopWrapperPort], because the browser keys IndexedDB by
/// origin -- a changing port would look like an app with no history.
Future<void> start(int requestedPort) async {
_server = await HttpServer.bind(
InternetAddress.loopbackIPv4,
requestedPort,
);
unawaited(_serve(_server!));
}
/// Stops serving and releases the port.
Future<void> stop() async {
await _server?.close(force: true);
gitHubProxy.close();
}
Future<void> _serve(HttpServer server) async {
await for (final request in server) {
try {
await _handle(request);
} on Exception {
request.response.statusCode = HttpStatus.internalServerError;
}
await request.response.close();
}
}
Future<void> _handle(HttpRequest request) async {
final path = request.uri.path;
if (path.startsWith(WrapperPaths.github)) {
final rest = path.substring(WrapperPaths.github.length);
if (await gitHubProxy.handle(request, rest)) return;
request.response.statusCode = HttpStatus.notFound;
return;
}
if (path.startsWith(WrapperPaths.documents)) {
return _storedFile(
request,
'documents',
path.substring(WrapperPaths.documents.length),
);
}
if (path.startsWith(WrapperPaths.blobs)) {
return _storedFile(
request,
'blobs',
path.substring(WrapperPaths.blobs.length),
);
}
return _static(request, path);
}
/// GET returns the stored bytes (404 when absent); POST overwrites them.
///
/// [name] is rejected unless it is a plain filename: these handlers write
/// into the user's home directory, so a `..` segment would turn a mirror
/// write into an arbitrary-file overwrite.
Future<void> _storedFile(
HttpRequest request,
String subdirectory,
String name,
) async {
if (name.isEmpty || name.contains('/') || name.contains('..')) {
request.response.statusCode = HttpStatus.badRequest;
return;
}
final file = File(p.join(dataDir, subdirectory, name));
if (request.method == 'POST') {
await file.parent.create(recursive: true);
final bytes = [for (final chunk in await request.toList()) ...chunk];
await file.writeAsBytes(bytes);
request.response.statusCode = HttpStatus.noContent;
return;
}
if (request.method != 'GET') {
request.response.statusCode = HttpStatus.methodNotAllowed;
return;
}
if (!file.existsSync()) {
request.response.statusCode = HttpStatus.notFound;
return;
}
request.response.headers.contentType = subdirectory == 'documents'
? ContentType.json
: ContentType.binary;
await request.response.addStream(file.openRead());
}
Future<void> _static(HttpRequest request, String path) async {
final relative = path == '/' ? 'index.html' : path.substring(1);
// Reject traversal before touching the filesystem: the served root sits
// next to the user's files, so `../` must not escape it.
final resolved = p.normalize(p.join(webRoot, relative));
// coverage:ignore-start
// Defence in depth, and currently unreachable: Dart's HttpServer decodes
// and normalises the path before a handler runs, so even `%2e%2e` arrives
// already collapsed. Kept so the guarantee does not depend on that
// implementation detail holding.
if (!p.isWithin(webRoot, resolved) && resolved != p.normalize(webRoot)) {
request.response.statusCode = HttpStatus.forbidden;
return;
}
// coverage:ignore-end
final file = File(resolved);
if (!file.existsSync()) {
request.response.statusCode = HttpStatus.notFound;
return;
}
request.response.headers.contentType = contentTypeFor(resolved);
await request.response.addStream(file.openRead());
}
/// Content type for [filePath].
///
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
/// served as anything but `application/wasm`, and the app then renders
/// nothing at all.
static ContentType contentTypeFor(String filePath) {
switch (p.extension(filePath).toLowerCase()) {
case '.html':
return ContentType.html;
case '.js' || '.mjs':
return ContentType('text', 'javascript', charset: 'utf-8');
case '.json':
return ContentType.json;
case '.wasm':
return ContentType('application', 'wasm');
case '.css':
return ContentType('text', 'css', charset: 'utf-8');
case '.png':
return ContentType('image', 'png');
case '.jpg' || '.jpeg':
return ContentType('image', 'jpeg');
case '.svg':
return ContentType('image', 'svg+xml');
case '.ttf':
return ContentType('font', 'ttf');
case '.otf':
return ContentType('font', 'otf');
case '.woff2':
return ContentType('font', 'woff2');
default:
return ContentType.binary;
}
}
}

View File

@ -2,16 +2,16 @@
/// background due-slot check, then shows the primary meal-logging screen.
library;
import 'dart:async';
import 'dart:io';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/background_tasks.dart';
import 'package:diet_guard_app/services/background_check_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/frame_stats.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:flutter/material.dart';
import 'package:workmanager/workmanager.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
@ -19,23 +19,18 @@ Future<void> main() async {
await AppSettingsService.init();
await FoodBankService.init();
final notifications = await NotificationService.init();
// Deliberately *not* awaited before the first frame: the browser's
// `Notification.requestPermission()` does not complete until the user
// answers the prompt, so awaiting it here left the desktop app as a blank
// white window behind the permission bubble. Scheduling is likewise
// platform-specific (WorkManager on Android, an in-page timer in the
// browser -- see background_tasks.dart) and equally not worth a delayed
// first frame.
await notifications.requestPermission();
// WorkManager has no Linux/web/desktop implementation -- registering it
// there throws. Guard to the two platforms that ship it.
// coverage:ignore-start
unawaited(
notifications.requestPermission().then((_) {
return initBackgroundTasks();
}),
);
// coverage:ignore-end
// Off unless armed with --dart-define=DIET_GUARD_FRAME_STATS=1.
// coverage:ignore-start
if (frameStatsEnabled) startFrameStats();
if (Platform.isAndroid || Platform.isIOS) {
await Workmanager().initialize(backgroundCheckCallbackDispatcher);
await Workmanager().registerPeriodicTask(
backgroundCheckTaskName,
backgroundCheckTaskName,
frequency: const Duration(minutes: 15),
);
}
// coverage:ignore-end
runApp(const DietGuardApp());
}

View File

@ -2,6 +2,7 @@
library;
import 'dart:async';
import 'dart:io';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
@ -9,7 +10,6 @@ import 'package:diet_guard_app/screens/photo_viewer_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/day_status_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/widgets/attached_image.dart';
import 'package:flutter/material.dart';
// ---------------------------------------------------------------------------
@ -636,11 +636,16 @@ class _Thumbnail extends StatelessWidget {
),
child: ClipRRect(
borderRadius: BorderRadius.circular(6),
child: AttachedImage(
path: path,
child: Image.file(
File(path),
width: 40,
height: 40,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) => const SizedBox(
width: 40,
height: 40,
child: Icon(Icons.broken_image),
),
),
),
);

View File

@ -3,6 +3,7 @@
library;
import 'dart:async';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_entry.dart';
@ -15,9 +16,8 @@ import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/screens/meal_builder_screen.dart';
import 'package:diet_guard_app/screens/settings_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/background_tasks.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
@ -28,6 +28,7 @@ import 'package:diet_guard_app/widgets/slot_selector_row.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart';
import 'package:workmanager/workmanager.dart';
/// Lets the user log one food item, with food-bank autocomplete and
/// today's slot status, or hop into [MealBuilderScreen] for a composite
@ -121,8 +122,10 @@ class _LogMealScreenState extends State<LogMealScreen>
try {
final settings = await SyncSettings.load();
if (!settings.isConfigured) return;
final client = createGitHubClient(
settings,
final client = GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: widget.httpClient,
);
try {
@ -140,12 +143,24 @@ class _LogMealScreenState extends State<LogMealScreen>
}
}
/// Queues the platform's offline push backstop so a meal logged while
/// offline still uploads on reconnect. The in-process [_autoSync] covers
/// the online case; this is the backstop (a no-op on web, which has no
/// out-of-page scheduler -- see background_tasks.dart).
/// Queues a connectivity-gated WorkManager push so a meal logged while
/// offline still uploads on reconnect, without the app being reopened. The
/// in-process [_autoSync] covers the online case; this is the backstop.
/// [ExistingWorkPolicy.replace] coalesces a burst of logs into one pending
/// job, and backoff retries a push that fails once connectivity returns.
/// No-op off mobile (WorkManager ships only on Android/iOS).
// coverage:ignore-start
Future<void> _enqueueSyncBackstop() => enqueueSyncBackstop();
Future<void> _enqueueSyncBackstop() async {
if (!Platform.isAndroid && !Platform.isIOS) return;
await Workmanager().registerOneOffTask(
syncPushTaskName,
syncPushTaskName,
constraints: Constraints(networkType: NetworkType.connected),
existingWorkPolicy: ExistingWorkPolicy.replace,
backoffPolicy: BackoffPolicy.linear,
backoffPolicyDelay: const Duration(minutes: 1),
);
}
// coverage:ignore-end

View File

@ -1,7 +1,8 @@
/// Full-screen, pinch-to-zoom view of a locally attached meal photo.
library;
import 'package:diet_guard_app/widgets/attached_image.dart';
import 'dart:io';
import 'package:flutter/material.dart';
/// Shows the image at [path] full-screen, with pinch-to-zoom and a back
@ -10,8 +11,7 @@ class PhotoViewerScreen extends StatelessWidget {
/// Creates a [PhotoViewerScreen] for the photo at [path].
const PhotoViewerScreen({required this.path, super.key});
/// Blob key of the image to display (a file path on Android, an IndexedDB
/// key in the desktop web build).
/// Local filesystem path to the image to display.
final String path;
@override
@ -24,10 +24,13 @@ class PhotoViewerScreen extends StatelessWidget {
),
body: Center(
child: InteractiveViewer(
child: AttachedImage(
path: path,
errorIconSize: 64,
errorIconColor: Colors.white,
child: Image.file(
File(path),
errorBuilder: (context, error, stackTrace) => const Icon(
Icons.broken_image,
color: Colors.white,
size: 64,
),
),
),
),

View File

@ -8,13 +8,12 @@ library;
import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart' as crdt_sync;
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/github_device_auth.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
@ -76,13 +75,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_rewardUrlController.text = AppSettingsService.rewardUrl ?? '';
_ownerController.text = settings.owner;
_repoController.text = settings.repo;
// On web the stored "token" is only a stand-in for one the desktop
// wrapper holds (see TokenVault); showing it would invite the user to
// edit a literal. [_storedToken] keeps it for round-tripping.
_storedToken = settings.token;
_tokenController.text = SyncSettings.exposesTokenValue
? settings.token
: '';
_tokenController.text = settings.token;
_clientIdController.text = settings.clientId;
setState(() => _loading = false);
}
@ -99,24 +92,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
super.dispose();
}
/// The token as loaded, so a platform that cannot display it (web) still
/// round-trips it instead of blanking it on the next save.
String _storedToken = '';
SyncSettings _currentSettings() {
final typed = _tokenController.text.trim();
return SyncSettings(
owner: _ownerController.text.trim(),
repo: _repoController.text.trim(),
// The `_storedToken` side is web-only (the wrapper holds the real
// token), so it is unreachable from a VM test.
token: typed.isEmpty && !SyncSettings.exposesTokenValue
// coverage:ignore-line
? _storedToken
: typed,
clientId: _clientIdController.text.trim(),
);
}
SyncSettings _currentSettings() => SyncSettings(
owner: _ownerController.text.trim(),
repo: _repoController.text.trim(),
token: _tokenController.text.trim(),
clientId: _clientIdController.text.trim(),
);
/// Persists the temptation-bundling reward fields, blank -> null.
Future<void> _saveReward() async {
@ -147,7 +128,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
setState(() => _clientIdController.text = clientId);
await _currentSettings().save();
}
final auth = createDeviceAuth(clientId, httpClient: widget.httpClient);
final auth = GitHubDeviceAuth(
clientId: clientId,
httpClient: widget.httpClient,
);
try {
final device = await auth.requestDeviceCode();
if (!mounted) return;
@ -157,10 +141,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
builder: (_) => _DeviceCodeDialog(device: device, auth: auth),
);
if (token != null && token.isNotEmpty) {
setState(() {
_storedToken = token;
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
});
setState(() => _tokenController.text = token);
_showMessage('Connected — syncing…');
await _currentSettings().save();
await _syncAfterConnect();
@ -176,7 +157,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
/// to work immediately, with clear confirmation either way.
Future<void> _syncAfterConnect() async {
final settings = _currentSettings();
final client = createGitHubClient(settings, httpClient: widget.httpClient);
final client = crdt_sync.GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: widget.httpClient,
);
try {
await runSync(client);
_showMessage('Connected and synced.');
@ -198,7 +184,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
Future<void> _testConnection() async {
setState(() => _busy = true);
final settings = _currentSettings();
final client = createGitHubClient(settings, httpClient: widget.httpClient);
final client = crdt_sync.GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: widget.httpClient,
);
try {
final ok = await client.canAccessRepo();
_showMessage(ok ? 'Connection OK.' : 'Connection failed.');
@ -214,7 +205,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
setState(() => _busy = true);
final settings = _currentSettings();
await settings.save();
final client = createGitHubClient(settings, httpClient: widget.httpClient);
final client = crdt_sync.GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: widget.httpClient,
);
try {
await runSync(client);
_showMessage('Synced.');
@ -245,13 +241,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
}
}
/// True on the one platform with OEM battery optimization to exempt from.
///
/// Uses [defaultTargetPlatform] rather than `Platform.isAndroid` because
/// `dart:io` is a throwing stub in the desktop web build.
bool get _isAndroid =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.android;
@override
Widget build(BuildContext context) {
if (_loading) {
@ -346,19 +335,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
TextField(
controller: _tokenController,
obscureText: true,
decoration: InputDecoration(
decoration: const InputDecoration(
labelText: 'Personal access token (fallback)',
// Both wrapper hints are web-only; a VM test always takes
// the null branch.
// coverage:ignore-start
helperText: SyncSettings.exposesTokenValue
? null
: _storedToken.isEmpty
? 'Stored by the desktop wrapper, never by the browser'
: 'A token is stored by the desktop wrapper; type here '
'only to replace it',
// coverage:ignore-end
helperMaxLines: 2,
),
),
],
@ -387,29 +365,18 @@ class _SettingsScreenState extends State<SettingsScreen> {
Text('Notifications', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 4),
Text(
_isAndroid
? 'A background check nags you every ~15 min if a meal slot '
'is overdue. Aggressive OEM battery optimization (MIUI, '
'some Samsung configs) can delay this well past 15 min '
'-- request an exemption for reliable nagging.'
: 'A check runs every 5 min while this window is open and '
'notifies you about an overdue meal slot. A browser '
'cannot run anything once the window is closed -- on '
'the PC the real backstop is the diet_guard gate, '
'which locks the screen instead.',
'A background check nags you every ~15 min if a meal slot is '
'overdue. Aggressive OEM battery optimization (MIUI, some '
'Samsung configs) can delay this well past 15 min -- request an '
'exemption for reliable nagging.',
style: Theme.of(context).textTheme.bodySmall,
),
// Battery-optimization exemption is an Android-only concept, and
// `permission_handler` has no web implementation at all; the row
// would throw rather than degrade if it were shown in the browser.
if (_isAndroid) ...[
const SizedBox(height: 12),
OutlinedButton.icon(
onPressed: _requestBatteryExemption,
icon: const Icon(Icons.battery_alert),
label: const Text('Disable battery optimization'),
),
],
const SizedBox(height: 12),
OutlinedButton.icon(
onPressed: _requestBatteryExemption,
icon: const Icon(Icons.battery_alert),
label: const Text('Disable battery optimization'),
),
if (_status != null) ...[
const SizedBox(height: 16),
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),

View File

@ -2,10 +2,11 @@
library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
/// Singleton storing lightweight settings such as the daily kcal goal.
///
@ -17,18 +18,14 @@ import 'package:flutter/foundation.dart';
/// nothing of its own to contribute yet, rather than silently syncing the
/// unset default.
class AppSettingsService {
AppSettingsService._(this._store);
/// Document name this service owns, unchanged from the pre-web on-disk
/// filename so an installed phone keeps reading its existing settings.
static const documentName = 'app_settings.json';
AppSettingsService._(this._file);
static AppSettingsService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static AppSettingsService get instance => _instance!;
final DocumentStore _store;
final File _file;
int _dailyKcalGoal = 2200;
DateTime? _dailyKcalGoalUpdatedAt;
String? _rewardLabel;
@ -52,15 +49,13 @@ class AppSettingsService {
/// Returns the configured temptation-bundling reward URL, or null.
static String? get rewardUrl => _instance?._rewardUrl;
/// Initialises the singleton against the platform document store (files on
/// Android, IndexedDB in the browser-hosted desktop app).
/// Initialises the singleton, pointing at the app's documents directory.
static Future<AppSettingsService> init() async {
if (_instance != null) return _instance!;
// Resolving the platform store is a plugin call (path_provider /
// IndexedDB), not reachable from `flutter test`.
// coverage:ignore-start
final svc = AppSettingsService._(await openDocumentStore());
// coverage:ignore-end
final dir = await getApplicationDocumentsDirectory();
final svc = AppSettingsService._(
File(p.join(dir.path, 'app_settings.json')),
);
await svc._load();
_instance = svc;
return svc;
@ -68,29 +63,35 @@ class AppSettingsService {
/// Resets the singleton so [init] can be called again in tests.
///
/// When [store] is given, reads/writes go there instead of the real
/// platform store.
/// When [testDir] is given, reads/writes go there instead of the real
/// documents directory.
@visibleForTesting
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : AppSettingsService._(store);
static void resetForTesting({Directory? testDir}) {
_instance = testDir == null
? null
: AppSettingsService._(
File(p.join(testDir.path, 'app_settings.json')),
);
}
/// Initialises from [store], calling [_load], for use in unit tests.
/// Initialises from [testDir], calling [_load], for use in unit tests.
///
/// Bypasses [openDocumentStore] so tests need no platform channels.
/// Bypasses [getApplicationDocumentsDirectory] so tests don't need platform
/// channels.
@visibleForTesting
static Future<AppSettingsService> initForTesting(DocumentStore store) async {
final svc = AppSettingsService._(store);
static Future<AppSettingsService> initForTesting(Directory testDir) async {
final svc = AppSettingsService._(
File(p.join(testDir.path, 'app_settings.json')),
);
await svc._load();
_instance = svc;
return svc;
}
Future<void> _load() async {
final raw = await _store.read(documentName);
if (raw == null) return;
if (!_file.existsSync()) return;
try {
final data = jsonDecode(raw);
final data = jsonDecode(await _file.readAsString());
if (data is Map && data['daily_kcal_goal'] is int) {
_dailyKcalGoal = data['daily_kcal_goal'] as int;
}
@ -140,12 +141,12 @@ class AppSettingsService {
await _writeToDisk();
}
/// Writes the full current in-memory state to the store -- the single write
/// Writes the full current in-memory state to disk -- the single write
/// path every setter funnels through, so no two methods can race on
/// independently overwriting the same document.
/// independently overwriting the same JSON file.
Future<void> _writeToDisk() async {
await _store.write(
documentName,
await _file.parent.create(recursive: true);
await _file.writeAsString(
jsonEncode({
'daily_kcal_goal': _dailyKcalGoal,
'daily_kcal_goal_updated_at': _dailyKcalGoalUpdatedAt

View File

@ -1,22 +1,38 @@
/// WorkManager wiring for the periodic due-slot check (Android/iOS only).
///
/// Registered as a 15-minute periodic task (WorkManager's periodic floor)
/// rather than four fixed exact alarms -- more robust against OEM
/// background-kill behavior, at the cost of ±15 min precision (accepted; see
/// the project plan). Deliberately **not** requesting `SCHEDULE_EXACT_ALARM`
/// for this reason -- don't reach for it to "fix" perceived lateness.
///
/// The check itself lives in `due_slot_check.dart` so it stays free of the
/// `workmanager` import, which has no web implementation.
/// WorkManager-driven periodic check: re-runs the same due/missing-slot
/// logic diet_guard's `_gate.py` uses to decide whether to lock the PC, and
/// syncs notifications to match. Registered as a 15-minute periodic task
/// (WorkManager's periodic floor) rather than four fixed exact alarms --
/// more robust against OEM background-kill behavior, at the cost of ±15 min
/// precision (accepted; see the project plan). Deliberately **not**
/// requesting `SCHEDULE_EXACT_ALARM` for this reason -- don't reach for it
/// to "fix" perceived lateness.
library;
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:workmanager/workmanager.dart';
/// Unique WorkManager task name for the periodic due-slot check.
const String backgroundCheckTaskName = 'diet_guard.background_check';
/// Reads the local log, computes today's due-but-unlogged slots as of
/// [now] (defaults to the real clock), and syncs notifications to match.
///
/// Extracted from [backgroundCheckCallbackDispatcher] so this logic is
/// unit-testable without the real WorkManager plugin, which only runs as a
/// true background isolate on-device. [now] is injectable for the same
/// reason `slot.dart`'s functions are clock-free: a test should not depend
/// on the wall-clock hour it happens to run at.
Future<void> checkAndNotify({DateTime? now}) async {
await LogStorageService.init();
await NotificationService.init();
final logged = await LogStorageService.instance.loggedSlotsToday();
final due = missingSlots(now ?? DateTime.now(), logged);
await NotificationService.instance.syncToSlots(due);
}
/// WorkManager entry point invoked by the OS on each periodic tick.
///
/// Deliberately thin: all logic lives in [checkAndNotify] so it stays unit

View File

@ -5,9 +5,9 @@
/// reconnect and uploads the log without the app being reopened.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
@ -41,7 +41,12 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
return false; // couldn't read config in-isolate; let WorkManager retry
}
if (!settings.isConfigured) return true; // nothing to push; don't retry
final client = createGitHubClient(settings, httpClient: httpClient);
final client = GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: httpClient,
);
try {
await runSync(client);
return true;

View File

@ -1,10 +0,0 @@
/// Platform entry point for scheduling the app's recurring work.
///
/// Conditional export because `workmanager` has no browser implementation at
/// all -- a closed tab runs nothing. Android schedules real OS-managed
/// background work; the browser-hosted desktop app runs an in-page timer that
/// lives only as long as its window (see `background_tasks_web.dart`).
library;
export 'background_tasks_io.dart'
if (dart.library.js_interop) 'background_tasks_web.dart';

View File

@ -1,46 +0,0 @@
/// WorkManager-backed scheduling, used on Android (and iOS).
library;
import 'dart:io';
import 'package:diet_guard_app/services/background_check_service.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:workmanager/workmanager.dart';
/// True on the two platforms that ship a WorkManager implementation.
///
/// Every entry point below is a no-op elsewhere: registering WorkManager on a
/// platform without it throws, which at app start would mean a blank window.
bool get _hasWorkManager => Platform.isAndroid || Platform.isIOS;
/// Registers the 15-minute periodic due-slot check with the OS.
// coverage:ignore-start
Future<void> initBackgroundTasks() async {
if (!_hasWorkManager) return;
await Workmanager().initialize(backgroundCheckCallbackDispatcher);
await Workmanager().registerPeriodicTask(
backgroundCheckTaskName,
backgroundCheckTaskName,
frequency: const Duration(minutes: 15),
);
}
/// Queues a connectivity-gated push so a meal logged while offline still
/// uploads on reconnect, without the app being reopened.
///
/// The in-process auto-sync covers the online case; this is the backstop.
/// [ExistingWorkPolicy.replace] coalesces a burst of logs into one pending
/// job, and backoff retries a push that fails once connectivity returns.
Future<void> enqueueSyncBackstop() async {
if (!_hasWorkManager) return;
await Workmanager().registerOneOffTask(
syncPushTaskName,
syncPushTaskName,
constraints: Constraints(networkType: NetworkType.connected),
existingWorkPolicy: ExistingWorkPolicy.replace,
backoffPolicy: BackoffPolicy.linear,
backoffPolicyDelay: const Duration(minutes: 1),
);
}
// coverage:ignore-end

View File

@ -1,54 +0,0 @@
/// In-page scheduling for the browser-hosted desktop app.
///
/// A browser has no equivalent of WorkManager: a closed tab runs nothing, so
/// the due-slot check can only run while the desktop window is open. That is
/// an accepted, deliberate reduction rather than an oversight -- on the PC the
/// real backstop is `diet-guard-gate.timer`, which *locks the screen* on an
/// unlogged slot and is strictly stronger than any notification this app could
/// raise.
library;
import 'dart:async';
import 'package:diet_guard_app/services/due_slot_check.dart';
/// How often the in-page check re-evaluates due slots.
///
/// Five minutes rather than WorkManager's 15: a foreground timer is cheap,
/// and the window is usually open for a short session, so a long period would
/// often mean the check never runs at all.
const inPageCheckInterval = Duration(minutes: 5);
Timer? _timer;
/// Starts the in-page periodic due-slot check (idempotent).
///
/// Runs one check immediately so opening the window is itself a check, then
/// repeats every [inPageCheckInterval] for as long as the page lives.
Future<void> initBackgroundTasks() async {
if (_timer != null) return;
_timer = Timer.periodic(inPageCheckInterval, (_) => _runCheck());
await _runCheck();
}
/// No-op on web: there is no out-of-page scheduler to hand a retry to.
///
/// A push that fails while the window is open is retried by the next
/// foreground sync; one that fails as the window closes is picked up on the
/// next launch.
Future<void> enqueueSyncBackstop() async {}
/// Cancels the in-page timer. Exposed so a test can stop the periodic work it
/// started rather than leaking it into the next test.
void stopBackgroundTasks() {
_timer?.cancel();
_timer = null;
}
Future<void> _runCheck() async {
try {
await checkAndNotify();
} on Exception {
// A failed check must never take the app down: the next tick retries.
}
}

View File

@ -1,22 +0,0 @@
/// Byte-blob persistence for attached meal photos.
library;
import 'dart:typed_data';
/// Stores and retrieves photo bytes under an opaque key.
///
/// The key is what ends up in [FoodEntry.imagePath]: an absolute file path on
/// Android (unchanged from before the web build existed, so installed phones
/// keep resolving their existing photos) and an IndexedDB key in the browser.
/// Callers must treat it as opaque and never join, split or stat it.
///
/// Deliberately free of `dart:io` -- see `document_store.dart` for why that
/// matters for the web build.
abstract class BlobStore {
/// Stores [bytes] as a new blob whose key ends with [extension] (`.jpg`),
/// returning the key.
Future<String> put(String extension, Uint8List bytes);
/// Returns the bytes stored under [key], or null when it is gone.
Future<Uint8List?> get(String key);
}

View File

@ -1,4 +0,0 @@
/// Platform entry point for opening the photo blob store.
library;
export 'blob_store_io.dart' if (dart.library.js_interop) 'blob_store_web.dart';

View File

@ -1,49 +0,0 @@
/// File-backed [BlobStore] used on Android.
library;
import 'dart:io';
import 'dart:typed_data';
import 'package:diet_guard_app/services/blob_store.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
/// [BlobStore] keeping one file per photo under `<documents>/images/`.
///
/// Keys are absolute paths, exactly as they were before photos went through
/// a store, so an already-installed phone keeps resolving the `imagePath` of
/// every photo it has ever attached.
class FileBlobStore implements BlobStore {
/// Creates a store keeping its blobs under `<[documentsDirectory]>/images`.
FileBlobStore(this.documentsDirectory);
/// Directory whose `images/` subdirectory holds the photos.
final Directory documentsDirectory;
@override
Future<String> put(String extension, Uint8List bytes) async {
final imagesDir = Directory(p.join(documentsDirectory.path, 'images'));
await imagesDir.create(recursive: true);
final dest = File(p.join(imagesDir.path, '${const Uuid().v4()}$extension'));
await dest.writeAsBytes(bytes);
return dest.path;
}
@override
Future<Uint8List?> get(String key) async {
final file = File(key);
if (!file.existsSync()) return null;
try {
return await file.readAsBytes();
} on FileSystemException {
return null;
}
}
}
/// Opens the platform blob store (the app's documents directory).
// coverage:ignore-start
Future<BlobStore> openBlobStore() async =>
FileBlobStore(await getApplicationDocumentsDirectory());
// coverage:ignore-end

View File

@ -1,94 +0,0 @@
/// IndexedDB-backed [BlobStore] for the browser-hosted desktop app.
library;
import 'dart:typed_data';
import 'package:diet_guard_app/services/blob_store.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:http/http.dart' as http;
import 'package:idb_shim/idb_browser.dart';
import 'package:uuid/uuid.dart';
/// [BlobStore] keeping photo bytes in IndexedDB, mirrored to the desktop
/// wrapper's on-disk copy.
///
/// Photos never sync (`imagePath` is stripped before push and ignored on
/// pull), so the wrapper mirror is the *only* thing standing between a wiped
/// Chrome profile and permanently losing them -- unlike the food log, which
/// GitHub would eventually restore.
class IndexedDbBlobStore implements BlobStore {
/// Creates a store over an already-open [database], mirroring to [baseUrl].
IndexedDbBlobStore(
this._database, {
this.baseUrl = desktopWrapperOrigin,
http.Client? httpClient,
}) : _client = httpClient ?? http.Client();
final Database _database;
final http.Client _client;
/// Origin of the desktop wrapper.
final String baseUrl;
/// Object store holding one entry per photo.
static const storeName = 'blobs';
/// IndexedDB database name.
static const databaseName = 'diet_guard_blobs';
@override
Future<String> put(String extension, Uint8List bytes) async {
final key = '${const Uuid().v4()}$extension';
final txn = _database.transaction(storeName, idbModeReadWrite);
await txn.objectStore(storeName).put(bytes, key);
await txn.completed;
await _writeMirror(key, bytes);
return key;
}
@override
Future<Uint8List?> get(String key) async {
final txn = _database.transaction(storeName, idbModeReadOnly);
final value = await txn.objectStore(storeName).getObject(key);
await txn.completed;
if (value is Uint8List) return value;
if (value is List<int>) return Uint8List.fromList(value);
// Missing locally: recover from the wrapper's disk copy (cleared profile).
return _readMirror(key);
}
Future<Uint8List?> _readMirror(String key) async {
try {
final response = await _client.get(_uriFor(key));
if (response.statusCode != 200 || response.bodyBytes.isEmpty) return null;
return response.bodyBytes;
} on Exception {
return null;
}
}
Future<void> _writeMirror(String key, Uint8List bytes) async {
try {
await _client.post(_uriFor(key), body: bytes);
} on Exception {
// Best-effort by design, like the document mirror.
}
}
Uri _uriFor(String key) => Uri.parse('$baseUrl${WrapperPaths.blobs}$key');
}
/// Opens (creating if needed) the IndexedDB-backed blob store.
Future<BlobStore> openBlobStore() async {
final database = await idbFactoryBrowser.open(
IndexedDbBlobStore.databaseName,
version: 1,
onUpgradeNeeded: (event) {
final db = event.database;
if (!db.objectStoreNames.contains(IndexedDbBlobStore.storeName)) {
db.createObjectStore(IndexedDbBlobStore.storeName);
}
},
);
return IndexedDbBlobStore(database);
}

View File

@ -1,32 +0,0 @@
/// Shared constants between the web app and the desktop wrapper that serves it.
library;
/// The fixed port the desktop wrapper serves on.
///
/// **Do not change this casually.** IndexedDB (the food log, the food bank,
/// the settings and the photo blobs) is keyed by origin, so a different port
/// looks like a different app with no history at all. The launcher, the
/// packaging and `bin/diet_guard_desktop.dart` must all use this value, and
/// the Chrome `--user-data-dir` must stay equally fixed for the same reason.
///
/// 8730 is `~/todo`'s wrapper and 8731 is `~/habit_stack`'s; this is the next
/// free one so all three can run at once.
const desktopWrapperPort = 8732;
/// Origin of the desktop wrapper, e.g. `http://localhost:8732`.
const desktopWrapperOrigin = 'http://localhost:$desktopWrapperPort';
/// URL paths the wrapper serves.
///
/// Kept beside the port so the client and the server cannot drift apart; the
/// server mirrors these constants rather than re-spelling the strings.
abstract final class WrapperPaths {
/// Prefix for document reads/writes: `/documents/<name>`.
static const documents = '/documents/';
/// Prefix for photo-blob reads/writes: `/blobs/<key>`.
static const blobs = '/blobs/';
/// Prefix for the GitHub proxy (see `wrapper_server.dart`).
static const github = '/github/';
}

View File

@ -1,24 +0,0 @@
/// Named-document persistence, independent of where the documents live.
library;
/// Reads and writes whole documents by name (`food_log.json`,
/// `food_bank.json`, `app_settings.json`).
///
/// Deliberately free of `dart:io` so the storage services compile for web:
/// the desktop app is a Flutter web build, and a single `dart:io` import
/// anywhere in the graph turns into a stub that throws at runtime (a blank
/// white window, not a build error). Implementations live in
/// `document_store_io.dart` (files) and `document_store_web.dart`
/// (IndexedDB), selected by the conditional export in
/// `document_store_factory.dart`.
///
/// Whole-document rather than key-value because every caller already
/// serialises a complete JSON structure, and a partial write of any of them
/// would be worse than none.
abstract class DocumentStore {
/// Returns the stored contents of [name], or null if nothing is stored.
Future<String?> read(String name);
/// Overwrites [name] with [contents].
Future<void> write(String name, String contents);
}

View File

@ -1,9 +0,0 @@
/// Platform entry point for opening the document store.
///
/// Conditional export because `dart:io` cannot even be *imported* in a web
/// compile: Android keeps the file-backed store, the browser-hosted desktop
/// app gets IndexedDB.
library;
export 'document_store_io.dart'
if (dart.library.js_interop) 'document_store_web.dart';

View File

@ -1,64 +0,0 @@
/// File-backed [DocumentStore] used on Android (and any `dart:io` platform).
library;
import 'dart:io';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
/// [DocumentStore] backed by one file per document.
///
/// Document names are the full on-disk filenames (`food_log.json`, …) rather
/// than bare keys, so the files an already-installed phone holds keep their
/// exact paths through this refactor -- renaming them would look to the app
/// like a device with no history.
class FileDocumentStore implements DocumentStore {
/// Creates a store keeping its documents under [directory].
FileDocumentStore(this.directory);
/// Directory holding the document files.
final Directory directory;
File _fileFor(String name) => File(p.join(directory.path, name));
@override
Future<String?> read(String name) async {
final file = _fileFor(name);
if (!file.existsSync()) return null;
try {
return await file.readAsString();
} on FileSystemException {
// An unreadable file is treated as absent; callers fall back to empty
// rather than failing to start.
return null;
}
}
/// Writes to a unique temp file then atomically renames it over the real
/// one, so a concurrent reader never observes a half-written document.
///
/// The temp name carries both the pid and a per-process counter: the pid
/// separates the foreground app from the connectivity-gated background
/// push, which can `runSync` -> write from a separate isolate, and the
/// counter separates two overlapping writes *within* one process (two
/// setters awaiting the same document would otherwise both create the same
/// temp file, and the second rename would fail with the first's file
/// already gone).
@override
Future<void> write(String name, String contents) async {
final file = _fileFor(name);
await file.parent.create(recursive: true);
final tmp = File('${file.path}.$pid.${_writeCounter++}.tmp');
await tmp.writeAsString(contents);
await tmp.rename(file.path);
}
static int _writeCounter = 0;
}
/// Opens the platform document store (the app's documents directory).
// coverage:ignore-start
Future<DocumentStore> openDocumentStore() async =>
FileDocumentStore(await getApplicationDocumentsDirectory());
// coverage:ignore-end

View File

@ -1,96 +0,0 @@
/// IndexedDB-backed [DocumentStore] used by the browser-hosted desktop app.
library;
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:http/http.dart' as http;
import 'package:idb_shim/idb_browser.dart';
/// [DocumentStore] backed by IndexedDB, mirrored to the desktop wrapper's
/// on-disk copy.
///
/// IndexedDB rather than `localStorage`: the latter caps at roughly 5-10MB per
/// origin and is evicted more eagerly, and these documents are the desktop
/// device's primary copy of the food log.
///
/// The wrapper mirror is the recovery path for a wiped Chrome profile. GitHub
/// sync would eventually restore the log too, but only what other devices have
/// already seen -- a meal logged on this desktop and never pushed exists
/// nowhere else. Reads fall back to the mirror when IndexedDB is empty; writes
/// to it are best-effort so the app still works opened in a plain browser tab
/// with no wrapper running.
class IndexedDbDocumentStore implements DocumentStore {
/// Creates a store over an already-open [database], mirroring to [baseUrl].
IndexedDbDocumentStore(
this._database, {
this.baseUrl = desktopWrapperOrigin,
http.Client? httpClient,
}) : _client = httpClient ?? http.Client();
final Database _database;
final http.Client _client;
/// Origin of the desktop wrapper.
final String baseUrl;
/// Object store holding one entry per document name.
static const storeName = 'documents';
/// IndexedDB database name.
static const databaseName = 'diet_guard';
@override
Future<String?> read(String name) async {
final txn = _database.transaction(storeName, idbModeReadOnly);
final value = await txn.objectStore(storeName).getObject(name);
await txn.completed;
if (value is String) return value;
// Empty IndexedDB: either a first run or a cleared profile. Recover from
// the wrapper's disk copy rather than silently starting from nothing.
return _readMirror(name);
}
@override
Future<void> write(String name, String contents) async {
final txn = _database.transaction(storeName, idbModeReadWrite);
await txn.objectStore(storeName).put(contents, name);
await txn.completed;
await _writeMirror(name, contents);
}
Future<String?> _readMirror(String name) async {
try {
final response = await _client.get(_uriFor(name));
if (response.statusCode != 200 || response.body.isEmpty) return null;
return response.body;
} on Exception {
return null;
}
}
Future<void> _writeMirror(String name, String contents) async {
try {
await _client.post(_uriFor(name), body: contents);
} on Exception {
// Best-effort by design; see the class docs.
}
}
Uri _uriFor(String name) =>
Uri.parse('$baseUrl${WrapperPaths.documents}$name');
}
/// Opens (creating if needed) the IndexedDB-backed document store.
Future<DocumentStore> openDocumentStore() async {
final database = await idbFactoryBrowser.open(
IndexedDbDocumentStore.databaseName,
version: 1,
onUpgradeNeeded: (event) {
final db = event.database;
if (!db.objectStoreNames.contains(IndexedDbDocumentStore.storeName)) {
db.createObjectStore(IndexedDbDocumentStore.storeName);
}
},
);
return IndexedDbDocumentStore(database);
}

View File

@ -1,27 +0,0 @@
/// The periodic due/missing-slot check, shared by every platform's scheduler.
///
/// Re-runs the same due/missing-slot logic diet_guard's `_gate.py` uses to
/// decide whether to lock the PC, and syncs notifications to match. Kept in
/// its own library, free of any scheduler plugin, because the two platforms
/// drive it very differently: Android hands it to WorkManager as a real
/// background isolate, while the browser-hosted desktop app can only run it
/// from an in-page timer while its window is open (see
/// `background_tasks_web.dart`).
library;
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
/// Reads the local log, computes today's due-but-unlogged slots as of
/// [now] (defaults to the real clock), and syncs notifications to match.
///
/// [now] is injectable so a test does not depend on the wall-clock hour it
/// happens to run at, the same reason `slot.dart`'s functions are clock-free.
Future<void> checkAndNotify({DateTime? now}) async {
await LogStorageService.init();
await NotificationService.init();
final logged = await LogStorageService.instance.loggedSlotsToday();
final due = missingSlots(now ?? DateTime.now(), logged);
await NotificationService.instance.syncToSlots(due);
}

View File

@ -5,15 +5,16 @@
library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:diet_guard_app/services/fuzzy.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
/// Below this similarity ratio a non-substring candidate is dropped.
/// Mirrors `_foodbank._FUZZY_THRESHOLD`.
@ -39,46 +40,41 @@ String _displayName(FoodBankRecord record, String key) =>
/// Singleton service for the locally-rebuilt food bank.
class FoodBankService {
FoodBankService._(this._store);
/// Document holding the log-derived bank. Unchanged from the pre-web
/// on-disk filename so an installed phone keeps its existing bank.
static const documentName = 'food_bank.json';
/// Document holding the manually-curated bank.
static const manualDocumentName = 'food_bank_manual.json';
FoodBankService._(this._file);
static FoodBankService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static FoodBankService get instance => _instance!;
final DocumentStore _store;
final File _file;
/// Initializes the singleton, pointing at the app's documents directory.
static Future<FoodBankService> init() async {
if (_instance != null) return _instance!;
final svc = FoodBankService._(await openDocumentStore());
final dir = await getApplicationDocumentsDirectory();
final svc = FoodBankService._(File(p.join(dir.path, 'food_bank.json')));
_instance = svc;
return svc;
}
/// Resets the singleton so [init] can be called again in tests.
@visibleForTesting
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : FoodBankService._(store);
static void resetForTesting({Directory? testDir}) {
_instance = testDir == null
? null
: FoodBankService._(File(p.join(testDir.path, 'food_bank.json')));
}
/// Reads the persisted bank (empty map on a missing/unparsable document).
Future<Map<String, FoodBankRecord>> readBank() => _readBank(documentName);
/// Persists [bank].
Future<void> writeBank(Map<String, FoodBankRecord> bank) =>
_writeBank(documentName, bank);
Future<Map<String, FoodBankRecord>> _readBank(String name) async {
final raw = await _store.read(name);
if (raw == null) return {};
/// Reads the persisted bank (empty map on a missing/unparsable file).
Future<Map<String, FoodBankRecord>> readBank() async {
if (!_file.existsSync()) return {};
String raw;
try {
raw = await _file.readAsString();
} on FileSystemException {
return {};
}
Object? data;
try {
data = jsonDecode(raw);
@ -97,15 +93,14 @@ class FoodBankService {
return result;
}
Future<void> _writeBank(
String name,
Map<String, FoodBankRecord> bank,
) async {
/// Persists [bank] to disk, creating the parent directory if needed.
Future<void> writeBank(Map<String, FoodBankRecord> bank) async {
await _file.parent.create(recursive: true);
final encoded = <String, Object?>{
for (final mapEntry in bank.entries)
mapEntry.key: mapEntry.value.toJson(),
};
await _store.write(name, jsonEncode(encoded));
await _file.writeAsString(jsonEncode(encoded));
}
/// Rebuilds the bank by replaying [log]'s entries in a fixed, device-
@ -209,11 +204,44 @@ class FoodBankService {
// Manual bank (food items added directly without logging them as eaten)
// ---------------------------------------------------------------------------
Future<Map<String, FoodBankRecord>> _readManualBank() =>
_readBank(manualDocumentName);
File get _manualFile =>
File(p.join(_file.parent.path, 'food_bank_manual.json'));
Future<void> _writeManualBank(Map<String, FoodBankRecord> bank) =>
_writeBank(manualDocumentName, bank);
Future<Map<String, FoodBankRecord>> _readManualBank() async {
final file = _manualFile;
if (!file.existsSync()) return {};
String raw;
try {
raw = await file.readAsString();
} on FileSystemException {
return {};
}
Object? data;
try {
data = jsonDecode(raw);
} on FormatException {
return {};
}
if (data is! Map) return {};
final result = <String, FoodBankRecord>{};
for (final entry in data.entries) {
final key = entry.key;
final value = entry.value;
if (key is String && value is Map) {
result[key] = FoodBankRecord.fromJson(value.cast<String, dynamic>());
}
}
return result;
}
Future<void> _writeManualBank(Map<String, FoodBankRecord> bank) async {
final file = _manualFile;
await file.parent.create(recursive: true);
final encoded = <String, Object?>{
for (final entry in bank.entries) entry.key: entry.value.toJson(),
};
await file.writeAsString(jsonEncode(encoded));
}
/// Adds or updates [record] in the manually-curated bank without logging it
/// as eaten. A repeated call with the same normalized name overwrites the

View File

@ -1,75 +0,0 @@
/// Optional frame-cadence instrument, armed with
/// `--dart-define=DIET_GUARD_FRAME_STATS=1`.
///
/// Reports **frame-to-frame cadence**, not build/raster durations: work that
/// fits the budget says nothing about the frame rate actually achieved, which
/// is the number the desktop migration exists to move.
///
/// Read with `String.fromEnvironment`, never `bool.fromEnvironment` -- the
/// latter only accepts the literal `true`, so `=1` would silently evaluate to
/// false and a whole measurement run would produce no data while looking like
/// a broken callback.
library;
import 'dart:async';
import 'dart:convert';
import 'dart:ui' show FramePhase;
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:flutter/scheduler.dart';
import 'package:http/http.dart' as http;
/// Whether the instrument is armed for this build.
const frameStatsEnabled =
String.fromEnvironment('DIET_GUARD_FRAME_STATS') == '1';
/// Starts collecting frame-to-frame intervals and periodically posts a
/// summary to the desktop wrapper, which writes it to disk.
///
/// The wrapper is used as the sink because a browser cannot write a file and
/// reading its console from outside needs a debugger attached; a POST lands
/// somewhere a measurement run can simply read.
// coverage:ignore-start
void startFrameStats({Duration reportEvery = const Duration(seconds: 2)}) {
final intervalsMs = <double>[];
int? previousMicros;
SchedulerBinding.instance.addTimingsCallback((timings) {
for (final timing in timings) {
final micros = timing.timestampInMicroseconds(FramePhase.rasterFinish);
if (previousMicros != null) {
intervalsMs.add((micros - previousMicros!) / 1000);
}
previousMicros = micros;
}
});
Timer.periodic(reportEvery, (_) {
if (intervalsMs.isEmpty) return;
final sample = [...intervalsMs]..sort();
intervalsMs.clear();
double percentile(double fraction) =>
sample[(sample.length * fraction).floor().clamp(
0,
sample.length - 1,
)];
unawaited(
http.post(
Uri.parse(
'$desktopWrapperOrigin${WrapperPaths.documents}'
'frame_stats.json',
),
body: jsonEncode({
'frames': sample.length,
'p50_ms': percentile(0.50),
'p95_ms': percentile(0.95),
'max_ms': sample.last,
'fps_at_p50': 1000 / percentile(0.50),
'fps_at_p95': 1000 / percentile(0.95),
}),
),
);
});
}
// coverage:ignore-end

View File

@ -1,5 +0,0 @@
/// Platform entry point for building the GitHub sync client.
library;
export 'github_client_factory_io.dart'
if (dart.library.js_interop) 'github_client_factory_web.dart';

View File

@ -1,34 +0,0 @@
/// Direct GitHub client, used on Android.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/github_device_auth.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:http/http.dart' as http;
/// This device's id in the `diet-guard-sync/devices/<id>/food_log.json`
/// layout.
///
/// The PC's Python side pushes under `pc` (`SYNC_DEVICE_ID` in
/// `diet_guard/_constants.py`) and the desktop web build under `desktop`;
/// every device must have its own, or two of them overwrite each other's
/// pushed log on every tick.
const syncDeviceId = 'phone';
/// Builds a client that talks to `api.github.com` directly with [settings]'
/// token.
GitHubClient createGitHubClient(
SyncSettings settings, {
http.Client? httpClient,
}) => GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: httpClient,
);
/// Builds the device-flow client, talking to GitHub directly.
GitHubDeviceAuth createDeviceAuth(
String clientId, {
http.Client? httpClient,
}) => GitHubDeviceAuth(clientId: clientId, httpClient: httpClient);

View File

@ -1,82 +0,0 @@
/// Wrapper-proxied GitHub client, used by the desktop web build.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:diet_guard_app/services/github_device_auth.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:http/http.dart' as http;
/// This device's id under `diet-guard-sync/devices/`.
///
/// Distinct from the phone's `phone` and the Python side's `pc`: the desktop
/// app is a third device, and sharing an id would make two devices overwrite
/// each other's pushed log on every tick.
const syncDeviceId = 'desktop';
/// Builds a client whose requests go through the desktop wrapper.
///
/// The token is deliberately empty: the wrapper attaches the real one
/// server-side (see `desktop/github_proxy.dart`), so it never enters the
/// browser. `settings.token` on web is only ever the stand-in constant.
GitHubClient createGitHubClient(
SyncSettings settings, {
http.Client? httpClient,
}) => GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: '',
httpClient: WrapperProxyClient(inner: httpClient),
);
/// Rewrites `https://api.github.com/...` to the wrapper's proxy endpoint.
///
/// A decorator rather than a `baseUrl` option on [GitHubClient] so the shared
/// `crdt_sync` library needs no web-specific knowledge; the rewrite is a
/// property of how this app is hosted, not of the transport.
class WrapperProxyClient extends http.BaseClient {
/// Creates a client delegating to [inner] after rewriting GitHub URLs.
WrapperProxyClient({http.Client? inner, this.baseUrl = desktopWrapperOrigin})
: _inner = inner ?? http.Client();
final http.Client _inner;
/// Origin of the desktop wrapper.
final String baseUrl;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) {
if (request.url.host != 'api.github.com' || request is! http.Request) {
return _inner.send(request);
}
final rewritten =
http.Request(
request.method,
Uri.parse(
'$baseUrl${WrapperPaths.github}api'
'${request.url.path}',
).replace(query: request.url.hasQuery ? request.url.query : null),
)
..headers.addAll(request.headers)
..bodyBytes = request.bodyBytes
..followRedirects = request.followRedirects;
return _inner.send(rewritten);
}
@override
void close() => _inner.close();
}
/// Builds the device-flow client, routed through the desktop wrapper.
///
/// GitHub's device-flow endpoints send no CORS headers, so the page cannot
/// call them; the wrapper does, and keeps the resulting token.
GitHubDeviceAuth createDeviceAuth(
String clientId, {
http.Client? httpClient,
}) => GitHubDeviceAuth(
clientId: clientId,
deviceCodeUrl: '$desktopWrapperOrigin${WrapperPaths.github}auth/device/start',
tokenUrl: '$desktopWrapperOrigin${WrapperPaths.github}auth/device/poll',
httpClient: httpClient,
);

View File

@ -1,15 +1,8 @@
import 'dart:async';
import 'dart:convert';
import 'package:diet_guard_app/services/token_vault.dart';
import 'package:http/http.dart' as http;
/// GitHub's device-code endpoint.
const githubDeviceCodeUrl = 'https://github.com/login/device/code';
/// GitHub's device-flow token endpoint.
const githubTokenUrl = 'https://github.com/login/oauth/access_token';
/// First-stage response of the GitHub OAuth Device Flow: the code the user
/// types on github.com and the URL to type it into.
class DeviceCodeResponse {
@ -79,8 +72,6 @@ class GitHubDeviceAuth {
GitHubDeviceAuth({
required this.clientId,
this.scope = 'repo',
this.deviceCodeUrl = githubDeviceCodeUrl,
this.tokenUrl = githubTokenUrl,
http.Client? httpClient,
Future<void> Function(Duration)? delay,
}) : _http = httpClient ?? http.Client(),
@ -93,26 +84,17 @@ class GitHubDeviceAuth {
/// OAuth scope requested. `repo` is required for private-repo contents.
final String scope;
/// Endpoint asked for a device + user code.
///
/// GitHub's own URL on Android. The desktop web build points both this and
/// [tokenUrl] at the local wrapper instead, because GitHub's device-flow
/// endpoints send no CORS headers and a page cannot call them at all (see
/// `desktop/github_proxy.dart`).
final String deviceCodeUrl;
/// Endpoint polled for the access token. See [deviceCodeUrl].
final String tokenUrl;
final http.Client _http;
final Future<void> Function(Duration) _delay;
static const _deviceCodeUrl = 'https://github.com/login/device/code';
static const _tokenUrl = 'https://github.com/login/oauth/access_token';
static const _grantType = 'urn:ietf:params:oauth:grant-type:device_code';
/// Step 1: ask GitHub for a device + user code.
Future<DeviceCodeResponse> requestDeviceCode() async {
final res = await _http.post(
Uri.parse(deviceCodeUrl),
Uri.parse(_deviceCodeUrl),
headers: const {'Accept': 'application/json'},
body: {'client_id': clientId, 'scope': scope},
);
@ -136,7 +118,7 @@ class GitHubDeviceAuth {
while (DateTime.now().isBefore(deadline)) {
await _delay(Duration(seconds: intervalSeconds));
final res = await _http.post(
Uri.parse(tokenUrl),
Uri.parse(_tokenUrl),
headers: const {'Accept': 'application/json'},
body: {
'client_id': clientId,
@ -148,9 +130,6 @@ class GitHubDeviceAuth {
final token = json['access_token'] as String?;
if (token != null) return token;
// The wrapper-proxied flow deliberately keeps the token server-side and
// answers with a bare acknowledgement instead (see [deviceCodeUrl]).
if (json['status'] == 'ok') return wrapperManagedToken;
switch (json['error'] as String?) {
case 'authorization_pending':

View File

@ -2,14 +2,15 @@
library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/meal_component.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
/// The on-disk log shape: date key (`YYYY-MM-DD`) to that day's entries.
@ -24,37 +25,34 @@ typedef DayLog = Map<String, List<FoodEntry>>;
/// autocomplete is small-corpus fuzzy string matching, not a relational
/// query.
class LogStorageService {
LogStorageService._(this._store);
/// Document name this service owns, unchanged from the pre-web on-disk
/// filename so an installed phone keeps reading its existing log.
static const documentName = 'food_log.json';
LogStorageService._(this._file);
static LogStorageService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static LogStorageService get instance => _instance!;
final DocumentStore _store;
final File _file;
/// Initializes the singleton against the platform document store: files in
/// the app's documents directory on Android (phone-sandboxed; no
/// external-storage permission needed), IndexedDB in the browser-hosted
/// desktop app.
/// Initializes the singleton, pointing at the app's documents directory
/// (phone-sandboxed; no external-storage permission needed).
static Future<LogStorageService> init() async {
if (_instance != null) return _instance!;
final svc = LogStorageService._(await openDocumentStore());
final dir = await getApplicationDocumentsDirectory();
final svc = LogStorageService._(File(p.join(dir.path, 'food_log.json')));
_instance = svc;
return svc;
}
/// Resets the singleton so [init] can be called again in tests.
///
/// When [store] is given, subsequent reads/writes go there instead of the
/// real platform store, so a test can never touch real data.
/// When [testDir] is given, subsequent reads/writes go there instead of
/// the real documents directory, so a test can never touch real data.
@visibleForTesting
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : LogStorageService._(store);
static void resetForTesting({Directory? testDir}) {
_instance = testDir == null
? null
: LogStorageService._(File(p.join(testDir.path, 'food_log.json')));
}
/// Reads the full log, including tombstoned entries.
@ -62,8 +60,13 @@ class LogStorageService {
/// Returns an empty log on a missing or unparsable file, mirroring
/// `_state._read_raw_log`'s defensive read.
Future<DayLog> readLog() async {
final raw = await _store.read(documentName);
if (raw == null) return {};
if (!_file.existsSync()) return {};
String raw;
try {
raw = await _file.readAsString();
} on FileSystemException {
return {};
}
Object? data;
try {
data = jsonDecode(raw);
@ -84,16 +87,22 @@ class LogStorageService {
return result;
}
/// Persists the full log to the store, mirroring `_state._write_log`.
///
/// Atomicity against a concurrent reader is the store's job (see
/// `FileDocumentStore.write`'s temp-file-and-rename), not this method's.
/// Persists the full log to disk, creating the parent directory if
/// needed, mirroring `_state._write_log`.
Future<void> writeLog(DayLog log) async {
await _file.parent.create(recursive: true);
final encoded = <String, Object?>{
for (final mapEntry in log.entries)
mapEntry.key: mapEntry.value.map((e) => e.toLocalJson()).toList(),
};
await _store.write(documentName, jsonEncode(encoded));
// Write to a per-process temp file then atomically rename it over the
// real one, so a concurrent reader never sees a half-written file. The
// connectivity-gated background push (see background_sync_service.dart)
// can `runSync` -> writeLog in a separate isolate while the foreground
// app also writes; the pid in the temp name keeps the two from colliding.
final tmp = File('${_file.path}.$pid.tmp');
await tmp.writeAsString(jsonEncode(encoded));
await tmp.rename(_file.path);
}
/// Appends a signed-on-PC-eventually entry for [desc] to today's log.

View File

@ -1,28 +0,0 @@
/// The platform notification surface behind [NotificationService].
library;
/// Shows and cancels one notification per meal slot.
///
/// Free of any plugin import so [NotificationService]'s due-slot logic
/// compiles for web: the implementations are
/// `notification_backend_io.dart` (`flutter_local_notifications`) and
/// `notification_backend_web.dart` (the browser's Notifications API),
/// selected by the conditional export in
/// `notification_backend_factory.dart`.
abstract class NotificationBackend {
/// Prepares the platform surface. Called once, before any [show]/[cancel].
Future<void> initialize();
/// Asks the platform for permission to post notifications.
///
/// Returns null where the concept does not apply, which callers treat the
/// same as false: notifications degrade silently rather than blocking use
/// of the app.
Future<bool?> requestPermission();
/// Posts (or replaces) the notification for [slot].
Future<void> show(int slot, String title, String body);
/// Removes the notification for [slot], if one is showing.
Future<void> cancel(int slot);
}

View File

@ -1,5 +0,0 @@
/// Platform entry point for opening the notification backend.
library;
export 'notification_backend_io.dart'
if (dart.library.js_interop) 'notification_backend_web.dart';

View File

@ -1,73 +0,0 @@
/// `flutter_local_notifications`-backed [NotificationBackend] (Android).
library;
import 'package:diet_guard_app/services/notification_backend.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
/// Wraps [FlutterLocalNotificationsPlugin] so the due-slot logic in
/// `notification_service.dart` is unit-testable against a fake platform
/// channel, independent of the real plugin's native implementation.
class LocalNotificationsBackend implements NotificationBackend {
/// Creates a backend over [plugin].
LocalNotificationsBackend(this.plugin);
/// The wrapped plugin. Injectable so a test can point it at a fake channel.
final FlutterLocalNotificationsPlugin plugin;
static const _channelId = 'diet_guard_due_slot';
static const _channelName = 'Meal reminders';
@override
Future<void> initialize() async {
const settings = InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
);
await plugin.initialize(settings: settings);
}
/// Requests Android 13+'s runtime `POST_NOTIFICATIONS` permission.
///
/// Returns null on platforms where this Android-specific call doesn't
/// apply -- the caller treats null and false the same way (don't block on
/// it; notifications degrade silently if denied, matching the rest of this
/// service's silent-on-failure stance). Since the desktop target became a
/// web build, `android/` is this backend's only real platform, so in
/// production the non-null path always runs; the fallback is not reachable
/// from `flutter test` without polluting the process-global plugin
/// registration other tests in this file rely on, so it's excluded from
/// coverage rather than chased with a fragile test-ordering trick.
@override
Future<bool?> requestPermission() =>
plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>()
?.requestNotificationsPermission() ??
// coverage:ignore-line
Future.value();
@override
Future<void> show(int slot, String title, String body) async {
const details = NotificationDetails(
android: AndroidNotificationDetails(
_channelId,
_channelName,
importance: Importance.high,
priority: Priority.high,
),
);
await plugin.show(
id: slot,
title: title,
body: body,
notificationDetails: details,
);
}
@override
Future<void> cancel(int slot) => plugin.cancel(id: slot);
}
/// Opens the platform notification backend.
NotificationBackend openNotificationBackend() =>
LocalNotificationsBackend(FlutterLocalNotificationsPlugin());

View File

@ -1,56 +0,0 @@
/// Browser-Notifications-API [NotificationBackend] for the desktop app.
///
/// A browser notification only exists while the page that raised it is open,
/// so this is a genuinely weaker surface than Android's: closing the desktop
/// window drops every pending reminder. That is accepted -- the PC's real
/// backstop is `diet-guard-gate.timer`, which locks the screen rather than
/// asking politely.
library;
import 'dart:js_interop';
import 'package:diet_guard_app/services/notification_backend.dart';
import 'package:web/web.dart' as web;
/// [NotificationBackend] over the browser's `Notification` API.
class WebNotificationBackend implements NotificationBackend {
/// Live notifications by slot, so [cancel] can close the right one. The
/// `tag` also makes the browser replace rather than stack a re-shown slot;
/// the map is what makes an explicit close possible.
final _shown = <int, web.Notification>{};
bool _granted = false;
@override
Future<void> initialize() async {}
@override
Future<bool?> requestPermission() async {
if (web.Notification.permission == 'granted') {
_granted = true;
return true;
}
if (web.Notification.permission == 'denied') return false;
final result = await web.Notification.requestPermission().toDart;
return _granted = result.toDart == 'granted';
}
@override
Future<void> show(int slot, String title, String body) async {
// Posting without permission throws; a silent no-op matches this
// service's degrade-quietly stance everywhere else.
if (!_granted) return;
_shown[slot] = web.Notification(
title,
web.NotificationOptions(body: body, tag: 'diet_guard_slot_$slot'),
);
}
@override
Future<void> cancel(int slot) async {
_shown.remove(slot)?.close();
}
}
/// Opens the platform notification backend.
NotificationBackend openNotificationBackend() => WebNotificationBackend();

View File

@ -5,51 +5,77 @@
library;
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/notification_backend.dart';
import 'package:diet_guard_app/services/notification_backend_factory.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
/// Owns the due-slot notification logic ([syncToSlots]) independently of the
/// platform surface that actually posts them: `flutter_local_notifications`
/// on Android, the browser's Notifications API in the desktop web build (see
/// `notification_backend.dart`).
/// Wraps [FlutterLocalNotificationsPlugin] so the due-slot notification
/// logic ([syncToSlots]) is unit-testable against a fake platform channel,
/// independent of the real plugin's native implementation.
class NotificationService {
NotificationService._(this._backend);
NotificationService._(this._plugin);
static NotificationService? _instance;
final NotificationBackend _backend;
final FlutterLocalNotificationsPlugin _plugin;
bool _initialized = false;
static const _channelId = 'diet_guard_due_slot';
static const _channelName = 'Meal reminders';
/// Returns the initialized singleton; throws if [init] was not called.
static NotificationService get instance => _instance!;
/// Initializes the singleton with the platform backend (idempotent -- a
/// Initializes the singleton with the real plugin (idempotent -- a
/// second call returns the already-initialized instance without
/// re-running platform setup).
static Future<NotificationService> init() async {
final svc = _instance ??= NotificationService._(openNotificationBackend());
final svc = _instance ??= NotificationService._(
FlutterLocalNotificationsPlugin(),
);
if (!svc._initialized) {
await svc._backend.initialize();
// `linux:` is required whenever the app runs on Linux (the desktop
// build used to visually verify screens); this app has no real
// Linux target otherwise.
const settings = InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
linux: LinuxInitializationSettings(defaultActionName: 'Open'),
);
await svc._plugin.initialize(settings: settings);
svc._initialized = true;
}
return svc;
}
/// Resets the singleton so tests can inject a backend -- typically one over
/// a plugin pointed at a fake platform channel. A subsequent [init] call
/// drives that backend's `initialize` codepath, same as production.
/// Resets the singleton so tests can inject a plugin pointed at a fake
/// platform channel. A subsequent [init] call drives that fake's
/// `initialize` codepath, same as production.
@visibleForTesting
static void resetForTesting({NotificationBackend? backend}) {
_instance = backend == null ? null : NotificationService._(backend);
static void resetForTesting({FlutterLocalNotificationsPlugin? plugin}) {
_instance = plugin == null ? null : NotificationService._(plugin);
}
/// Requests the platform's notification permission.
/// Requests Android 13+'s runtime `POST_NOTIFICATIONS` permission.
///
/// Returns null where the concept doesn't apply; callers treat null and
/// false the same way.
Future<bool?> requestPermission() => _backend.requestPermission();
/// Returns null on platforms where this Android-specific call doesn't
/// apply -- the caller treats null and false the same way (don't block on
/// it; notifications degrade silently if denied, matching the rest of
/// this service's silent-on-failure stance). This app only ships an
/// `android/` target, so in production the non-null path always runs;
/// the fallback exists for the Linux desktop build used to visually
/// verify this screen, where `resolvePlatformSpecificImplementation`
/// correctly resolves to null -- not reachable from `flutter test`
/// without polluting the process-global plugin registration other tests
/// in this file rely on, so it's excluded from coverage rather than
/// chased with a fragile test-ordering trick.
Future<bool?> requestPermission() =>
_plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>()
?.requestNotificationsPermission() ??
// coverage:ignore-line
Future.value();
/// Shows a notification for every slot in [dueSlots] and cancels one for
/// every other known slot.
@ -62,14 +88,27 @@ class NotificationService {
final due = dueSlots.toSet();
for (final slot in daySlots()) {
if (due.contains(slot)) {
await _backend.show(
slot,
'Meal not logged',
"You haven't logged your ${slotLabel(slot)} meal yet.",
);
await _show(slot);
} else {
await _backend.cancel(slot);
await _plugin.cancel(id: slot);
}
}
}
Future<void> _show(int slot) async {
const details = NotificationDetails(
android: AndroidNotificationDetails(
_channelId,
_channelName,
importance: Importance.high,
priority: Priority.high,
),
);
await _plugin.show(
id: slot,
title: 'Meal not logged',
body: "You haven't logged your ${slotLabel(slot)} meal yet.",
notificationDetails: details,
);
}
}

View File

@ -1,56 +1,52 @@
/// Picks a photo and copies it into permanent app-local storage.
/// Picks a photo and copies it into permanent phone-local storage.
library;
import 'package:diet_guard_app/services/blob_store.dart';
import 'package:diet_guard_app/services/blob_store_factory.dart';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
/// Wraps [ImagePicker] and persists the result in a [BlobStore], so the
/// returned key survives after the picker's own (possibly cache-cleared)
/// temp file is gone.
/// Wraps [ImagePicker] and persists the result under the app's documents
/// directory, so the returned path survives after the picker's own
/// (possibly cache-cleared) temp file is gone.
///
/// Photos are device-local only: per the sync plan (Milestone 3), a logged
/// Photos are phone-local only: per the sync plan (Milestone 3), a logged
/// entry's `imagePath` is stripped before push and never read from a pulled
/// remote copy, so nothing here needs to be sync-aware. That also means a
/// photo attached on the desktop is never visible on the phone, and vice
/// versa -- by design, not by omission.
/// remote copy, so no storage here needs to be sync-aware.
class PhotoAttachService {
PhotoAttachService._(this._store);
PhotoAttachService._(this._testDir);
static PhotoAttachService _instance = PhotoAttachService._(null);
/// The singleton instance.
static PhotoAttachService get instance => _instance;
BlobStore? _store;
final Directory? _testDir;
/// Redirects where picked photos are stored, so a test never touches the
/// real store. Pass null to restore default behavior.
/// Redirects where picked photos are copied to, so a test never touches
/// the real documents directory. Pass null to restore default behavior.
@visibleForTesting
static void resetForTesting({BlobStore? store}) {
_instance = PhotoAttachService._(store);
static void resetForTesting({Directory? testDir}) {
_instance = PhotoAttachService._(testDir);
}
Future<BlobStore> _resolveStore() async => _store ??= await openBlobStore();
/// Opens [source] (camera or gallery) and stores the picked image.
/// Opens [source] (camera or gallery), and on a successful pick, copies
/// the image into `<app documents>/images/<uuid>.<ext>`.
///
/// Returns the new blob key -- an absolute path on Android, an IndexedDB
/// key in the browser -- or null if the user cancelled the picker.
/// Returns the new permanent path, or null if the user cancelled the
/// picker.
Future<String?> pickAndStore(ImageSource source) async {
final picked = await ImagePicker().pickImage(source: source);
if (picked == null) return null;
final store = await _resolveStore();
// `readAsBytes` rather than a file copy: the browser's picker hands back
// a blob URL with no filesystem behind it.
return store.put(p.extension(picked.path), await picked.readAsBytes());
final docsDir = _testDir ?? await getApplicationDocumentsDirectory();
final imagesDir = Directory(p.join(docsDir.path, 'images'));
await imagesDir.create(recursive: true);
final ext = p.extension(picked.path);
final dest = p.join(imagesDir.path, '${const Uuid().v4()}$ext');
await File(picked.path).copy(dest);
return dest;
}
/// Returns the bytes stored under [key], or null when the photo is gone.
///
/// Backs the web image widget, which cannot render from a path.
Future<Uint8List?> readBytes(String key) async =>
(await _resolveStore()).get(key);
}

View File

@ -20,12 +20,17 @@ import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_merge.dart';
const _devicesDir = 'diet-guard-sync/devices';
/// This device's id in the `diet-guard-sync/devices/<id>/food_log.json`
/// layout. The PC pushes under `pc` (`SYNC_DEVICE_ID` in
/// `diet_guard/_constants.py`); the phone is the only other device in this
/// design.
const phoneDeviceId = 'phone';
/// Runs one full sync tick: pull, merge, preserve photos, persist, push.
///
/// Returns the merged log as it now sits on disk locally. Propagates any
@ -38,7 +43,7 @@ Future<DayLog> runSync(GitHubClient client) async {
final mergedLog = await syncLog(
client: client,
deviceId: syncDeviceId,
deviceId: phoneDeviceId,
pathPrefix: _devicesDir,
localLog: dayLogToLog(local),
encode: encodeLogForPush,
@ -77,7 +82,7 @@ Future<void> _syncBudget(GitHubClient client) async {
final mergedBudgetLog = await syncLog(
client: client,
deviceId: syncDeviceId,
deviceId: phoneDeviceId,
pathPrefix: _devicesDir,
localLog: budgetToLog(localRecord),
encode: encodeBudgetForPush,

View File

@ -4,17 +4,16 @@
/// manual fallback.
library;
import 'package:diet_guard_app/services/token_vault.dart';
import 'package:diet_guard_app/services/token_vault_factory.dart';
import 'package:flutter/services.dart' show PlatformException;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// The GitHub token is kept out of `SharedPreferences`, which holds only the
/// non-secret owner/repo: on Android it lives in the OS keystore, and in the
/// desktop web build it lives in the wrapper process rather than the browser
/// at all (see [TokenVault]). Older builds stored the token in plaintext
/// prefs; [load]/[save] migrate it transparently and never drop the plaintext
/// copy until a vault write is confirmed (so we degrade to -- never below --
/// the old behaviour when no secure store is available).
/// The GitHub token is kept in the OS keystore (Android Keystore / libsecret)
/// via [flutter_secure_storage]; only the non-secret owner/repo live in
/// `SharedPreferences`. Older builds stored the token in plaintext prefs;
/// [load]/[save] migrate it transparently and never drop the plaintext copy
/// until a secure write is confirmed (so we degrade to -- never below -- the
/// old behaviour when no secret service is available).
class SyncSettings {
/// Creates a [SyncSettings] from its owner/repo/token.
const SyncSettings({
@ -60,10 +59,12 @@ class SyncSettings {
// the token has been migrated into secure storage.
static const _kToken = 'sync.token';
static final TokenVault _vault = openTokenVault();
/// Key for the token inside the OS keystore.
static const _secureToken = 'sync.token';
/// True when this platform can show the stored token back to the user.
static bool get exposesTokenValue => _vault.exposesTokenValue;
/// Default options keep us off the deprecated `encryptedSharedPreferences`
/// path on Android and use libsecret on Linux.
static const _secure = FlutterSecureStorage();
/// Loads settings, defaulting the owner/repo to `kuhyx/syncs`
/// (matching the PC's `SYNC_REPO_OWNER`/`SYNC_REPO_NAME` constants) and the
@ -89,36 +90,57 @@ class SyncSettings {
);
}
/// Reads the token, preferring the vault and falling back to the legacy
/// plaintext value. A legacy value is migrated into the vault on read, but
/// only dropped from prefs once that write succeeds.
/// Reads the token, preferring the keystore and falling back to the legacy
/// plaintext value. A legacy value is migrated into the keystore on read,
/// but only dropped from prefs once that secure write succeeds.
static Future<String> _loadToken(SharedPreferences prefs) async {
final stored = await _vault.read();
if (stored.isNotEmpty) return stored;
String? secure;
try {
secure = await _secure.read(key: _secureToken);
} on PlatformException {
// No secret service available -- fall back to the legacy plaintext copy.
secure = null;
}
if (secure != null && secure.isNotEmpty) return secure;
final legacy = prefs.getString(_kToken) ?? '';
if (legacy.isNotEmpty && await _vault.write(legacy)) {
if (legacy.isNotEmpty && await _writeSecureToken(legacy)) {
await prefs.remove(_kToken);
}
return legacy;
}
/// Persists [owner]/[repo] to prefs and [token] to the vault (or plaintext
/// prefs as a fallback -- see [_loadToken]).
/// Persists [owner]/[repo] to prefs and [token] to the keystore (or
/// plaintext prefs as a fallback -- see [_loadToken]).
Future<void> save() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_kOwner, owner);
await prefs.setString(_kRepo, repo);
await prefs.setString(_kClientId, clientId);
// Confirm-before-delete: only remove the plaintext copy once the vault
// Confirm-before-delete: only remove the plaintext copy once the keystore
// write succeeds; otherwise keep persisting it to prefs as before.
if (await _vault.write(token)) {
if (await _writeSecureToken(token)) {
await prefs.remove(_kToken);
} else {
await prefs.setString(_kToken, token);
}
}
/// Writes [token] to the keystore (deleting the entry when empty). Returns
/// false if the platform secret service is unavailable.
static Future<bool> _writeSecureToken(String token) async {
try {
if (token.isEmpty) {
await _secure.delete(key: _secureToken);
} else {
await _secure.write(key: _secureToken, value: token);
}
return true;
} on PlatformException {
return false;
}
}
/// Returns a copy of this with only the given fields replaced.
SyncSettings copyWith({
String? owner,

View File

@ -1,34 +0,0 @@
/// Where the GitHub sync token lives, per platform.
library;
/// Reads and writes the GitHub sync token.
///
/// Two very different implementations sit behind this:
///
/// * Android keeps the token in the OS keystore via `flutter_secure_storage`
/// (`token_vault_io.dart`), migrating any legacy plaintext copy.
/// * The desktop web build never holds the token at all: the wrapper owns it
/// on disk and attaches it to proxied requests, so the vault only reports
/// *whether* one exists (`token_vault_web.dart`).
abstract class TokenVault {
/// Returns the token, or the empty string when none is stored.
///
/// On web this returns [wrapperManagedToken] as a stand-in whenever the
/// wrapper holds a token: callers only ever test it for emptiness or hand
/// it to a client whose requests are proxied, and the real value stays out
/// of the browser.
Future<String> read();
/// Stores [token] (clearing it when empty). Returns false when the platform
/// has nowhere secure to put it, so the caller can fall back.
Future<bool> write(String token);
/// True when this platform can show the token back to the user.
///
/// False on web -- the settings screen hides the PAT field rather than
/// displaying a placeholder that cannot be edited meaningfully.
bool get exposesTokenValue;
}
/// Stand-in value used on web in place of the real, wrapper-held token.
const wrapperManagedToken = 'wrapper-managed';

View File

@ -1,5 +0,0 @@
/// Platform entry point for the GitHub sync token vault.
library;
export 'token_vault_io.dart'
if (dart.library.js_interop) 'token_vault_web.dart';

View File

@ -1,53 +0,0 @@
/// Keystore-backed [TokenVault] used on Android.
library;
import 'package:diet_guard_app/services/token_vault.dart';
import 'package:flutter/services.dart' show PlatformException;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
/// Keeps the token in the OS keystore (Android Keystore) via
/// [FlutterSecureStorage].
///
/// Default options keep us off the deprecated `encryptedSharedPreferences`
/// path on Android.
class SecureStorageTokenVault implements TokenVault {
/// Creates a vault over [storage].
const SecureStorageTokenVault({this.storage = const FlutterSecureStorage()});
/// The wrapped keystore. Injectable so a test can supply a fake.
final FlutterSecureStorage storage;
/// Key for the token inside the OS keystore.
static const _secureToken = 'sync.token';
@override
bool get exposesTokenValue => true;
@override
Future<String> read() async {
try {
return await storage.read(key: _secureToken) ?? '';
} on PlatformException {
// No secret service available -- the caller falls back to the legacy
// plaintext copy in SharedPreferences.
return '';
}
}
@override
Future<bool> write(String token) async {
try {
if (token.isEmpty) {
await storage.delete(key: _secureToken);
} else {
await storage.write(key: _secureToken, value: token);
}
return true;
} on PlatformException {
return false;
}
}
}
/// Opens the platform token vault.
TokenVault openTokenVault() => const SecureStorageTokenVault();

View File

@ -1,65 +0,0 @@
/// Wrapper-backed [TokenVault] for the desktop web build.
library;
import 'dart:convert';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:diet_guard_app/services/token_vault.dart';
import 'package:http/http.dart' as http;
/// Delegates token storage to the desktop wrapper.
///
/// The browser never holds the token: [read] reports only whether the wrapper
/// has one, and [write] hands a pasted PAT straight through to the wrapper's
/// 600-mode token file. This is deliberately *not* `flutter_secure_storage`'s
/// web backend, which is WebCrypto-wrapped `localStorage` with the wrap key
/// stored beside the ciphertext -- obfuscation, not encryption at rest.
class WrapperTokenVault implements TokenVault {
/// Creates a vault talking to the wrapper at [baseUrl].
WrapperTokenVault({this.baseUrl = desktopWrapperOrigin, http.Client? client})
: _client = client ?? http.Client();
/// Origin of the desktop wrapper.
final String baseUrl;
final http.Client _client;
@override
bool get exposesTokenValue => false;
@override
Future<String> read() async {
try {
final response = await _client.get(
Uri.parse('$baseUrl${WrapperPaths.github}auth/status'),
);
if (response.statusCode != 200) return '';
final body = jsonDecode(response.body);
final configured = body is Map && body['configured'] == true;
return configured ? wrapperManagedToken : '';
} on Exception {
// No wrapper running (a plain browser tab): behave as unconfigured
// rather than failing the whole settings screen.
return '';
}
}
@override
Future<bool> write(String token) async {
// The stand-in is what `read` handed out; writing it back would replace a
// real token with a literal.
if (token == wrapperManagedToken) return true;
try {
final response = await _client.post(
Uri.parse('$baseUrl${WrapperPaths.github}auth/token'),
body: token,
);
return response.statusCode == 204;
} on Exception {
return false;
}
}
}
/// Opens the platform token vault.
TokenVault openTokenVault() => WrapperTokenVault();

View File

@ -1,10 +0,0 @@
/// Platform entry point for rendering an attached meal photo.
///
/// Conditional export because the two platforms resolve a photo differently:
/// Android has a real file at the stored path, while the browser-hosted
/// desktop app has to read the bytes back out of IndexedDB before it can show
/// anything (`Image.file` is a `dart:io` stub there and would throw).
library;
export 'attached_image_io.dart'
if (dart.library.js_interop) 'attached_image_web.dart';

View File

@ -1,58 +0,0 @@
/// File-backed attached-photo widget (Android).
library;
import 'dart:io';
import 'package:flutter/material.dart';
/// Renders the photo stored under [path], falling back to a broken-image
/// icon when it cannot be read.
class AttachedImage extends StatelessWidget {
/// Creates an [AttachedImage] for the blob key [path].
const AttachedImage({
required this.path,
this.width,
this.height,
this.fit,
this.errorIconSize,
this.errorIconColor,
super.key,
});
/// Blob key of the photo -- an absolute file path on this platform.
final String path;
/// Optional fixed width; null renders at the image's own size.
final double? width;
/// Optional fixed height; null renders at the image's own size.
final double? height;
/// How to inscribe the image into its box.
final BoxFit? fit;
/// Size of the fallback broken-image icon.
final double? errorIconSize;
/// Colour of the fallback broken-image icon.
final Color? errorIconColor;
@override
Widget build(BuildContext context) {
return Image.file(
File(path),
width: width,
height: height,
fit: fit,
errorBuilder: (context, error, stackTrace) => SizedBox(
width: width,
height: height,
child: Icon(
Icons.broken_image,
size: errorIconSize,
color: errorIconColor,
),
),
);
}
}

View File

@ -1,92 +0,0 @@
/// IndexedDB-backed attached-photo widget (desktop web build).
library;
import 'dart:typed_data';
import 'package:diet_guard_app/services/photo_attach_service.dart';
import 'package:flutter/material.dart';
/// Renders the photo stored under [path], falling back to a broken-image
/// icon when it cannot be read.
///
/// Unlike the Android build this is inherently asynchronous: the bytes come
/// from IndexedDB (or, for a cleared profile, the desktop wrapper's disk
/// mirror), not from a path the rasteriser can open itself.
class AttachedImage extends StatefulWidget {
/// Creates an [AttachedImage] for the blob key [path].
const AttachedImage({
required this.path,
this.width,
this.height,
this.fit,
this.errorIconSize,
this.errorIconColor,
super.key,
});
/// Blob key of the photo -- an IndexedDB key on this platform.
final String path;
/// Optional fixed width; null renders at the image's own size.
final double? width;
/// Optional fixed height; null renders at the image's own size.
final double? height;
/// How to inscribe the image into its box.
final BoxFit? fit;
/// Size of the fallback broken-image icon.
final double? errorIconSize;
/// Colour of the fallback broken-image icon.
final Color? errorIconColor;
@override
State<AttachedImage> createState() => _AttachedImageState();
}
class _AttachedImageState extends State<AttachedImage> {
late Future<Uint8List?> _bytes = _load();
Future<Uint8List?> _load() => PhotoAttachService.instance.readBytes(
widget.path,
);
@override
void didUpdateWidget(AttachedImage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.path != widget.path) _bytes = _load();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Uint8List?>(
future: _bytes,
builder: (context, snapshot) {
final bytes = snapshot.data;
if (bytes == null) {
// Covers both "still loading" and "gone": a spinner that flashes
// for one frame per thumbnail would be worse than an empty box.
return SizedBox(
width: widget.width,
height: widget.height,
child: snapshot.connectionState == ConnectionState.done
? Icon(
Icons.broken_image,
size: widget.errorIconSize,
color: widget.errorIconColor,
)
: null,
);
}
return Image.memory(
bytes,
width: widget.width,
height: widget.height,
fit: widget.fit,
);
},
);
}
}

View File

@ -1,10 +1,10 @@
/// Shared attach/preview/remove control for a meal entry's optional photo.
library;
import 'dart:io';
import 'package:diet_guard_app/screens/photo_viewer_screen.dart';
import 'package:diet_guard_app/services/photo_attach_service.dart';
import 'package:diet_guard_app/widgets/attached_image.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
@ -41,21 +41,14 @@ class PhotoAttachField extends StatelessWidget {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// No camera row on web: the browser's picker is a file input,
// and `ImageSource.camera` silently falls back to the same file
// dialog -- an option that lies about what it does is worse than
// no option.
if (!kIsWeb)
ListTile(
leading: const Icon(Icons.photo_camera),
title: const Text('Take a photo'),
onTap: () => Navigator.of(sheetContext).pop(ImageSource.camera),
),
ListTile(
leading: const Icon(Icons.photo_camera),
title: const Text('Take a photo'),
onTap: () => Navigator.of(sheetContext).pop(ImageSource.camera),
),
ListTile(
leading: const Icon(Icons.photo_library),
title: const Text(
kIsWeb ? 'Choose a file' : 'Choose from gallery',
),
title: const Text('Choose from gallery'),
onTap: () => Navigator.of(sheetContext).pop(ImageSource.gallery),
),
],
@ -93,11 +86,16 @@ class PhotoAttachField extends StatelessWidget {
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: AttachedImage(
path: path,
child: Image.file(
File(path),
width: thumbnailSize,
height: thumbnailSize,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) => SizedBox(
width: thumbnailSize,
height: thumbnailSize,
child: const Icon(Icons.broken_image),
),
),
),
);

1
app/linux/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
flutter/ephemeral

128
app/linux/CMakeLists.txt Normal file
View File

@ -0,0 +1,128 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "diet_guard_app")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "com.kuhy.diet_guard_app")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Load bundled libraries from the lib/ directory relative to the binary.
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Define build configuration options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()

View File

@ -0,0 +1,88 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.10)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
# which isn't available in 3.10.
function(list_prepend LIST_NAME PREFIX)
set(NEW_LIST "")
foreach(element ${${LIST_NAME}})
list(APPEND NEW_LIST "${PREFIX}${element}")
endforeach(element)
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
endfunction()
# === Flutter Library ===
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"fl_basic_message_channel.h"
"fl_binary_codec.h"
"fl_binary_messenger.h"
"fl_dart_project.h"
"fl_engine.h"
"fl_json_message_codec.h"
"fl_json_method_codec.h"
"fl_message_codec.h"
"fl_method_call.h"
"fl_method_channel.h"
"fl_method_codec.h"
"fl_method_response.h"
"fl_plugin_registrar.h"
"fl_plugin_registry.h"
"fl_standard_message_codec.h"
"fl_standard_method_codec.h"
"fl_string_codec.h"
"fl_value.h"
"fl_view.h"
"flutter_linux.h"
)
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
target_link_libraries(flutter INTERFACE
PkgConfig::GTK
PkgConfig::GLIB
PkgConfig::GIO
)
add_dependencies(flutter flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CMAKE_CURRENT_BINARY_DIR}/_phony_
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
)

View File

@ -0,0 +1,23 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <file_selector_linux/file_selector_plugin.h>
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
#include <url_launcher_linux/url_launcher_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");
file_selector_plugin_register_with_registrar(file_selector_linux_registrar);
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
}

View File

@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter_linux/flutter_linux.h>
// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_

View File

@ -0,0 +1,27 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
file_selector_linux
flutter_secure_storage_linux
url_launcher_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)

View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

Before

Width:  |  Height:  |  Size: 380 B

After

Width:  |  Height:  |  Size: 380 B

View File

Before

Width:  |  Height:  |  Size: 542 B

After

Width:  |  Height:  |  Size: 542 B

View File

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

View File

Before

Width:  |  Height:  |  Size: 726 B

After

Width:  |  Height:  |  Size: 726 B

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -1,34 +1,34 @@
#!/bin/bash
# ============================================================================
# Install the diet_guard_app launcher icon and .desktop entry for the Linux
# desktop.
# Install the diet_guard_app launcher icon and .desktop entry for the Linux desktop.
#
# The desktop app is a Flutter *web* build shown in a Chrome app window (the
# Linux embedder manages only ~20fps at 4K), so the launcher starts the
# wrapper, which serves the build and opens the browser.
# Flutter's GTK runner has no icon of its own: my_application.cc calls
# gtk_window_set_icon_name("diet-guard-app"), which resolves through the hicolor icon
# theme. This script is what puts the icon into that theme, plus a .desktop
# entry so the app appears in application menus.
#
# Icon PNGs are pre-rendered and committed under desktop/icons/, so this script
# Icon PNGs are pre-rendered and committed under linux/icons/, so this script
# needs no image tooling at run time. Regenerate them with:
# PYTHONPATH=~/testsAndMisc python3 -m python_pkg.app_icons \
# generate --app diet_guard_app --linux-out desktop/icons
# generate --app diet_guard_app --linux-out linux/icons
# ============================================================================
set -euo pipefail
SCRIPT_NAME="$(basename "$0")"
DESKTOP_SRC_DIR="$(cd "$(dirname "$0")" && pwd)"
readonly SCRIPT_NAME DESKTOP_SRC_DIR
LINUX_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_DIR="$(dirname "$LINUX_DIR")"
readonly SCRIPT_NAME LINUX_DIR REPO_DIR
readonly ICON_NAME="diet-guard-app"
# Chrome sets WM_CLASS from --class, which the wrapper passes explicitly.
# Without it the window inherits the browser's own class and the taskbar shows
# a browser icon instead of this app's.
readonly WM_CLASS="diet_guard_app"
readonly ICON_SRC_DIR="$DESKTOP_SRC_DIR/icons"
readonly BINARY_NAME="diet_guard_app"
# GTK derives WM_CLASS from the GApplication id in linux/CMakeLists.txt,
# not from the binary name; verified with xprop on the running window.
readonly WM_CLASS="com.kuhy.diet_guard_app"
readonly ICON_SRC_DIR="$LINUX_DIR/icons"
readonly ICON_THEME_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor"
readonly DESKTOP_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
# Installed by install_arch.sh; the repo copy is only used for development.
readonly LAUNCHER="/usr/bin/diet-guard-app"
readonly BUNDLE_BIN="$REPO_DIR/build/linux/x64/release/bundle/$BINARY_NAME"
usage() {
echo "Usage: $SCRIPT_NAME"
@ -79,7 +79,7 @@ install_desktop_entry() {
Type=Application
Name=diet guard
Comment=Diet logging and budget companion
Exec=$LAUNCHER
Exec=$BUNDLE_BIN
Icon=$ICON_NAME
Terminal=false
Categories=Utility;
@ -97,9 +97,9 @@ main() {
install_desktop_entry
echo "Installed $ICON_NAME icon into $ICON_THEME_DIR"
echo "Installed $DESKTOP_DIR/$ICON_NAME.desktop"
if [[ ! -x "$LAUNCHER" ]]; then
echo "Note: $LAUNCHER does not exist yet."
echo " Run 'bash install_arch.sh' to make the entry launchable."
if [[ ! -x "$BUNDLE_BIN" ]]; then
echo "Note: $BUNDLE_BIN does not exist yet."
echo " Run 'flutter build linux --release' to make the entry launchable."
fi
}

View File

@ -0,0 +1,26 @@
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the application ID.
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Add dependency libraries. Add any application-specific dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")

6
app/linux/runner/main.cc Normal file
View File

@ -0,0 +1,6 @@
#include "my_application.h"
int main(int argc, char** argv) {
g_autoptr(MyApplication) app = my_application_new();
return g_application_run(G_APPLICATION(app), argc, argv);
}

View File

@ -0,0 +1,153 @@
#include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Called when first Flutter frame received.
static void first_frame_cb(MyApplication* self, FlView* view) {
gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));
}
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen* screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "diet_guard_app");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
} else {
gtk_window_set_title(window, "diet_guard_app");
}
gtk_window_set_default_size(window, 1280, 720);
// Resolved from the hicolor icon theme, which linux/install_desktop_entry.sh
// populates from linux/icons/. Without this the GTK runner shows a generic
// placeholder in the taskbar, since Flutter never sets a window icon itself.
gtk_window_set_icon_name(window, "diet-guard-app");
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(
project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
GdkRGBA background_color;
// Background defaults to black, override it here if necessary, e.g. #00000000
// for transparent.
gdk_rgba_parse(&background_color, "#000000");
fl_view_set_background_color(view, &background_color);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
// Show the window when Flutter renders.
// Requires the view to be realized so we can start rendering.
g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb),
self);
gtk_widget_realize(GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application,
gchar*** arguments,
int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GApplication::startup.
static void my_application_startup(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application startup.
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
}
// Implements GApplication::shutdown.
static void my_application_shutdown(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application shutdown.
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line =
my_application_local_command_line;
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
// Set the program name to the application ID, which helps various systems
// like GTK and desktop environments map this running application to its
// corresponding .desktop file. This ensures better integration by allowing
// the application to be recognized beyond its binary name.
g_set_prgname(APPLICATION_ID);
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID, "flags",
G_APPLICATION_NON_UNIQUE, nullptr));
}

View File

@ -0,0 +1,21 @@
#ifndef FLUTTER_MY_APPLICATION_H_
#define FLUTTER_MY_APPLICATION_H_
#include <gtk/gtk.h>
G_DECLARE_FINAL_TYPE(MyApplication,
my_application,
MY,
APPLICATION,
GtkApplication)
/**
* my_application_new:
*
* Creates a new Flutter-based application.
*
* Returns: a new #MyApplication.
*/
MyApplication* my_application_new();
#endif // FLUTTER_MY_APPLICATION_H_

View File

@ -94,10 +94,10 @@ packages:
dependency: transitive
description:
name: cross_file
sha256: "92c9c43c383bfa1c32079d3bc492d55d6d4318044b7b47edaff8971cbb555c51"
sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937"
url: "https://pub.dev"
source: hosted
version: "0.3.5+4"
version: "0.3.5+2"
crypto:
dependency: "direct main"
description:
@ -203,10 +203,10 @@ packages:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: "40c6a69189a622bda89ddcf50a139f4ba0f0eb9c0fef6718845b1f8b95452ed6"
sha256: a0d7141f14cabcee42967470a858dfc99dd6cfb70d3cab404bacfcafa9e84e70
url: "https://pub.dev"
source: hosted
version: "22.1.0"
version: "22.0.1"
flutter_local_notifications_linux:
dependency: transitive
description:
@ -219,10 +219,10 @@ packages:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
sha256: "4dfbae10debab9ac975d8b01943fed94c0c19dad43f825964b29f3c3f9a8a852"
sha256: ff0013eae795e8dc8fad4a8992a209e64d3ba2fbd8bf5e43c36bf448f95bd814
url: "https://pub.dev"
source: hosted
version: "12.0.1"
version: "12.0.0"
flutter_local_notifications_web:
dependency: transitive
description:
@ -329,14 +329,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.1.2"
idb_shim:
dependency: "direct main"
description:
name: idb_shim
sha256: "3448298f244bc76a14aca71461eeab6add2b8a877930521c42c2e8b71b644590"
url: "https://pub.dev"
source: hosted
version: "2.9.6+2"
image:
dependency: transitive
description:
@ -349,10 +341,10 @@ packages:
dependency: "direct main"
description:
name: image_picker
sha256: d8402284df184bc05f4a2210c6c23983b0720f4cd87cbd05c5390a78af602667
sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac"
url: "https://pub.dev"
source: hosted
version: "1.2.3"
version: "1.2.2"
image_picker_android:
dependency: transitive
description:
@ -549,10 +541,10 @@ packages:
dependency: transitive
description:
name: path_provider_linux
sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
url: "https://pub.dev"
source: hosted
version: "2.2.2"
version: "2.2.1"
path_provider_platform_interface:
dependency: transitive
description:
@ -665,14 +657,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.6.0"
sembast:
dependency: transitive
description:
name: sembast
sha256: a58b26925e23071cf0f4754d8449aabe829e9a9930a872fb18e6ae4c2c88e025
url: "https://pub.dev"
source: hosted
version: "3.8.9+1"
shared_preferences:
dependency: "direct main"
description:
@ -685,10 +669,10 @@ packages:
dependency: transitive
description:
name: shared_preferences_android
sha256: "0634e64bd719f89c012f392938e173521f535d3ecaf66558fa94a056d22b5cc7"
sha256: "93ae5884a9df5d3bb696825bceb3a17590754548b5d740eba51500afc8d088f5"
url: "https://pub.dev"
source: hosted
version: "2.4.27"
version: "2.4.26"
shared_preferences_foundation:
dependency: transitive
description:
@ -766,14 +750,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.1"
synchronized:
dependency: transitive
description:
name: synchronized
sha256: "93b153dcb6a26dcddee6ca087dd634b53e38c10b5aa163e8e49501a776456153"
url: "https://pub.dev"
source: hosted
version: "3.4.1"
term_glyph:
dependency: transitive
description:
@ -794,10 +770,10 @@ packages:
dependency: transitive
description:
name: timezone
sha256: "981d1020d6ef8fe1e7b3de5054e5b25579ae7c403d7734adc508ffc47668e9cb"
sha256: "784a5e34d2eb62e1326f24d6f600aaaee452eb8ca8ef2f384a59244e292d158b"
url: "https://pub.dev"
source: hosted
version: "0.11.1"
version: "0.11.0"
typed_data:
dependency: transitive
description:
@ -874,10 +850,10 @@ packages:
dependency: "direct main"
description:
name: uuid
sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd"
sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489"
url: "https://pub.dev"
source: hosted
version: "4.6.0"
version: "4.5.3"
vector_math:
dependency: transitive
description:
@ -903,7 +879,7 @@ packages:
source: hosted
version: "15.2.0"
web:
dependency: "direct main"
dependency: transitive
description:
name: web
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"

View File

@ -19,7 +19,6 @@ dependencies:
flutter_local_notifications: ^22.0.1
flutter_secure_storage: ^10.3.1
http: ^1.6.0
idb_shim: ^2.9.6+2
image_picker: ^1.1.2
path: ^1.9.1
path_provider: ^2.1.5
@ -27,7 +26,6 @@ dependencies:
shared_preferences: ^2.5.5
url_launcher: ^6.3.2
uuid: ^4.5.3
web: ^1.1.1
workmanager: ^0.9.0+3
dev_dependencies:

View File

@ -1,31 +0,0 @@
#!/bin/bash
# Builds the web bundle and launches the diet_guard companion app through the
# desktop wrapper, straight out of the repo (no packaging step).
#
# The desktop app is a Flutter *web* build rather than a Linux embedder build:
# the embedder manages only ~20fps at 4K, while the same Dart code in Chrome
# sustains ~144fps.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
log() { echo "==> $*"; }
command -v flutter >/dev/null 2>&1 || {
echo "flutter is not on PATH" >&2
exit 1
}
cd "$SCRIPT_DIR"
flutter config --enable-web >/dev/null
log "fetching pub packages"
flutter pub get
log "building the web bundle"
flutter build web --release
log "launching the app"
exec dart run bin/diet_guard_desktop.dart --web-root "$SCRIPT_DIR/build/web"

View File

@ -1,292 +0,0 @@
// The desktop wrapper is the other half of the web-build desktop app: it
// serves the assets, owns the on-disk mirror of the app's storage, and fronts
// GitHub. These tests drive it over a real loopback socket, since its
// contract is HTTP.
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/desktop/github_proxy.dart';
import 'package:diet_guard_app/desktop/wrapper_server.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:path/path.dart' as p;
void main() {
late Directory tempDir;
late String webRoot;
late String dataDir;
late WrapperServer server;
late List<http.Request> outbound;
late Map<String, http.Response> canned;
Future<void> startServer() async {
outbound = [];
canned = {};
final proxy = GitHubProxy(
tokenPath: p.join(tempDir.path, 'config', 'sync_token'),
fallbackTokenPath: p.join(tempDir.path, 'config', 'fallback_token'),
httpClient: MockClient((request) async {
outbound.add(request);
return canned[request.url.toString()] ??
http.Response('{"ok":true}', 200);
}),
);
server = WrapperServer(
webRoot: webRoot,
dataDir: dataDir,
gitHubProxy: proxy,
);
await server.start(0);
}
Uri url(String path) => Uri.parse('http://localhost:${server.port}$path');
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_wrapper_');
webRoot = p.join(tempDir.path, 'web');
dataDir = p.join(tempDir.path, 'data');
await Directory(webRoot).create(recursive: true);
File(p.join(webRoot, 'index.html')).writeAsStringSync('<html>app</html>');
File(p.join(webRoot, 'main.wasm')).writeAsBytesSync([0, 97, 115, 109]);
await startServer();
});
tearDown(() async {
await server.stop();
await tempDir.delete(recursive: true);
});
group('static assets', () {
test('serves index.html at the root', () async {
final response = await http.get(url('/'));
expect(response.statusCode, 200);
expect(response.body, '<html>app</html>');
expect(response.headers['content-type'], contains('text/html'));
});
test('serves .wasm as application/wasm', () async {
// CanvasKit refuses any other content type and the app then renders
// nothing at all -- the failure looks like a blank window, not an error.
final response = await http.get(url('/main.wasm'));
expect(response.statusCode, 200);
expect(response.headers['content-type'], 'application/wasm');
});
test('404s a missing asset', () async {
expect((await http.get(url('/nope.js'))).statusCode, 404);
});
});
group('document mirror', () {
test('round-trips a document', () async {
final posted = await http.post(
url('/documents/food_log.json'),
body: '{"2026-07-20":[]}',
);
final fetched = await http.get(url('/documents/food_log.json'));
expect(posted.statusCode, 204);
expect(fetched.body, '{"2026-07-20":[]}');
expect(
File(p.join(dataDir, 'documents', 'food_log.json')).readAsStringSync(),
'{"2026-07-20":[]}',
);
});
test('404s an unmirrored document', () async {
expect((await http.get(url('/documents/food_bank.json'))).statusCode, 404);
});
test('rejects a traversing name instead of writing outside dataDir', () {
// The mirror writes into the user's home directory, so a `..` segment
// would turn a document write into an arbitrary-file overwrite.
expect(
http
.post(url('/documents/..%2F..%2Fevil'), body: 'x')
.then((r) => r.statusCode),
completion(400),
);
});
test('rejects a method other than GET/POST', () async {
expect((await http.delete(url('/documents/x.json'))).statusCode, 405);
});
});
group('blob mirror', () {
test('round-trips photo bytes', () async {
final bytes = [1, 2, 3, 4];
final posted = await http.post(url('/blobs/photo.jpg'), body: bytes);
final fetched = await http.get(url('/blobs/photo.jpg'));
expect(posted.statusCode, 204);
expect(fetched.bodyBytes, bytes);
});
});
group('github proxy', () {
test('reports no token before one is stored', () async {
final response = await http.get(url('/github/auth/status'));
expect(jsonDecode(response.body), {'configured': false});
});
test('stores a pasted token and then reports configured', () async {
await http.post(url('/github/auth/token'), body: 'ghp_pasted');
final response = await http.get(url('/github/auth/status'));
expect(jsonDecode(response.body), {'configured': true});
expect(
File(p.join(tempDir.path, 'config', 'sync_token')).readAsStringSync(),
'ghp_pasted',
);
});
test('falls back to the PC gate token when it has none of its own', () async {
// The Python side already keeps a token for diet-guard-sync.timer;
// reusing it is what makes the desktop app need no second setup.
final fallback = File(p.join(tempDir.path, 'config', 'fallback_token'))
..createSync(recursive: true)
..writeAsStringSync('ghp_from_gate\n');
addTearDown(fallback.deleteSync);
final response = await http.get(url('/github/auth/status'));
expect(jsonDecode(response.body), {'configured': true});
});
test('attaches the token to a proxied API call', () async {
await http.post(url('/github/auth/token'), body: 'ghp_stored');
canned['https://api.github.com/repos/kuhyx/syncs'] = http.Response(
'{"name":"syncs"}',
200,
);
final response = await http.get(url('/github/api/repos/kuhyx/syncs'));
expect(response.body, '{"name":"syncs"}');
expect(outbound.single.headers['Authorization'], 'Bearer ghp_stored');
});
test('keeps a device-flow token server-side', () async {
canned['https://github.com/login/oauth/access_token'] = http.Response(
'{"access_token":"ghp_device"}',
200,
);
final response = await http.post(
url('/github/auth/device/poll'),
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
);
// The point of the proxy: the browser is told "ok", never the token.
expect(jsonDecode(response.body), {'status': 'ok'});
expect(response.body, isNot(contains('ghp_device')));
expect(
File(p.join(tempDir.path, 'config', 'sync_token')).readAsStringSync(),
'ghp_device',
);
});
test('passes a still-pending device-flow poll straight back', () async {
canned['https://github.com/login/oauth/access_token'] = http.Response(
'{"error":"authorization_pending"}',
200,
);
final response = await http.post(
url('/github/auth/device/poll'),
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
);
expect(jsonDecode(response.body), {'error': 'authorization_pending'});
});
test('forwards the device-code request with the client id', () async {
canned['https://github.com/login/device/code'] = http.Response(
'{"device_code":"dc","user_code":"ABCD-1234"}',
200,
);
final response = await http.post(
url('/github/auth/device/start'),
body: jsonEncode({'client_id': 'cid'}),
);
expect(jsonDecode(response.body), containsPair('user_code', 'ABCD-1234'));
expect(outbound.single.bodyFields['client_id'], 'cid');
});
test('404s an unknown /github path', () async {
expect((await http.get(url('/github/nope'))).statusCode, 404);
});
test('clears the stored token when handed an empty one', () async {
await http.post(url('/github/auth/token'), body: 'ghp_stored');
await http.post(url('/github/auth/token'), body: '');
expect(jsonDecode((await http.get(url('/github/auth/status'))).body), {
'configured': false,
});
});
test('ignores an unreadable token file rather than failing', () async {
// A directory where the token file should be: readToken must fall
// through to "no token" instead of throwing out of every request.
Directory(p.join(tempDir.path, 'config', 'sync_token'))
.createSync(recursive: true);
expect(jsonDecode((await http.get(url('/github/auth/status'))).body), {
'configured': false,
});
});
test('passes a non-JSON device-flow response straight back', () async {
canned['https://github.com/login/oauth/access_token'] = http.Response(
'<html>rate limited</html>',
200,
);
final response = await http.post(
url('/github/auth/device/poll'),
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
);
expect(response.body, contains('rate limited'));
});
test('treats a malformed request body as empty fields', () async {
final response = await http.post(
url('/github/auth/device/start'),
body: 'not json',
);
expect(response.statusCode, 200);
expect(outbound.single.bodyFields['client_id'], 'null');
});
});
group('content types', () {
test('labels each asset kind the browser is strict about', () {
ContentType typeOf(String name) =>
WrapperServer.contentTypeFor('/web/$name');
expect(typeOf('main.dart.js').toString(), contains('text/javascript'));
expect(typeOf('m.mjs').toString(), contains('text/javascript'));
expect(typeOf('manifest.json').mimeType, 'application/json');
expect(typeOf('style.css').toString(), contains('text/css'));
expect(typeOf('icon.png').mimeType, 'image/png');
expect(typeOf('photo.jpg').mimeType, 'image/jpeg');
expect(typeOf('logo.svg').mimeType, 'image/svg+xml');
expect(typeOf('f.ttf').mimeType, 'font/ttf');
expect(typeOf('f.otf').mimeType, 'font/otf');
expect(typeOf('f.woff2').mimeType, 'font/woff2');
expect(typeOf('data.bin').mimeType, 'application/octet-stream');
});
});
}

View File

@ -1,6 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/screens/calendar_screen.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
@ -30,8 +29,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_calendar_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
await AppSettingsService.initForTesting(tempDir);
});
tearDown(() async {

View File

@ -1,6 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
@ -27,8 +26,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_edit_test_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
});
tearDown(() async {

View File

@ -1,6 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/food_bank_screen.dart';
@ -14,8 +13,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_screen_');
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(testDir: tempDir);
});
tearDown(() async {

View File

@ -1,6 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/screens/photo_viewer_screen.dart';
@ -13,7 +12,7 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_history_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
});
tearDown(() async {

View File

@ -3,7 +3,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
@ -21,8 +20,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_autosync_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
});
tearDown(() async {

View File

@ -1,7 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/blob_store_io.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
@ -135,10 +133,10 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_screen_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
PhotoAttachService.resetForTesting(store: FileBlobStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
PhotoAttachService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(testDir: tempDir);
originalImagePickerPlatform = ImagePickerPlatform.instance;
});

View File

@ -1,7 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/blob_store_io.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/screens/meal_builder_screen.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
@ -30,9 +28,9 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_builder_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
PhotoAttachService.resetForTesting(store: FileBlobStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
PhotoAttachService.resetForTesting(testDir: tempDir);
originalImagePickerPlatform = ImagePickerPlatform.instance;
});

View File

@ -1,7 +1,6 @@
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/screens/settings_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
@ -44,9 +43,9 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_settings_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(testDir: tempDir);
SharedPreferences.setMockInitialValues({});
installFakeSecureStorage();
});

View File

@ -1,7 +1,6 @@
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:flutter_test/flutter_test.dart';
@ -29,12 +28,12 @@ void main() {
group('resetForTesting', () {
test('with testDir creates a working instance', () {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
expect(AppSettingsService.instance, isNotNull);
});
test('without testDir nulls the singleton', () {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting();
// instance getter throws when null — verify via dailyKcalGoal fallback.
expect(AppSettingsService.dailyKcalGoal, 2200);
@ -43,7 +42,7 @@ void main() {
group('init early-return', () {
test('returns existing instance without re-initialising', () async {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
final first = AppSettingsService.instance;
// init() sees _instance != null and returns early (no platform channel).
final second = await AppSettingsService.init();
@ -53,7 +52,7 @@ void main() {
group('saveDailyKcalGoal', () {
test('updates in-memory value and persists to file', () async {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
await AppSettingsService.instance.saveDailyKcalGoal(1800);
expect(AppSettingsService.dailyKcalGoal, 1800);
@ -66,7 +65,7 @@ void main() {
});
test('stamps a fresh dailyKcalGoalUpdatedAt', () async {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
final before = DateTime.now();
await AppSettingsService.instance.saveDailyKcalGoal(1800);
final after = DateTime.now();
@ -82,7 +81,7 @@ void main() {
test(
'persists the given value and updatedAt verbatim, not "now"',
() async {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
final winningEdit = DateTime.utc(2020);
await AppSettingsService.instance.applySyncedBudget(
@ -106,7 +105,7 @@ void main() {
);
test('a null updatedAt is accepted and persisted as null', () async {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
await AppSettingsService.instance.applySyncedBudget(1700);
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
});
@ -118,13 +117,13 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.dailyKcalGoal, 1600);
});
test('keeps default 2200 when file does not exist', () async {
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.dailyKcalGoal, 2200);
});
@ -134,7 +133,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString('not json at all');
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.dailyKcalGoal, 2200);
});
@ -144,7 +143,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode([1, 2, 3]));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.dailyKcalGoal, 2200);
});
@ -154,7 +153,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode({'daily_kcal_goal': 'two thousand'}));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.dailyKcalGoal, 2200);
});
@ -167,7 +166,7 @@ void main() {
}),
);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(
AppSettingsService.dailyKcalGoalUpdatedAt,
@ -182,7 +181,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
},
@ -198,7 +197,7 @@ void main() {
}),
);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
},
@ -213,7 +212,7 @@ void main() {
}),
);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.rewardLabel, 'Podcast');
expect(AppSettingsService.rewardUrl, 'https://example.com/podcast');
@ -224,7 +223,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.rewardLabel, isNull);
expect(AppSettingsService.rewardUrl, isNull);
@ -239,7 +238,7 @@ void main() {
}),
);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(tempDir);
expect(AppSettingsService.rewardLabel, isNull);
expect(AppSettingsService.rewardUrl, isNull);
@ -255,7 +254,7 @@ void main() {
group('saveReward', () {
test('persists label and url, readable back via static getters', () async {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
await AppSettingsService.instance.saveReward(
label: 'Podcast',
url: 'https://example.com/podcast',
@ -273,7 +272,7 @@ void main() {
});
test('clears fields back to null when saved as null', () async {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
await AppSettingsService.instance.saveReward(
label: 'Podcast',
url: 'https://example.com/podcast',
@ -285,7 +284,7 @@ void main() {
});
test('does not disturb the existing kcal goal fields', () async {
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
await AppSettingsService.instance.saveDailyKcalGoal(1800);
await AppSettingsService.instance.saveReward(
label: 'Podcast',

View File

@ -1,15 +1,13 @@
// `checkAndNotify` is the scheduler-independent half of the periodic
// `checkAndNotify` is the unit-testable half of the WorkManager periodic
// check; `backgroundCheckCallbackDispatcher` itself is integration-only
// (real WorkManager isolate, manual on-device smoke test) per the project
// plan, and is excluded from coverage.
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/background_check_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/notification_backend_io.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
@ -33,10 +31,10 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_bg_check_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
notificationLog = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
plugin: FlutterLocalNotificationsPlugin(),
);
});

View File

@ -5,7 +5,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
@ -23,12 +22,12 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_bg_sync_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
// Pre-seeds the singleton so backgroundSyncPush's own AppSettingsService
// .init() call short-circuits instead of hitting the real (unmocked in
// this test) path_provider channel.
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(testDir: tempDir);
});
tearDown(() async {

View File

@ -1,65 +0,0 @@
// Photo bytes went behind a BlobStore when the desktop target became a web
// build: Android keeps files, the browser keeps IndexedDB entries. These
// tests pin the file backend, which is what the phone actually runs.
import 'dart:io';
import 'dart:typed_data';
import 'package:diet_guard_app/services/blob_store_io.dart';
import 'package:diet_guard_app/services/photo_attach_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
void main() {
late Directory tempDir;
late FileBlobStore store;
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_blob_');
store = FileBlobStore(tempDir);
});
tearDown(() async => tempDir.delete(recursive: true));
test('put writes under images/ with the given extension', () async {
final key = await store.put('.jpg', Uint8List.fromList([1, 2, 3]));
expect(key, startsWith(p.join(tempDir.path, 'images')));
expect(key, endsWith('.jpg'));
expect(File(key).readAsBytesSync(), [1, 2, 3]);
});
test('put gives each blob its own key', () async {
final first = await store.put('.jpg', Uint8List.fromList([1]));
final second = await store.put('.jpg', Uint8List.fromList([2]));
expect(first, isNot(second));
});
test('get returns the stored bytes', () async {
final key = await store.put('.png', Uint8List.fromList([9, 8]));
expect(await store.get(key), [9, 8]);
});
test('get returns null for a photo that is gone', () async {
// The entry outlives its file when the user clears app storage; the UI
// shows a broken-image icon rather than failing to build.
expect(await store.get(p.join(tempDir.path, 'images', 'missing.jpg')), null);
});
test('get returns null when the path is not a readable file', () async {
final directoryPath = p.join(tempDir.path, 'a_directory')..toString();
Directory(directoryPath).createSync();
expect(await store.get(directoryPath), null);
});
test('PhotoAttachService.readBytes reads through its store', () async {
// Backs the web image widget, which cannot render from a path.
PhotoAttachService.resetForTesting(store: store);
addTearDown(PhotoAttachService.resetForTesting);
final key = await store.put('.jpg', Uint8List.fromList([4, 5]));
expect(await PhotoAttachService.instance.readBytes(key), [4, 5]);
});
}

View File

@ -1,6 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/meal_component.dart';
@ -130,8 +129,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_bank_');
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(testDir: tempDir);
});
tearDown(() async {
@ -190,8 +189,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_manual_');
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(testDir: tempDir);
});
tearDown(() async {
@ -339,8 +338,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_err_');
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(testDir: tempDir);
});
tearDown(() async {

View File

@ -1,6 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/meal_component.dart';
@ -22,7 +21,7 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_test_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
});
tearDown(() async {

View File

@ -1,4 +1,3 @@
import 'package:diet_guard_app/services/notification_backend_io.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
@ -22,7 +21,7 @@ void main() {
test('init calls the platform initialize method, idempotently', () async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
plugin: FlutterLocalNotificationsPlugin(),
);
await NotificationService.init();
@ -34,7 +33,7 @@ void main() {
test('requestPermission delegates to the Android implementation', () async {
installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
plugin: FlutterLocalNotificationsPlugin(),
);
await NotificationService.init();
@ -44,7 +43,7 @@ void main() {
test('syncToSlots shows due slots and cancels the rest', () async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
plugin: FlutterLocalNotificationsPlugin(),
);
await NotificationService.init();
log.clear();
@ -66,7 +65,7 @@ void main() {
test('syncToSlots with no due slots cancels every known slot', () async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
plugin: FlutterLocalNotificationsPlugin(),
);
await NotificationService.init();
log.clear();
@ -82,9 +81,7 @@ void main() {
() async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(
FlutterLocalNotificationsPlugin(),
),
plugin: FlutterLocalNotificationsPlugin(),
);
await NotificationService.init();

View File

@ -1,6 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/blob_store_io.dart';
import 'package:diet_guard_app/services/photo_attach_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker/image_picker.dart';
@ -27,7 +26,7 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_photo_');
originalPlatform = ImagePickerPlatform.instance;
PhotoAttachService.resetForTesting(store: FileBlobStore(tempDir));
PhotoAttachService.resetForTesting(testDir: tempDir);
});
tearDown(() async {

View File

@ -7,7 +7,6 @@
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/nutrition.dart';
@ -122,9 +121,9 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_sync_test_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
await AppSettingsService.initForTesting(tempDir);
});
tearDown(() async {

View File

@ -1,6 +1,5 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/main.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
@ -11,8 +10,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_app_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
});
tearDown(() async {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 917 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

View File

@ -1,46 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
This is a placeholder for base href that will be replaced by the value of
the `--base-href` argument provided to `flutter build`.
-->
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="diet_guard_app">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>diet_guard_app</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!--
You can customize the "flutter_bootstrap.js" script.
This is useful to provide a custom configuration to the Flutter loader
or to give the user feedback during the initialization process.
For more details:
* https://docs.flutter.dev/platform-integration/web/initialization
-->
<script src="flutter_bootstrap.js" async></script>
</body>
</html>

View File

@ -1,35 +0,0 @@
{
"name": "diet_guard_app",
"short_name": "diet_guard_app",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A new Flutter project.",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "icons/Icon-maskable-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "icons/Icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}