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

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

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

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

55
server/src/db.php Normal file
View file

@ -0,0 +1,55 @@
<?php
// The mailbox's storage: one SQLite file (outside the web root — config.php says where).
declare(strict_types=1);
function open_db(string $path): PDO {
$new = !file_exists($path);
$pdo = new PDO('sqlite:' . $path, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 10000; PRAGMA foreign_keys = ON;');
$pdo->exec(<<<SQL
CREATE TABLE IF NOT EXISTS account (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
created TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS device (
id INTEGER PRIMARY KEY,
account_id INTEGER NOT NULL REFERENCES account(id),
name TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE, -- SHA-256 of the token; the token itself is shown once
created TEXT NOT NULL,
last_seen TEXT,
revoked INTEGER NOT NULL DEFAULT 0,
UNIQUE (account_id, name)
);
CREATE TABLE IF NOT EXISTS batch (
seq INTEGER PRIMARY KEY AUTOINCREMENT, -- the order every device reads in
account_id INTEGER NOT NULL REFERENCES account(id),
device_id INTEGER NOT NULL REFERENCES device(id),
at TEXT NOT NULL,
size INTEGER NOT NULL,
blob BLOB NOT NULL -- encrypted; "DS1\\0" + nonce + ciphertext
);
CREATE INDEX IF NOT EXISTS batch_account ON batch (account_id, seq);
CREATE TABLE IF NOT EXISTS keyblob (
account_id INTEGER PRIMARY KEY REFERENCES account(id),
data TEXT NOT NULL, -- the data key wrapped with the passphrase (JSON)
updated TEXT NOT NULL,
device_id INTEGER
);
CREATE TABLE IF NOT EXISTS keyblob_old ( -- earlier wrapped keys (a passphrase change undone by hand)
account_id INTEGER NOT NULL,
data TEXT NOT NULL,
updated TEXT NOT NULL,
device_id INTEGER,
replaced TEXT NOT NULL
);
SQL);
if ($new) {
@chmod($path, 0600);
}
return $pdo;
}

154
server/src/food.php Normal file
View file

@ -0,0 +1,154 @@
<?php
// The food archive: every Open Food Facts product (one read-only SQLite file built by the dashboard's
// plugins/food/off.py --archive, uploaded over SSH next to the code — food/off-archive.db). Searched by
// name / brand, filtered by brand, country, category, Nutri-Score, or found by barcode. A product comes
// back in the dashboard's food shape (fooddb._food: per100, portions …) with the facts its added-sugar
// estimate needs (sugars_in, dairy, added_sugar, nova, labels — the rules are the clients': sugar.py / sugar.dart).
declare(strict_types=1);
const FOOD_COLS = ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'mono_fat', 'poly_fat', 'trans_fat',
'sodium_mg', 'cholesterol_mg', 'potassium_mg'];
const FOOD_STOP = ['with', 'and', 'of', 'a', 'an', 'the', 'in', 'on', 'some', 'my'];
const FOOD_COUNTRY = ['ro' => 'romania', 'sk' => 'slovakia', 'cz' => 'czech republic', 'hu' => 'hungary', 'de' => 'germany',
'at' => 'austria', 'pl' => 'poland', 'fr' => 'france', 'it' => 'italy', 'es' => 'spain', 'uk' => 'united kingdom',
'gb' => 'united kingdom', 'us' => 'united states', 'nl' => 'netherlands', 'be' => 'belgium', 'ch' => 'switzerland'];
function food_db(string $path): ?PDO {
if (!is_file($path)) {
return null;
}
return new PDO('sqlite:' . $path, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::SQLITE_ATTR_OPEN_FLAGS => PDO::SQLITE_OPEN_READONLY,
]);
}
/** Lower case without diacritics (the dashboard's sugar.fold; FTS folds the same way). */
function food_fold(string $s): string {
static $map = null;
if ($map === null) {
$map = ['ß' => 'ss', 'æ' => 'ae', 'œ' => 'oe'];
foreach (['áàâäãåāăą' => 'a', 'çčć' => 'c', 'ďđ' => 'd', 'éèêëěęē' => 'e', 'íìîïī' => 'i', 'ľĺł' => 'l', 'ňńñ' => 'n',
'óòôöõőø' => 'o', 'řŕ' => 'r', 'śšşș' => 's', 'ťţț' => 't', 'úùûüůűū' => 'u', 'ýÿ' => 'y', 'žźż' => 'z'] as $from => $to) {
foreach (mb_str_split($from) as $c) {
$map[$c] = $to;
}
}
}
return strtr(mb_strtolower($s), $map);
}
function food_words(string $q): array {
preg_match_all('/[\p{L}\p{N}]+/u', food_fold($q), $m);
return array_values(array_filter($m[0], fn($w) => (mb_strlen($w) > 1 || ctype_digit($w)) && !in_array($w, FOOD_STOP, true)));
}
/** An FTS5 phrase ("w"), prefix ("w"*) or column filter (col : "w x"*). */
function food_term(string $w, bool $prefix = true, ?string $col = null): string {
$t = '"' . str_replace('"', '""', $w) . '"' . ($prefix ? '*' : '');
return $col ? "$col : $t" : $t;
}
function food_row(array $r): array {
$per100 = [];
foreach (FOOD_COLS as $c) {
$per100[$c] = $r[$c] === null ? null : (float)$r[$c];
}
$portions = [];
foreach (json_decode($r['portions'] ?? 'null', true) ?: [] as [$label, $grams]) {
$portions[] = ['label' => $label, 'grams' => (float)$grams];
}
return ['ref' => 'usda:' . $r['id'], 'kind' => 'off', 'id' => (int)$r['id'], 'name' => $r['name'], 'category' => $r['category'],
'source' => 'off', 'brand' => $r['brand'], 'barcode' => $r['barcode'], 'countries' => $r['countries'],
'nutriscore' => $r['nutriscore'], 'nova' => $r['nova'] === null ? null : (int)$r['nova'],
'allergens' => $r['allergens'], 'labels' => $r['labels'], 'ingredients' => $r['ingredients'],
'sugars_in' => $r['sugars_in'], 'dairy' => $r['dairy'] === null ? null : (int)$r['dairy'],
'added_sugar' => $r['added_sugar'] === null ? null : (float)$r['added_sugar'],
'per100' => $per100, 'portions' => $portions];
}
/**
* GET /v1/food/search: q (every word a prefix of the name / brand / category), brand, country (a name or
* ro / sk / de …), category, nutriscore ("a" or "ab"), barcode (exact, the merged duplicates' too), limit (≤ 50).
* Ranked as the dashboard's fooddb.search: all of q in the name first, home-country products, the name
* starting with the first word, fewer words, FTS relevance (name ≫ brand), shorter names.
*/
function food_search(PDO $db, array $p, array $home = []): array { // $home: config.php 'food_home'
$home = array_map(fn($c) => food_fold((string)$c), $home);
$limit = min(50, max(1, (int)($p['limit'] ?? 20)));
$code = preg_replace('/\D/', '', (string)($p['barcode'] ?? ''));
if ($code !== '') {
$st = $db->prepare('SELECT * FROM food WHERE barcode = ? UNION SELECT f.* FROM alias a JOIN food f ON f.id = a.food_id WHERE a.barcode = ?');
$st->execute([$code, $code]);
return array_map('food_row', $st->fetchAll());
}
$words = food_words((string)($p['q'] ?? ''));
$terms = array_map(fn($w) => food_term($w), $words);
foreach (['brand' => 'brand', 'category' => 'category'] as $k => $col) {
$v = implode(' ', food_words((string)($p[$k] ?? '')));
if ($v !== '') {
$terms[] = food_term($v, true, $col);
}
}
$country = food_fold(trim((string)($p['country'] ?? '')));
$country = FOOD_COUNTRY[$country] ?? str_replace('-', ' ', $country);
if ($country !== '') {
$terms[] = food_term($country, false, 'countries');
}
$grades = array_values(array_intersect(str_split(strtolower((string)($p['nutriscore'] ?? ''))), ['a', 'b', 'c', 'd', 'e']));
if (!$terms || (mb_strlen(implode('', $words)) < 3 && count($terms) === count($words))) {
return []; // at least 3 letters, or a filter
}
$sql = 'SELECT f.*, bm25(food_fts, 10, 3, 1, 0) AS rank FROM food_fts JOIN food f ON f.id = food_fts.rowid WHERE food_fts MATCH ?';
$args = [implode(' ', $terms)];
if ($grades) {
$sql .= ' AND f.nutriscore IN (' . implode(',', array_fill(0, count($grades), '?')) . ')';
array_push($args, ...$grades);
}
$st = $db->prepare($sql . ' ORDER BY rank LIMIT 300');
$st->execute($args);
$rows = $st->fetchAll();
$first = $words[0] ?? '';
$key = function (array $r) use ($words, $first, $home): array {
preg_match_all('/[\p{L}\p{N}]+/u', food_fold($r['name']), $m);
$ws = $m[0];
$lead = $ws[0] ?? '';
$inName = 0;
foreach ($words as $w) {
$hit = false;
foreach ($ws as $x) {
if (str_starts_with($x, $w)) { $hit = true; break; }
}
if (!$hit) { $inName = 1; break; }
}
$exact = $first === '' ? 0 : (in_array($lead, [$first, $first . 's', $first . 'es'], true)
|| in_array($first, [$lead . 's', $lead . 'es'], true) ? 0 : (str_starts_with($lead, $first) ? 1 : 2));
$home = array_intersect(explode(' ', $r['countries']), $home) ? 0 : 1;
return [$inName, $home, $exact, count($ws), round((float)$r['rank'], 1), mb_strlen($r['name'])];
};
$keyed = array_map(fn($r) => [$key($r), $r], $rows);
usort($keyed, fn($a, $b) => $a[0] <=> $b[0]);
$out = [];
$seen = [];
foreach ($keyed as [, $r]) {
$k = food_fold($r['name']) . '|' . food_fold((string)$r['brand']);
if (isset($seen[$k])) {
continue;
}
$seen[$k] = true;
$out[] = food_row($r);
if (count($out) >= $limit) {
break;
}
}
return $out;
}
function food_info(PDO $db): array {
$meta = [];
foreach ($db->query('SELECT k, v FROM meta') as $r) {
$meta[$r['k']] = $r['v'];
}
return ['products' => (int)($meta['products'] ?? 0), 'built' => $meta['off_built'] ?? null, 'source' => $meta['off_source'] ?? null];
}