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:
commit
fb3c01cdd7
333 changed files with 45151 additions and 0 deletions
8
server/.gitignore
vendored
Normal file
8
server/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
config.php
|
||||
data/
|
||||
app/
|
||||
|
||||
# Syncthing, if you sync the source between computers
|
||||
.stignore
|
||||
.stfolder
|
||||
food/
|
||||
109
server/PROTOCOL.md
Normal file
109
server/PROTOCOL.md
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
# dash-sync protocol, version 1
|
||||
|
||||
How the dashboard and the app keep their own copies of the data in step through this
|
||||
server. The server is a mailbox: it stores encrypted batches in order and hands them out; it can't
|
||||
read them and never merges anything. Every device does the merging itself, the same way.
|
||||
|
||||
Reference implementation: `dashboard/sync.py` (client) + `dashboard/syncdb.py` (stamps and merging).
|
||||
|
||||
## Devices, accounts, tokens
|
||||
|
||||
- An **account** is one person's data (e.g. `me`). A **device** belongs to one account and has a
|
||||
name (`dashboard`, `phone`) and a secret **token** (`php bin/admin.php add-device me phone`).
|
||||
- Every request: `Authorization: Bearer <token>`, over HTTPS.
|
||||
- Each device also makes itself a random **device id** (12 hex characters) when it first starts.
|
||||
It goes into every change it makes (`d`) and every batch (`dev`); it is not the server's device name.
|
||||
|
||||
## HTTP
|
||||
|
||||
| Request | Answer |
|
||||
|---|---|
|
||||
| `GET /v1/hello` | `{"account", "device", "latest", "server": "dash-sync/1"}` — `device` = the server's name for you |
|
||||
| `GET /v1/key` | the wrapped data key (JSON below); `404` until the first device sets it |
|
||||
| `PUT /v1/key` | store it; `409` if there is one — `PUT /v1/key?replace=1` to change the passphrase (only the device that set it: `403` otherwise; the old one is kept on the server) |
|
||||
| `POST /v1/batches` | body = one encrypted batch (`application/octet-stream`, ≤ 8 MB) → `{"seq"}`; `507` when the account is full |
|
||||
| `GET /v1/batches?after=N&limit=50` | `{"batches": [{"seq", "device", "at", "size", "blob"}], "latest"}`, oldest first, `blob` base64; fewer than `limit` when they're big (≤ 32 MB an answer): ask again until empty |
|
||||
| `GET /v1/devices` | `{"devices": [{"name", "created", "last_seen", "revoked", "you", "manager"}], "manager"}` — `manager` = the device that set the key (it may manage the others) |
|
||||
| `POST /v1/devices` | `{"name"}` → `{"name", "token"}`, the new device's token, shown once; the managing device only (`403`), `409` = name taken (a revoked one is reused) |
|
||||
| `POST /v1/devices/revoke` | `{"name"}` → its token stops working; the managing device only, not itself |
|
||||
| `GET /v1/app` | the newest phone app build `{"version", "build", "size", "sha256", "published", "notes"}`, 404 = none |
|
||||
| `GET /v1/app/apk` | that APK (`application/vnd.android.package-archive`); uploaded over SSH by `app/tool/publish.sh` |
|
||||
| `GET /v1/food/search?q=…` | `{"items": [food]}` from the Open Food Facts archive — `q` (every word a prefix of the name / brand / category, ≥ 3 letters unless a filter is given), `brand`, `country` (a name or `ro` / `sk` / `de` …), `category`, `nutriscore` (`a`, `ab` …), `barcode` (exact; merged duplicates' barcodes too), `limit` ≤ 50. A food = the dashboard's shape (`ref` "usda:ID", `kind` "off", `per100`, `portions` [{label, grams}], brand, barcode, countries, nutriscore, nova, allergens, labels, ingredients) + the added-sugar facts `sugars_in`, `dairy`, `added_sugar` (the clients' sugar.py / sugar.dart decide). Not account data: any device may search |
|
||||
| `GET /v1/food/info` | `{"products", "built", "source"}`; 404 = no archive uploaded (`food/off-archive.db`, built by the dashboard's `plugins/food/off.py --archive`) |
|
||||
|
||||
Errors: `{"error": "…"}` with 400 / 401 / 403 / 404 / 409 / 413 / 500 / 507.
|
||||
|
||||
## Keys
|
||||
|
||||
- **Data key**: 32 random bytes, made once by the first device. Everything is encrypted with it.
|
||||
Devices keep it locally (the Pi: `dash_data/sync/state.json`, chmod 600; the app: the platform's
|
||||
secure storage).
|
||||
- **Wrapped key** (on the server, so a new device can join with the passphrase):
|
||||
|
||||
```json
|
||||
{"v": 1, "kdf": "argon2id13", "ops": 3, "mem": 67108864,
|
||||
"salt": "<16 bytes, base64>", "nonce": "<24 bytes, base64>", "box": "<base64>"}
|
||||
```
|
||||
`kek = Argon2id(passphrase UTF-8, salt, opslimit=ops, memlimit=mem, 32 bytes)` (libsodium
|
||||
`crypto_pwhash`, ALG_ARGON2ID13); `box = XChaCha20-Poly1305-IETF(kek, nonce, data key, ad = "dash-sync/key/1")`.
|
||||
Optional `"check"`: a sealed batch-format blob (`"DS1\0"` + nonce + ciphertext) of the bytes `ok` under the data key with
|
||||
ad = `"dash-sync/key-check/1"` (base64) — lets a device test a recovery key without the passphrase. Wrapped keys
|
||||
made before it have none; a device writing the key adds it.
|
||||
- **Recovery key**: the data key itself in base32 (RFC 4648, no padding), in groups of 4 with
|
||||
dashes. With it a device can wrap the key again under a new passphrase.
|
||||
|
||||
## A batch
|
||||
|
||||
On the wire: `"DS1\0"` (4 bytes) + nonce (24 random bytes) +
|
||||
`XChaCha20-Poly1305-IETF(data key, nonce, plaintext, ad = "dash-sync/1/<account>")`.
|
||||
|
||||
Plaintext = zlib (deflate, RFC 1950) of UTF-8 JSON:
|
||||
|
||||
```json
|
||||
{"v": 1, "dev": "aa5403e5376a", "made": 1792482314874, "changes": [
|
||||
{"t": "food.entry", "u": "91019d2e…", "h": 1792482314899, "d": "aa5403e5376a",
|
||||
"row": {"day": "2026-10-20", "meal": "snack", "name": "Apple", "kcal": 60, "my_food_id": "0aef8cce…", …}},
|
||||
{"t": "food.entry", "u": "91019d2e…", "h": 1792482314917, "d": "aa5403e5376a", "del": true}
|
||||
]}
|
||||
```
|
||||
|
||||
- `t` = `<plugin>.<table>`; `u` = the row's id (`_uid`); `h` = its change stamp (`_hlc`); `d` = the device that made the change.
|
||||
- `row` = every column but the local integer id; foreign keys (`refs`) and ids inside text
|
||||
(`refs_in`, e.g. `"my:~<uid>"` in a meal's recipe) are already ids — see each plugin's
|
||||
`META["sync"]` for which columns. Columns a device doesn't know are ignored.
|
||||
- At most 2000 changes a batch; a device sends its changes since its last send, in stamp order.
|
||||
|
||||
## Merging (every device, the same rules)
|
||||
|
||||
- **Stamps** (`h`): milliseconds since 1970, but each new local stamp = max(now, last stamp + 1),
|
||||
and on receiving, the local clock moves up to the highest stamp seen. So stamps keep their order
|
||||
even if a device's clock is off.
|
||||
- **Last change wins**, per row: apply a change only if `(h, d)` is greater than the local row's
|
||||
`(_hlc, _dev)` (compare `h` first, then `d` as text). Otherwise skip it.
|
||||
- **Deletes** (`del`): keep a marker (table, id, h, d). Delete the local row if the marker wins over
|
||||
it. A row change that doesn't win over a marker for its id is skipped (it was deleted later
|
||||
elsewhere); a newer one brings the row back.
|
||||
- **Order inside a batch**: tables in the order the plugin lists them; rows whose reference (a
|
||||
parent node, a meal's ingredient) isn't there yet wait for another round; then the deletes.
|
||||
- **Natural ids**: some rows have an id made from what they are (`day:2026-10-07`,
|
||||
`measure:2026-10-17`, `src:<import id>`, `<node id>:<date>` for rates) so two devices making
|
||||
"the same" row agree on it.
|
||||
- **Reading**: page through `GET /v1/batches?after=<last seq read>` until it's empty; skip
|
||||
batches your own device sent (`dev`); remember the last `seq` only after a batch is applied
|
||||
(applying again is harmless).
|
||||
|
||||
## What syncs (dashboard v1)
|
||||
|
||||
| Table | Id |
|
||||
|---|---|
|
||||
| `food.food` (My foods + meals) | random |
|
||||
| `food.entry` (the diary) | `src:<src_id>` for imports, else random |
|
||||
| `cycle.day` | `day:<date>` |
|
||||
| `health.measure` | `measure:<date>` |
|
||||
| `health.vital` | `vital:<time>` for imports, else random |
|
||||
| `health.layout` | `layout:<owner>:<tab>` |
|
||||
| `workload.node`, `workload.entry` | random |
|
||||
| `workload.rate` | `<node id>:<since>` |
|
||||
|
||||
Planned: Health summaries from the Pi (nights, steps, heart-rate days, workouts — Pi → app only),
|
||||
snapshots so a new device needn't replay every batch.
|
||||
53
server/README.md
Normal file
53
server/README.md
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
# The sync server (dash-sync)
|
||||
|
||||
A mailbox for the dashboard's sync. Devices (dashboards, phones) send it encrypted batches of changes and
|
||||
read each other's, in order. It can't read them: the key is made on the first dashboard and never leaves
|
||||
the devices. Plain PHP and SQLite, no daemon, about 500 lines.
|
||||
|
||||
You only need it to sync with the phone app or between two dashboards. The dashboard works without it.
|
||||
|
||||
## Set up
|
||||
|
||||
On a Debian / Ubuntu machine with a (sub)domain pointing at it:
|
||||
|
||||
```bash
|
||||
sudo apt install apache2 libapache2-mod-php php-sqlite3 certbot python3-certbot-apache rsync
|
||||
sudo rsync -a server/ /srv/dash-sync/ # outside any other site's folder
|
||||
sudo bash /srv/dash-sync/bin/setup-server.sh sync.example.com me
|
||||
```
|
||||
|
||||
It makes the Apache site and the Let's Encrypt certificate, then the account `me` and its first device,
|
||||
`dashboard`, and prints that device's token **once**. Paste the token into the dashboard's Settings ▸
|
||||
General ▸ Sync. Phones and other dashboards get their tokens from the dashboard as a QR code; you never
|
||||
come back here for them.
|
||||
|
||||
nginx, a shared host, a path instead of a subdomain: [../docs/server.md](../docs/server.md).
|
||||
|
||||
## Files
|
||||
|
||||
```
|
||||
public/index.php the API: the only thing the web server serves
|
||||
public/.htaccess Apache: every request → index.php (mod_rewrite)
|
||||
src/db.php storage: one SQLite file in data/
|
||||
src/food.php the optional food archive search (an Open Food Facts database you add)
|
||||
bin/admin.php accounts and device tokens from the command line
|
||||
bin/setup-server.sh the one-time setup above
|
||||
config.example.php → config.php: quotas, base path, the food archive
|
||||
PROTOCOL.md the API and the encryption, for writing another client
|
||||
```
|
||||
|
||||
## What it keeps
|
||||
|
||||
- **Per account:**
|
||||
- The wrapped data key: the key encrypted with your passphrase (Argon2id), plus a check value.
|
||||
- The devices: names, and their tokens' SHA-256 hashes.
|
||||
- The batches: encrypted blobs with a sequence number, the device name and the time.
|
||||
- **Never:** the passphrase, the key itself, or any of your data in a readable form.
|
||||
|
||||
Quotas (`max_account_bytes`, default 1 GB) and the answer size are in `config.php`. Batches aren't
|
||||
pruned yet (see the issues).
|
||||
|
||||
## Check it
|
||||
|
||||
`tests/server-setup.sh` (from the repo root, needs Docker) runs this setup in a clean Debian container and
|
||||
checks the result: no token → 401, the printed token works, `data/` is not reachable.
|
||||
72
server/bin/admin.php
Normal file
72
server/bin/admin.php
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
// Accounts and device tokens, on the server's command line:
|
||||
//
|
||||
// php bin/admin.php add-account <name>
|
||||
// php bin/admin.php add-device <account> <device name> prints the token once (only its hash is kept)
|
||||
// php bin/admin.php list
|
||||
// php bin/admin.php revoke <account> <device name>
|
||||
// php bin/admin.php stats
|
||||
declare(strict_types=1);
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
exit(1);
|
||||
}
|
||||
$config = require __DIR__ . '/../config.php';
|
||||
require __DIR__ . '/../src/db.php';
|
||||
$pdo = open_db($config['db']);
|
||||
$a = $argv;
|
||||
$now = gmdate('c');
|
||||
|
||||
function account_id(PDO $pdo, string $name): int {
|
||||
$st = $pdo->prepare('SELECT id FROM account WHERE name = ?');
|
||||
$st->execute([$name]);
|
||||
$id = $st->fetchColumn();
|
||||
if ($id === false) {
|
||||
fwrite(STDERR, "No account “{$name}”.\n");
|
||||
exit(1);
|
||||
}
|
||||
return (int)$id;
|
||||
}
|
||||
|
||||
switch ($a[1] ?? '') {
|
||||
case 'add-account':
|
||||
if (!isset($a[2]) || !preg_match('/^[a-z0-9_-]{2,40}$/', $a[2])) {
|
||||
exit("Usage: add-account <name> (a-z, 0-9, _ -)\n");
|
||||
}
|
||||
$pdo->prepare('INSERT INTO account (name, created) VALUES (?, ?)')->execute([$a[2], $now]);
|
||||
echo "Account “{$a[2]}” made.\n";
|
||||
break;
|
||||
case 'add-device':
|
||||
if (!isset($a[2], $a[3])) {
|
||||
exit("Usage: add-device <account> <device name>\n");
|
||||
}
|
||||
$acc = account_id($pdo, $a[2]);
|
||||
$token = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
|
||||
$pdo->prepare('INSERT INTO device (account_id, name, token_hash, created) VALUES (?, ?, ?, ?)')
|
||||
->execute([$acc, $a[3], hash('sha256', $token), $now]);
|
||||
echo "Device “{$a[3]}” added to “{$a[2]}”. Its token (shown only now):\n\n {$token}\n\n";
|
||||
break;
|
||||
case 'list':
|
||||
foreach ($pdo->query('SELECT a.name AS account, d.name, d.created, d.last_seen, d.revoked
|
||||
FROM device d JOIN account a ON a.id = d.account_id ORDER BY a.name, d.id') as $r) {
|
||||
printf("%-12s %-20s made %s seen %s%s\n", $r['account'], $r['name'], substr($r['created'], 0, 10),
|
||||
$r['last_seen'] ? substr($r['last_seen'], 0, 16) : 'never', $r['revoked'] ? ' REVOKED' : '');
|
||||
}
|
||||
break;
|
||||
case 'revoke':
|
||||
if (!isset($a[2], $a[3])) {
|
||||
exit("Usage: revoke <account> <device name>\n");
|
||||
}
|
||||
$st = $pdo->prepare('UPDATE device SET revoked = 1 WHERE account_id = ? AND name = ?');
|
||||
$st->execute([account_id($pdo, $a[2]), $a[3]]);
|
||||
echo $st->rowCount() ? "Revoked.\n" : "No such device.\n";
|
||||
break;
|
||||
case 'stats':
|
||||
foreach ($pdo->query('SELECT a.name, COUNT(b.seq) AS n, COALESCE(SUM(b.size), 0) AS bytes, MAX(b.at) AS last
|
||||
FROM account a LEFT JOIN batch b ON b.account_id = a.id GROUP BY a.id') as $r) {
|
||||
printf("%-12s %6d batches %8.1f KB last %s\n", $r['name'], $r['n'], $r['bytes'] / 1024, $r['last'] ?? '—');
|
||||
}
|
||||
break;
|
||||
default:
|
||||
echo "php bin/admin.php add-account <name> | add-device <account> <device> | list | revoke <account> <device> | stats\n";
|
||||
}
|
||||
65
server/bin/setup-server.sh
Normal file
65
server/bin/setup-server.sh
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
#!/bin/bash
|
||||
# One-time setup of the sync server on a Debian/Ubuntu machine with Apache + PHP + certbot, run as
|
||||
# root from the folder the server was copied to (e.g. /srv/dash-sync — anywhere outside other sites):
|
||||
#
|
||||
# sudo bash /srv/dash-sync/bin/setup-server.sh <host name> <account> [<device> …]
|
||||
# sudo bash /srv/dash-sync/bin/setup-server.sh sync.example.com me
|
||||
#
|
||||
# It makes data/ (the web server's, 700), the Apache site (own file, nothing existing is edited),
|
||||
# the Let's Encrypt certificate, the account and its first device (default: dashboard) — whose
|
||||
# token it prints once, here in your terminal only. Phones and other dashboards get theirs from the
|
||||
# dashboard: Settings ▸ General ▸ Devices (a QR code). Safe to run again: existing pieces are left alone.
|
||||
set -euo pipefail
|
||||
[ $# -ge 2 ] || { sed -n '2,10p' "$0"; exit 2; }
|
||||
HOST=$1; ACCOUNT=$2; shift 2
|
||||
if [ $# -gt 0 ]; then DEVICES=("$@"); else DEVICES=(dashboard); fi
|
||||
DIR=$(cd "$(dirname "$0")/.." && pwd)
|
||||
SITE=/etc/apache2/sites-available/dash-sync-$HOST.conf
|
||||
LOGS='${APACHE_LOG_DIR}'
|
||||
|
||||
[ "$(id -u)" = 0 ] || { echo "run it with sudo"; exit 1; }
|
||||
case "$DIR" in /var/www/html|/var/www/html/*) echo "copy it outside another site's folder (e.g. /srv/dash-sync)"; exit 1 ;; esac
|
||||
cd "$DIR"
|
||||
|
||||
[ -f config.php ] || cp config.example.php config.php
|
||||
mkdir -p data
|
||||
chown -R www-data:www-data data
|
||||
chmod 700 data
|
||||
|
||||
if [ ! -f "$SITE" ]; then
|
||||
cat > "$SITE" <<EOF
|
||||
# ── $HOST — dash-sync mailbox (dashboard + phone app; PROTOCOL.md) ──────
|
||||
<VirtualHost *:80>
|
||||
ServerName $HOST
|
||||
DocumentRoot $DIR/public
|
||||
<Directory $DIR/public>
|
||||
AllowOverride All
|
||||
Require all granted
|
||||
</Directory>
|
||||
LimitRequestBody 9437184
|
||||
ErrorLog $LOGS/dash-sync.error.log
|
||||
CustomLog $LOGS/dash-sync.access.log combined
|
||||
</VirtualHost>
|
||||
EOF
|
||||
echo "site written: $SITE"
|
||||
fi
|
||||
a2enmod -q rewrite >/dev/null # public/.htaccess: every request → index.php
|
||||
a2ensite -q "dash-sync-$HOST" >/dev/null
|
||||
apache2ctl configtest
|
||||
systemctl reload apache2
|
||||
|
||||
if [ ! -d /etc/letsencrypt/live/$HOST ]; then
|
||||
certbot --apache -n --redirect -d $HOST
|
||||
fi
|
||||
|
||||
admin() { sudo -u www-data php "$DIR/bin/admin.php" "$@"; }
|
||||
admin add-account "$ACCOUNT" >/dev/null 2>&1 || true # already there on a second run
|
||||
for dev in "${DEVICES[@]}"; do
|
||||
if ! admin list 2>/dev/null | grep -qE "^$ACCOUNT +$dev "; then
|
||||
echo; echo "== token for $dev (shown once — keep it for its setup):"
|
||||
admin add-device "$ACCOUNT" "$dev"
|
||||
fi
|
||||
done
|
||||
|
||||
echo; echo "== check (should say 401 without a token):"
|
||||
curl -s -o /dev/null -w "%{http_code}\n" https://$HOST/v1/hello || echo "not reachable yet (DNS / certificate?)"
|
||||
13
server/config.example.php
Normal file
13
server/config.example.php
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<?php
|
||||
// Copy to config.php and adjust. Keep the database OUTSIDE the web root (only public/ is served).
|
||||
return [
|
||||
'db' => __DIR__ . '/data/sync.db', // the directory must be writable by PHP (the web server's user)
|
||||
'base_path' => '', // the URL prefix if it doesn't live at the root, e.g. '/dash-sync'
|
||||
'max_batch_bytes' => 8 * 1024 * 1024, // also mind PHP's post_max_size / nginx client_max_body_size
|
||||
// 'app_dir' => __DIR__ . '/app', // the phone app's published builds (default: app/ next to this file)
|
||||
// 'food_db' => __DIR__ . '/food/off-archive.db', // the Open Food Facts archive (dashboard: plugins/food/off.py --archive)
|
||||
// 'food_home' => ['romania', 'slovakia'], // food search: these countries' products first (OFF's names)
|
||||
// 'max_account_bytes' => 1024 * 1024 * 1024, // all of an account's batches together (0 = no limit)
|
||||
// 'max_answer_bytes' => 32 * 1024 * 1024, // batches per GET /v1/batches answer, by size
|
||||
// 'key_replace_any' => false, // true: any device of the account may change the passphrase
|
||||
];
|
||||
6
server/public/.htaccess
Normal file
6
server/public/.htaccess
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
# Apache: every request → index.php, and pass the Authorization header through to PHP
|
||||
RewriteEngine On
|
||||
RewriteCond %{HTTP:Authorization} .
|
||||
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteRule ^ index.php [QSA,L]
|
||||
286
server/public/index.php
Normal file
286
server/public/index.php
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
<?php
|
||||
// dash-sync-server: a mailbox for the dashboard's encrypted sync batches (see ../PROTOCOL.md).
|
||||
// It never sees a key: it stores what devices send and hands it to the account's other devices.
|
||||
//
|
||||
// GET /v1/hello who you are + the newest batch number
|
||||
// GET /v1/key the account's wrapped data key (404 until the first device sets it)
|
||||
// PUT /v1/key[?replace=1] store it (replace=1: a new passphrase — only from the device that set it)
|
||||
// POST /v1/batches an encrypted batch (application/octet-stream) → {seq}
|
||||
// GET /v1/batches?after=N&limit=50 batches after N, oldest first (blob base64)
|
||||
// GET /v1/devices the account's devices (+ you, and whether you may manage them)
|
||||
// POST /v1/devices {name} a new device → {name, token} (shown once) — the managing device only
|
||||
// POST /v1/devices/revoke {name} its token stops working — the managing device only
|
||||
// GET /v1/app the newest phone app build: {version, build, size, sha256, published, notes} (404: none)
|
||||
// GET /v1/app/apk that APK (the app updates itself from it — app/tool/publish.sh puts it here)
|
||||
// GET /v1/food/search?q=… the Open Food Facts archive (src/food.php): q, brand, country, category, nutriscore, barcode, limit
|
||||
// GET /v1/food/info the archive: {products, built, source} (404: none uploaded)
|
||||
//
|
||||
// Auth: "Authorization: Bearer <device token>" (bin/admin.php makes tokens; only their SHA-256 is kept).
|
||||
declare(strict_types=1);
|
||||
|
||||
$config = require __DIR__ . '/../config.php';
|
||||
require __DIR__ . '/../src/db.php';
|
||||
require __DIR__ . '/../src/food.php';
|
||||
|
||||
header('Content-Type: application/json');
|
||||
header('Cache-Control: no-store');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
|
||||
function out(int $code, array $body): never {
|
||||
global $pdo, $writing;
|
||||
if (!empty($writing)) { // a POST's / PUT's writes (see "who is asking"): in before the answer
|
||||
$pdo->exec('COMMIT'); // (a raw BEGIN: PDO's inTransaction() doesn't know about it)
|
||||
$writing = false;
|
||||
}
|
||||
http_response_code($code);
|
||||
echo json_encode($body, JSON_UNESCAPED_SLASHES);
|
||||
exit;
|
||||
}
|
||||
|
||||
// the route: /v1/… from PATH_INFO / the rewritten URI (Apache, nginx), or ?r=/v1/… without rewriting
|
||||
$path = $_GET['r'] ?? (parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
|
||||
$base = rtrim($config['base_path'] ?? '', '/');
|
||||
if ($base !== '' && str_starts_with($path, $base)) {
|
||||
$path = substr($path, strlen($base));
|
||||
}
|
||||
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
|
||||
|
||||
try {
|
||||
$pdo = open_db($config['db']);
|
||||
} catch (Throwable $e) {
|
||||
error_log('dash-sync: ' . $e->getMessage());
|
||||
out(500, ['error' => 'storage unavailable']);
|
||||
}
|
||||
|
||||
// ---- who is asking
|
||||
$auth = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
|
||||
if (!preg_match('/^Bearer\s+([A-Za-z0-9_-]{20,})$/', $auth, $m)) {
|
||||
out(401, ['error' => 'missing token']);
|
||||
}
|
||||
$st = $pdo->prepare('SELECT d.id, d.name, d.account_id, a.name AS account FROM device d JOIN account a ON a.id = d.account_id
|
||||
WHERE d.token_hash = ? AND d.revoked = 0');
|
||||
$st->execute([hash('sha256', $m[1])]);
|
||||
$dev = $st->fetch();
|
||||
$st->closeCursor(); // else the read stays open and a write after it is an upgrade (below)
|
||||
if (!$dev) {
|
||||
out(401, ['error' => 'unknown or revoked token']);
|
||||
}
|
||||
// A POST / PUT is one write transaction, its lock taken first (BEGIN IMMEDIATE waits up to busy_timeout). A write
|
||||
// that starts as a read can't wait in WAL mode: it fails at once ("database is locked") when another device's
|
||||
// batch got in between. out() commits. A GET only notes last_seen, and that may be skipped when busy.
|
||||
$writing = false;
|
||||
if ($method !== 'GET') {
|
||||
$pdo->exec('BEGIN IMMEDIATE');
|
||||
$writing = true;
|
||||
}
|
||||
try {
|
||||
$pdo->prepare('UPDATE device SET last_seen = ? WHERE id = ?')->execute([gmdate('c'), $dev['id']]);
|
||||
} catch (PDOException $e) {
|
||||
if ($method !== 'GET') {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
$acc = (int)$dev['account_id'];
|
||||
|
||||
function latest(PDO $pdo, int $acc): int {
|
||||
$st = $pdo->prepare('SELECT COALESCE(MAX(seq), 0) FROM batch WHERE account_id = ?');
|
||||
$st->execute([$acc]);
|
||||
return (int)$st->fetchColumn();
|
||||
}
|
||||
|
||||
// ---- routes
|
||||
if ($path === '/v1/hello' && $method === 'GET') {
|
||||
out(200, ['account' => $dev['account'], 'device' => $dev['name'], 'latest' => latest($pdo, $acc), 'server' => 'dash-sync/1']);
|
||||
}
|
||||
|
||||
if ($path === '/v1/key' && $method === 'GET') {
|
||||
$st = $pdo->prepare('SELECT data FROM keyblob WHERE account_id = ?');
|
||||
$st->execute([$acc]);
|
||||
$k = $st->fetchColumn();
|
||||
if ($k === false) {
|
||||
out(404, ['error' => 'no key yet']);
|
||||
}
|
||||
echo $k;
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($path === '/v1/key' && $method === 'PUT') {
|
||||
$raw = file_get_contents('php://input') ?: '';
|
||||
$k = json_decode($raw, true);
|
||||
if (!is_array($k) || strlen($raw) > 4096 || !isset($k['v'], $k['salt'], $k['nonce'], $k['box'])) {
|
||||
out(400, ['error' => 'not a wrapped key']);
|
||||
}
|
||||
$st = $pdo->prepare('SELECT data, updated, device_id FROM keyblob WHERE account_id = ?');
|
||||
$st->execute([$acc]);
|
||||
$old = $st->fetch();
|
||||
if ($old && ($_GET['replace'] ?? '') !== '1') {
|
||||
out(409, ['error' => 'the account has a key already (replace=1 to change the passphrase)']);
|
||||
}
|
||||
// a lost phone's token mustn't be able to swap the key for every new device: only the device that set it
|
||||
// (or any, with 'key_replace_any' => true in config.php); the old one is kept (keyblob_old)
|
||||
if ($old && (int)$old['device_id'] !== (int)$dev['id'] && empty($config['key_replace_any'])) {
|
||||
out(403, ['error' => 'only the device that set the key can change the passphrase']);
|
||||
}
|
||||
if ($old) {
|
||||
$pdo->prepare('INSERT INTO keyblob_old (account_id, data, updated, device_id, replaced) VALUES (?, ?, ?, ?, ?)')
|
||||
->execute([$acc, $old['data'], $old['updated'], $old['device_id'], gmdate('c')]);
|
||||
}
|
||||
$pdo->prepare('INSERT INTO keyblob (account_id, data, updated, device_id) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(account_id) DO UPDATE SET data = excluded.data, updated = excluded.updated, device_id = excluded.device_id')
|
||||
->execute([$acc, json_encode($k, JSON_UNESCAPED_SLASHES), gmdate('c'), $dev['id']]);
|
||||
out(200, ['ok' => true]);
|
||||
}
|
||||
|
||||
if ($path === '/v1/batches' && $method === 'POST') {
|
||||
$max = (int)($config['max_batch_bytes'] ?? 8 * 1024 * 1024);
|
||||
$len = (int)($_SERVER['CONTENT_LENGTH'] ?? 0);
|
||||
if ($len > $max) {
|
||||
out(413, ['error' => 'batch too big']);
|
||||
}
|
||||
$blob = file_get_contents('php://input') ?: '';
|
||||
if (strlen($blob) < 45 || strlen($blob) > $max || substr($blob, 0, 4) !== "DS1\0") {
|
||||
out(400, ['error' => 'not a sync batch']);
|
||||
}
|
||||
$quota = (int)($config['max_account_bytes'] ?? 1024 * 1024 * 1024);
|
||||
$st = $pdo->prepare('SELECT COALESCE(SUM(size), 0) FROM batch WHERE account_id = ?');
|
||||
$st->execute([$acc]);
|
||||
if ($quota > 0 && (int)$st->fetchColumn() + strlen($blob) > $quota) {
|
||||
out(507, ['error' => 'the account is full (max_account_bytes in config.php)']);
|
||||
}
|
||||
$st = $pdo->prepare('INSERT INTO batch (account_id, device_id, at, size, blob) VALUES (?, ?, ?, ?, ?)');
|
||||
$st->bindValue(1, $acc, PDO::PARAM_INT);
|
||||
$st->bindValue(2, (int)$dev['id'], PDO::PARAM_INT);
|
||||
$st->bindValue(3, gmdate('c'));
|
||||
$st->bindValue(4, strlen($blob), PDO::PARAM_INT);
|
||||
$st->bindValue(5, $blob, PDO::PARAM_LOB);
|
||||
$st->execute();
|
||||
out(200, ['seq' => (int)$pdo->lastInsertId()]);
|
||||
}
|
||||
|
||||
if ($path === '/v1/batches' && $method === 'GET') {
|
||||
$after = max(0, (int)($_GET['after'] ?? 0));
|
||||
$limit = min(200, max(1, (int)($_GET['limit'] ?? 50)));
|
||||
$st = $pdo->prepare('SELECT b.seq, d.name AS device, b.at, b.size, b.blob FROM batch b JOIN device d ON d.id = b.device_id
|
||||
WHERE b.account_id = ? AND b.seq > ? ORDER BY b.seq LIMIT ' . $limit);
|
||||
$st->execute([$acc, $after]);
|
||||
$rows = [];
|
||||
$bytes = 0;
|
||||
$cap = (int)($config['max_answer_bytes'] ?? 32 * 1024 * 1024); // fewer batches then; clients ask again
|
||||
while ($r = $st->fetch()) {
|
||||
if ($rows && $bytes + (int)$r['size'] > $cap) {
|
||||
break;
|
||||
}
|
||||
$bytes += (int)$r['size'];
|
||||
$blob = is_resource($r['blob']) ? stream_get_contents($r['blob']) : $r['blob'];
|
||||
$rows[] = ['seq' => (int)$r['seq'], 'device' => $r['device'], 'at' => $r['at'], 'size' => (int)$r['size'],
|
||||
'blob' => base64_encode($blob)];
|
||||
}
|
||||
out(200, ['batches' => $rows, 'latest' => latest($pdo, $acc)]);
|
||||
}
|
||||
|
||||
// ---- the phone app's updates: files in app/ next to the code (not served directly), uploaded over SSH by
|
||||
// app/tool/publish.sh — app.json + dash-app.apk. Any device of any account may fetch them (it's the app,
|
||||
// not anyone's data); Android itself refuses an update not signed with the installed app's key.
|
||||
$appDir = rtrim($config['app_dir'] ?? __DIR__ . '/../app', '/');
|
||||
if ($path === '/v1/app' && $method === 'GET') {
|
||||
$j = @file_get_contents($appDir . '/app.json');
|
||||
$info = $j === false ? null : json_decode($j, true);
|
||||
if (!is_array($info) || !is_file($appDir . '/dash-app.apk')) {
|
||||
out(404, ['error' => 'no app published']);
|
||||
}
|
||||
out(200, $info);
|
||||
}
|
||||
|
||||
if ($path === '/v1/app/apk' && $method === 'GET') {
|
||||
$f = $appDir . '/dash-app.apk';
|
||||
if (!is_file($f)) {
|
||||
out(404, ['error' => 'no app published']);
|
||||
}
|
||||
header_remove('Content-Type');
|
||||
header('Content-Type: application/vnd.android.package-archive');
|
||||
header('Content-Length: ' . filesize($f));
|
||||
header('Content-Disposition: attachment; filename="dash-app.apk"');
|
||||
while (ob_get_level()) {
|
||||
ob_end_clean();
|
||||
}
|
||||
readfile($f);
|
||||
exit;
|
||||
}
|
||||
|
||||
// ---- the food archive: a read-only file next to the code (food/off-archive.db, uploaded over SSH — the dashboard's
|
||||
// plugins/food/off.py --archive). Not anyone's data: any device may search it.
|
||||
if (str_starts_with($path, '/v1/food/') && $method === 'GET') {
|
||||
try {
|
||||
$fdb = food_db($config['food_db'] ?? __DIR__ . '/../food/off-archive.db');
|
||||
if (!$fdb) {
|
||||
out(404, ['error' => 'no food archive uploaded']);
|
||||
}
|
||||
if ($path === '/v1/food/info') {
|
||||
out(200, food_info($fdb));
|
||||
}
|
||||
if ($path === '/v1/food/search') {
|
||||
out(200, ['items' => food_search($fdb, $_GET, $config['food_home'] ?? [])]);
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
error_log('dash-sync food: ' . $e->getMessage());
|
||||
out(500, ['error' => 'food search failed']);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the account's devices. The managing device is the one that set the data key (the first dashboard): it may
|
||||
// add devices (the phone's token comes from its Settings ▸ General ▸ Sync as a QR code) and revoke them.
|
||||
function manager(PDO $pdo, int $acc): ?int {
|
||||
$st = $pdo->prepare('SELECT device_id FROM keyblob WHERE account_id = ?');
|
||||
$st->execute([$acc]);
|
||||
$id = $st->fetchColumn();
|
||||
return $id === false || $id === null ? null : (int)$id;
|
||||
}
|
||||
|
||||
function body_json(): array {
|
||||
$raw = file_get_contents('php://input') ?: '';
|
||||
$j = strlen($raw) <= 4096 ? json_decode($raw, true) : null;
|
||||
return is_array($j) ? $j : [];
|
||||
}
|
||||
|
||||
if ($path === '/v1/devices' && $method === 'GET') {
|
||||
$st = $pdo->prepare('SELECT id, name, created, last_seen, revoked FROM device WHERE account_id = ? ORDER BY id');
|
||||
$st->execute([$acc]);
|
||||
$boss = manager($pdo, $acc);
|
||||
$rows = array_map(fn($r) => ['name' => $r['name'], 'created' => $r['created'], 'last_seen' => $r['last_seen'],
|
||||
'revoked' => (int)$r['revoked'], 'you' => (int)$r['id'] === (int)$dev['id'],
|
||||
'manager' => (int)$r['id'] === $boss], $st->fetchAll());
|
||||
out(200, ['devices' => $rows, 'manager' => $boss === (int)$dev['id']]);
|
||||
}
|
||||
|
||||
if (($path === '/v1/devices' || $path === '/v1/devices/revoke') && $method === 'POST') {
|
||||
if (manager($pdo, $acc) !== (int)$dev['id']) {
|
||||
out(403, ['error' => 'only the device that set up the key can manage devices']);
|
||||
}
|
||||
$name = trim((string)(body_json()['name'] ?? ''));
|
||||
if (!preg_match('/^[A-Za-z0-9 ._-]{1,40}$/', $name)) {
|
||||
out(400, ['error' => 'a device name: letters, digits, space . _ - (up to 40)']);
|
||||
}
|
||||
if ($path === '/v1/devices/revoke') {
|
||||
if ($name === $dev['name']) {
|
||||
out(400, ['error' => "a device can't revoke itself"]);
|
||||
}
|
||||
$st = $pdo->prepare('UPDATE device SET revoked = 1 WHERE account_id = ? AND name = ?');
|
||||
$st->execute([$acc, $name]);
|
||||
out($st->rowCount() ? 200 : 404, $st->rowCount() ? ['ok' => true] : ['error' => 'no such device']);
|
||||
}
|
||||
$token = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
|
||||
try {
|
||||
$pdo->prepare('INSERT INTO device (account_id, name, token_hash, created) VALUES (?, ?, ?, ?)')
|
||||
->execute([$acc, $name, hash('sha256', $token), gmdate('c')]);
|
||||
} catch (PDOException $e) { // the name is taken: a revoked one gets the new token
|
||||
$st = $pdo->prepare('UPDATE device SET token_hash = ?, created = ?, last_seen = NULL, revoked = 0
|
||||
WHERE account_id = ? AND name = ? AND revoked = 1');
|
||||
$st->execute([hash('sha256', $token), gmdate('c'), $acc, $name]);
|
||||
if (!$st->rowCount()) {
|
||||
out(409, ['error' => 'there is a device with that name already (revoke it first to replace it)']);
|
||||
}
|
||||
}
|
||||
out(200, ['name' => $name, 'token' => $token]);
|
||||
}
|
||||
|
||||
out(404, ['error' => 'no such endpoint']);
|
||||
55
server/src/db.php
Normal file
55
server/src/db.php
Normal 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
154
server/src/food.php
Normal 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];
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue