The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end encrypted sync mailbox (PHP + SQLite) and the Android companion app (Flutter), with docs, clean-install checks and screenshots made from demo data. Built mostly with an AI coding assistant; not yet reviewed line by line by a human (see README and SECURITY.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
226 lines
8.9 KiB
Dart
226 lines
8.9 KiB
Dart
// Every Open Food Facts product (2 million+, every country), searched on the sync server's archive
|
||
// (GET /v1/food/search — sync-server/src/food.php), with filters: country, brand, Nutri-Score; a
|
||
// barcode finds that product. A pick is kept ("food.product", food_model.dart keepProduct) and synced,
|
||
// so entries made from it work on every device. Also the camera barcode scanner (ZXing, no Google services).
|
||
import 'dart:async';
|
||
import 'dart:convert';
|
||
|
||
import 'package:flutter/material.dart';
|
||
import 'package:http/http.dart' as http;
|
||
import 'package:flutter_zxing/flutter_zxing.dart' show Format;
|
||
|
||
import '../app/scanner.dart';
|
||
|
||
import '../app/sync_service.dart';
|
||
import '../app/theme.dart';
|
||
import 'food_model.dart';
|
||
|
||
const _countries = [('', 'Any country'), ('ro', 'Romania'), ('sk', 'Slovakia'), ('cz', 'Czechia'), ('hu', 'Hungary'), ('at', 'Austria'),
|
||
('de', 'Germany'), ('pl', 'Poland'), ('it', 'Italy'), ('fr', 'France'), ('es', 'Spain'), ('uk', 'UK'), ('us', 'USA')];
|
||
const _scores = [('', 'Any Nutri-Score'), ('a', 'A'), ('ab', 'A–B'), ('abc', 'A–C')];
|
||
|
||
/// The archive's search: [q] (or a barcode), filters → its products (as it sends them), or throws a message.
|
||
Future<List<Map<String, dynamic>>> archiveSearch(SyncService sync, Map<String, String> p) async {
|
||
final s = sync.settings;
|
||
final query = {for (final e in p.entries) if (e.value.isNotEmpty) e.key: e.value, 'limit': '25'};
|
||
final uri = Uri.parse('${s.server.replaceAll(RegExp(r'/+$'), '')}/v1/food/search').replace(queryParameters: query);
|
||
final http.Response r;
|
||
try {
|
||
r = await http.get(uri, headers: {'Authorization': 'Bearer ${s.token}', 'Accept': 'application/json'})
|
||
.timeout(const Duration(seconds: 20));
|
||
} catch (_) {
|
||
throw 'The sync server can\'t be reached — no connection?';
|
||
}
|
||
final j = jsonDecode(r.body);
|
||
if (r.statusCode != 200) throw (j is Map ? j['error'] : null) ?? 'Error ${r.statusCode}';
|
||
return ((j as Map)['items'] as List).cast<Map<String, dynamic>>();
|
||
}
|
||
|
||
/// The archive's search sheet → the product picked (kept already), or null.
|
||
Future<Food?> openArchive(BuildContext context, SyncService sync, FoodDb? fdb, String q) => showModalBottomSheet<Food>(
|
||
context: context,
|
||
isScrollControlled: true,
|
||
backgroundColor: card,
|
||
builder: (_) => ArchiveSheet(sync: sync, fdb: fdb, q: q),
|
||
);
|
||
|
||
class ArchiveSheet extends StatefulWidget {
|
||
const ArchiveSheet({super.key, required this.sync, required this.fdb, required this.q});
|
||
final SyncService sync;
|
||
final FoodDb? fdb;
|
||
final String q;
|
||
@override
|
||
State<ArchiveSheet> createState() => _ArchiveSheetState();
|
||
}
|
||
|
||
class _ArchiveSheetState extends State<ArchiveSheet> {
|
||
late final q = TextEditingController(text: widget.q);
|
||
final brand = TextEditingController();
|
||
String country = '', score = '';
|
||
List<Map<String, dynamic>> items = [];
|
||
String? status;
|
||
Timer? timer;
|
||
int seq = 0;
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
_run();
|
||
}
|
||
|
||
@override
|
||
void dispose() {
|
||
timer?.cancel();
|
||
super.dispose();
|
||
}
|
||
|
||
void _soon() {
|
||
timer?.cancel();
|
||
timer = Timer(const Duration(milliseconds: 350), _run);
|
||
}
|
||
|
||
Future<void> _run() async {
|
||
final text = q.text.trim(), n = ++seq;
|
||
final code = RegExp(r'^\d{8,14}$').hasMatch(text);
|
||
if (!code && text.length < 3 && brand.text.trim().isEmpty && country.isEmpty) {
|
||
setState(() {
|
||
items = [];
|
||
status = 'Type at least 3 letters, or pick a filter.';
|
||
});
|
||
return;
|
||
}
|
||
setState(() => status = 'Searching…');
|
||
try {
|
||
final got = await archiveSearch(widget.sync, {
|
||
if (code) 'barcode': text else 'q': text,
|
||
'country': country, 'brand': brand.text.trim(), 'nutriscore': score,
|
||
});
|
||
if (!mounted || n != seq) return;
|
||
setState(() {
|
||
items = got;
|
||
status = got.isEmpty ? 'Nothing found.' : null;
|
||
});
|
||
} catch (e) {
|
||
if (mounted && n == seq) {
|
||
setState(() {
|
||
items = [];
|
||
status = '$e';
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
String _home(String c) {
|
||
final cs = c.split(' ').where((x) => x.isNotEmpty).toList();
|
||
return cs.take(3).map((x) => x[0].toUpperCase() + x.substring(1).replaceAll('-', ' ')).join(', ') + (cs.length > 3 ? ' …' : '');
|
||
}
|
||
|
||
void _pick(Map<String, dynamic> it) {
|
||
final id = (it['id'] as num).toInt();
|
||
final f = widget.fdb?.food(id) ?? keepProduct(widget.sync.store, it); // one you have already: that one
|
||
if (f == null) {
|
||
setState(() => status = 'That product came back garbled.');
|
||
return;
|
||
}
|
||
widget.sync.changed();
|
||
Navigator.of(context).pop(f);
|
||
}
|
||
|
||
Widget _drop(List<(String, String)> opts, String value, void Function(String) set) => DropdownButton<String>(
|
||
value: value,
|
||
isDense: true,
|
||
underline: const SizedBox(),
|
||
dropdownColor: card2,
|
||
items: [for (final (k, l) in opts) DropdownMenuItem(value: k, child: Text(l, style: const TextStyle(fontSize: 13.5)))],
|
||
onChanged: (v) {
|
||
set(v ?? '');
|
||
_run();
|
||
},
|
||
);
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final h = MediaQuery.of(context).size.height;
|
||
return Padding(
|
||
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
|
||
child: ConstrainedBox(
|
||
constraints: BoxConstraints(maxHeight: h * 0.85),
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
|
||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
const Text('All products', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||
const Text('Open Food Facts — every country, through the sync server', style: TextStyle(color: muted, fontSize: 12.5)),
|
||
const SizedBox(height: 6),
|
||
TextField(
|
||
controller: q,
|
||
autofocus: widget.q.isEmpty,
|
||
decoration: InputDecoration(
|
||
prefixIcon: const Icon(Icons.search),
|
||
hintText: 'Name, brand or barcode…',
|
||
suffixIcon: IconButton(
|
||
tooltip: 'Scan a barcode',
|
||
icon: const Icon(Icons.qr_code_scanner),
|
||
onPressed: () async {
|
||
final code = await scanBarcode(context);
|
||
if (code != null) {
|
||
q.text = code;
|
||
_run();
|
||
}
|
||
},
|
||
),
|
||
),
|
||
onChanged: (_) => _soon(),
|
||
onSubmitted: (_) => _run(),
|
||
),
|
||
Wrap(spacing: 12, crossAxisAlignment: WrapCrossAlignment.center, children: [
|
||
_drop(_countries, country, (v) => country = v),
|
||
_drop(_scores, score, (v) => score = v),
|
||
SizedBox(
|
||
width: 120,
|
||
child: TextField(
|
||
controller: brand,
|
||
style: const TextStyle(fontSize: 13.5),
|
||
decoration: const InputDecoration(isDense: true, hintText: 'Brand'),
|
||
onChanged: (_) => _soon(),
|
||
),
|
||
),
|
||
]),
|
||
if (status != null) Padding(padding: const EdgeInsets.only(top: 10), child: Text(status!, style: const TextStyle(color: muted))),
|
||
Flexible(
|
||
child: ListView(shrinkWrap: true, children: [
|
||
for (final it in items)
|
||
ListTile(
|
||
dense: true,
|
||
contentPadding: EdgeInsets.zero,
|
||
title: Text('${it['name']}', maxLines: 1, overflow: TextOverflow.ellipsis),
|
||
subtitle: Text(
|
||
[
|
||
if ('${it['brand'] ?? ''}'.isNotEmpty) '${it['brand']}',
|
||
_home('${it['countries'] ?? ''}'),
|
||
if (widget.fdb?.food((it['id'] as num).toInt()) != null) '✓ you have it',
|
||
].where((x) => x.isNotEmpty).join(' · '),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: const TextStyle(color: muted),
|
||
),
|
||
trailing: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [
|
||
Text('${((it['per100'] as Map?)?['kcal'] as num? ?? 0).round()} kcal', style: const TextStyle(fontSize: 13.5)),
|
||
if (it['nutriscore'] != null)
|
||
Text('Nutri-Score ${'${it['nutriscore']}'.toUpperCase()}', style: const TextStyle(color: muted, fontSize: 11.5)),
|
||
]),
|
||
onTap: () => _pick(it),
|
||
),
|
||
]),
|
||
),
|
||
]),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// The camera, until a product barcode (EAN / UPC) is read → its digits, or null (closed) — app/scanner.dart.
|
||
Future<String?> scanBarcode(BuildContext context) => scanCode(context,
|
||
title: 'Scan a barcode',
|
||
format: Format.ean13 | Format.ean8 | Format.upca | Format.upce,
|
||
accept: (v) => RegExp(r'^\d{8,14}$').hasMatch(v));
|