Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
651d0def2f | ||
|
|
584a95753d | ||
|
|
3ddf9942c2 | ||
|
|
c236120a72 | ||
|
|
ac55520a8c | ||
|
|
a7483164b8 |
No files matched your search
@@ -34,6 +34,9 @@ jobs:
|
|||||||
- run: node tools/backup-test.js # backup restore (unsafe archives refused, old data kept) and personal export
|
- run: node tools/backup-test.js # backup restore (unsafe archives refused, old data kept) and personal export
|
||||||
- run: node tools/listening-test.js # listening stats: real listening counted, seeks not, streak and finished books
|
- run: node tools/listening-test.js # listening stats: real listening counted, seeks not, streak and finished books
|
||||||
- run: node tools/moviefam-test.js # Movies & TV: favorites and the family movie night vote
|
- run: node tools/moviefam-test.js # Movies & TV: favorites and the family movie night vote
|
||||||
|
- run: node tools/pantry-test.js # pantry: counts, low levels, barcodes (several per item), kids can only take
|
||||||
|
- run: node tools/chatextras-test.js # chat: GIFs (family-friendly filter, kept in the chat) and sharing a place
|
||||||
|
- run: node tools/units-test.js # units: reading recipe lines, converting, what a recipe takes out of the pantry
|
||||||
- run: node tools/automations-test.js # automations: validation, triggers, daily cap, privacy
|
- run: node tools/automations-test.js # automations: validation, triggers, daily cap, privacy
|
||||||
|
|
||||||
- run: node tools/signal-test.js # Signal: linking, messages, sending, live updates
|
- run: node tools/signal-test.js # Signal: linking, messages, sending, live updates
|
||||||
|
|||||||
@@ -148,6 +148,7 @@ playing an episode or pressing the button still works. Settings -> Health shows
|
|||||||
|
|
||||||
- **Podcast discovery**: *Add podcast* searches Apple's free directory and, when `PODCASTINDEX_KEY` and `PODCASTINDEX_SECRET` are set (a free key from podcastindex.org), Podcast Index too, with topic buttons (News, History, Science...) that list trending shows. A feed in both appears once.
|
- **Podcast discovery**: *Add podcast* searches Apple's free directory and, when `PODCASTINDEX_KEY` and `PODCASTINDEX_SECRET` are set (a free key from podcastindex.org), Podcast Index too, with topic buttons (News, History, Science...) that list trending shows. A feed in both appears once.
|
||||||
- **Search what's said** (Podcast screen): finds a word or phrase in every transcript on the server and plays that episode from that moment. Only podcasts on your own list (and audiobooks) are searched; older transcripts are matched to their episode the first time.
|
- **Search what's said** (Podcast screen): finds a word or phrase in every transcript on the server and plays that episode from that moment. Only podcasts on your own list (and audiobooks) are searched; older transcripts are matched to their episode the first time.
|
||||||
|
- **Chat extras**: a **GIF** button (with no key it uses Wikimedia Commons through MediaWiki's search API: free animated pictures of animals, nature, space and science; set `TENOR_API_KEY` or `GIPHY_API_KEY` for reaction GIFs instead, or `GIF_PROVIDER=wikimedia|tenor|giphy|off` to choose; the hub does all the talking to the service, asks only for G-rated results, refuses searches and drops results containing words that could bring up adult material, keeps a sent GIF in the chat like a photo, and a sender or admin can delete one that slips through), **Place or location** (your phone's location after it asks, or a place search through OpenStreetMap; shared as a card whose link is an Apple Maps link, `maps.apple.com`, which opens the Maps app on an iPhone or iPad), and the Chat list also shows **Signal** conversations, labelled, on screens where Signal is available.
|
||||||
- **Recipes** (needs `MEALIE_TOKEN`; `MEALIE_URL` defaults to `https://mealie.necloud.us`): browse and search your Mealie recipes, read one (ingredients, steps, times), import a recipe from a web link, and add its ingredients to the Mealie shopping list (Mealie adds up repeats). The shopping list is also kept in **Tasks** as a "Shopping" list: ticking, adding or deleting an item in either place is carried over when either screen opens or an item changes. In a recipe, tick ingredients (and tap steps) as you go; this is remembered on the device, with *Uncheck all* to start over. On wide screens the ingredients sit beside the steps. Turn the tab on per person in the admin screen.
|
- **Recipes** (needs `MEALIE_TOKEN`; `MEALIE_URL` defaults to `https://mealie.necloud.us`): browse and search your Mealie recipes, read one (ingredients, steps, times), import a recipe from a web link, and add its ingredients to the Mealie shopping list (Mealie adds up repeats). The shopping list is also kept in **Tasks** as a "Shopping" list: ticking, adding or deleting an item in either place is carried over when either screen opens or an item changes. In a recipe, tick ingredients (and tap steps) as you go; this is remembered on the device, with *Uncheck all* to start over. On wide screens the ingredients sit beside the steps. Turn the tab on per person in the admin screen.
|
||||||
- **Contacts**: an address book per person (name, company, emails, phones, address, birthday, notes). Mail suggests contacts while you type a recipient, a message you are reading can be saved as a contact (or opens the one you have), birthdays appear in the Calendar, and .vcf files from iCloud, Google or a phone can be imported and exported.
|
- **Contacts**: an address book per person (name, company, emails, phones, address, birthday, notes). Mail suggests contacts while you type a recipient, a message you are reading can be saved as a contact (or opens the one you have), birthdays appear in the Calendar, and .vcf files from iCloud, Google or a phone can be imported and exported.
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
// Family Chat: a messenger built into the hub, for the people who have an account here. Direct chats and groups, text, attachments, replies, reactions, edit and delete,
|
// Family Chat: a messenger built into the hub, for the people who have an account here. Direct chats and groups, text, attachments, replies, reactions, edit and delete,
|
||||||
// unread counts, search, mute and archive, live delivery (server-sent events) and phone push when someone is not looking. Everything is kept on this server, in
|
// unread counts, search, mute and archive, live delivery (server-sent events) and phone push when someone is not looking. Everything is kept on this server, in
|
||||||
// DATA_DIR/chat: conversations and messages as JSON, attachments as files. (Messages are stored readable on the server; end-to-end encryption is a later decision.)
|
// DATA_DIR/chat: conversations and messages as JSON, attachments as files. (Messages are stored readable on the server; end-to-end encryption is a later decision.)
|
||||||
|
const gifs = require('./gifs');
|
||||||
|
let placeAt = 0;
|
||||||
const fs = require('fs'), path = require('path'), crypto = require('crypto');
|
const fs = require('fs'), path = require('path'), crypto = require('crypto');
|
||||||
const { pipeline } = require('stream/promises');
|
const { pipeline } = require('stream/promises');
|
||||||
const atomicWrite = require('./atomic');
|
const atomicWrite = require('./atomic');
|
||||||
@@ -18,11 +20,16 @@ const fail = (code, message) => Object.assign(new Error(message), { code });
|
|||||||
const str = (v, n) => String(v == null ? '' : v).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').slice(0, n);
|
const str = (v, n) => String(v == null ? '' : v).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').slice(0, n);
|
||||||
const newId = () => crypto.randomBytes(8).toString('hex');
|
const newId = () => crypto.randomBytes(8).toString('hex');
|
||||||
// ---- share cards: a song, film, book... from elsewhere in the hub, with the picture and a link back to it
|
// ---- share cards: a song, film, book... from elsewhere in the hub, with the picture and a link back to it
|
||||||
const SHARE = { song: ['🎵', 'a song'], album: ['💿', 'an album'], artist: ['🎤', 'an artist'], playlist: ['📃', 'a playlist'], movie: ['🎬', 'a movie'], show: ['📺', 'a show'], episode: ['📺', 'an episode'], book: ['📖', 'a book'], audiobook: ['🎧', 'an audiobook'], podcast: ['🎙️', 'a podcast'], podcastep: ['🎙️', 'a podcast episode'], radio: ['📻', 'a radio station'] };
|
const SHARE = { song: ['🎵', 'a song'], album: ['💿', 'an album'], artist: ['🎤', 'an artist'], playlist: ['📃', 'a playlist'], movie: ['🎬', 'a movie'], show: ['📺', 'a show'], episode: ['📺', 'an episode'], book: ['📖', 'a book'], audiobook: ['🎧', 'an audiobook'], podcast: ['🎙️', 'a podcast'], podcastep: ['🎙️', 'a podcast episode'], radio: ['📻', 'a radio station'], place: ['📍', 'a place'] };
|
||||||
const ART_OK = /^\/(plex|api)\/[^\s"'<>\\]*$/, LINK_OK = /^#\/[\w-]+(\/[\w.~%:@+,=&?-]*)*$/;
|
const ART_OK = /^\/(plex|api)\/[^\s"'<>\\]*$/, LINK_OK = /^#\/[\w-]+(\/[\w.~%:@+,=&?-]*)*$/;
|
||||||
/** What a client sent as a share, made safe: whitelisted kind, short words, a picture from this hub only and a link that is a hash route (never another site). */
|
/** What a client sent as a share, made safe: whitelisted kind, short words, a picture from this hub only and a link that is a hash route (never another site). */
|
||||||
function cleanShare(s) {
|
function cleanShare(s) {
|
||||||
if (!s || typeof s !== 'object' || !SHARE[s.kind]) throw fail(400, 'That cannot be shared');
|
if (!s || typeof s !== 'object' || !SHARE[s.kind]) throw fail(400, 'That cannot be shared');
|
||||||
|
if (s.kind === 'place') { // a place on the map: the coordinates are checked and the link is made here (Apple Maps), never taken from the sender
|
||||||
|
const lat = Math.round(+s.lat * 1e5) / 1e5, lng = Math.round(+s.lng * 1e5) / 1e5, title = str(s.title, 120).trim() || 'Shared location';
|
||||||
|
if (!(Math.abs(lat) <= 90) || !(Math.abs(lng) <= 180) || s.lat === '' || s.lng === '' || s.lat == null || s.lng == null) throw fail(400, 'That place has no location');
|
||||||
|
return { kind: 'place', title, sub: str(s.sub, 160).trim(), art: '', link: `https://maps.apple.com/?ll=${lat},${lng}&q=${encodeURIComponent(title)}`, lat, lng };
|
||||||
|
}
|
||||||
const title = str(s.title, 120).trim(), link = String(s.link || ''), art = String(s.art || '');
|
const title = str(s.title, 120).trim(), link = String(s.link || ''), art = String(s.art || '');
|
||||||
if (!title) throw fail(400, 'Nothing to share');
|
if (!title) throw fail(400, 'Nothing to share');
|
||||||
if (link.length > 300 || !LINK_OK.test(link)) throw fail(400, 'That link cannot be shared');
|
if (link.length > 300 || !LINK_OK.test(link)) throw fail(400, 'That link cannot be shared');
|
||||||
@@ -173,6 +180,23 @@ async function handle(req, res) {
|
|||||||
return json(res, 200, { conv: view(c, me.id, stateOf(me.id)), pinned: (c.pins || []).map(id => all.find(x => x.id === id)).filter(x => x && !x.deleted).map(x => msgView(x, me.id, c, sts)), msgs: page.map(x => msgView(x, me.id, c, sts)), more: eligible.length > page.length, names: Object.fromEntries(c.members.map(x => [x, nameOf(x)])) });
|
return json(res, 200, { conv: view(c, me.id, stateOf(me.id)), pinned: (c.pins || []).map(id => all.find(x => x.id === id)).filter(x => x && !x.deleted).map(x => msgView(x, me.id, c, sts)), msgs: page.map(x => msgView(x, me.id, c, sts)), more: eligible.length > page.length, names: Object.fromEntries(c.members.map(x => [x, nameOf(x)])) });
|
||||||
}
|
}
|
||||||
if (p === '/send' && req.method === 'POST') return json(res, 200, { msg: send(me, JSON.parse(await readBody(req, 5e4) || '{}')) });
|
if (p === '/send' && req.method === 'POST') return json(res, 200, { msg: send(me, JSON.parse(await readBody(req, 5e4) || '{}')) });
|
||||||
|
if (p === '/places' && req.method === 'GET') { // search for a place by name (OpenStreetMap's Nominatim, one request a second at most, asked from here)
|
||||||
|
const term = str(q.get('q'), 100).trim(); if (term.length < 3) throw fail(400, 'Type at least three letters');
|
||||||
|
const wait = Math.max(0, placeAt + 1100 - Date.now()); placeAt = Date.now() + wait; if (wait) await new Promise(r => setTimeout(r, wait));
|
||||||
|
let j; try { const r = await fetch(`${(process.env.NOMINATIM_URL || 'https://nominatim.openstreetmap.org').replace(/\/+$/, '')}/search?format=jsonv2&limit=6&addressdetails=0&q=${encodeURIComponent(term)}`, { headers: { 'user-agent': 'NE-Hub/1.0 (family chat)', accept: 'application/json' }, signal: AbortSignal.timeout(8000) }); if (!r.ok) throw new Error('status ' + r.status); j = await r.json(); } catch { throw fail(502, 'The map search did not answer. Try again in a moment.'); }
|
||||||
|
return json(res, 200, { items: (Array.isArray(j) ? j : []).filter(x => isFinite(+x.lat) && isFinite(+x.lon)).slice(0, 6).map(x => { const parts = String(x.display_name || '').split(', '); return { title: str(x.name || parts[0] || term, 120), sub: str(parts.slice(1, 4).join(', '), 160), lat: +x.lat, lng: +x.lon }; }) });
|
||||||
|
}
|
||||||
|
if (p === '/gif/status') return json(res, 200, { enabled: gifs.enabled(), provider: gifs.provider() });
|
||||||
|
if (p === '/gif' && req.method === 'GET') { try { return json(res, 200, await gifs.search(q.get('q'), q.get('pos'))); } catch (e) { throw fail(e.code && e.code < 600 ? e.code : 502, e.message); } }
|
||||||
|
if (p === '/gifimg' && req.method === 'GET') { // a preview, fetched here so the phone never contacts the GIF service
|
||||||
|
try { const g = await gifs.fetchBytes(String(q.get('u') || ''), 2 * 1024 * 1024); res.writeHead(200, { 'content-type': g.type, 'cache-control': 'private, max-age=3600', 'x-content-type-options': 'nosniff', 'content-length': g.buf.length }); return res.end(g.buf); } catch (e) { throw fail(e.code && e.code < 600 ? e.code : 502, e.message); }
|
||||||
|
}
|
||||||
|
if (p === '/gif/send' && req.method === 'POST') { // the chosen GIF is downloaded and kept in the chat like a photo
|
||||||
|
const b = JSON.parse(await readBody(req, 5e3) || '{}'), c = convOf(String(b.conv || ''), me); let g; try { g = await gifs.fetchBytes(String(b.url || '')); } catch (e) { throw fail(e.code && e.code < 600 ? e.code : 502, e.message); }
|
||||||
|
const id = newId(); fs.mkdirSync(path.dirname(blob(id)), { recursive: true, mode: 0o700 }); fs.writeFileSync(blob(id), g.buf, { mode: 0o600 });
|
||||||
|
files()[id] = { conv: c.id, by: me.id, name: (str(b.title, 60).replace(/[\\/:*?"<>|\u0000-\u001f]+/g, ' ').trim() || 'GIF') + (g.type === 'image/gif' ? '.gif' : '.' + g.type.slice(6)), type: g.type, size: g.buf.length, ts: Date.now() }; saveFiles();
|
||||||
|
return json(res, 200, { msg: send(me, { conv: c.id, files: [id] }) });
|
||||||
|
}
|
||||||
if (p === '/upload' && req.method === 'POST') { // the body is the file; ?conv= says which chat it is for
|
if (p === '/upload' && req.method === 'POST') { // the body is the file; ?conv= says which chat it is for
|
||||||
const c = convOf(String(q.get('conv') || ''), me); if ((+req.headers['content-length'] || 0) > MAX_FILE) throw fail(413, 'That file is too large (100 MB at most)');
|
const c = convOf(String(q.get('conv') || ''), me); if ((+req.headers['content-length'] || 0) > MAX_FILE) throw fail(413, 'That file is too large (100 MB at most)');
|
||||||
const id = newId(), type = /^[\w.+-]+\/[\w.+-]+$/.test(String(req.headers['content-type'] || '').split(';')[0].trim()) ? String(req.headers['content-type']).split(';')[0].trim().toLowerCase() : 'application/octet-stream', name = path.basename(str(q.get('name'), 160)).replace(/[\\/:*?"<>|]+/g, '_') || 'file';
|
const id = newId(), type = /^[\w.+-]+\/[\w.+-]+$/.test(String(req.headers['content-type'] || '').split(';')[0].trim()) ? String(req.headers['content-type']).split(';')[0].trim().toLowerCase() : 'application/octet-stream', name = path.basename(str(q.get('name'), 160)).replace(/[\\/:*?"<>|]+/g, '_') || 'file';
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ services:
|
|||||||
PODCASTINDEX_SECRET: ${PODCASTINDEX_SECRET:-}
|
PODCASTINDEX_SECRET: ${PODCASTINDEX_SECRET:-}
|
||||||
MEALIE_URL: ${MEALIE_URL:-https://mealie.necloud.us} # Recipes tab: your Mealie server, and an API token (Mealie: your profile -> API tokens); the token stays on the server
|
MEALIE_URL: ${MEALIE_URL:-https://mealie.necloud.us} # Recipes tab: your Mealie server, and an API token (Mealie: your profile -> API tokens); the token stays on the server
|
||||||
MEALIE_TOKEN: ${MEALIE_TOKEN:-}
|
MEALIE_TOKEN: ${MEALIE_TOKEN:-}
|
||||||
|
TENOR_API_KEY: ${TENOR_API_KEY:-} # GIFs in Family Chat work with no key (Wikimedia Commons). For reaction GIFs, a Tenor key (Google Cloud, Tenor API) ...
|
||||||
|
GIPHY_API_KEY: ${GIPHY_API_KEY:-} # ... or a GIPHY key; either replaces Commons. GIF_PROVIDER=off turns the button off. Tenor and GIPHY results are G-rated only; Commons has no ratings, so its results are checked by words and categories.
|
||||||
ONLYOFFICE_JWT_SECRET: ${ONLYOFFICE_JWT_SECRET:-} # same value as the OnlyOffice server's JWT secret
|
ONLYOFFICE_JWT_SECRET: ${ONLYOFFICE_JWT_SECRET:-} # same value as the OnlyOffice server's JWT secret
|
||||||
PUBLIC_URL: ${PUBLIC_URL:-} # e.g. https://hub.necloud.us (OnlyOffice posts saved edits here)
|
PUBLIC_URL: ${PUBLIC_URL:-} # e.g. https://hub.necloud.us (OnlyOffice posts saved edits here)
|
||||||
HUB_SETUP_CODE: ${HUB_SETUP_CODE:-} # first passkey; if empty, a code is printed in the log
|
HUB_SETUP_CODE: ${HUB_SETUP_CODE:-} # first passkey; if empty, a code is printed in the log
|
||||||
|
|||||||
+4
-4
@@ -22,12 +22,12 @@ A messenger inside the hub for the family, so family chats do not need Signal. E
|
|||||||
- [x] Disappearing messages (a timer per chat)
|
- [x] Disappearing messages (a timer per chat)
|
||||||
- [x] @mentions in groups, pinned messages, forward a message
|
- [x] @mentions in groups, pinned messages, forward a message
|
||||||
|
|
||||||
**Phase 3: richer messages (M): done except the GIF picker and shared places**
|
**Phase 3: richer messages (M): done**
|
||||||
- [x] Voice notes (record and play, with a waveform)
|
- [x] Voice notes (record and play, with a waveform)
|
||||||
- [x] Link previews (fetched safely by the server)
|
- [x] Link previews (fetched safely by the server)
|
||||||
- [x] Polls
|
- [x] Polls
|
||||||
- [ ] GIF or sticker picker (optional)
|
- [x] GIF picker: **Done (gifs.js, chat-extras.js): works with no key through Wikimedia Commons (MediaWiki search), or with a Tenor or GIPHY key; a blocklist on searches and results (and categories for Commons), previews and the sent GIF go through the hub.**
|
||||||
- [ ] Share a place as a link
|
- [x] Share a place as a link: **Done: your location (the phone asks) or a place search through OpenStreetMap, shown as a card with an Apple Maps (maps.apple.com) link.**
|
||||||
|
|
||||||
**Family extras (M): mostly done**
|
**Family extras (M): mostly done**
|
||||||
- [x] Turn a message into a task, an event or a shopping item in one tap
|
- [x] Turn a message into a task, an event or a shopping item in one tap
|
||||||
@@ -46,7 +46,7 @@ Not planned: voice and video calls, stories, usernames and phone-number lookup,
|
|||||||
- [x] **Shared lists and notes (M): done (notes.js, the Notes tab):** a real Notes and Lists tab the whole family edits (grocery, packing, gift ideas, house to-dos)
|
- [x] **Shared lists and notes (M): done (notes.js, the Notes tab):** a real Notes and Lists tab the whole family edits (grocery, packing, gift ideas, house to-dos)
|
||||||
- [x] **Chores and routines (M):** recurring chores per person, check-offs, optional points and a weekly summary; kids see their own **Done: chores.js and the Chores tab: repeats, points, weekly and monthly board.**
|
- [x] **Chores and routines (M):** recurring chores per person, check-offs, optional points and a weekly summary; kids see their own **Done: chores.js and the Chores tab: repeats, points, weekly and monthly board.**
|
||||||
- [x] **Family calendar (M):** **Done: the Family calendar shows each event in the colour of whoever added it (Settings > Look sets yours); birthdays and anniversaries come from Contacts; inviting people puts the event on their calendar and tells them (no accept or decline). The week view already existed.**
|
- [x] **Family calendar (M):** **Done: the Family calendar shows each event in the colour of whoever added it (Settings > Look sets yours); birthdays and anniversaries come from Contacts; inviting people puts the event on their calendar and tells them (no accept or decline). The week view already existed.**
|
||||||
- [x] **Meal planning (M):** **Done: a shared week plan (Recipes > Meal plan) that adds the week's ingredients to the shopping list, and a Pantry (items with a count and a running-low level) that the plan checks against. Pantry counts are kept by hand; they do not go down when you cook.**
|
- [x] **Meal planning (M):** **Done: a shared week plan (Recipes > Meal plan) that adds the week's ingredients to the shopping list, and a Pantry (items with a count and a running-low level) that the plan checks against. Pantry items can have units (10 lb of flour); **Cooked it** on a recipe (or on a meal plan entry) shows what it would take out, converting cups to pounds for common ingredients, and takes it out when confirmed; **Use some** takes an amount in any convertible unit. These are estimates, and lines that cannot be converted (a whole onion against pounds of onions, pinches) are left alone and listed. The Pantry lives at Recipes > Pantry and works without Mealie. A phone can scan a barcode to add or use one (several barcodes can belong to one item, so different brands of corn share a count), and a Take one screen lets anyone, children included, tap an item to take one; children can do nothing else to the pantry.**
|
||||||
- [x] **Worship and devotion (S):** a shared daily verse, a Bible reading plan with check-ins, a family prayer list **Done: Bible > Devotion (devotion-view.js, bible.js).**
|
- [x] **Worship and devotion (S):** a shared daily verse, a Bible reading plan with check-ins, a family prayer list **Done: Bible > Devotion (devotion-view.js, bible.js).**
|
||||||
|
|
||||||
## 3. Kids and safety
|
## 3. Kids and safety
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// GIFs for Family Chat, from Tenor or GIPHY (whichever key the admin gives: TENOR_API_KEY or GIPHY_API_KEY), or with no key at all from Wikimedia Commons (MediaWiki's search API): free animated
|
||||||
|
// pictures of animals, space, science and nature rather than reaction memes. GIF_PROVIDER=tenor|giphy|wikimedia|off picks one; the default is the first of Tenor, GIPHY, Wikimedia that works. The hub does all the talking to the service, so phones never contact it:
|
||||||
|
// searches come back through here, previews are fetched here, and a GIF that is sent is downloaded and kept in the chat like any other picture.
|
||||||
|
// Everything is kept family-friendly, for everybody: only the services' G-rated results are asked for, words that could bring up adult material are refused in a search and in what comes
|
||||||
|
// back (title and tags), and only GIFs this server itself listed can be sent. A filter like this is a strong guard, not a promise: a sender or an admin can delete anything that slips through.
|
||||||
|
const TENOR = () => (process.env.TENOR_URL || 'https://tenor.googleapis.com').replace(/\/+$/, ''), GIPHY = () => (process.env.GIPHY_URL || 'https://api.giphy.com').replace(/\/+$/, '');
|
||||||
|
const WIKI = () => (process.env.WIKIMEDIA_URL || 'https://commons.wikimedia.org').replace(/\/+$/, '');
|
||||||
|
const provider = () => { const w = String(process.env.GIF_PROVIDER || '').toLowerCase(); if (w === 'off') return ''; if (w === 'wikimedia' || w === 'tenor' && process.env.TENOR_API_KEY || w === 'giphy' && process.env.GIPHY_API_KEY) return w; return process.env.TENOR_API_KEY ? 'tenor' : process.env.GIPHY_API_KEY ? 'giphy' : 'wikimedia'; };
|
||||||
|
const enabled = () => !!provider();
|
||||||
|
|
||||||
|
// whole words (and stems) that are never searched for and never shown
|
||||||
|
const BLOCK = ['sex', 'sexy', 'sexual', 'sexually', 'sexier', 'sexiest', 'porn', 'porno', 'pornography', 'pornographic', 'xxx', 'nsfw', 'nude', 'nudes', 'nudity', 'naked', 'topless', 'bottomless', 'boob', 'boobs', 'boobies', 'breast', 'breasts', 'tit', 'tits', 'titty', 'titties', 'nipple', 'nipples', 'cleavage', 'butt', 'butts', 'booty', 'twerk', 'twerking', 'thong', 'thongs', 'lingerie', 'bikini', 'bikinis', 'underwear', 'panties', 'bra', 'bras', 'strip', 'stripper', 'strippers', 'striptease', 'erotic', 'erotica', 'fetish', 'kink', 'kinky', 'bdsm', 'hentai', 'orgasm', 'orgasms', 'penis', 'vagina', 'dick', 'dicks', 'cock', 'cocks', 'pussy', 'pussies', 'cum', 'cumming', 'horny', 'slut', 'sluts', 'whore', 'hooker', 'hookers', 'masturbate', 'masturbation', 'blowjob', 'handjob', 'anal', 'milf', 'onlyfans', 'playboy', 'adult', 'adults', 'lust', 'seduce', 'seductive', 'foreplay', 'grope', 'groping', 'fuck', 'fucking', 'fucker', 'fucked', 'shit', 'bitch', 'bitches', 'asshole', 'ass', 'drugs', 'cocaine', 'marijuana', 'gore', 'suicide'];
|
||||||
|
const BLOCKED = new Set(BLOCK);
|
||||||
|
// Commons files carry categories, so those are checked too, against a few more phrases (a category is a phrase, not a word)
|
||||||
|
const RISKY = /nudity|nude|naked|sexual|sexuality|erotic|pornograph|genital|fetish|bdsm|topless|underwear|swimwear|bikini|lingerie|breast|buttock|nipple|prostitut|obscene|sex education|human sexuality|anatomy of the|violence|corpse|dead bod|execution|torture|massacre|gore|suicide|drug use|cannabis|cocaine|heroin/i;
|
||||||
|
/** Does this text (a search, a title, tags) contain a word that is not allowed? Whole words only, so "class" and "assistant" are fine. */
|
||||||
|
const unsafe = text => (String(text || '').toLowerCase().match(/[a-z0-9]+/g) || []).some(w => BLOCKED.has(w) || BLOCKED.has(w.replace(/s$/, '')));
|
||||||
|
|
||||||
|
// only GIFs this server has just listed can be sent or previewed (so the download address cannot be chosen by the sender)
|
||||||
|
const known = new Map(); // url -> expiry
|
||||||
|
const remember = urls => { const t = Date.now() + 3600e3; for (const u of urls) known.set(u, t); if (known.size > 4000) for (const [k, v] of known) if (v < Date.now()) known.delete(k); };
|
||||||
|
const isKnown = u => (known.get(u) || 0) > Date.now();
|
||||||
|
const MEDIA = /^https:\/\/(media[0-9]*\.tenor\.com|media[0-9]*\.giphy\.com|i\.giphy\.com|c\.tenor\.com|upload\.wikimedia\.org)\//i;
|
||||||
|
const mediaOk = u => { try { const x = new URL(u); return MEDIA.test(u) || String(process.env.GIF_MEDIA_HOSTS || '').split(',').filter(Boolean).includes(x.host); } catch { return false; } };
|
||||||
|
|
||||||
|
async function getJson(url) {
|
||||||
|
const r = await fetch(url, { headers: { accept: 'application/json', 'user-agent': 'NE-Hub/1.0 (family chat)' }, signal: AbortSignal.timeout(8000) });
|
||||||
|
if (r.status === 403 || r.status === 401) throw Object.assign(new Error('The GIF service refused the key. Check it in the stack settings.'), { code: 502 });
|
||||||
|
if (r.status === 429) throw Object.assign(new Error('The GIF service is busy. Try again in a minute.'), { code: 429 });
|
||||||
|
if (!r.ok) throw Object.assign(new Error('The GIF service did not answer (' + r.status + ')'), { code: 502 });
|
||||||
|
return r.json();
|
||||||
|
}
|
||||||
|
/** Search (or, with no words, what is popular). Returns { items: [{ title, w, h, preview, url }], next }. */
|
||||||
|
async function search(q, pos) {
|
||||||
|
q = String(q || '').trim().slice(0, 60);
|
||||||
|
if (q && unsafe(q)) throw Object.assign(new Error('That search is not available. Try something else.'), { code: 400 });
|
||||||
|
const n = 24; let items = [], next = '';
|
||||||
|
if (provider() === 'tenor') {
|
||||||
|
const key = encodeURIComponent(process.env.TENOR_API_KEY), base = `${TENOR()}/v2/${q ? 'search?q=' + encodeURIComponent(q) + '&' : 'featured?'}key=${key}&client_key=nehub&limit=${n}&contentfilter=high&media_filter=tinygif,gif${pos ? '&pos=' + encodeURIComponent(pos) : ''}`;
|
||||||
|
const j = await getJson(base); next = j.next || '';
|
||||||
|
items = (j.results || []).map(x => { const t = (x.media_formats || {}).tinygif, g = (x.media_formats || {}).gif || t; return t && g ? { title: x.content_description || '', tags: (x.tags || []).join(' '), w: (t.dims || [])[0] || 0, h: (t.dims || [])[1] || 0, preview: t.url, url: g.url } : null; });
|
||||||
|
} else if (provider() === 'giphy') {
|
||||||
|
const off = Math.max(0, parseInt(pos, 10) || 0), key = encodeURIComponent(process.env.GIPHY_API_KEY), base = `${GIPHY()}/v1/gifs/${q ? 'search?q=' + encodeURIComponent(q) + '&' : 'trending?'}api_key=${key}&limit=${n}&offset=${off}&rating=g&bundle=messaging_non_clips`;
|
||||||
|
const j = await getJson(base); next = (j.data || []).length >= n ? String(off + n) : '';
|
||||||
|
items = (j.data || []).filter(x => !x.rating || x.rating === 'g').map(x => { const t = (x.images || {}).fixed_width_small || (x.images || {}).fixed_width, g = (x.images || {}).fixed_width || (x.images || {}).original; return t && g && t.url && g.url ? { title: x.title || '', tags: '', w: +t.width || 0, h: +t.height || 0, preview: t.url, url: g.url } : null; });
|
||||||
|
} else if (provider() === 'wikimedia') { // Wikimedia Commons: animated GIFs only, chosen by the search itself; no rating exists, so the word and category checks do the work
|
||||||
|
const off = Math.max(0, parseInt(pos, 10) || 0), term = (q || 'animal') + ' filemime:image/gif';
|
||||||
|
const url = `${WIKI()}/w/api.php?action=query&format=json&generator=search&gsrnamespace=6&gsrlimit=${n}&gsroffset=${off}&gsrsearch=${encodeURIComponent(term)}&prop=imageinfo&iiprop=url|size|mime|extmetadata&iiurlwidth=320&iiextmetadatafilter=ImageDescription|Categories|ObjectName`;
|
||||||
|
const j = await getJson(url); next = j.continue && j.continue.gsroffset != null ? String(j.continue.gsroffset) : '';
|
||||||
|
items = Object.values((j.query || {}).pages || {}).sort((a, b) => (a.index || 0) - (b.index || 0)).map(pg => {
|
||||||
|
const ii = (pg.imageinfo || [])[0]; if (!ii || ii.mime !== 'image/gif' || !ii.thumburl) return null; const em = ii.extmetadata || {}, plain = v => String(v && v.value || '').replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||||
|
const title = String(pg.title || '').replace(/^File:/, '').replace(/\.gif$/i, '').replace(/[_]+/g, ' '), cats = plain(em.Categories).replace(/\|/g, ' · '), desc = plain(em.ImageDescription).slice(0, 300);
|
||||||
|
if (RISKY.test(cats) || RISKY.test(title) || RISKY.test(desc)) return null; return { title: plain(em.ObjectName) || title, tags: cats + ' ' + desc, w: ii.thumbwidth || 0, h: ii.thumbheight || 0, preview: ii.thumburl, url: ii.thumburl };
|
||||||
|
});
|
||||||
|
} else throw Object.assign(new Error('GIFs are not set up on this server'), { code: 503 });
|
||||||
|
items = items.filter(x => x && mediaOk(x.preview) && mediaOk(x.url) && !unsafe(x.title) && !unsafe(x.tags)).map(({ tags, ...x }) => x);
|
||||||
|
remember(items.flatMap(x => [x.preview, x.url])); return { items, next };
|
||||||
|
}
|
||||||
|
/** The bytes of a GIF this server listed (a preview or the full one), size-limited. */
|
||||||
|
async function fetchBytes(url, max = 8 * 1024 * 1024) {
|
||||||
|
if (!isKnown(url) || !mediaOk(url)) throw Object.assign(new Error('That GIF is not available'), { code: 400 });
|
||||||
|
const r = await fetch(url, { headers: { 'user-agent': 'NE-Hub/1.0 (family chat)' }, signal: AbortSignal.timeout(15000), redirect: 'error' });
|
||||||
|
if (!r.ok) throw Object.assign(new Error('The GIF could not be downloaded'), { code: 502 });
|
||||||
|
const type = String(r.headers.get('content-type') || '').split(';')[0].trim().toLowerCase(); if (!/^image\/(gif|webp|png|jpeg)$/.test(type)) throw Object.assign(new Error('That is not a picture'), { code: 502 });
|
||||||
|
const buf = Buffer.from(await r.arrayBuffer()); if (buf.length > max) throw Object.assign(new Error('That GIF is too large'), { code: 413 }); return { buf, type };
|
||||||
|
}
|
||||||
|
module.exports = { enabled, provider, search, fetchBytes, unsafe, isKnown, remember };
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// The pantry: what the family keeps in the kitchen, one shared list. Each item has a name, how many are left (blank when you do not count it), the level it counts as running low
|
||||||
|
// at (blank: never), and any number of barcodes linked to it, so Green Giant corn and the store brand are both "Corn" with one count. Scanning a barcode (on a phone) looks the product
|
||||||
|
// up in Open Food Facts (through this server, so the phone never contacts it) and adds or uses one; the first time a barcode is seen the person says which item it is.
|
||||||
|
// An item going low starts the "pantry item runs low" automations.
|
||||||
|
const fs = require('fs'), path = require('path'), crypto = require('crypto');
|
||||||
|
const atomicWrite = require('./atomic');
|
||||||
|
const users = require('./users');
|
||||||
|
const { readBody } = require('./body');
|
||||||
|
const U = require('./units');
|
||||||
|
|
||||||
|
const DATA = () => process.env.DATA_DIR || path.join(__dirname, 'data');
|
||||||
|
const file = () => path.join(DATA(), 'pantry.json'), cacheFile = () => path.join(DATA(), 'barcode-cache.json');
|
||||||
|
const OFF = () => (process.env.OPENFOODFACTS_URL || 'https://world.openfoodfacts.org').replace(/\/+$/, '');
|
||||||
|
const json = (res, code, o) => { res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(o)); };
|
||||||
|
const fail = (code, message) => Object.assign(new Error(message), { code });
|
||||||
|
const unitClean = v => U.UNITS.includes(String(v || '')) ? String(v || '') : '';
|
||||||
|
const num = v => v === '' || v == null || !isFinite(+v) || +v < 0 ? null : Math.min(100000, Math.round(+v * 100) / 100);
|
||||||
|
const CODE = /^\d{8,14}$/;
|
||||||
|
|
||||||
|
const read = () => { try { const a = JSON.parse(fs.readFileSync(file(), 'utf8')); return (Array.isArray(a) ? a : []).map(x => typeof x === 'string' ? { id: crypto.randomBytes(4).toString('hex'), name: x, qty: null, low: null, unit: '', codes: [] } : { ...x, unit: unitClean(x.unit), codes: Array.isArray(x.codes) ? x.codes : [] }).filter(x => x && x.name); } catch { return []; } };
|
||||||
|
const write = l => atomicWrite(file(), JSON.stringify(l), { mode: 0o600 });
|
||||||
|
const isLow = x => x.qty != null && x.low != null && x.qty <= x.low;
|
||||||
|
const view = l => l.map(x => ({ id: x.id, name: x.name, qty: x.qty, unit: x.unit || '', label: U.fmt(x.qty, x.unit || ''), low: x.low, lowLabel: U.fmt(x.low, x.unit || ''), isLow: isLow(x), codes: x.codes })).sort((a, b) => b.isLow - a.isLow || a.name.localeCompare(b.name));
|
||||||
|
// Who took what: the last few uses, so parents can see where the snacks went.
|
||||||
|
const logFile = () => path.join(DATA(), 'pantry-log.json');
|
||||||
|
const readLog = () => { try { const a = JSON.parse(fs.readFileSync(logFile(), 'utf8')); return Array.isArray(a) ? a : []; } catch { return []; } };
|
||||||
|
function logUse(me, it, delta, note) { const l = readLog(); l.unshift({ t: Date.now(), who: me.name, item: it.name, delta, ...(note ? { note: String(note).slice(0, 80) } : {}) }); atomicWrite(logFile(), JSON.stringify(l.slice(0, 60)), { mode: 0o600 }); }
|
||||||
|
const isKid = u => !!(u && u.kid && u.kid.on);
|
||||||
|
/** An item has just gone low: tell the automations of everyone who asked to hear about it. */
|
||||||
|
function lowNow(it) { try { require('./automations').fireAll('pantry.low', { title: it.name }); } catch (e) { console.warn('[pantry] rules failed:', e.message); } }
|
||||||
|
/** Change an item's count, firing the "went low" rules when it crosses into low. */
|
||||||
|
function bump(it, delta) { const before = isLow(it); it.qty = Math.max(0, Math.round(((it.qty || 0) + delta) * 10000) / 10000); if (isLow(it) && !before) lowNow(it); }
|
||||||
|
|
||||||
|
// ---- matching words: "3 cups flour" has "flour"; "Green Giant Sweet Corn" has "Corn"
|
||||||
|
const stem = w => w.replace(/(ies)$/, 'y').replace(/(es|s)$/, '');
|
||||||
|
const wordsOf = t => (String(t).toLowerCase().match(/[a-z]+/g) || []).map(stem);
|
||||||
|
/** The pantry names (from items or strings) that every word of is in `text`. */
|
||||||
|
function inPantry(text, items) { const have = new Set(wordsOf(text)); return items.map(x => typeof x === 'string' ? x : x.name).filter(n => { const ws = wordsOf(n); return ws.length && ws.every(w => have.has(w)); }); }
|
||||||
|
/** A short name for a product: the brand and the size taken off ("Heinz Tomato Ketchup 500 ml" -> "Tomato Ketchup"). */
|
||||||
|
function shortName(name, brand) {
|
||||||
|
let n = String(name || '').replace(/\b\d+([.,]\d+)?\s?(x\s?\d+\s?)?(ml|cl|l|g|kg|oz|fl\.?\s?oz|lb|lbs|ct|count|pack|pk)\b\.?/gi, ' ');
|
||||||
|
for (const b of String(brand || '').split(',').map(x => x.trim()).filter(Boolean)) n = n.replace(new RegExp('\\b' + b.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b', 'ig'), ' ');
|
||||||
|
n = n.replace(/[()\[\],]/g, ' ').replace(/\s+/g, ' ').trim(); return (n || String(name || '').trim()).replace(/\b\w/g, c => c.toUpperCase()).slice(0, 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the product database (Open Food Facts), remembered so a barcode is only looked up once
|
||||||
|
const loadCache = () => { try { return JSON.parse(fs.readFileSync(cacheFile(), 'utf8')) || {}; } catch { return {}; } };
|
||||||
|
async function product(code) {
|
||||||
|
const c = loadCache(), hit = c[code]; if (hit && (hit.found || Date.now() - hit.t < 24 * 3600e3)) return hit.found ? hit : null; // (a miss is tried again after a day)
|
||||||
|
let found = null;
|
||||||
|
try {
|
||||||
|
const r = await fetch(`${OFF()}/api/v2/product/${code}.json?fields=product_name,brands,quantity,generic_name`, { headers: { 'user-agent': 'NE-Hub/1.0 (family pantry)', accept: 'application/json' }, signal: AbortSignal.timeout(6000) });
|
||||||
|
if (r.ok) { const j = await r.json(), p = j && j.status === 1 && j.product; if (p && (p.product_name || p.generic_name)) found = { name: String(p.product_name || p.generic_name).slice(0, 120), brand: String(p.brands || '').slice(0, 80), quantity: String(p.quantity || '').slice(0, 30) }; }
|
||||||
|
} catch { return undefined; } // (could not ask: not remembered)
|
||||||
|
c[code] = found ? { found: true, t: Date.now(), ...found } : { found: false, t: Date.now() };
|
||||||
|
const keys = Object.keys(c); if (keys.length > 3000) for (const k of keys.sort((a, b) => c[a].t - c[b].t).slice(0, 500)) delete c[k];
|
||||||
|
fs.mkdirSync(DATA(), { recursive: true }); atomicWrite(cacheFile(), JSON.stringify(c), { mode: 0o600 }); return found ? c[code] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handle(req, res) {
|
||||||
|
const me = users.current(), u = new URL(req.url, 'http://x'), p = u.pathname.slice('/api/pantry'.length) || '/';
|
||||||
|
try {
|
||||||
|
if (!me) throw fail(401, 'Sign in');
|
||||||
|
if (p === '/' && req.method === 'GET') return json(res, 200, { items: view(read()), recent: readLog().slice(0, 12), kid: isKid(me) });
|
||||||
|
if (p === '/lookup' && req.method === 'GET') { // what is this barcode? Linked to an item already, or which products and items it might be
|
||||||
|
const code = u.searchParams.get('code') || ''; if (!CODE.test(code)) throw fail(400, 'That is not a barcode number (8 to 14 digits)');
|
||||||
|
const l = read(), linked = l.find(x => x.codes.includes(code)); if (linked) return json(res, 200, { code, linked: { id: linked.id, name: linked.name } });
|
||||||
|
const pr = await product(code), name = pr ? shortName(pr.name, pr.brand) : '';
|
||||||
|
return json(res, 200, { code, linked: null, product: pr ? { name: pr.name, brand: pr.brand, quantity: pr.quantity, short: name } : null, lookedUp: pr !== undefined, matches: pr ? view(l.filter(x => inPantry(pr.name, [x.name]).length)).map(x => ({ id: x.id, name: x.name })) : [] });
|
||||||
|
}
|
||||||
|
if (req.method !== 'POST') throw fail(404, 'Not found');
|
||||||
|
const b = JSON.parse(await readBody(req, 4e3) || '{}'), l = read();
|
||||||
|
if (p === '/use') { // the simple way: take one (or put it back, to undo). Open to everyone, children included.
|
||||||
|
const it = l.find(x => x.id === b.id); if (!it) throw fail(404, 'That item is gone'); const delta = b.undo ? 1 : -1;
|
||||||
|
if (it.unit) throw fail(409, 'Use an amount for ' + it.name.toLowerCase() + ' (it is kept in ' + it.unit + ')');
|
||||||
|
if (it.qty != null) { if (delta < 0 && it.qty <= 0) throw fail(409, 'There is none left of ' + it.name); bump(it, delta); write(l); }
|
||||||
|
logUse(me, it, b.undo ? 0 : -1); return json(res, 200, { item: { id: it.id, name: it.name, qty: it.qty, isLow: isLow(it) }, items: view(l), recent: readLog().slice(0, 12) });
|
||||||
|
}
|
||||||
|
if (isKid(me) && !(p === '/scan' && b.mode === 'use' && l.some(x => x.codes.includes(String(b.code))))) throw fail(403, 'Ask a grown-up to change the pantry. You can tap an item to take one.');
|
||||||
|
if (p === '/item') { // add an item, or change one (the same name changes the existing item)
|
||||||
|
const name = String(b.name || '').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 60); if (!name) throw fail(400, 'Give the item a name');
|
||||||
|
const i = b.id ? l.findIndex(x => x.id === b.id) : l.findIndex(x => x.name.toLowerCase() === name.toLowerCase()); if (b.id && i < 0) throw fail(404, 'That item is gone'); if (i < 0 && l.length >= 400) throw fail(400, 'The pantry is full');
|
||||||
|
const before = i >= 0 ? isLow(l[i]) : false, it = { id: i >= 0 ? l[i].id : crypto.randomBytes(4).toString('hex'), name: i >= 0 && !b.id ? l[i].name : name, qty: num(b.qty), unit: unitClean(b.unit), low: num(b.low), codes: i >= 0 ? l[i].codes : [] };
|
||||||
|
if (i >= 0) l[i] = it; else l.push(it); write(l); if (isLow(it) && !before) lowNow(it); return json(res, 200, { items: view(l) });
|
||||||
|
}
|
||||||
|
if (p === '/adjust') { const it = l.find(x => x.id === b.id); if (!it) throw fail(404, 'That item is gone'); bump(it, +b.delta || 0); write(l); return json(res, 200, { items: view(l) }); }
|
||||||
|
if (p === '/delete') { const k = l.filter(x => x.id !== b.id); write(k); return json(res, 200, { items: view(k) }); }
|
||||||
|
if (p === '/take') { // take amounts out (cooking, or a spoonful from the bag): [{ id, amount, unit }], the unit being any that can be turned into the item's own
|
||||||
|
const takes = Array.isArray(b.takes) ? b.takes.slice(0, 80) : [], done = [], skipped = [];
|
||||||
|
for (const t of takes) {
|
||||||
|
const it = l.find(x => x.id === t.id), amt = +t.amount; if (!it || !(amt > 0)) { skipped.push({ id: t.id, why: 'nothing to take' }); continue; }
|
||||||
|
if (it.qty == null) { skipped.push({ id: it.id, name: it.name, why: 'not counted' }); continue; }
|
||||||
|
const unit = t.unit == null ? (it.unit || '') : U.unitOf(t.unit) || '', c = unit === (it.unit || '') ? amt : U.convert(amt, unit, it.unit || '', it.name);
|
||||||
|
if (c == null) { skipped.push({ id: it.id, name: it.name, why: `cannot turn ${unit || 'a count'} into ${it.unit || 'a count'} for ${it.name.toLowerCase()}` }); continue; }
|
||||||
|
const before = it.qty; bump(it, -Math.round(c * 10000) / 10000); done.push({ id: it.id, name: it.name, took: Math.round((before - it.qty) * 10000) / 10000, label: U.fmt(it.qty, it.unit || ''), isLow: isLow(it) });
|
||||||
|
}
|
||||||
|
if (done.length) { write(l); const first = done.map(x => x.name).slice(0, 3).join(', '); logUse(me, { name: first + (done.length > 3 ? '…' : '') }, -1, b.note || 'cooked'); }
|
||||||
|
return json(res, 200, { done, skipped, items: view(l), recent: readLog().slice(0, 12) });
|
||||||
|
}
|
||||||
|
if (p === '/scan') { // one scanned: add one ("add") or use one ("use"). A new barcode must say which item it is (itemId) or name a new one (name).
|
||||||
|
const code = String(b.code || ''); if (!CODE.test(code)) throw fail(400, 'That is not a barcode number (8 to 14 digits)'); const delta = b.mode === 'use' ? -1 : 1;
|
||||||
|
let it = l.find(x => x.codes.includes(code)), made = false;
|
||||||
|
if (!it && b.itemId) { it = l.find(x => x.id === b.itemId); if (!it) throw fail(404, 'That item is gone'); }
|
||||||
|
if (!it && String(b.name || '').trim()) { const name = String(b.name).replace(/[\u0000-\u001f]/g, '').trim().slice(0, 60); it = l.find(x => x.name.toLowerCase() === name.toLowerCase()); if (!it) { if (l.length >= 400) throw fail(400, 'The pantry is full'); it = { id: crypto.randomBytes(4).toString('hex'), name, qty: 0, low: null, unit: unitClean(b.unit), codes: [] }; l.push(it); made = true; } }
|
||||||
|
if (!it) throw fail(400, 'Say which item this is');
|
||||||
|
if (!it.codes.includes(code)) { for (const x of l) x.codes = x.codes.filter(c => c !== code); it.codes.push(code); it.codes = it.codes.slice(-30); }
|
||||||
|
let step = delta; // an item measured in pounds, cups and so on goes up and down by the size of the package scanned (a 15 oz can into an item in ounces); a counted item by one
|
||||||
|
if (it.unit) { const pk = (loadCache()[code] || {}).quantity, pi = pk ? U.parseIngredient(pk) : null; if (pi && pi.amount && pi.unit) { const c = U.convert(pi.amount, pi.unit, it.unit, it.name); if (c && c > 0) step = delta * Math.round(c * 100) / 100; } }
|
||||||
|
bump(it, step); write(l); if (delta < 0) logUse(me, it, -1); return json(res, 200, { item: { id: it.id, name: it.name, qty: it.qty, label: U.fmt(it.qty, it.unit || ''), isLow: isLow(it) }, step, made, items: view(l), recent: readLog().slice(0, 12) });
|
||||||
|
}
|
||||||
|
if (p === '/unlink') { const it = l.find(x => x.id === b.id); if (!it) throw fail(404, 'That item is gone'); it.codes = it.codes.filter(c => c !== String(b.code)); write(l); return json(res, 200, { items: view(l) }); }
|
||||||
|
throw fail(404, 'Not found');
|
||||||
|
} catch (e) { json(res, e.code && e.code < 600 ? e.code : 400, { error: e.message }); }
|
||||||
|
}
|
||||||
|
module.exports = { handle, read, isLow, inPantry, shortName };
|
||||||
@@ -114,6 +114,7 @@ const ICONS = {
|
|||||||
heart: '<path d="M12 20s-7-4.4-7-10a4 4 0 017-2.5A4 4 0 0119 10c0 5.6-7 10-7 10z"/>',
|
heart: '<path d="M12 20s-7-4.4-7-10a4 4 0 017-2.5A4 4 0 0119 10c0 5.6-7 10-7 10z"/>',
|
||||||
bible: '<path d="M5 5a2 2 0 012-2h12v15H7a2 2 0 00-2 2z"/><path d="M5 20a2 2 0 002 2h12v-4M12 7v7M9.5 9.5h5"/>',
|
bible: '<path d="M5 5a2 2 0 012-2h12v15H7a2 2 0 00-2 2z"/><path d="M5 20a2 2 0 002 2h12v-4M12 7v7M9.5 9.5h5"/>',
|
||||||
list: '<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01"/>',
|
list: '<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01"/>',
|
||||||
|
pin: '<path d="M12 21s-7-6.2-7-11a7 7 0 0114 0c0 4.8-7 11-7 11z"/><circle cx="12" cy="10" r="2.5"/>',
|
||||||
font: '<path d="M3 19l5-13 5 13M5 14h6M15 19l3.5-9 3.5 9M16.2 16h4.6"/>',
|
font: '<path d="M3 19l5-13 5 13M5 14h6M15 19l3.5-9 3.5 9M16.2 16h4.6"/>',
|
||||||
};
|
};
|
||||||
const icon = (n, cls = '') => `<svg class="${cls}" viewBox="0 0 24 24">${ICONS[n]}</svg>`;
|
const icon = (n, cls = '') => `<svg class="${cls}" viewBox="0 0 24 24">${ICONS[n]}</svg>`;
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
'use strict';
|
||||||
|
// ---- Family Chat extras: a GIF picker (kept family-friendly by the hub; phones never contact the GIF service) and sharing a place (your location, or a place you search for).
|
||||||
|
// The Chat list also shows Signal conversations, labelled, when Signal is available on this screen.
|
||||||
|
async function chGifOn() { if (ch.gifOn === undefined) { try { const st = await chApi('/gif/status'); ch.gifOn = !!st.enabled; ch.gifBy = st.provider; } catch { ch.gifOn = false; } } return ch.gifOn; }
|
||||||
|
function chGifPicker() {
|
||||||
|
const to = ch.cur, by = ch.gifBy === 'giphy' ? 'GIPHY' : ch.gifBy === 'wikimedia' ? 'Wikimedia Commons (free pictures; mostly animals, nature, space and science)' : 'Tenor';
|
||||||
|
const el = openSheet('GIF', 'Family-friendly only', `<form id="gpf" class="bar" style="flex-wrap:nowrap;gap:6px"><input type="search" id="gpq" placeholder="Search GIFs" autocomplete="off" maxlength="60" style="flex:1;min-width:0"><button class="btn ghost">Search</button></form>${ch.gifBy === 'wikimedia' ? `<div class="seg" id="gpc" style="flex-wrap:wrap">${['animals', 'space', 'weather', 'ocean', 'science', 'dance', 'cartoon', 'sports'].map(w => `<a href="#" data-w="${w}">${w}</a>`).join('')}</div>` : ''}<div class="gifgrid" id="gpg" role="list"></div><p class="err" id="gpe"></p><div class="bar" style="justify-content:center"><button class="btn ghost" id="gpm" hidden>More</button></div><p class="sub" style="text-align:center;margin:4px 0 0;font-size:12px">Powered by ${by}</p>`);
|
||||||
|
el.querySelector('.sheet').classList.add('wide'); let next = '', q = '', busy = false;
|
||||||
|
const load = async more => {
|
||||||
|
if (busy) return; busy = true; el.querySelector('#gpe').textContent = '';
|
||||||
|
try { const r = await chApi('/gif?q=' + encodeURIComponent(q) + (more && next ? '&pos=' + encodeURIComponent(next) : '')); next = r.next || ''; const g = el.querySelector('#gpg'); if (!more) g.innerHTML = '';
|
||||||
|
g.insertAdjacentHTML('beforeend', r.items.map(x => `<button type="button" class="gifc" role="listitem" data-u="${esc(x.url)}" data-t="${esc(x.title)}" aria-label="Send GIF ${esc(x.title || '')}"><img alt="${esc(x.title || 'GIF')}" loading="lazy" ${x.w && x.h ? `width="${x.w}" height="${x.h}"` : ''} src="/api/chat/gifimg?u=${encodeURIComponent(x.preview)}"></button>`).join('')); if (!more && !r.items.length) el.querySelector('#gpe').textContent = 'Nothing found. Try another word.';
|
||||||
|
el.querySelector('#gpm').hidden = !next; } catch (e) { el.querySelector('#gpe').textContent = e.message; } busy = false;
|
||||||
|
};
|
||||||
|
el.querySelector('#gpf').onsubmit = e => { e.preventDefault(); q = el.querySelector('#gpq').value.trim(); next = ''; load(false); };
|
||||||
|
el.querySelector('#gpm').onclick = () => load(true);
|
||||||
|
el.querySelectorAll('#gpc [data-w]').forEach(a => a.onclick = e => { e.preventDefault(); el.querySelector('#gpq').value = a.dataset.w; el.querySelector('#gpf').requestSubmit(); });
|
||||||
|
el.querySelector('#gpg').onclick = async e => { const b = e.target.closest('.gifc'); if (!b || b.disabled) return; b.disabled = true; b.style.opacity = '.5';
|
||||||
|
try { await chPost('/gif/send', { conv: to, url: b.dataset.u, title: b.dataset.t }); closeSheet(); } catch (er) { b.disabled = false; b.style.opacity = ''; el.querySelector('#gpe').textContent = er.message; } };
|
||||||
|
load(false);
|
||||||
|
}
|
||||||
|
function chPlacePicker() {
|
||||||
|
const to = ch.cur, el = openSheet('Share a place', '', `<div class="bar" style="justify-content:flex-start"><button class="btn" id="plme">📍 Send my location</button></div><p class="sub" id="plmm" style="margin:0 0 8px">Your phone asks first. This sends where you are right now, once; it does not keep following you.</p>
|
||||||
|
<form id="plf" class="bar" style="flex-wrap:nowrap;gap:6px"><input type="search" id="plq" placeholder="Or search for a place" autocomplete="off" maxlength="100" style="flex:1;min-width:0"><button class="btn ghost">Search</button></form><div class="list" id="plr"></div><p class="err" id="ple"></p>`);
|
||||||
|
const send = async (title, sub, lat, lng) => { try { await chPost('/send', { conv: to, share: { kind: 'place', title, sub, lat, lng } }); closeSheet(); } catch (e) { el.querySelector('#ple').textContent = e.message; } };
|
||||||
|
el.querySelector('#plme').onclick = () => {
|
||||||
|
if (!navigator.geolocation) { el.querySelector('#ple').textContent = 'This browser cannot share a location here. Search for the place instead.'; return; }
|
||||||
|
el.querySelector('#plmm').textContent = 'Finding you…';
|
||||||
|
navigator.geolocation.getCurrentPosition(p => send('My location', `${p.coords.latitude.toFixed(4)}, ${p.coords.longitude.toFixed(4)}`, p.coords.latitude, p.coords.longitude), e => { el.querySelector('#plmm').textContent = e.code === 1 ? 'Location is blocked. Allow it for this site in your browser settings, or search for the place instead.' : 'Could not find your location. Search for the place instead.'; }, { enableHighAccuracy: true, timeout: 12000, maximumAge: 30000 });
|
||||||
|
};
|
||||||
|
el.querySelector('#plf').onsubmit = async e => { e.preventDefault(); const q = el.querySelector('#plq').value.trim(), box = el.querySelector('#plr'); el.querySelector('#ple').textContent = ''; if (q.length < 3) { el.querySelector('#ple').textContent = 'Type at least three letters.'; return; }
|
||||||
|
box.innerHTML = '<div class="row"><span class="grow"><small>Searching…</small></span></div>';
|
||||||
|
try { const r = await chApi('/places?q=' + encodeURIComponent(q)); box.innerHTML = r.items.map((x, i) => `<a href="#" class="row" data-i="${i}"><span class="grow" style="white-space:normal"><b>${esc(x.title)}</b><small>${esc(x.sub)}</small></span></a>`).join('') || '<div class="row"><span class="grow"><small>No places found.</small></span></div>';
|
||||||
|
box.querySelectorAll('[data-i]').forEach(a => a.onclick = ev => { ev.preventDefault(); const x = r.items[+a.dataset.i]; send(x.title, x.sub, x.lat, x.lng); }); } catch (er) { box.innerHTML = ''; el.querySelector('#ple').textContent = er.message; } };
|
||||||
|
}
|
||||||
|
// ---- one list for Chat and Signal
|
||||||
|
async function chLoadSignal() {
|
||||||
|
ch.sig = []; if (typeof allowed !== 'function' || !allowed('signal') || typeof sgApi !== 'function') return;
|
||||||
|
try { const r = await sgApi('/convs'); ch.sig = (r.convs || []).map(c => ({ ...c, source: 'signal', name: c.name || c.id })); } catch { ch.sig = []; }
|
||||||
|
}
|
||||||
|
const chSigRow = c => `<a class="row sgrow" data-sig="1" href="#/signal/${encodeURIComponent(c.id)}"><span class="sgav" style="background:${sgColor(c.id)}">${c.type === 'group' ? icon('chat') : esc(sgInitial(c.name))}</span>
|
||||||
|
<span class="grow"><b>${esc(c.name)} <small class="srcbadge">Signal</small></b><small>${esc(c.preview || '')}</small></span><span class="sgside"><small>${c.ts ? sgTime(c.ts) : ''}</small>${c.unread ? `<i class="nbadge" style="position:static">${c.unread}</i>` : ''}</span></a>`;
|
||||||
|
/** Signal changed (a message came in): redraw the Chat list if it is showing. */
|
||||||
|
function chSigChanged() { if (typeof ch !== 'undefined' && ch.root && document.contains(ch.root) && location.hash.startsWith('#/chat')) chLoadSignal().then(() => { if (chq('#chlist')) chDrawList(); }); }
|
||||||
+7
-5
@@ -44,7 +44,7 @@ async function chMount(root) {
|
|||||||
}
|
}
|
||||||
async function chRefresh(first) {
|
async function chRefresh(first) {
|
||||||
try {
|
try {
|
||||||
const r = await chApi('/convs'); ch.convs = r.convs; ch.unread = r.unread; renderNav(activeTab);
|
const [r] = await Promise.all([chApi('/convs'), typeof chLoadSignal === 'function' ? chLoadSignal() : null]); ch.convs = r.convs; ch.unread = r.unread; renderNav(activeTab);
|
||||||
if (!chq('#chlist')) return; chDrawList();
|
if (!chq('#chlist')) return; chDrawList();
|
||||||
if (ch.cur) await chDrawThread(first); else chq('#chm').innerHTML = '<p class="empty">Choose a chat, or start a new one.</p>';
|
if (ch.cur) await chDrawThread(first); else chq('#chm').innerHTML = '<p class="empty">Choose a chat, or start a new one.</p>';
|
||||||
} catch (e) { const l = chq('#chlist'); if (l) l.innerHTML = `<p class="err" style="padding:12px">${esc(e.message)}</p>`; }
|
} catch (e) { const l = chq('#chlist'); if (l) l.innerHTML = `<p class="err" style="padding:12px">${esc(e.message)}</p>`; }
|
||||||
@@ -61,7 +61,8 @@ function chDrawList() {
|
|||||||
const q = (chq('#chq') || {}).value ? chq('#chq').value.toLowerCase().trim() : '', box = chq('#chlist'); if (!box) return;
|
const q = (chq('#chq') || {}).value ? chq('#chq').value.toLowerCase().trim() : '', box = chq('#chlist'); if (!box) return;
|
||||||
const match = c => !q || c.name.toLowerCase().includes(q) || (c.preview || '').toLowerCase().includes(q), live = ch.convs.filter(c => !c.archived && match(c)), arch = ch.convs.filter(c => c.archived && match(c));
|
const match = c => !q || c.name.toLowerCase().includes(q) || (c.preview || '').toLowerCase().includes(q), live = ch.convs.filter(c => !c.archived && match(c)), arch = ch.convs.filter(c => c.archived && match(c));
|
||||||
const found = q.length >= 2 && ch.found ? ch.found : [];
|
const found = q.length >= 2 && ch.found ? ch.found : [];
|
||||||
box.innerHTML = live.map(chRow).join('') + (arch.length ? `<button class="row" id="charch"><span class="grow"><small>${ch.showArchived || q ? '▾' : '▸'} Archived (${arch.length})</small></span></button>${ch.showArchived || q ? arch.map(chRow).join('') : ''}` : '')
|
const sig = (ch.sig || []).filter(match), rows = [...live.map(c => ({ ts: c.ts || 0, html: chRow(c) })), ...sig.map(c => ({ ts: c.ts || 0, html: chSigRow(c) }))].sort((a, b) => b.ts - a.ts);
|
||||||
|
box.innerHTML = rows.map(r => r.html).join('') + (arch.length ? `<button class="row" id="charch"><span class="grow"><small>${ch.showArchived || q ? '▾' : '▸'} Archived (${arch.length})</small></span></button>${ch.showArchived || q ? arch.map(chRow).join('') : ''}` : '')
|
||||||
+ (found.length ? `<p class="sub" style="margin:12px 12px 4px">In messages</p>${found.map(f => `<a class="row sgrow" href="#/chat/${encodeURIComponent(f.conv)}"><span class="grow"><b>${esc(f.convName)}</b><small>${esc(f.msg.name)}: ${esc(f.msg.text || (f.msg.share ? f.msg.share.title : ''))}</small></span><span class="sgside"><small>${sgTime(f.msg.ts)}</small></span></a>`).join('')}` : '')
|
+ (found.length ? `<p class="sub" style="margin:12px 12px 4px">In messages</p>${found.map(f => `<a class="row sgrow" href="#/chat/${encodeURIComponent(f.conv)}"><span class="grow"><b>${esc(f.convName)}</b><small>${esc(f.msg.name)}: ${esc(f.msg.text || (f.msg.share ? f.msg.share.title : ''))}</small></span><span class="sgside"><small>${sgTime(f.msg.ts)}</small></span></a>`).join('')}` : '')
|
||||||
|| '';
|
|| '';
|
||||||
if (!box.innerHTML) box.innerHTML = `<p class="empty">${q ? 'Nothing matches' : 'No chats yet. Tap New to start one.'}</p>`;
|
if (!box.innerHTML) box.innerHTML = `<p class="empty">${q ? 'Nothing matches' : 'No chats yet. Tap New to start one.'}</p>`;
|
||||||
@@ -79,13 +80,14 @@ function chPoll(m) {
|
|||||||
<small>${total} ${total === 1 ? 'person has' : 'people have'} voted</small></div>`;
|
<small>${total} ${total === 1 ? 'person has' : 'people have'} voted</small></div>`;
|
||||||
}
|
}
|
||||||
// ---- share cards: a song, film, book... sent from its own screen. Tapping opens it, unless that part of the hub is not turned on for this person.
|
// ---- share cards: a song, film, book... sent from its own screen. Tapping opens it, unless that part of the hub is not turned on for this person.
|
||||||
const CH_SHARE = { song: ['🎵', 'Song'], album: ['💿', 'Album'], artist: ['🎤', 'Artist'], playlist: ['📃', 'Playlist'], movie: ['🎬', 'Movie'], show: ['📺', 'TV show'], episode: ['📺', 'Episode'], book: ['📖', 'Book'], audiobook: ['🎧', 'Audiobook'], podcast: ['🎙️', 'Podcast'], podcastep: ['🎙️', 'Podcast episode'], radio: ['📻', 'Radio'] };
|
const CH_SHARE = { song: ['🎵', 'Song'], album: ['💿', 'Album'], artist: ['🎤', 'Artist'], playlist: ['📃', 'Playlist'], movie: ['🎬', 'Movie'], show: ['📺', 'TV show'], episode: ['📺', 'Episode'], book: ['📖', 'Book'], audiobook: ['🎧', 'Audiobook'], podcast: ['🎙️', 'Podcast'], podcastep: ['🎙️', 'Podcast episode'], radio: ['📻', 'Radio'], place: ['📍', 'Place'] };
|
||||||
/** The tab a deep link lives in decides whether this person can open it (a child account only gets the tabs a parent allowed). */
|
/** The tab a deep link lives in decides whether this person can open it (a child account only gets the tabs a parent allowed). */
|
||||||
const chShareOk = link => { const tab = String(link || '').split('/')[1]; return !!tab && !!routesOf()[tab] && allowed(tab); };
|
const chShareOk = link => { if (/^https:\/\/maps\.apple\.com\/\?ll=/.test(String(link || ''))) return true; const tab = String(link || '').split('/')[1]; return !!tab && !!routesOf()[tab] && allowed(tab); };
|
||||||
function chShareCard(m) {
|
function chShareCard(m) {
|
||||||
const s = m.share, k = CH_SHARE[s.kind] || ['🔗', 'Shared'], ok = chShareOk(s.link), art = /^\/(plex|api)\//.test(s.art || '') ? s.art : '';
|
const s = m.share, k = CH_SHARE[s.kind] || ['🔗', 'Shared'], ok = chShareOk(s.link), art = /^\/(plex|api)\//.test(s.art || '') ? s.art : '';
|
||||||
const body = `${art ? `<img class="sgshare-art" alt="" loading="lazy" src="${esc(art)}" onerror="this.replaceWith(Object.assign(document.createElement('i'),{className:'sgshare-art',textContent:'${k[0]}'}))">` : `<i class="sgshare-art">${k[0]}</i>`}
|
const body = `${art ? `<img class="sgshare-art" alt="" loading="lazy" src="${esc(art)}" onerror="this.replaceWith(Object.assign(document.createElement('i'),{className:'sgshare-art',textContent:'${k[0]}'}))">` : `<i class="sgshare-art">${k[0]}</i>`}
|
||||||
<span class="sgshare-t"><small>${k[0]} ${esc(k[1])}</small><b>${esc(s.title)}</b>${s.sub ? `<em>${esc(s.sub)}</em>` : ''}${ok ? '' : '<small class="sgshare-off">Not available for you</small>'}</span>`;
|
<span class="sgshare-t"><small>${k[0]} ${esc(k[1])}</small><b>${esc(s.title)}</b>${s.sub ? `<em>${esc(s.sub)}</em>` : ''}${ok ? '' : '<small class="sgshare-off">Not available for you</small>'}</span>`;
|
||||||
|
if (s.kind === 'place') return `<a class="sgshare" href="${esc(s.link)}" target="_blank" rel="noopener noreferrer">${body}<span class="sgshare-go">›</span></a>`;
|
||||||
return ok ? `<a class="sgshare" href="${esc(s.link)}">${body}<span class="sgshare-go">›</span></a>` : `<div class="sgshare off" role="note">${body}</div>`;
|
return ok ? `<a class="sgshare" href="${esc(s.link)}">${body}<span class="sgshare-go">›</span></a>` : `<div class="sgshare off" role="note">${body}</div>`;
|
||||||
}
|
}
|
||||||
function chBubble(m, c, prev) {
|
function chBubble(m, c, prev) {
|
||||||
@@ -162,7 +164,7 @@ function chWireComposer() {
|
|||||||
ta.oninput = () => { grow(); chSetDraft(ch.cur, ta.value); if (ta.value.trim() && Date.now() - ch.typedAt > 3000) { ch.typedAt = Date.now(); chPost('/typing', { conv: ch.cur }).catch(() => {}); } };
|
ta.oninput = () => { grow(); chSetDraft(ch.cur, ta.value); if (ta.value.trim() && Date.now() - ch.typedAt > 3000) { ch.typedAt = Date.now(); chPost('/typing', { conv: ch.cur }).catch(() => {}); } };
|
||||||
chMentionBox(ta);
|
chMentionBox(ta);
|
||||||
ta.onkeydown = e => { if (e.key === 'Enter' && !e.shiftKey && matchMedia('(pointer: fine)').matches) { e.preventDefault(); chq('#chform').requestSubmit(); } };
|
ta.onkeydown = e => { if (e.key === 'Enter' && !e.shiftKey && matchMedia('(pointer: fine)').matches) { e.preventDefault(); chq('#chform').requestSubmit(); } };
|
||||||
chq('#chat').onclick = () => actionSheet('Attach', '', [{ label: 'Photo or file', icon: 'clip', run: () => chq('#chfile').click() }, { label: 'Poll', icon: 'check', run: chNewPoll }]);
|
chGifOn(); chq('#chat').onclick = () => actionSheet('Attach', '', [{ label: 'Photo or file', icon: 'clip', run: () => chq('#chfile').click() }, ...(ch.gifOn ? [{ label: 'GIF', icon: 'play', run: chGifPicker }] : []), { label: 'Place or location', icon: 'pin', run: chPlacePicker }, { label: 'Poll', icon: 'check', run: chNewPoll }]);
|
||||||
chq('#chem').onclick = chEmojiPanel; chq('#chmic').onclick = chRecStart;
|
chq('#chem').onclick = chEmojiPanel; chq('#chmic').onclick = chRecStart;
|
||||||
const sw = () => { const has = !!ta.value.trim() || ch.tray.length; chq('#chmic').hidden = has; chq('#chsend').hidden = !has; }; ta.addEventListener('input', sw); sw(); ch.swSend = sw;
|
const sw = () => { const has = !!ta.value.trim() || ch.tray.length; chq('#chmic').hidden = has; chq('#chsend').hidden = !has; }; ta.addEventListener('input', sw); sw(); ch.swSend = sw;
|
||||||
chq('#chfile').onchange = e => { ch.tray.push(...e.target.files); e.target.value = ''; chDrawTray(); ch.swSend(); };
|
chq('#chfile').onchange = e => { ch.tray.push(...e.target.files); e.target.value = ''; chDrawTray(); ch.swSend(); };
|
||||||
|
|||||||
@@ -81,6 +81,7 @@
|
|||||||
<script defer src="/radio-view.js"></script>
|
<script defer src="/radio-view.js"></script>
|
||||||
<script defer src="/store-view.js"></script>
|
<script defer src="/store-view.js"></script>
|
||||||
<script defer src="/recipes-view.js"></script>
|
<script defer src="/recipes-view.js"></script>
|
||||||
|
<script defer src="/pantry-view.js"></script>
|
||||||
<script defer src="/contacts-view.js"></script>
|
<script defer src="/contacts-view.js"></script>
|
||||||
<script defer src="/bible-view.js"></script>
|
<script defer src="/bible-view.js"></script>
|
||||||
<script defer src="/devotion-view.js"></script>
|
<script defer src="/devotion-view.js"></script>
|
||||||
@@ -95,6 +96,7 @@
|
|||||||
<script defer src="/file-actions.js"></script>
|
<script defer src="/file-actions.js"></script>
|
||||||
<script defer src="/signal-view.js"></script>
|
<script defer src="/signal-view.js"></script>
|
||||||
<script defer src="/chat-view.js"></script>
|
<script defer src="/chat-view.js"></script>
|
||||||
|
<script defer src="/chat-extras.js"></script>
|
||||||
<script defer src="/notes-view.js"></script>
|
<script defer src="/notes-view.js"></script>
|
||||||
<script defer src="/chores-view.js"></script>
|
<script defer src="/chores-view.js"></script>
|
||||||
<script defer src="/family-view.js"></script>
|
<script defer src="/family-view.js"></script>
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
'use strict';
|
||||||
|
// ---- Pantry (Recipes > Pantry): what you keep in the kitchen, how many are left, and the level that counts as running low. A phone can scan a barcode to add one or use one;
|
||||||
|
// the first time a barcode is seen you say which item it is (so Green Giant corn and the store brand are both "Corn"). Low items go on the shopping list in a tap.
|
||||||
|
const PA_UNITS = [['', 'each'], ['g', 'g'], ['kg', 'kg'], ['oz', 'oz'], ['lb', 'lb'], ['ml', 'ml'], ['l', 'litres'], ['tsp', 'tsp'], ['tbsp', 'tbsp'], ['cup', 'cups'], ['fl oz', 'fl oz'], ['pint', 'pints'], ['quart', 'quarts'], ['gallon', 'gallons']];
|
||||||
|
const paStep = u => ({ g: 100, ml: 100 }[u] || 1);
|
||||||
|
const paApi = (p, o) => jfetch('/api/pantry' + p, o), paOpt = o => ({ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(o) });
|
||||||
|
const paAgo = t => { const m = Math.round((Date.now() - t) / 60000); return m < 1 ? 'just now' : m < 60 ? m + ' min ago' : m < 1440 ? Math.round(m / 60) + ' h ago' : new Date(t).toLocaleDateString(undefined, { weekday: 'short' }); };
|
||||||
|
const paRecent = r => r.length ? `<h2>Recently</h2><div class="list">${r.map(x => `<div class="row"><span class="grow"><b>${esc(x.who)}</b> ${x.delta < 0 ? 'took' : 'put back'} ${esc(x.item)}<small>${esc(paAgo(x.t))}${x.note ? ' · ' + esc(x.note) : ''}</small></span></div>`).join('')}</div>` : '';
|
||||||
|
/** The simple way to use things: a big tile for each item, tap to take one (with Undo). Children see only this. */
|
||||||
|
async function viewPantryTake() {
|
||||||
|
let st; const v = $('#view'), kid = !!(ME && ME.kid && ME.kid.on);
|
||||||
|
try { st = await paApi('/'); } catch (e) { v.innerHTML = `<div class="wrap"><h1>Pantry</h1><p class="err">${esc(e.message)}</p></div>`; return; }
|
||||||
|
if (!location.hash.startsWith('#/recipes')) return;
|
||||||
|
const draw = () => {
|
||||||
|
v.innerHTML = `<div class="wrap"><div class="ptop"><h1>${kid ? 'Pantry' : 'Take one'}</h1><span class="grow"></span>${kid ? '' : `<a class="btn ghost" href="#/recipes/pantry">Manage</a>`}</div>
|
||||||
|
<p class="sub" style="margin-top:0">Tap what you are taking. It counts one off so the family knows when to buy more.</p>
|
||||||
|
<div class="paTiles">${st.items.filter(x => !kid || !x.unit).map(x => `<button type="button" class="paTile${x.qty === 0 ? ' out' : ''}${x.isLow && x.qty ? ' low' : ''}" data-u="${esc(x.id)}"${x.qty === 0 ? ' disabled' : ''} aria-label="${x.unit ? 'Use some ' : 'Take one '}${esc(x.name)}${x.qty != null ? ', ' + x.label + ' left' : ''}"><b>${esc(x.name)}</b><small>${x.qty == null ? '' : x.qty === 0 ? 'none left' : x.label + ' left'}</small></button>`).join('') || '<p class="empty">Nothing in the pantry yet.</p>'}</div>
|
||||||
|
<div class="bar" style="justify-content:flex-start"><button class="btn ghost" id="pasuse">${icon('plus')}Scan a barcode instead</button></div>${paRecent(st.recent || [])}</div>`;
|
||||||
|
v.querySelectorAll('[data-u]').forEach(b => b.onclick = async () => { const own = st.items.find(x => x.id === b.dataset.u); if (own && own.unit) return paUseSome(own, list => { st.items = list.items; st.recent = list.recent; draw(); }); b.disabled = true; try { const r = await paApi('/use', paOpt({ id: b.dataset.u })); st.items = r.items; st.recent = r.recent; draw(); const it = r.item;
|
||||||
|
toast(`Took one ${it.name}${it.qty != null ? ': ' + it.qty + ' left' : ''}`, { label: 'Undo', run: async () => { try { const u = await paApi('/use', paOpt({ id: it.id, undo: true })); st.items = u.items; st.recent = u.recent; if ($('.paTiles')) draw(); toast('Put back'); } catch (e) { toast(e.message); } } }); } catch (e) { b.disabled = false; toast(e.message); } });
|
||||||
|
$('#pasuse').onclick = () => pantryScan('use', list => { st.items = list; draw(); }, () => st.items);
|
||||||
|
};
|
||||||
|
draw();
|
||||||
|
}
|
||||||
|
async function viewPantry(sub) {
|
||||||
|
if (sub === 'take' || (ME && ME.kid && ME.kid.on)) return viewPantryTake();
|
||||||
|
let items = [], recent = []; const v = $('#view');
|
||||||
|
try { const r = await paApi('/'); items = r.items; recent = r.recent || []; } catch (e) { v.innerHTML = `<div class="wrap"><h1>Pantry</h1><p class="err">${esc(e.message)}</p></div>`; return; }
|
||||||
|
if (!location.hash.startsWith('#/recipes/pantry')) return;
|
||||||
|
const draw = () => {
|
||||||
|
v.innerHTML = `<div class="wrap"><div class="ptop"><h1>Recipes</h1></div>${typeof rcTabs === 'function' ? rcTabs('pantry') : ''}
|
||||||
|
<div class="bar" style="justify-content:flex-start"><a class="btn" href="#/recipes/pantry/take">Take one</a><button class="btn ghost" id="pasadd">${icon('plus')}Scan to add</button><button class="btn ghost" id="pasuse">Scan to use one</button></div>
|
||||||
|
<form id="paf" class="bar" style="flex-wrap:nowrap;gap:6px"><input type="text" id="pan" placeholder="Add an item" autocomplete="off" required style="flex:2;min-width:0"><input type="number" id="paq" placeholder="How many" min="0" step="any" inputmode="decimal" style="flex:1;min-width:0" aria-label="How many are left"><select id="pau" aria-label="Unit" style="flex:1;min-width:0">${PA_UNITS.map(u => `<option value="${esc(u[0])}">${esc(u[1])}</option>`).join('')}</select><input type="number" id="paw" placeholder="Low at" min="0" step="any" inputmode="decimal" style="flex:1;min-width:0" aria-label="Counts as running low at"><button class="btn">Add</button></form>
|
||||||
|
<div class="list">${items.map(x => `<div class="row"><span class="grow" style="white-space:normal"><b>${esc(x.name)}</b>${x.isLow ? ' <small style="color:var(--danger)">running low</small>' : ''}<small>${x.qty == null ? 'not counted' : x.label + ' left'}${x.low != null ? ' · low at ' + x.lowLabel : ''}${x.codes.length ? ' · ' + x.codes.length + ' barcode' + (x.codes.length === 1 ? '' : 's') : ''}</small></span>
|
||||||
|
${x.isLow && typeof rcApi === 'function' ? `<button class="btn ghost" data-shop="${esc(x.id)}" style="min-height:36px">To shopping</button>` : ''}${x.codes.length ? `<button class="ibtn" data-bc="${esc(x.id)}" aria-label="Barcodes for ${esc(x.name)}" title="Barcodes">${icon('list')}</button>` : ''}${x.qty != null && x.unit ? `<button class="btn ghost" data-some="${esc(x.id)}" style="min-height:36px">Use some</button>` : ''}${x.qty != null ? `<button class="ibtn" data-d="${esc(x.id)}:-${paStep(x.unit)}" aria-label="Less ${esc(x.name)}">−</button><button class="ibtn" data-d="${esc(x.id)}:${paStep(x.unit)}" aria-label="More ${esc(x.name)}">+</button>` : ''}<button class="ibtn" data-x="${esc(x.id)}" aria-label="Remove ${esc(x.name)}">${icon('trash')}</button></div>`).join('') || '<div class="row"><span class="grow"><small>Nothing yet. Add what you keep in the kitchen, or scan a barcode.</small></span></div>'}</div>
|
||||||
|
<p class="sub" style="margin-top:12px">Counts are kept by hand (and by scanning); they do not go down when you cook. The meal plan points out ingredients you already have.</p>${paRecent(recent)}</div>`;
|
||||||
|
const go = async (p, o) => { try { items = (await paApi(p, paOpt(o))).items; draw(); } catch (e) { toast(e.message); } };
|
||||||
|
$('#paf').onsubmit = e => { e.preventDefault(); go('/item', { name: $('#pan').value, qty: $('#paq').value, unit: $('#pau').value, low: $('#paw').value }); };
|
||||||
|
v.querySelectorAll('[data-some]').forEach(b => b.onclick = () => paUseSome(items.find(x => x.id === b.dataset.some), r => { items = r.items; recent = r.recent || recent; draw(); }));
|
||||||
|
v.querySelectorAll('[data-d]').forEach(b => b.onclick = () => { const i = b.dataset.d.lastIndexOf(':'); go('/adjust', { id: b.dataset.d.slice(0, i), delta: +b.dataset.d.slice(i + 1) }); });
|
||||||
|
v.querySelectorAll('[data-x]').forEach(b => b.onclick = () => go('/delete', { id: b.dataset.x }));
|
||||||
|
v.querySelectorAll('[data-shop]').forEach(b => b.onclick = async () => { const it = items.find(x => x.id === b.dataset.shop); try { await rcApi('/shopping/add', rcOpt('POST', { text: it.name })); toast(it.name + ' added to the shopping list'); } catch (e) { toast(e.message); } });
|
||||||
|
v.querySelectorAll('[data-bc]').forEach(b => b.onclick = () => { const it = items.find(x => x.id === b.dataset.bc), el = openSheet('Barcodes for ' + it.name, 'Scanning any of these counts as ' + it.name + '.', `<div class="list">${it.codes.map(c => `<div class="row"><span class="grow"><b>${esc(c)}</b></span><button class="ibtn" data-u="${esc(c)}" aria-label="Unlink ${esc(c)}">${icon('trash')}</button></div>`).join('')}</div>`); el.querySelectorAll('[data-u]').forEach(u => u.onclick = async () => { closeSheet(); go('/unlink', { id: it.id, code: u.dataset.u }); }); });
|
||||||
|
$('#pasadd').onclick = () => pantryScan('add', list => { items = list; draw(); }, () => items); $('#pasuse').onclick = () => pantryScan('use', list => { items = list; draw(); }, () => items);
|
||||||
|
};
|
||||||
|
draw();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The scanner: the camera looks for barcodes and each one found adds one (or uses one). Keeps going so a bag of shopping can be done in a row. */
|
||||||
|
let paZx = null;
|
||||||
|
const paLoadZx = () => paZx || (paZx = new Promise((ok, no) => { if (window.ZXing) return ok(window.ZXing); const s = document.createElement('script'); s.src = '/vendor/zxing/zxing.min.js'; s.onload = () => ok(window.ZXing); s.onerror = () => { paZx = null; no(new Error('Could not load the scanner')); }; document.head.appendChild(s); }));
|
||||||
|
function pantryScan(mode, onChange, getItems) {
|
||||||
|
const el = openSheet(mode === 'use' ? 'Scan to use one' : 'Scan to add', mode === 'use' ? 'Each barcode takes one off the count.' : 'Each barcode adds one to the count.', `<video id="pscv" playsinline muted autoplay style="width:100%;border-radius:12px;background:#000;aspect-ratio:4/3;object-fit:cover"></video>
|
||||||
|
<p class="sub" id="pscs" role="status" style="margin:8px 0">Starting the camera…</p><div id="pscq"></div>
|
||||||
|
<form id="pscm" class="bar" style="flex-wrap:nowrap;gap:6px"><input type="text" id="pscn" inputmode="numeric" placeholder="Or type the barcode number" autocomplete="off" aria-label="Barcode number" style="flex:1;min-width:0"><button class="btn ghost">Go</button></form>`);
|
||||||
|
const video = el.querySelector('#pscv'), status = t => { const s = el.querySelector('#pscs'); if (s) s.textContent = t; };
|
||||||
|
let stream = null, stopped = false, busy = false, last = '', lastAt = 0, reader = null, timer = 0;
|
||||||
|
const stop = () => { stopped = true; clearInterval(timer); try { reader && reader.reset(); } catch { /* not started */ } if (stream) stream.getTracks().forEach(t => t.stop()); };
|
||||||
|
const alive = () => !stopped && el.isConnected;
|
||||||
|
const resume = () => { busy = false; if (alive()) { el.querySelector('#pscq').innerHTML = ''; status('Point the camera at a barcode'); } };
|
||||||
|
const finish = (r, said) => { onChange(r.items); status(said); toast(said); try { navigator.vibrate && navigator.vibrate(60); } catch { /* no vibration */ } setTimeout(resume, 1300); };
|
||||||
|
const found = async code => {
|
||||||
|
if (busy || !alive() || (code === last && Date.now() - lastAt < 4000)) return; busy = true; last = code; lastAt = Date.now(); status('Looking up ' + code + '…');
|
||||||
|
try {
|
||||||
|
const r = await paApi('/lookup?code=' + code); if (!alive()) return;
|
||||||
|
if (r.linked) { const o = await paApi('/scan', paOpt({ code, mode })); return finish(o, `${o.item.name}: ${o.item.qty} left${o.item.isLow ? ' (running low)' : ''}`); }
|
||||||
|
const list = (getItems() || []), matches = (r.matches || []).map(m => m.id), sorted = [...list.filter(x => matches.includes(x.id)), ...list.filter(x => !matches.includes(x.id))];
|
||||||
|
el.querySelector('#pscq').innerHTML = `<form id="pscf"><p style="margin:0 0 6px"><b>${esc(r.product ? r.product.name : 'Barcode ' + code)}</b>${r.product && r.product.brand ? ' <small>· ' + esc(r.product.brand) + '</small>' : ''}</p>
|
||||||
|
${!r.product ? `<p class="sub" style="margin:0 0 6px">${r.lookedUp ? 'The product database does not know this one.' : 'Could not reach the product database.'} Say what it is once and it is remembered.</p>` : '<p class="sub" style="margin:0 0 6px">First time this barcode is seen. Which item is it?</p>'}
|
||||||
|
<label for="pscw">Which item</label><select id="pscw">${sorted.map(x => `<option value="${esc(x.id)}">${esc(x.name)}</option>`).join('')}<option value=""${matches.length ? '' : ' selected'}>A new item…</option></select>
|
||||||
|
<div id="pscnw"${matches.length ? ' hidden' : ''}><label for="pscnn">Name of the new item</label><input type="text" id="pscnn" value="${esc(r.product ? r.product.short : '')}" autocomplete="off" maxlength="60"></div>
|
||||||
|
<div class="bar"><button type="button" class="btn ghost" id="pscx" style="flex:1;justify-content:center">Skip</button><button class="btn" style="flex:1;justify-content:center">${mode === 'use' ? 'Use one' : 'Add one'}</button></div><div class="err" id="psce"></div></form>`;
|
||||||
|
const sel = el.querySelector('#pscw'), nw = el.querySelector('#pscnw'); sel.onchange = () => { nw.hidden = !!sel.value; }; if (sel.value === '' ) nw.hidden = false; status('Which item is this?');
|
||||||
|
el.querySelector('#pscx').onclick = resume;
|
||||||
|
el.querySelector('#pscf').onsubmit = async e => { e.preventDefault(); try { const o = await paApi('/scan', paOpt({ code, mode, itemId: sel.value || undefined, name: sel.value ? undefined : el.querySelector('#pscnn').value })); finish(o, `${o.item.name}: ${o.item.qty} left${o.made ? ' (new item)' : ''}`); } catch (er) { el.querySelector('#psce').textContent = er.message; } };
|
||||||
|
} catch (e) { status(e.message); toast(e.message); setTimeout(resume, 1500); }
|
||||||
|
};
|
||||||
|
el.querySelector('#pscm').onsubmit = e => { e.preventDefault(); const c = el.querySelector('#pscn').value.replace(/\D/g, ''); el.querySelector('#pscn').value = ''; if (/^\d{8,14}$/.test(c)) { last = ''; found(c); } else status('A barcode is 8 to 14 digits.'); };
|
||||||
|
(async () => {
|
||||||
|
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) return status('This browser cannot use the camera here (it needs a secure page). Type the number instead.');
|
||||||
|
try { stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); } catch (e) { return status(e && e.name === 'NotAllowedError' ? 'The camera is blocked. Allow it for this site, or type the number instead.' : 'No camera could be started. Type the number instead.'); }
|
||||||
|
if (!alive()) return stop(); video.srcObject = stream; try { await video.play(); } catch { /* autoplay is allowed on a tap */ } status('Point the camera at a barcode');
|
||||||
|
if ('BarcodeDetector' in window) { // Chrome and Android have a built-in reader
|
||||||
|
let det; try { det = new BarcodeDetector({ formats: ['ean_13', 'ean_8', 'upc_a', 'upc_e'] }); } catch { det = null; }
|
||||||
|
if (det) { timer = setInterval(async () => { if (!alive()) return stop(); if (busy || video.readyState < 2) return; try { const r = await det.detect(video); if (r[0] && r[0].rawValue) found(r[0].rawValue); } catch { /* a frame that cannot be read */ } }, 300); return; }
|
||||||
|
}
|
||||||
|
try { // everything else (iPhone Safari): a reader written in JavaScript, loaded only now
|
||||||
|
const Z = await paLoadZx(), hints = new Map(); hints.set(Z.DecodeHintType.POSSIBLE_FORMATS, [Z.BarcodeFormat.EAN_13, Z.BarcodeFormat.EAN_8, Z.BarcodeFormat.UPC_A, Z.BarcodeFormat.UPC_E]); reader = new Z.BrowserMultiFormatReader(hints);
|
||||||
|
timer = setInterval(() => { if (!alive()) stop(); }, 500);
|
||||||
|
reader.decodeFromVideoElement(video, (res) => { if (res && alive() && !busy) found(res.getText()); });
|
||||||
|
} catch (e) { status(e.message + ' Type the number instead.'); }
|
||||||
|
})();
|
||||||
|
new MutationObserver((_, ob) => { if (!el.isConnected) { stop(); ob.disconnect(); } }).observe(document.body, { childList: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Use some of an item: an amount in any unit that can be turned into the item's own (4 cups of the flour that is kept in pounds). */
|
||||||
|
function paUseSome(it, done) {
|
||||||
|
const el = openSheet('Use some ' + it.name.toLowerCase(), `${it.label} left. Any unit works if it can be turned into ${it.unit || 'a count'} (cups of flour into pounds, for instance).`, `<form id="pusf"><div class="bar" style="flex-wrap:nowrap;gap:6px"><input type="number" id="pusa" min="0" step="any" inputmode="decimal" placeholder="Amount" required style="flex:1;min-width:0"><select id="pusu" aria-label="Unit" style="flex:1;min-width:0">${PA_UNITS.map(u => `<option value="${esc(u[0])}"${u[0] === it.unit ? ' selected' : ''}>${esc(u[1])}</option>`).join('')}</select></div><div class="err" id="puse"></div><div class="bar"><button class="btn" style="flex:1;justify-content:center">Take it out</button></div></form>`);
|
||||||
|
setTimeout(() => el.querySelector('#pusa').focus(), 80);
|
||||||
|
el.querySelector('#pusf').onsubmit = async e => { e.preventDefault(); try { const r = await paApi('/take', paOpt({ takes: [{ id: it.id, amount: +el.querySelector('#pusa').value, unit: el.querySelector('#pusu').value }], note: 'used some' })); if (r.skipped.length) { el.querySelector('#puse').textContent = 'That cannot be turned into ' + (it.unit || 'a count') + ' for ' + it.name.toLowerCase() + '. Pick a matching unit.'; return; } closeSheet(); const d = r.done[0]; toast(`${d.name}: ${d.label || 'none'} left${d.isLow ? ' (running low)' : ''}`); done(r); } catch (er) { el.querySelector('#puse').textContent = er.message; } };
|
||||||
|
}
|
||||||
+25
-22
@@ -4,7 +4,7 @@
|
|||||||
const rcApi = (p, opts) => jfetch('/api/recipes' + p, opts);
|
const rcApi = (p, opts) => jfetch('/api/recipes' + p, opts);
|
||||||
const rcOpt = (m, o) => ({ method: m, headers: { 'content-type': 'application/json' }, body: o ? JSON.stringify(o) : undefined });
|
const rcOpt = (m, o) => ({ method: m, headers: { 'content-type': 'application/json' }, body: o ? JSON.stringify(o) : undefined });
|
||||||
const rcTime = m => { m = +m || 0; if (!m) return ''; const h = Math.floor(m / 60); return h ? h + ' h' + (m % 60 ? ' ' + (m % 60) + ' min' : '') : m + ' min'; };
|
const rcTime = m => { m = +m || 0; if (!m) return ''; const h = Math.floor(m / 60); return h ? h + ' h' + (m % 60 ? ' ' + (m % 60) + ' min' : '') : m + ' min'; };
|
||||||
const rcTabs = on => `<div class="bar" style="margin:0 0 12px;justify-content:flex-start"><a class="btn${on === 'all' ? '' : ' ghost'}" href="#/recipes">${icon('chef')}Recipes</a><a class="btn${on === 'plan' ? '' : ' ghost'}" href="#/recipes/plan">${icon('cal')}Meal plan</a><a class="btn${on === 'shop' ? '' : ' ghost'}" href="#/recipes/shop">${icon('check')}Shopping list</a></div>`;
|
const rcTabs = on => `<div class="bar" style="margin:0 0 12px;justify-content:flex-start"><a class="btn${on === 'all' ? '' : ' ghost'}" href="#/recipes">${icon('chef')}Recipes</a><a class="btn${on === 'plan' ? '' : ' ghost'}" href="#/recipes/plan">${icon('cal')}Meal plan</a><a class="btn${on === 'pantry' ? '' : ' ghost'}" href="#/recipes/pantry">${icon('list')}Pantry</a><a class="btn${on === 'shop' ? '' : ' ghost'}" href="#/recipes/shop">${icon('check')}Shopping list</a></div>`;
|
||||||
let rcQuery = '', rcPage = 1;
|
let rcQuery = '', rcPage = 1;
|
||||||
|
|
||||||
async function viewRecipes(args = []) {
|
async function viewRecipes(args = []) {
|
||||||
@@ -12,12 +12,14 @@ async function viewRecipes(args = []) {
|
|||||||
v.innerHTML = '<div class="wrap"><h1>Recipes</h1><p class="empty">Loading…</p></div>';
|
v.innerHTML = '<div class="wrap"><h1>Recipes</h1><p class="empty">Loading…</p></div>';
|
||||||
try {
|
try {
|
||||||
if (args[0] === 'r' && args[1]) return await rcOne(decodeURIComponent(args[1]));
|
if (args[0] === 'r' && args[1]) return await rcOne(decodeURIComponent(args[1]));
|
||||||
|
if (args[0] === 'pantry') return await viewPantry(args[1]);
|
||||||
|
if (ME && ME.kid && ME.kid.on && !args[0]) return await viewPantry('take'); // children see the pantry to take from
|
||||||
if (args[0] === 'shop') return await rcShop();
|
if (args[0] === 'shop') return await rcShop();
|
||||||
if (args[0] === 'plan') return await rcPlan(args[1]);
|
if (args[0] === 'plan') return await rcPlan(args[1]);
|
||||||
return await rcHome();
|
return await rcHome();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!location.hash.startsWith('#/recipes')) return;
|
if (!location.hash.startsWith('#/recipes')) return;
|
||||||
v.innerHTML = `<div class="wrap"><h1>Recipes</h1><p class="err">${esc(e.message)}</p><div class="bar"><button class="btn ghost" id="rcretry">Try again</button></div></div>`;
|
v.innerHTML = `<div class="wrap"><h1>Recipes</h1>${rcTabs('')}<p class="err">${esc(e.message)}</p><div class="bar"><button class="btn ghost" id="rcretry">Try again</button></div></div>`; // (the Pantry does not need Mealie, so its tab is here even when recipes are not set up)
|
||||||
$('#rcretry').onclick = () => route();
|
$('#rcretry').onclick = () => route();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,7 +62,7 @@ async function rcOne(slug) {
|
|||||||
<div style="min-width:0"><h1 style="margin:0">${esc(r.name)}</h1>${r.description ? `<p class="sub" style="margin:6px 0 0;white-space:normal">${esc(r.description)}</p>` : ''}
|
<div style="min-width:0"><h1 style="margin:0">${esc(r.name)}</h1>${r.description ? `<p class="sub" style="margin:6px 0 0;white-space:normal">${esc(r.description)}</p>` : ''}
|
||||||
${facts.length ? `<p class="sub" style="margin:8px 0 0">${facts.map(f => `<b>${esc(f[0])}</b> ${esc(f[1])}`).join(' · ')}</p>` : ''}
|
${facts.length ? `<p class="sub" style="margin:8px 0 0">${facts.map(f => `<b>${esc(f[0])}</b> ${esc(f[1])}`).join(' · ')}</p>` : ''}
|
||||||
${r.orgUrl ? `<p class="sub" style="margin:4px 0 0"><a href="${esc(r.orgUrl)}" target="_blank" rel="noopener noreferrer" style="color:var(--accent)">Original page</a></p>` : ''}</div></div>
|
${r.orgUrl ? `<p class="sub" style="margin:4px 0 0"><a href="${esc(r.orgUrl)}" target="_blank" rel="noopener noreferrer" style="color:var(--accent)">Original page</a></p>` : ''}</div></div>
|
||||||
<div class="bar" style="justify-content:flex-start"><button class="btn" id="rcadd">${icon('plus')}Add ingredients to shopping list</button><button class="btn ghost" id="rcplan">${icon('cal')}Plan it</button><a class="btn ghost" href="#/recipes/shop">Shopping list</a>${allowed('chat') ? '<button class="btn ghost" id="rcshare">Share to Chat</button>' : ''}</div>
|
<div class="bar" style="justify-content:flex-start"><button class="btn" id="rcadd">${icon('plus')}Add ingredients to shopping list</button><button class="btn ghost" id="rcplan">${icon('cal')}Plan it</button><button class="btn ghost" id="rccook">${icon('check')}Cooked it</button><a class="btn ghost" href="#/recipes/shop">Shopping list</a>${allowed('chat') ? '<button class="btn ghost" id="rcshare">Share to Chat</button>' : ''}</div>
|
||||||
<div class="rccols"><section><div class="rchead"><h2>Ingredients</h2><button class="btn ghost" id="rcreset" style="min-height:32px">Uncheck all</button></div>
|
<div class="rccols"><section><div class="rchead"><h2>Ingredients</h2><button class="btn ghost" id="rcreset" style="min-height:32px">Uncheck all</button></div>
|
||||||
<div class="list">${r.ingredients.map((i, n) => i.title && !i.text ? `<p class="sub" style="margin:10px 0 2px"><b>${esc(i.title)}</b></p>` : `<label class="row rcing" style="cursor:pointer"><input type="checkbox" data-n="${n}"><span class="grow">${esc(i.text)}</span></label>`).join('') || '<p class="empty">No ingredients.</p>'}</div></section>
|
<div class="list">${r.ingredients.map((i, n) => i.title && !i.text ? `<p class="sub" style="margin:10px 0 2px"><b>${esc(i.title)}</b></p>` : `<label class="row rcing" style="cursor:pointer"><input type="checkbox" data-n="${n}"><span class="grow">${esc(i.text)}</span></label>`).join('') || '<p class="empty">No ingredients.</p>'}</div></section>
|
||||||
<section><div class="rchead"><h2>Steps</h2></div><ol class="rcsteps">${r.steps.map((s, n) => `<li data-s="${n}">${s.title ? `<b>${esc(s.title)}</b> ` : ''}${esc(s.text).replace(/\n/g, '<br>')}</li>`).join('') || '<li class="empty">No steps.</li>'}</ol></section></div>
|
<section><div class="rchead"><h2>Steps</h2></div><ol class="rcsteps">${r.steps.map((s, n) => `<li data-s="${n}">${s.title ? `<b>${esc(s.title)}</b> ` : ''}${esc(s.text).replace(/\n/g, '<br>')}</li>`).join('') || '<li class="empty">No steps.</li>'}</ol></section></div>
|
||||||
@@ -78,7 +80,7 @@ async function rcOne(slug) {
|
|||||||
$('#rcreset').onclick = () => { done = { i: [], s: [] }; store.del(sk); paint(); };
|
$('#rcreset').onclick = () => { done = { i: [], s: [] }; store.del(sk); paint(); };
|
||||||
paint();
|
paint();
|
||||||
if ($('#rcshare')) $('#rcshare').onclick = () => shareToChat(r.name + ' ' + location.origin + '/#/recipes/r/' + encodeURIComponent(slug));
|
if ($('#rcshare')) $('#rcshare').onclick = () => shareToChat(r.name + ' ' + location.origin + '/#/recipes/r/' + encodeURIComponent(slug));
|
||||||
$('#rcplan').onclick = () => rcPlanPick(r.slug, r.name, r.id);
|
$('#rcplan').onclick = () => rcPlanPick(r.slug, r.name, r.id); $('#rccook').onclick = () => rcCook(r.slug, r.name);
|
||||||
$('#rcadd').onclick = async e => {
|
$('#rcadd').onclick = async e => {
|
||||||
const b = e.currentTarget; b.disabled = true;
|
const b = e.currentTarget; b.disabled = true;
|
||||||
try { const o = await rcApi('/shopping/add-recipe', rcOpt('POST', { slug })); toast('Added to your shopping list'); b.disabled = false; return o; }
|
try { const o = await rcApi('/shopping/add-recipe', rcOpt('POST', { slug })); toast('Added to your shopping list'); b.disabled = false; return o; }
|
||||||
@@ -117,12 +119,13 @@ async function rcPlan(start) {
|
|||||||
<div class="bar" style="justify-content:space-between;align-items:center"><a class="btn ghost" href="${shift(-7)}" aria-label="Previous week">${icon('back')}</a><b>${days[0].toLocaleDateString(undefined, { month: 'short', day: 'numeric' })} – ${days[6].toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}</b><a class="btn ghost" href="${shift(7)}" aria-label="Next week">${icon('chev')}</a></div>
|
<div class="bar" style="justify-content:space-between;align-items:center"><a class="btn ghost" href="${shift(-7)}" aria-label="Previous week">${icon('back')}</a><b>${days[0].toLocaleDateString(undefined, { month: 'short', day: 'numeric' })} – ${days[6].toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}</b><a class="btn ghost" href="${shift(7)}" aria-label="Next week">${icon('chev')}</a></div>
|
||||||
<div class="list">${days.map(d => { const k = rcYmd(d), es = (plan[k] || []).slice().sort((a, b) => RC_MEALS.findIndex(m => m[0] === a.meal) - RC_MEALS.findIndex(m => m[0] === b.meal));
|
<div class="list">${days.map(d => { const k = rcYmd(d), es = (plan[k] || []).slice().sort((a, b) => RC_MEALS.findIndex(m => m[0] === a.meal) - RC_MEALS.findIndex(m => m[0] === b.meal));
|
||||||
return `<div class="row" style="align-items:flex-start${k === today ? ';outline:2px solid var(--accent);outline-offset:-2px;border-radius:12px' : ''}"><span style="width:52px;flex:none"><b>${d.toLocaleDateString(undefined, { weekday: 'short' })}</b><small style="display:block">${d.getDate()}</small></span>
|
return `<div class="row" style="align-items:flex-start${k === today ? ';outline:2px solid var(--accent);outline-offset:-2px;border-radius:12px' : ''}"><span style="width:52px;flex:none"><b>${d.toLocaleDateString(undefined, { weekday: 'short' })}</b><small style="display:block">${d.getDate()}</small></span>
|
||||||
<span class="grow">${es.map(e => `<span style="display:flex;align-items:center;gap:6px;margin:2px 0"><a href="#/recipes/r/${encodeURIComponent(e.slug)}" class="grow" style="white-space:normal">${esc(e.name)}${e.meal !== 'dinner' ? ` <small>· ${esc(e.meal)}</small>` : ''}</a><button class="ibtn" data-rm="${e.id}" aria-label="Remove ${esc(e.name)}" title="Remove">${icon('x')}</button></span>`).join('') || '<small>Nothing planned</small>'}</span>
|
<span class="grow">${es.map(e => `<span style="display:flex;align-items:center;gap:6px;margin:2px 0"><a href="#/recipes/r/${encodeURIComponent(e.slug)}" class="grow" style="white-space:normal">${esc(e.name)}${e.meal !== 'dinner' ? ` <small>· ${esc(e.meal)}</small>` : ''}</a><button class="ibtn" data-cook="${esc(e.slug)}|${esc(e.name)}" aria-label="Cooked ${esc(e.name)}" title="Cooked it: take it out of the pantry">${icon('check')}</button><button class="ibtn" data-rm="${e.id}" aria-label="Remove ${esc(e.name)}" title="Remove">${icon('x')}</button></span>`).join('') || '<small>Nothing planned</small>'}</span>
|
||||||
<button class="ibtn" data-add="${k}" aria-label="Plan a meal on ${d.toLocaleDateString(undefined, { weekday: 'long' })}" title="Add a meal">${icon('plus')}</button></div>`; }).join('')}</div>
|
<button class="ibtn" data-add="${k}" aria-label="Plan a meal on ${d.toLocaleDateString(undefined, { weekday: 'long' })}" title="Add a meal">${icon('plus')}</button></div>`; }).join('')}</div>
|
||||||
<div class="bar"><button class="btn" id="rcpshop"${count ? '' : ' disabled'}>${icon('check')}Add this week's ingredients to the shopping list</button><button class="btn ghost" id="rcpantry">Pantry</button></div><div id="rcphave"></div></div>`;
|
<div class="bar"><button class="btn" id="rcpshop"${count ? '' : ' disabled'}>${icon('check')}Add this week's ingredients to the shopping list</button><button class="btn ghost" id="rcpantry">Pantry</button></div><div id="rcphave"></div></div>`;
|
||||||
document.querySelectorAll('[data-add]').forEach(b => b.onclick = () => rcPlanPick(null, '', '', b.dataset.add));
|
document.querySelectorAll('[data-add]').forEach(b => b.onclick = () => rcPlanPick(null, '', '', b.dataset.add));
|
||||||
|
document.querySelectorAll('[data-cook]').forEach(b => b.onclick = () => { const i = b.dataset.cook.indexOf('|'); rcCook(b.dataset.cook.slice(0, i), b.dataset.cook.slice(i + 1)); });
|
||||||
document.querySelectorAll('[data-rm]').forEach(b => b.onclick = async () => { try { await rcApi('/plan/remove', rcOpt('POST', { id: b.dataset.rm })); rcPlan(rcYmd(mon)); } catch (e) { toast(e.message); } });
|
document.querySelectorAll('[data-rm]').forEach(b => b.onclick = async () => { try { await rcApi('/plan/remove', rcOpt('POST', { id: b.dataset.rm })); rcPlan(rcYmd(mon)); } catch (e) { toast(e.message); } });
|
||||||
$('#rcpantry').onclick = () => rcPantry(() => rcPlan(rcYmd(mon)));
|
$('#rcpantry').onclick = () => { location.hash = '#/recipes/pantry'; };
|
||||||
if (count) rcApi(`/plan/pantry?from=${from}&to=${to}`).then(r => { const box = $('#rcphave'); if (!box || !r.items.length) return; const names = [...new Set(r.items.map(i => i.have))]; box.innerHTML = `<p class="sub" style="white-space:normal">You may already have ${esc(names.slice(0, 8).join(', '))}${names.length > 8 ? '…' : ''} (${r.items.length} ingredient${r.items.length === 1 ? '' : 's'} this week). They still go on the shopping list; tick them off there.</p>`; }).catch(() => {});
|
if (count) rcApi(`/plan/pantry?from=${from}&to=${to}`).then(r => { const box = $('#rcphave'); if (!box || !r.items.length) return; const names = [...new Set(r.items.map(i => i.have))]; box.innerHTML = `<p class="sub" style="white-space:normal">You may already have ${esc(names.slice(0, 8).join(', '))}${names.length > 8 ? '…' : ''} (${r.items.length} ingredient${r.items.length === 1 ? '' : 's'} this week). They still go on the shopping list; tick them off there.</p>`; }).catch(() => {});
|
||||||
$('#rcpshop').onclick = async e => { const b = e.currentTarget; b.disabled = true; try { const o = await rcApi('/plan/shop', rcOpt('POST', { from, to })); toast(`Ingredients for ${o.recipes} recipe${o.recipes === 1 ? '' : 's'} added`, { label: 'Open', run: () => { location.hash = '#/recipes/shop'; } }); } catch (er) { toast(er.message); } b.disabled = false; };
|
$('#rcpshop').onclick = async e => { const b = e.currentTarget; b.disabled = true; try { const o = await rcApi('/plan/shop', rcOpt('POST', { from, to })); toast(`Ingredients for ${o.recipes} recipe${o.recipes === 1 ? '' : 's'} added`, { label: 'Open', run: () => { location.hash = '#/recipes/shop'; } }); } catch (er) { toast(er.message); } b.disabled = false; };
|
||||||
}
|
}
|
||||||
@@ -138,21 +141,21 @@ function rcPlanPick(slug, name, rid, date) {
|
|||||||
el.querySelector('#rcpq').oninput = () => { clearTimeout(t); t = setTimeout(find, 250); }; find();
|
el.querySelector('#rcpq').oninput = () => { clearTimeout(t); t = setTimeout(find, 250); }; find();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The pantry: what you keep in stock, how many are left, and the level that counts as running low (low ones go on the shopping list in a tap). */
|
/** "Cooked it": shows what cooking this recipe would take out of the pantry (an estimate), lets you untick lines, and takes the rest out when you confirm. */
|
||||||
async function rcPantry(onClose) {
|
async function rcCook(slug, name, scale = 1) {
|
||||||
let items = []; try { items = (await rcApi('/pantry')).items; } catch (e) { return toast(e.message); }
|
const el = openSheet('Cooked ' + name, 'What this takes out of the pantry', '<div id="rcck"><p class="sub">Working it out…</p></div>');
|
||||||
const el = openSheet('Pantry', 'What you keep in stock. The meal plan points out ingredients you have, and an item running low can start an automation.', '<div id="pyl"></div>');
|
const show = async sc => {
|
||||||
const draw = () => {
|
let r; try { r = await rcApi(`/cook-plan?slug=${encodeURIComponent(slug)}&scale=${sc}`); } catch (e) { el.querySelector('.sheet').insertAdjacentHTML('beforeend', `<p class="err">${esc(e.message)}</p>`); return; }
|
||||||
el.querySelector('#pyl').innerHTML = `<form id="pyf" class="bar" style="flex-wrap:nowrap;gap:6px"><input type="text" id="pyn" placeholder="Add an item" autocomplete="off" required style="flex:2;min-width:0"><input type="number" id="pyq" placeholder="How many" min="0" step="any" inputmode="decimal" style="flex:1;min-width:0" aria-label="How many are left"><input type="number" id="pyw" placeholder="Low at" min="0" step="any" inputmode="decimal" style="flex:1;min-width:0" aria-label="Counts as running low at"><button class="btn">Add</button></form>
|
const ok = r.rows.filter(x => x.ok), skip = r.rows.filter(x => !x.ok), body = `<div id="rcck"><div class="seg" role="radiogroup" aria-label="How much did you make">${[[0.5, 'Half'], [1, 'As written'], [2, 'Double'], [3, 'Triple']].map(([v, l]) => `<a href="#" role="radio" aria-checked="${sc === v}" data-sc="${v}" class="${sc === v ? 'on' : ''}">${l}</a>`).join('')}</div>
|
||||||
<div class="list">${items.map(x => `<div class="row"><span class="grow" style="white-space:normal"><b>${esc(x.name)}</b>${x.isLow ? ' <small style="color:var(--danger)">running low</small>' : ''}<small>${x.qty == null ? 'not counted' : x.qty + ' left'}${x.low != null ? ' · low at ' + x.low : ''}</small></span>
|
${ok.length ? `<div class="list">${ok.map((x, i) => `<label class="row" style="cursor:pointer"><input type="checkbox" data-i="${i}" checked><span class="grow" style="white-space:normal"><b>${esc(x.item.name)}</b> −${esc(x.takeLabel)}<small>${esc(x.line)} · ${x.left === 0 ? 'none' : esc(x.leftLabel || x.left)} left${x.why ? ' · ' + esc(x.why) : ''}</small></span></label>`).join('')}</div>` : '<p class="empty">Nothing in your pantry matches this recipe\'s ingredients that can be counted off.</p>'}
|
||||||
${x.isLow ? `<button class="btn ghost" data-shop="${esc(x.id)}" style="min-height:36px">To shopping</button>` : ''}${x.qty != null ? `<button class="ibtn" data-d="${esc(x.id)}:-1" aria-label="One less ${esc(x.name)}">−</button><button class="ibtn" data-d="${esc(x.id)}:1" aria-label="One more ${esc(x.name)}">+</button>` : ''}<button class="ibtn" data-x="${esc(x.id)}" aria-label="Remove ${esc(x.name)}">${icon('trash')}</button></div>`).join('') || '<div class="row"><span class="grow"><small>Nothing yet. Add what you keep in the kitchen.</small></span></div>'}</div>
|
${skip.length ? `<h3 class="sub" style="margin:12px 0 4px">Left alone</h3><div class="list">${skip.map(x => `<div class="row"><span class="grow" style="white-space:normal"><b>${esc(x.item.name)}</b><small>${esc(x.line)} · ${esc(x.why)}</small></span></div>`).join('')}</div>` : ''}
|
||||||
<div class="bar"><button class="btn" id="pydone" style="flex:1;justify-content:center">Done</button></div>`;
|
<p class="sub" style="margin-top:8px">These are estimates (a cup of flour is about 4¼ oz). Untick anything that is not right.</p><div id="rcce" class="err"></div>
|
||||||
const go = async (p, o) => { try { items = (await rcApi(p, rcOpt('POST', o))).items; draw(); } catch (e) { toast(e.message); } };
|
<div class="bar"><a class="btn ghost" href="#/recipes/pantry" id="rccp" style="flex:1;justify-content:center">Pantry</a>${ok.length ? '<button class="btn" id="rccgo" style="flex:1;justify-content:center">Take these out</button>' : ''}</div></div>`;
|
||||||
el.querySelector('#pyf').onsubmit = e => { e.preventDefault(); go('/pantry/item', { name: el.querySelector('#pyn').value, qty: el.querySelector('#pyq').value, low: el.querySelector('#pyw').value }); };
|
el.querySelector('#rcck').outerHTML = body;
|
||||||
el.querySelectorAll('[data-d]').forEach(b => b.onclick = () => { const [id, d] = b.dataset.d.split(':'); go('/pantry/adjust', { id, delta: +d }); });
|
el.querySelectorAll('[data-sc]').forEach(a => a.onclick = e => { e.preventDefault(); show(+a.dataset.sc); });
|
||||||
el.querySelectorAll('[data-x]').forEach(b => b.onclick = () => go('/pantry/delete', { id: b.dataset.x }));
|
const go = el.querySelector('#rccgo'); if (go) go.onclick = async () => { const picks = [...el.querySelectorAll('[data-i]:checked')].map(c => ok[+c.dataset.i]); if (!picks.length) return closeSheet();
|
||||||
el.querySelectorAll('[data-shop]').forEach(b => b.onclick = async () => { const it = items.find(x => x.id === b.dataset.shop); try { await rcApi('/shopping/add', rcOpt('POST', { text: it.name })); toast(it.name + ' added to the shopping list'); } catch (e) { toast(e.message); } });
|
try { const t = await jfetch('/api/pantry/take', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ takes: picks.map(x => ({ id: x.item.id, amount: x.take, unit: x.unit })), note: 'cooked ' + name }) }); closeSheet(); const low = t.done.filter(d => d.isLow).map(d => d.name); toast(`Took ${t.done.length} item${t.done.length === 1 ? '' : 's'} out of the pantry${low.length ? '. Running low: ' + low.join(', ') : ''}`, low.length ? { label: 'Pantry', run: () => { location.hash = '#/recipes/pantry'; } } : undefined); }
|
||||||
el.querySelector('#pydone').onclick = () => { closeSheet(); if (onClose) onClose(); };
|
catch (e) { el.querySelector('#rcce').textContent = e.message; } };
|
||||||
};
|
};
|
||||||
draw();
|
show(scale);
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,7 @@ async function sgStart() { // keep the unread count and live updates running wha
|
|||||||
if (!allowed('signal') || sg.es) return;
|
if (!allowed('signal') || sg.es) return;
|
||||||
try { const st = await sgApi('/status'); sg.st = st; sg.unread = st.unread || 0; renderNav(activeTab); } catch {}
|
try { const st = await sgApi('/status'); sg.st = st; sg.unread = st.unread || 0; renderNav(activeTab); } catch {}
|
||||||
sg.es = new EventSource('/api/signal/events');
|
sg.es = new EventSource('/api/signal/events');
|
||||||
sg.es.onmessage = e => { let ev; try { ev = JSON.parse(e.data); } catch { return; } sgEvent(ev); };
|
sg.es.onmessage = e => { let ev; try { ev = JSON.parse(e.data); } catch { return; } sgEvent(ev); if (typeof chSigChanged === 'function') chSigChanged(); };
|
||||||
}
|
}
|
||||||
function sgStop() { if (sg.es) { sg.es.close(); sg.es = null; } }
|
function sgStop() { if (sg.es) { sg.es.close(); sg.es = null; } }
|
||||||
// ---- Getting your attention: a chime, a desktop notification when the app is in the background, the count in the tab title and on the app icon.
|
// ---- Getting your attention: a chime, a desktop notification when the app is in the background, the count in the tab title and on the app icon.
|
||||||
|
|||||||
@@ -1106,3 +1106,6 @@ body:has(#sheet) #simplehome, body:has(#sheet) #kidreq, body:has(#lyr) #simpleho
|
|||||||
html.rm *, html.rm *::before, html.rm *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; scroll-behavior: auto !important; }
|
html.rm *, html.rm *::before, html.rm *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; scroll-behavior: auto !important; }
|
||||||
html.hc #view a:not(.btn):not(.row):not(.vcard):not(.seg a):not(.sgrp a) { text-decoration: underline; } html.hc .btn.ghost, html.hc select, html.hc input[type=text], html.hc input[type=search], html.hc textarea { border: 2px solid var(--line); } html.hc :focus-visible { outline-width: 3px; }
|
html.hc #view a:not(.btn):not(.row):not(.vcard):not(.seg a):not(.sgrp a) { text-decoration: underline; } html.hc .btn.ghost, html.hc select, html.hc input[type=text], html.hc input[type=search], html.hc textarea { border: 2px solid var(--line); } html.hc :focus-visible { outline-width: 3px; }
|
||||||
#offnote { position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(var(--sab) + 70px); z-index: 90; max-width: min(92vw, 460px); padding: 10px 16px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); box-shadow: 0 6px 24px rgba(0, 0, 0, .3); font-size: 14px; text-align: center; } #offnote[hidden] { display: none; }
|
#offnote { position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(var(--sab) + 70px); z-index: 90; max-width: min(92vw, 460px); padding: 10px 16px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); box-shadow: 0 6px 24px rgba(0, 0, 0, .3); font-size: 14px; text-align: center; } #offnote[hidden] { display: none; }
|
||||||
|
.paTiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 10px; margin: 8px 0 16px; } .paTile { min-height: 84px; padding: 12px; border-radius: 16px; border: 1px solid var(--line); background: var(--panel); text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; font-size: 17px; } .paTile small { color: var(--muted); font-size: 14px; } .paTile:active { transform: scale(.97); } .paTile.low { border-color: var(--danger); } .paTile.out { opacity: .45; }
|
||||||
|
.gifgrid { columns: 3 110px; column-gap: 6px; margin: 8px 0; } .gifc { display: block; width: 100%; margin: 0 0 6px; padding: 0; border: 0; border-radius: 10px; overflow: hidden; background: var(--panel2); break-inside: avoid; min-height: 0; cursor: pointer; } .gifc img { display: block; width: 100%; height: auto; } .gifc:focus-visible { outline: 3px solid var(--accent); }
|
||||||
|
.srcbadge { display: inline-block; margin-left: 6px; padding: 1px 7px; border-radius: 999px; background: var(--panel2); color: var(--muted); font-size: 11px; vertical-align: middle; }
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
// App-shell cache only; Seafile/API traffic always goes to the network.
|
// App-shell cache only; Seafile/API traffic always goes to the network.
|
||||||
const CACHE = 'hub-v122';
|
const CACHE = 'hub-v130';
|
||||||
const KEEP = /^hub-(offline|share|who|data-)/; // caches that outlive a new version
|
const KEEP = /^hub-(offline|share|who|data-)/; // caches that outlive a new version
|
||||||
const SHARE = 'hub-share'; // files shared into the app from other apps, held until the person picks a folder
|
const SHARE = 'hub-share'; // files shared into the app from other apps, held until the person picks a folder
|
||||||
const SHELL = ['/icon.svg', '/manifest.webmanifest', '/icons/icon-192.png', '/icons/apple-touch-icon.png'];
|
const SHELL = ['/icon.svg', '/manifest.webmanifest', '/icons/icon-192.png', '/icons/apple-touch-icon.png'];
|
||||||
|
|||||||
Vendored
+245
@@ -0,0 +1,245 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
||||||
|
========================================================================
|
||||||
|
jai-imageio
|
||||||
|
========================================================================
|
||||||
|
|
||||||
|
Copyright (c) 2005 Sun Microsystems, Inc.
|
||||||
|
Copyright © 2010-2014 University of Manchester
|
||||||
|
Copyright © 2010-2015 Stian Soiland-Reyes
|
||||||
|
Copyright © 2015 Peter Hull
|
||||||
|
All Rights Reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions
|
||||||
|
are met:
|
||||||
|
|
||||||
|
- Redistribution of source code must retain the above copyright
|
||||||
|
notice, this list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
- Redistribution in binary form must reproduce the above copyright
|
||||||
|
notice, this list of conditions and the following disclaimer in
|
||||||
|
the documentation and/or other materials provided with the
|
||||||
|
distribution.
|
||||||
|
|
||||||
|
Neither the name of Sun Microsystems, Inc. or the names of
|
||||||
|
contributors may be used to endorse or promote products derived
|
||||||
|
from this software without specific prior written permission.
|
||||||
|
|
||||||
|
This software is provided "AS IS," without a warranty of any
|
||||||
|
kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
|
||||||
|
WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
|
||||||
|
EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
|
||||||
|
NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
|
||||||
|
USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
|
||||||
|
DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
|
||||||
|
ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
|
||||||
|
CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
|
||||||
|
REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
|
||||||
|
INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
|
||||||
|
POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
You acknowledge that this software is not designed or intended for
|
||||||
|
use in the design, construction, operation or maintenance of any
|
||||||
|
nuclear facility.
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ZXing={})}(this,(function(t){"use strict";var e,r,n=(e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},e(t,r)},function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}),i=function(t){function e(e,r){var n,i,s,o=this.constructor,a=t.call(this,e,r)||this;return Object.defineProperty(a,"name",{value:o.name,enumerable:!1,configurable:!0}),n=a,i=o.prototype,(s=Object.setPrototypeOf)?s(n,i):n.__proto__=i,function(t,e){void 0===e&&(e=t.constructor);var r=Error.captureStackTrace;r&&r(t,e)}(a),a}return n(e,t),e}(Error);class s extends i{constructor(t=void 0){super(t),this.message=t}getKind(){return this.constructor.kind}}s.kind="Exception";class o extends s{}o.kind="ArgumentException";class a extends s{}a.kind="IllegalArgumentException";class h{constructor(t){if(this.binarizer=t,null===t)throw new a("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(t,e){return this.binarizer.getBlackRow(t,e)}getBlackMatrix(){return null!==this.matrix&&void 0!==this.matrix||(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(t,e,r,n){const i=this.binarizer.getLuminanceSource().crop(t,e,r,n);return new h(this.binarizer.createBinarizer(i))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const t=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new h(this.binarizer.createBinarizer(t))}rotateCounterClockwise45(){const t=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new h(this.binarizer.createBinarizer(t))}toString(){try{return this.getBlackMatrix().toString()}catch(t){return""}}}class l extends s{static getChecksumInstance(){return new l}}l.kind="ChecksumException";class c{constructor(t){this.source=t}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class d{static arraycopy(t,e,r,n,i){for(;i--;)r[n++]=t[e++]}static currentTimeMillis(){return Date.now()}}class u extends s{}u.kind="IndexOutOfBoundsException";class g extends u{constructor(t=void 0,e=void 0){super(e),this.index=t,this.message=e}}g.kind="ArrayIndexOutOfBoundsException";class f{static fill(t,e){for(let r=0,n=t.length;r<n;r++)t[r]=e}static fillWithin(t,e,r,n){f.rangeCheck(t.length,e,r);for(let i=e;i<r;i++)t[i]=n}static rangeCheck(t,e,r){if(e>r)throw new a("fromIndex("+e+") > toIndex("+r+")");if(e<0)throw new g(e);if(r>t)throw new g(r)}static asList(...t){return t}static create(t,e,r){return Array.from({length:t}).map((t=>Array.from({length:e}).fill(r)))}static createInt32Array(t,e,r){return Array.from({length:t}).map((t=>Int32Array.from({length:e}).fill(r)))}static equals(t,e){if(!t)return!1;if(!e)return!1;if(!t.length)return!1;if(!e.length)return!1;if(t.length!==e.length)return!1;for(let r=0,n=t.length;r<n;r++)if(t[r]!==e[r])return!1;return!0}static hashCode(t){if(null===t)return 0;let e=1;for(const r of t)e=31*e+r;return e}static fillUint8Array(t,e){for(let r=0;r!==t.length;r++)t[r]=e}static copyOf(t,e){return t.slice(0,e)}static copyOfUint8Array(t,e){if(t.length<=e){const r=new Uint8Array(e);return r.set(t),r}return t.slice(0,e)}static copyOfRange(t,e,r){const n=r-e,i=new Int32Array(n);return d.arraycopy(t,e,i,0,n),i}static binarySearch(t,e,r){void 0===r&&(r=f.numberComparator);let n=0,i=t.length-1;for(;n<=i;){const s=i+n>>1,o=r(e,t[s]);if(o>0)n=s+1;else{if(!(o<0))return s;i=s-1}}return-n-1}static numberComparator(t,e){return t-e}}class w{static numberOfTrailingZeros(t){let e;if(0===t)return 32;let r=31;return e=t<<16,0!==e&&(r-=16,t=e),e=t<<8,0!==e&&(r-=8,t=e),e=t<<4,0!==e&&(r-=4,t=e),e=t<<2,0!==e&&(r-=2,t=e),r-(t<<1>>>31)}static numberOfLeadingZeros(t){if(0===t)return 32;let e=1;return t>>>16==0&&(e+=16,t<<=16),t>>>24==0&&(e+=8,t<<=8),t>>>28==0&&(e+=4,t<<=4),t>>>30==0&&(e+=2,t<<=2),e-=t>>>31,e}static toHexString(t){return t.toString(16)}static toBinaryString(t){return String(parseInt(String(t),2))}static bitCount(t){return t=(t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135,t+=t>>>8,63&(t+=t>>>16)}static truncDivision(t,e){return Math.trunc(t/e)}static parseInt(t,e=void 0){return parseInt(t,e)}}w.MIN_VALUE_32_BITS=-2147483648,w.MAX_VALUE=Number.MAX_SAFE_INTEGER;class C{constructor(t,e){void 0===t?(this.size=0,this.bits=new Int32Array(1)):(this.size=t,this.bits=null==e?C.makeArray(t):e)}gLine truncated
|
||||||
+12
-26
@@ -104,18 +104,7 @@ const DAY = /^\d{4}-\d{2}-\d{2}$/, MEALS = ['breakfast', 'lunch', 'dinner'], pla
|
|||||||
const readPlan = () => { try { const d = JSON.parse(fs.readFileSync(planFile(), 'utf8')); return { days: d && d.days && typeof d.days === 'object' ? d.days : {} }; } catch { return { days: {} }; } };
|
const readPlan = () => { try { const d = JSON.parse(fs.readFileSync(planFile(), 'utf8')); return { days: d && d.days && typeof d.days === 'object' ? d.days : {} }; } catch { return { days: {} }; } };
|
||||||
const writePlan = d => atomicWrite(planFile(), JSON.stringify(d), { mode: 0o600 });
|
const writePlan = d => atomicWrite(planFile(), JSON.stringify(d), { mode: 0o600 });
|
||||||
const planBetween = (from, to) => { const out = {}; for (const [k, v] of Object.entries(readPlan().days)) if (k >= from && k <= to) out[k] = v; return out; };
|
const planBetween = (from, to) => { const out = {}; for (const [k, v] of Object.entries(readPlan().days)) if (k >= from && k <= to) out[k] = v; return out; };
|
||||||
// The pantry: what the family keeps in stock, one shared list. Each item has a name, how many are left (blank when you do not count it) and the level it counts as
|
const pantry = require('./pantry'), U = require('./units'); // what is in stock (the plan checks its ingredients against it)
|
||||||
// running low at (blank: never). The meal plan points out planned ingredients you have; an item going low can start an automation and goes on the shopping list in a tap.
|
|
||||||
const pantryFile = () => path.join(process.env.DATA_DIR || path.join(__dirname, 'data'), 'pantry.json');
|
|
||||||
const num = v => v === '' || v == null || !isFinite(+v) || +v < 0 ? null : Math.min(100000, Math.round(+v * 100) / 100);
|
|
||||||
const readPantry = () => { try { const a = JSON.parse(fs.readFileSync(pantryFile(), 'utf8')); return (Array.isArray(a) ? a : []).map(x => typeof x === 'string' ? { id: crypto.randomBytes(4).toString('hex'), name: x, qty: null, low: null } : x).filter(x => x && x.name); } catch { return []; } };
|
|
||||||
const writePantry = l => atomicWrite(pantryFile(), JSON.stringify(l), { mode: 0o600 });
|
|
||||||
const isLow = x => x.qty != null && x.low != null && x.qty <= x.low;
|
|
||||||
const pantryView = l => l.map(x => ({ id: x.id, name: x.name, qty: x.qty, low: x.low, isLow: isLow(x) })).sort((a, b) => b.isLow - a.isLow || a.name.localeCompare(b.name));
|
|
||||||
const stem = w => w.replace(/(ies)$/, 'y').replace(/(es|s)$/, '');
|
|
||||||
const inPantry = (text, items) => { items = items.map(x => typeof x === 'string' ? x : x.name); const words = new Set(String(text).toLowerCase().match(/[a-z]+/g) || []), stems = new Set([...words].map(stem)); return items.filter(it => { const ws = (String(it).toLowerCase().match(/[a-z]+/g) || []).map(stem); return ws.length && ws.every(w => stems.has(w)); }); };
|
|
||||||
/** An item has just gone low: tell the automations of everyone who asked to hear about it. */
|
|
||||||
function pantryLow(it) { try { require('./automations').fireAll('pantry.low', { title: it.name }); } catch (e) { console.warn('[recipes] pantry rules failed:', e.message); } }
|
|
||||||
/** A recipe's ingredients onto Mealie's shopping list, `times` over (Mealie adds up what is already there). */
|
/** A recipe's ingredients onto Mealie's shopping list, `times` over (Mealie adds up what is already there). */
|
||||||
async function addRecipe(slug, times) {
|
async function addRecipe(slug, times) {
|
||||||
const r = await mealie('/api/recipes/' + (slugOk(slug) ? slug : '-')), list = await mainList(), mult = Math.max(0.25, Math.min(20, +times || 1));
|
const r = await mealie('/api/recipes/' + (slugOk(slug) ? slug : '-')), list = await mainList(), mult = Math.max(0.25, Math.min(20, +times || 1));
|
||||||
@@ -164,22 +153,19 @@ async function handle(req, res) {
|
|||||||
if (d.days[b.date].length > 12) throw fail(400, 'That day is full'); writePlan(d); return json(res, 200, { ok: true, id });
|
if (d.days[b.date].length > 12) throw fail(400, 'That day is full'); writePlan(d); return json(res, 200, { ok: true, id });
|
||||||
}
|
}
|
||||||
if (p === '/plan/remove' && req.method === 'POST') { const b = JSON.parse(await readBody(req, 1e4) || '{}'), d = readPlan(); for (const k of Object.keys(d.days)) { d.days[k] = d.days[k].filter(e => e.id !== b.id); if (!d.days[k].length) delete d.days[k]; } writePlan(d); return json(res, 200, { ok: true }); }
|
if (p === '/plan/remove' && req.method === 'POST') { const b = JSON.parse(await readBody(req, 1e4) || '{}'), d = readPlan(); for (const k of Object.keys(d.days)) { d.days[k] = d.days[k].filter(e => e.id !== b.id); if (!d.days[k].length) delete d.days[k]; } writePlan(d); return json(res, 200, { ok: true }); }
|
||||||
if (p === '/pantry' && req.method === 'GET') return json(res, 200, { items: pantryView(readPantry()) });
|
if (p === '/cook-plan' && req.method === 'GET') { // what cooking this recipe would take out of the pantry (nothing is changed here; the person confirms in the pantry)
|
||||||
if (p === '/pantry/item' && req.method === 'POST') { // add an item, or change one
|
const slug = q.get('slug') || '', scale = Math.max(0.25, Math.min(20, +q.get('scale') || 1)); if (!slugOk(slug)) throw fail(400, 'Pick a recipe');
|
||||||
const b = JSON.parse(await readBody(req, 2e3) || '{}'), l = readPantry(), name = String(b.name || '').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 60); if (!name) throw fail(400, 'Give the item a name');
|
const r = await mealie('/api/recipes/' + slug), ings = (r.recipeIngredient || []).filter(i => i && !(i.title && !i.display && !i.originalText && !i.food)).map(i => {
|
||||||
const i = b.id ? l.findIndex(x => x.id === b.id) : l.findIndex(x => x.name.toLowerCase() === name.toLowerCase()); if (b.id && i < 0) throw fail(404, 'That item is gone'); if (i < 0 && l.length >= 400) throw fail(400, 'The pantry is full');
|
const line = ingredientText(i), qn = +i.quantity, food = i.food && (i.food.name || i.food), uname = i.unit && (i.unit.name || i.unit);
|
||||||
const before = i >= 0 ? isLow(l[i]) : false, it = { id: i >= 0 ? l[i].id : crypto.randomBytes(4).toString('hex'), name: i >= 0 && !b.id ? l[i].name : name, qty: num(b.qty), low: num(b.low) }; if (i >= 0) l[i] = it; else l.push(it); writePantry(l);
|
if (qn > 0 && food) return { amount: qn, unit: U.unitOf(uname) || '', name: [food, i.note].filter(Boolean).join(' '), line }; // (Mealie already split it up)
|
||||||
if (isLow(it) && !before) pantryLow(it);
|
return { ...U.parseIngredient(line), line };
|
||||||
return json(res, 200, { items: pantryView(l) });
|
});
|
||||||
|
const rows = U.plan(ings, pantry.read(), scale).map(x => ({ ...x, takeLabel: U.fmt(x.take, x.unit), leftLabel: x.left == null ? '' : U.fmt(x.left, x.unit) }));
|
||||||
|
return json(res, 200, { name: r.name, servings: r.recipeServings || r.recipeYield || '', scale, rows, lines: ings.length });
|
||||||
}
|
}
|
||||||
if (p === '/pantry/adjust' && req.method === 'POST') { // one more or one less
|
|
||||||
const b = JSON.parse(await readBody(req, 1e3) || '{}'), l = readPantry(), it = l.find(x => x.id === b.id); if (!it) throw fail(404, 'That item is gone');
|
|
||||||
const before = isLow(it); it.qty = Math.max(0, Math.round(((it.qty || 0) + (+b.delta || 0)) * 100) / 100); writePantry(l); if (isLow(it) && !before) pantryLow(it); return json(res, 200, { items: pantryView(l) });
|
|
||||||
}
|
|
||||||
if (p === '/pantry/delete' && req.method === 'POST') { const b = JSON.parse(await readBody(req, 1e3) || '{}'); const l = readPantry().filter(x => x.id !== b.id); writePantry(l); return json(res, 200, { items: pantryView(l) }); }
|
|
||||||
if (p === '/plan/pantry' && req.method === 'GET') { // which planned ingredients the pantry already covers
|
if (p === '/plan/pantry' && req.method === 'GET') { // which planned ingredients the pantry already covers
|
||||||
const from = q.get('from') || '', to = q.get('to') || ''; if (!DAY.test(from) || !DAY.test(to)) throw fail(400, 'Bad dates'); const items = readPantry().filter(x => x.qty !== 0), out = []; if (!items.length) return json(res, 200, { items: [] });
|
const from = q.get('from') || '', to = q.get('to') || ''; if (!DAY.test(from) || !DAY.test(to)) throw fail(400, 'Bad dates'); const items = pantry.read().filter(x => x.qty !== 0), out = []; if (!items.length) return json(res, 200, { items: [] });
|
||||||
for (const sl of [...new Set(Object.values(planBetween(from, to)).flat().map(e => e.slug))]) { try { const r = full(await mealie('/api/recipes/' + sl)); for (const i of r.ingredients) { const hit = i.text && inPantry(i.text, items); if (hit && hit.length) out.push({ recipe: r.name, text: i.text, have: hit[0] }); } } catch (e) { if (e.code !== 404 && e.status !== 404) throw e; } }
|
for (const sl of [...new Set(Object.values(planBetween(from, to)).flat().map(e => e.slug))]) { try { const r = full(await mealie('/api/recipes/' + sl)); for (const i of r.ingredients) { const hit = i.text && pantry.inPantry(i.text, items); if (hit && hit.length) out.push({ recipe: r.name, text: i.text, have: hit[0] }); } } catch (e) { if (e.code !== 404 && e.status !== 404) throw e; } }
|
||||||
return json(res, 200, { items: out });
|
return json(res, 200, { items: out });
|
||||||
}
|
}
|
||||||
if (p === '/plan/shop' && req.method === 'POST') { // every planned meal in the range goes on the shopping list (a recipe planned twice counts twice)
|
if (p === '/plan/shop' && req.method === 'POST') { // every planned meal in the range goes on the shopping list (a recipe planned twice counts twice)
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ const contacts = require('./contacts'); // each person's address book (mail su
|
|||||||
const activity = require('./activity'), alertParents = activity.alertParents;
|
const activity = require('./activity'), alertParents = activity.alertParents;
|
||||||
const kidlimits = require('./kidlimits'); // child accounts: a daily time limit and bedtime, and asking a parent for more time
|
const kidlimits = require('./kidlimits'); // child accounts: a daily time limit and bedtime, and asking a parent for more time
|
||||||
const screentime = require('./screentime'); // fewer web addresses for iPad Screen Time: a report-only policy, the list of what devices reached, and a picture pass-through
|
const screentime = require('./screentime'); // fewer web addresses for iPad Screen Time: a report-only policy, the list of what devices reached, and a picture pass-through
|
||||||
|
const pantry = require('./pantry'); // the family pantry, with barcode scanning
|
||||||
const automations = require('./automations'); // when this happens, do that (per person)
|
const automations = require('./automations'); // when this happens, do that (per person)
|
||||||
const moviefam = require('./moviefam'); // Movies & TV: favorites and the family's movie night list
|
const moviefam = require('./moviefam'); // Movies & TV: favorites and the family's movie night list
|
||||||
const chores = require('./chores'); // chores for the family, with points
|
const chores = require('./chores'); // chores for the family, with points
|
||||||
@@ -586,6 +587,7 @@ const ACCESS = [
|
|||||||
[/^\/api\/bible\//, ['bible']],
|
[/^\/api\/bible\//, ['bible']],
|
||||||
[/^\/api\/read\//, ['read']],
|
[/^\/api\/read\//, ['read']],
|
||||||
[/^\/api\/radio\//, ['radio']],
|
[/^\/api\/radio\//, ['radio']],
|
||||||
|
[/^\/api\/pantry(\/|$)/, ['recipes']],
|
||||||
[/^\/api\/moviefam(\/|$)/, ['video']],
|
[/^\/api\/moviefam(\/|$)/, ['video']],
|
||||||
[/^\/api\/chores(\/|$)/, ['chores']],
|
[/^\/api\/chores(\/|$)/, ['chores']],
|
||||||
[/^\/api\/notes(\/|$)/, ['notes']],
|
[/^\/api\/notes(\/|$)/, ['notes']],
|
||||||
@@ -612,7 +614,7 @@ function securityHeaders(res) {
|
|||||||
res.setHeader('Referrer-Policy', 'same-origin');
|
res.setHeader('Referrer-Policy', 'same-origin');
|
||||||
res.setHeader('Content-Security-Policy', "frame-ancestors 'self'; base-uri 'self'; object-src 'none'; form-action 'self'");
|
res.setHeader('Content-Security-Policy', "frame-ancestors 'self'; base-uri 'self'; object-src 'none'; form-action 'self'");
|
||||||
res.setHeader('Content-Security-Policy-Report-Only', screentime.policy()); // (reports only: nothing is blocked)
|
res.setHeader('Content-Security-Policy-Report-Only', screentime.policy()); // (reports only: nothing is blocked)
|
||||||
res.setHeader('Permissions-Policy', 'camera=(), geolocation=(), payment=()');
|
res.setHeader('Permissions-Policy', 'camera=(self), geolocation=(self), payment=()');
|
||||||
if (process.env.PUBLIC_URL && process.env.PUBLIC_URL.startsWith('https://')) res.setHeader('Strict-Transport-Security', 'max-age=15552000');
|
if (process.env.PUBLIC_URL && process.env.PUBLIC_URL.startsWith('https://')) res.setHeader('Strict-Transport-Security', 'max-age=15552000');
|
||||||
}
|
}
|
||||||
/** Cross-site request check: a browser request that changes something must come from this same site. */
|
/** Cross-site request check: a browser request that changes something must come from this same site. */
|
||||||
@@ -716,6 +718,7 @@ async function handleRequest(req, res) {
|
|||||||
if (pathname === '/api/kid/requests' || pathname.startsWith('/api/kid/requests/')) return require('./requests').handle(req, res, user);
|
if (pathname === '/api/kid/requests' || pathname.startsWith('/api/kid/requests/')) return require('./requests').handle(req, res, user);
|
||||||
if (pathname.startsWith('/api/kid/')) return kidlimits.handle(req, res, user, { askParents: chat.askParents });
|
if (pathname.startsWith('/api/kid/')) return kidlimits.handle(req, res, user, { askParents: chat.askParents });
|
||||||
if (pathname === '/api/csp-report' || pathname === '/api/img' || pathname === '/api/screentime') return screentime.handle(req, res, user);
|
if (pathname === '/api/csp-report' || pathname === '/api/img' || pathname === '/api/screentime') return screentime.handle(req, res, user);
|
||||||
|
if (pathname === '/api/pantry' || pathname.startsWith('/api/pantry/')) return pantry.handle(req, res);
|
||||||
if (pathname === '/api/auto' || pathname.startsWith('/api/auto/')) return automations.handle(req, res);
|
if (pathname === '/api/auto' || pathname.startsWith('/api/auto/')) return automations.handle(req, res);
|
||||||
if (pathname === '/api/moviefam' || pathname.startsWith('/api/moviefam/')) return moviefam.handle(req, res);
|
if (pathname === '/api/moviefam' || pathname.startsWith('/api/moviefam/')) return moviefam.handle(req, res);
|
||||||
if (pathname === '/api/chores' || pathname.startsWith('/api/chores/')) return chores.handle(req, res);
|
if (pathname === '/api/chores' || pathname.startsWith('/api/chores/')) return chores.handle(req, res);
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
// Family Chat extras: GIFs (kept family-friendly, fetched through the hub, kept in the chat) and sharing a place (a search, and coordinates that are checked).
|
||||||
|
const http = require('http'), assert = require('assert'), fs = require('fs'), os = require('os'), path = require('path');
|
||||||
|
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'nehub-chatx-'));
|
||||||
|
const GIF = Buffer.from('R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', 'base64'); let commonsPages = null, asked = [], tenorQ = [], giphyQ = [], wikiQ = [];
|
||||||
|
const media = http.createServer((req, res) => { asked.push(req.url); if (req.url.startsWith('/big')) { res.writeHead(200, { 'content-type': 'image/gif' }); return res.end(Buffer.alloc(9 * 1024 * 1024)); } if (req.url.startsWith('/html')) { res.writeHead(200, { 'content-type': 'text/html' }); return res.end('<b>x</b>'); } res.writeHead(200, { 'content-type': 'image/gif' }); res.end(GIF); }).listen(0);
|
||||||
|
const svc = http.createServer((req, res) => {
|
||||||
|
const u = new URL(req.url, 'http://x'), M = 'http://127.0.0.1:' + media.address().port; res.setHeader('content-type', 'application/json');
|
||||||
|
if (u.pathname.startsWith('/v2/')) { tenorQ.push(u.pathname + u.search); return res.end(JSON.stringify({ next: 'n2', results: [
|
||||||
|
{ content_description: 'happy dance', tags: ['dance'], media_formats: { tinygif: { url: M + '/t1.gif', dims: [100, 80] }, gif: { url: M + '/g1.gif', dims: [300, 240] } } },
|
||||||
|
{ content_description: 'sexy dance', tags: ['dance'], media_formats: { tinygif: { url: M + '/t2.gif', dims: [100, 80] }, gif: { url: M + '/g2.gif', dims: [300, 240] } } },
|
||||||
|
{ content_description: 'party', tags: ['topless', 'fun'], media_formats: { tinygif: { url: M + '/t3.gif', dims: [100, 80] }, gif: { url: M + '/g3.gif', dims: [300, 240] } } },
|
||||||
|
{ content_description: 'elsewhere', tags: [], media_formats: { tinygif: { url: 'https://evil.example/t4.gif', dims: [1, 1] }, gif: { url: 'https://evil.example/g4.gif', dims: [1, 1] } } }] })); }
|
||||||
|
if (u.pathname.startsWith('/v1/gifs/')) { giphyQ.push(u.pathname + u.search); return res.end(JSON.stringify({ data: [{ title: 'cat', rating: 'g', images: { fixed_width_small: { url: M + '/s1.gif', width: '100', height: '80' }, fixed_width: { url: M + '/f1.gif' } } }, { title: 'cat 2', rating: 'pg-13', images: { fixed_width_small: { url: M + '/s2.gif', width: '100', height: '80' }, fixed_width: { url: M + '/f2.gif' } } }] })); }
|
||||||
|
if (u.pathname === '/w/api.php') { wikiQ.push(u.search); const M2 = M, mk = (i, title, mime, desc, cats, thumb) => ({ pageid: i, index: i, title: 'File:' + title, imageinfo: [{ mime, thumburl: thumb === null ? '' : (thumb || M2 + '/commons-' + i + '.gif'), thumbwidth: 320, thumbheight: 240, extmetadata: { ImageDescription: { value: desc }, Categories: { value: cats } } }] });
|
||||||
|
const pages = [mk(1, 'Cat walking.gif', 'image/gif', 'A <b>cat</b> walking', 'Cats|Animation'), mk(2, 'Nude study.gif', 'image/gif', 'Study', 'Nudity in art'), mk(3, 'Cat.png', 'image/png', 'still', 'Cats'), mk(4, 'Dancing robot.gif', 'image/gif', 'A robot', 'Robots'), mk(5, 'Clinic.gif', 'image/gif', 'Medical animation of the female genitalia', 'Medicine'), mk(6, 'No thumb.gif', 'image/gif', 'x', 'Cats', null)];
|
||||||
|
commonsPages = pages; const cont = pages.length ? { continue: { gsroffset: 24 } } : {}; return res.end(JSON.stringify({ ...cont, query: { pages: Object.fromEntries(pages.map(p => [p.pageid, p])) } })); }
|
||||||
|
if (u.pathname === '/search') { return res.end(JSON.stringify([{ name: 'Central Park', display_name: 'Central Park, Manhattan, New York, United States', lat: '40.78', lon: '-73.96' }, { name: 'Bad', display_name: 'Bad', lat: 'x', lon: 'y' }])); }
|
||||||
|
res.statusCode = 404; res.end('{}'); }).listen(0, async () => {
|
||||||
|
process.env.GIF_MEDIA_HOSTS = '127.0.0.1:' + media.address().port; process.env.WIKIMEDIA_URL = process.env.TENOR_URL = process.env.GIPHY_URL = process.env.NOMINATIM_URL = 'http://127.0.0.1:' + svc.address().port;
|
||||||
|
const users = require('../users'), chat = require('../chat'), gifs = require('../gifs');
|
||||||
|
const P = { a: users.create({ name: 'Ann', role: 'admin', handle: 'YQ' }), b: users.create({ name: 'Bob', role: 'user', tabs: ['chat'], handle: 'Yg' }), c: users.create({ name: 'Cy', role: 'user', tabs: ['chat'], handle: 'Yw' }) };
|
||||||
|
const hub = http.createServer((req, res) => users.runAs(P[req.headers['x-user'] || 'a'], () => chat.handle(req, res))).listen(0, async () => {
|
||||||
|
const B = 'http://127.0.0.1:' + hub.address().port + '/api/chat', j = r => r.json(), call = (p, o = {}, who) => fetch(B + p, { ...o, headers: { ...(o.headers || {}), ...(who ? { 'x-user': who } : {}) } }), post = (p, b, who) => call(p, { method: 'POST', body: JSON.stringify(b) }, who);
|
||||||
|
try {
|
||||||
|
// the filter's words
|
||||||
|
for (const bad of ['sexy dance', 'Boobs', 'naked man', 'p0rn'.replace('0', 'o'), 'bikini beach', 'F-U-C-K'.replace(/-/g, '')]) assert.equal(gifs.unsafe(bad), true, bad + ' is refused'); for (const ok of ['happy dance', 'class', 'assistant', 'Scunthorpe', 'cat', 'thanks', 'high five', 'book club', 'pass the butter']) assert.equal(gifs.unsafe(ok), false, ok + ' is fine');
|
||||||
|
// not set up
|
||||||
|
process.env.GIF_PROVIDER = 'off'; let r = await call('/gif/status'); assert.deepEqual(await j(r), { enabled: false, provider: '' }); assert.equal((await call('/gif?q=cat')).status, 503); delete process.env.GIF_PROVIDER;
|
||||||
|
// Tenor: always the strictest setting, and what comes back is filtered by words and by where it is hosted
|
||||||
|
process.env.TENOR_API_KEY = 'k1'; assert.deepEqual(await j(await call('/gif/status')), { enabled: true, provider: 'tenor' });
|
||||||
|
r = await j(await call('/gif?q=dance')); assert.match(tenorQ[0], /contentfilter=high/); assert.match(tenorQ[0], /q=dance/); assert.deepEqual(r.items.map(x => x.title), ['happy dance'], 'a title or a tag with a bad word, and a picture from another site, are dropped'); assert.equal(r.next, 'n2');
|
||||||
|
assert.equal((await call('/gif?q=sexy')).status, 400, 'a bad search is refused before it is sent'); assert.equal(tenorQ.length, 1, 'and never reaches the service'); await call('/gif'); assert.match(tenorQ[1], /featured/, 'with no words: what is popular');
|
||||||
|
// previews come through the hub (only ones it listed), never the phone's own request
|
||||||
|
const prev = r.items[0].preview; assert.equal((await call('/gifimg?u=' + encodeURIComponent(prev))).status, 200); assert.equal((await call('/gifimg?u=' + encodeURIComponent('http://127.0.0.1:' + media.address().port + '/other.gif'))).status, 400, 'an address the hub did not list is refused'); assert.equal((await call('/gifimg?u=' + encodeURIComponent('https://evil.example/x.gif'))).status, 400);
|
||||||
|
// sending: downloaded and kept in the chat like a photo
|
||||||
|
const dm = (await j(await post('/new', { type: 'direct', with: P.b.id }))).conv; r = await post('/gif/send', { conv: dm.id, url: r.items[0].url, title: 'happy dance' }); assert.equal(r.status, 200); const m = (await j(r)).msg; assert.equal(m.att[0].type, 'image/gif'); assert.equal(m.att[0].name, 'happy dance.gif');
|
||||||
|
const f = await call('/file/' + m.att[0].id, {}, 'b'); assert.equal(f.status, 200); assert.deepEqual(Buffer.from(await f.arrayBuffer()), GIF, 'Bob sees the very same picture, from the hub'); assert.equal((await post('/gif/send', { conv: dm.id, url: 'http://127.0.0.1:' + media.address().port + '/g1.gif' }, 'c')).status, 404, 'a stranger cannot send into the chat');
|
||||||
|
assert.equal((await post('/gif/send', { conv: dm.id, url: 'http://127.0.0.1:' + media.address().port + '/never-listed.gif' })).status, 400, 'only listed GIFs can be sent');
|
||||||
|
// size and type limits
|
||||||
|
{ const M = 'http://127.0.0.1:' + media.address().port; gifs.remember([M + '/big.gif', M + '/html.gif']); assert.equal((await post('/gif/send', { conv: dm.id, url: M + '/big.gif' })).status, 413, 'a huge GIF is refused'); assert.equal((await post('/gif/send', { conv: dm.id, url: M + '/html.gif' })).status, 502, 'something that is not a picture is refused'); }
|
||||||
|
// Wikimedia Commons (MediaWiki's search): no key needed, the default when there is no Tenor or GIPHY key; animated GIFs only, and files with risky titles, descriptions or categories are dropped
|
||||||
|
delete process.env.TENOR_API_KEY; delete process.env.GIPHY_API_KEY; assert.deepEqual(await j(await call('/gif/status')), { enabled: true, provider: 'wikimedia' }, 'with no key, Commons is used');
|
||||||
|
r = await j(await call('/gif?q=cats')); assert.match(wikiQ[0], /filemime%3Aimage%2Fgif/); assert.match(wikiQ[0], /gsrsearch=cats/); assert.deepEqual(r.items.map(x => x.title), ['Cat walking', 'Dancing robot'], 'a risky category, a risky description, a still picture and one with no thumbnail are dropped, in search order'); assert.equal(r.next, '24'); assert.ok(!r.items.some(x => /Bikini|Nude/i.test(x.title)));
|
||||||
|
await call('/gif'); assert.match(wikiQ[1], /gsrsearch=animal/, 'with no words, something to look at'); r = await j(await call('/gif?q=cats&pos=24')); assert.match(wikiQ[2], /gsroffset=24/); assert.equal((await call('/gif?q=naked')).status, 400, 'the same word list applies');
|
||||||
|
{ const M = 'http://127.0.0.1:' + media.address().port; assert.equal((await post('/gif/send', { conv: (await j(await post('/new', { type: 'direct', with: P.b.id }))).conv.id, url: M + '/commons-1.gif', title: 'Cat walking' })).status, 200, 'a Commons GIF is kept in the chat too'); }
|
||||||
|
process.env.TENOR_API_KEY = 'k1'; process.env.GIF_PROVIDER = 'wikimedia'; assert.equal((await j(await call('/gif/status'))).provider, 'wikimedia', 'GIF_PROVIDER picks one even when keys exist'); delete process.env.GIF_PROVIDER; delete process.env.TENOR_API_KEY;
|
||||||
|
// Giphy: G only, and nothing above it slips through
|
||||||
|
delete process.env.TENOR_API_KEY; process.env.GIPHY_API_KEY = 'k2'; r = await j(await call('/gif?q=cat')); assert.match(giphyQ[0], /rating=g/); assert.match(giphyQ[0], /api_key=k2/); assert.deepEqual(r.items.map(x => x.title), ['cat'], 'a result rated above G is dropped even if the service sent it');
|
||||||
|
// a place: search through the hub, and a share with checked coordinates
|
||||||
|
assert.equal((await call('/places?q=ab')).status, 400); r = await j(await call('/places?q=central park')); assert.deepEqual(r.items, [{ title: 'Central Park', sub: 'Manhattan, New York, United States', lat: 40.78, lng: -73.96 }], 'bad rows are dropped');
|
||||||
|
r = await post('/send', { conv: dm.id, share: { kind: 'place', title: 'Central Park', sub: 'New York', lat: 40.78, lng: -73.96, link: 'https://evil.example/' } }); assert.equal(r.status, 200); const sh = (await j(r)).msg.share; assert.equal(sh.link, 'https://maps.apple.com/?ll=40.78,-73.96&q=Central%20Park', 'the Apple Maps link is made by the hub, not taken from the sender'); assert.equal(sh.kind, 'place');
|
||||||
|
for (const bad of [{ lat: 91, lng: 0 }, { lat: 0, lng: 181 }, { lat: 'x', lng: 1 }, { lat: '', lng: '' }, {}]) assert.equal((await post('/send', { conv: dm.id, share: { kind: 'place', title: 'x', ...bad } })).status, 400, JSON.stringify(bad) + ' is not a place');
|
||||||
|
console.log('chat extras ok');
|
||||||
|
} catch (e) { console.error(e); process.exitCode = 1; }
|
||||||
|
hub.close(); svc.close(); media.close(); setTimeout(() => process.exit(process.exitCode || 0), 80);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -32,7 +32,7 @@ for (const f of listed) {
|
|||||||
}
|
}
|
||||||
assert.deepEqual(failures, [], 'every script loads:\n ' + failures.join('\n '));
|
assert.deepEqual(failures, [], 'every script loads:\n ' + failures.join('\n '));
|
||||||
// the pieces the app calls by name across files are there
|
// the pieces the app calls by name across files are there
|
||||||
for (const name of ['route', 'viewHome', 'viewSettings', 'viewTasks', 'viewCalendar', 'viewBible', 'viewMail', 'viewRecipes', 'viewVideo', 'themeApply', 'autoSettings', 'bbToday', 'homeListening', 'saveToFiles', 'downloadText']) assert.equal(typeof vm.runInContext(`typeof ${name}`, ctx), 'string') && assert.equal(vm.runInContext(`typeof ${name}`, ctx), 'function', name + ' is defined');
|
for (const name of ['route', 'viewHome', 'viewSettings', 'viewTasks', 'viewCalendar', 'viewBible', 'viewMail', 'viewRecipes', 'viewVideo', 'themeApply', 'autoSettings', 'bbToday', 'homeListening', 'saveToFiles', 'downloadText', 'viewPantry', 'pantryScan', 'chGifPicker', 'chPlacePicker', 'chSigRow']) assert.equal(typeof vm.runInContext(`typeof ${name}`, ctx), 'string') && assert.equal(vm.runInContext(`typeof ${name}`, ctx), 'function', name + ' is defined');
|
||||||
// the watch-stats counting (a pure function)
|
// the watch-stats counting (a pure function)
|
||||||
{ const now = Date.UTC(2026, 5, 15, 12), at = d => Math.floor((now - d * 864e5) / 1000), agg = vm.runInContext('vdAgg', ctx);
|
{ const now = Date.UTC(2026, 5, 15, 12), at = d => Math.floor((now - d * 864e5) / 1000), agg = vm.runInContext('vdAgg', ctx);
|
||||||
const a = agg([{ lastViewedAt: at(1), duration: 6e6, Genre: [{ tag: 'Drama' }, { tag: 'Comedy' }] }, { lastViewedAt: at(3), duration: 3e6, Genre: [{ tag: 'Drama' }] }, { lastViewedAt: at(20), duration: 6e6 }, { lastViewedAt: at(200), duration: 6e6, Genre: [{ tag: 'Drama' }] }, { lastViewedAt: at(400), duration: 6e6 }, { duration: 6e6 }], now);
|
const a = agg([{ lastViewedAt: at(1), duration: 6e6, Genre: [{ tag: 'Drama' }, { tag: 'Comedy' }] }, { lastViewedAt: at(3), duration: 3e6, Genre: [{ tag: 'Drama' }] }, { lastViewedAt: at(20), duration: 6e6 }, { lastViewedAt: at(200), duration: 6e6, Genre: [{ tag: 'Drama' }] }, { lastViewedAt: at(400), duration: 6e6 }, { duration: 6e6 }], now);
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
// The pantry: items with counts and low levels, several barcodes per item (corn from different brands is one item), product lookup (a stand-in for Open Food Facts), and what happens when a count goes low.
|
||||||
|
const assert = require('assert'), fs = require('fs'), os = require('os'), path = require('path'), http = require('http');
|
||||||
|
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'nehub-pantry-'));
|
||||||
|
let asked = [], down = false;
|
||||||
|
const off = http.createServer((req, res) => { const code = /product\/(\d+)\.json/.exec(req.url)[1]; asked.push(code); if (down) { res.destroy(); return; }
|
||||||
|
const P = { '0016000275287': { product_name: 'Green Giant Sweet Corn 15.25 oz', brands: 'Green Giant', quantity: '15.25 oz' }, '0024000163275': { product_name: "Libby's Whole Kernel Corn 425 g", brands: "Libby's" }, '0070470003344': { product_name: 'Greek Yogurt', brands: 'Chobani' } };
|
||||||
|
res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(P[code] ? { status: 1, product: P[code] } : { status: 0 })); }).listen(0, () => {
|
||||||
|
process.env.OPENFOODFACTS_URL = 'http://127.0.0.1:' + off.address().port;
|
||||||
|
const users = require('../users'), pantry = require('../pantry'), automations = require('../automations');
|
||||||
|
const ann = users.create({ name: 'Ann', role: 'admin', handle: 'YQ' }), bo = users.create({ name: 'Bo', role: 'user', tabs: ['recipes'], handle: 'ZP' }), kid = users.create({ name: 'Kit', role: 'user', tabs: ['recipes'], handle: 'KD' }); kid.kid = { on: true };
|
||||||
|
const hub = http.createServer((req, res) => users.runAs(req.headers['x-user'] === 'bo' ? bo : req.headers['x-user'] === 'kid' ? kid : ann, () => pantry.handle(req, res))).listen(0, async () => {
|
||||||
|
const base = 'http://127.0.0.1:' + hub.address().port + '/api/pantry', j = r => r.json(), get = p => fetch(base + p), post = (p, o, who) => fetch(base + p, { method: 'POST', body: JSON.stringify(o), headers: who ? { 'x-user': who } : {} });
|
||||||
|
const fired = []; const realFireAll = automations.fireAll; automations.fireAll = async (t, c) => { fired.push(t + ':' + c.title); };
|
||||||
|
try {
|
||||||
|
// names are cleaned from products
|
||||||
|
assert.equal(pantry.shortName('Heinz Tomato Ketchup 500 ml', 'Heinz'), 'Tomato Ketchup'); assert.equal(pantry.shortName('Green Giant Sweet Corn 15.25 oz', 'Green Giant'), 'Sweet Corn'); assert.equal(pantry.shortName('', ''), '');
|
||||||
|
// items: add, count, change by the same name, adjust, low levels
|
||||||
|
assert.equal((await post('/item', { name: ' ' })).status, 400);
|
||||||
|
let r = await j(await post('/item', { name: 'Corn', qty: 2, low: 1 })); assert.deepEqual(r.items.map(x => [x.name, x.qty, x.low, x.isLow, x.codes.length]), [['Corn', 2, 1, false, 0]]); const corn = r.items[0].id;
|
||||||
|
r = await j(await post('/item', { name: 'corn', qty: 2, low: 1 })); assert.equal(r.items.length, 1, 'the same name updates the item'); assert.equal(r.items[0].name, 'Corn');
|
||||||
|
r = await j(await post('/adjust', { id: corn, delta: -1 })); assert.equal(r.items[0].isLow, true); assert.deepEqual(fired, ['pantry.low:Corn'], 'going low starts the rules, once'); await post('/adjust', { id: corn, delta: -1 }); assert.equal(fired.length, 1, 'and not again while it stays low');
|
||||||
|
assert.equal((await j(await post('/adjust', { id: corn, delta: -9 }))).items[0].qty, 0, 'never below none'); await post('/adjust', { id: corn, delta: 5 });
|
||||||
|
// a barcode we have not seen: the product is looked up, and the items it might be are offered
|
||||||
|
assert.equal((await get('/lookup?code=abc')).status, 400);
|
||||||
|
r = await j(await get('/lookup?code=0016000275287')); assert.equal(r.linked, null); assert.equal(r.product.short, 'Sweet Corn'); assert.deepEqual(r.matches.map(m => m.name), ['Corn'], 'Corn is offered, since the product has the word corn');
|
||||||
|
assert.equal((await post('/scan', { code: '0016000275287' })).status, 400, 'a new barcode must say which item it is');
|
||||||
|
// scanning links it to the chosen item and adds one
|
||||||
|
r = await j(await post('/scan', { code: '0016000275287', itemId: corn })); assert.equal(r.item.name, 'Corn'); assert.equal(r.item.qty, 6); assert.equal(r.made, false);
|
||||||
|
asked = []; r = await j(await get('/lookup?code=0016000275287')); assert.deepEqual(r.linked, { id: corn, name: 'Corn' }, 'next time it goes straight to Corn'); assert.deepEqual(asked, [], 'without asking the product database again');
|
||||||
|
r = await j(await post('/scan', { code: '0016000275287' })); assert.equal(r.item.qty, 7);
|
||||||
|
// a second brand is the same item, with one count
|
||||||
|
r = await j(await post('/scan', { code: '0024000163275', itemId: corn })); assert.equal(r.items.length, 1, 'still one item'); assert.equal(r.items[0].qty, 8); assert.equal(r.items[0].codes.length, 2, 'with two barcodes');
|
||||||
|
// use one
|
||||||
|
r = await j(await post('/scan', { code: '0024000163275', mode: 'use' })); assert.equal(r.item.qty, 7);
|
||||||
|
// a new item made from a scan; the same name later finds it; products the database does not know are named by hand
|
||||||
|
r = await j(await post('/scan', { code: '0070470003344', name: 'Yogurt' })); assert.equal(r.made, true); assert.equal(r.item.qty, 1); r = await j(await get('/lookup?code=1234567890128')); assert.equal(r.product, null); assert.equal(r.lookedUp, true);
|
||||||
|
r = await j(await post('/scan', { code: '1234567890128', name: 'yogurt' })); assert.equal(r.made, false, 'a name that exists links to it'); assert.equal(r.item.qty, 2);
|
||||||
|
// using one that takes it to its low level fires the rules
|
||||||
|
fired.length = 0; await post('/item', { id: corn, name: 'Corn', qty: 3, low: 2 }); await post('/scan', { code: '0016000275287', mode: 'use' }); assert.deepEqual(fired, ['pantry.low:Corn']);
|
||||||
|
// the database being down is not an error for the person: they just name it
|
||||||
|
down = true; r = await j(await get('/lookup?code=5000112637922')); assert.equal(r.lookedUp, false); assert.equal(r.product, null); down = false;
|
||||||
|
// moving a barcode to another item takes it off the first; unlinking
|
||||||
|
const yog = (await j(await get('/'))).items.find(x => x.name === 'Yogurt').id; r = await j(await post('/scan', { code: '0016000275287', itemId: yog })); assert.equal((await j(await get('/lookup?code=0016000275287'))).linked.name, 'Corn', 'a linked barcode stays with its item');
|
||||||
|
r = await j(await post('/unlink', { id: corn, code: '0016000275287' })); assert.equal(r.items.find(x => x.id === corn).codes.length, 1);
|
||||||
|
assert.equal((await post('/delete', { id: yog })).status, 200); assert.ok(!(await j(await get('/'))).items.some(x => x.name === 'Yogurt'));
|
||||||
|
// the simple way: take one (children too), with undo, and a note of who took what
|
||||||
|
r = await j(await post('/item', { name: 'Granola bars', qty: 2, low: 1 })); const gb = r.items.find(x => x.name === 'Granola bars').id; fired.length = 0;
|
||||||
|
r = await j(await post('/use', { id: gb }, 'kid')); assert.equal(r.item.qty, 1); assert.equal(r.item.isLow, true); assert.deepEqual(fired, ['pantry.low:Granola bars'], 'taking the second-to-last one starts the low rule'); assert.equal(r.recent[0].who, 'Kit'); assert.equal(r.recent[0].item, 'Granola bars');
|
||||||
|
r = await j(await post('/use', { id: gb, undo: true }, 'kid')); assert.equal(r.item.qty, 2, 'undo puts it back'); await post('/use', { id: gb }, 'kid'); await post('/use', { id: gb }, 'kid'); assert.equal((await post('/use', { id: gb }, 'kid')).status, 409, 'none left to take');
|
||||||
|
const note = (await j(await post('/item', { name: 'Napkins' }))).items.find(x => x.name === 'Napkins').id; r = await j(await post('/use', { id: note })); assert.equal(r.item.qty, null, 'an item that is not counted is only noted');
|
||||||
|
// a child can look and take, and nothing else
|
||||||
|
for (const [p, o] of [['/item', { name: 'Candy', qty: 9 }], ['/adjust', { id: gb, delta: 5 }], ['/delete', { id: gb }], ['/unlink', { id: gb, code: '1' }], ['/scan', { code: '0099999999999', mode: 'add', name: 'Candy' }]]) assert.equal((await post(p, o, 'kid')).status, 403, p + ' is for grown-ups');
|
||||||
|
assert.equal((await get('/')).status, 200); assert.equal((await j(await fetch(base + '/', { headers: { 'x-user': 'kid' } }))).kid, true);
|
||||||
|
r = await j(await post('/scan', { code: '0016000275287', itemId: corn })); const before = r.item.qty; r = await j(await post('/scan', { code: '0016000275287', mode: 'use' }, 'kid')); assert.equal(r.item.qty, before - 1, 'a child can scan a known barcode to take one'); assert.equal((await post('/scan', { code: '0555555555555', mode: 'use', name: 'Mystery' }, 'kid')).status, 403, 'but not make new items');
|
||||||
|
// units: an item in pounds, amounts in cups, taken out together (grown-ups only), and the shown amount
|
||||||
|
r = await j(await post('/item', { name: 'Flour', qty: 10, unit: 'lb', low: 2 })); let fl = r.items.find(x => x.name === 'Flour'); assert.deepEqual([fl.unit, fl.label, fl.lowLabel], ['lb', '10 lb', '2 lb']); assert.equal((await j(await post('/item', { name: 'Bad', qty: 1, unit: 'furlongs' }))).items.find(x => x.name === 'Bad').unit, '', 'an unknown unit is a count');
|
||||||
|
r = await j(await post('/take', { takes: [{ id: fl.id, amount: 4, unit: 'cup' }], note: 'cooked Pancakes' })); assert.equal(r.done.length, 1); assert.ok(Math.abs(r.done[0].took - 4 * 120 / 453.592) < 0.01); assert.equal(r.items.find(x => x.name === 'Flour').label, '8 lb 15 oz', '10 lb less 4 cups'); assert.equal(r.recent[0].note, 'cooked Pancakes');
|
||||||
|
r = await j(await post('/take', { takes: [{ id: fl.id, amount: 8, unit: 'oz' }, { id: fl.id, amount: 3, unit: 'furlongs' }, { id: 'nope', amount: 1 }, { id: note, amount: 1 }] })); assert.equal(r.done.length, 1); assert.equal(r.skipped.length, 3, 'what cannot be turned into the item\'s unit, is missing or is not counted is skipped, with a reason'); assert.match(r.skipped.find(x => x.name === 'Napkins').why, /not counted/);
|
||||||
|
r = await j(await post('/take', { takes: [{ id: fl.id, amount: 99, unit: 'lb' }] })); assert.equal(r.items.find(x => x.name === 'Flour').qty, 0, 'never below none'); assert.equal((await post('/take', { takes: [{ id: fl.id, amount: 1 }] }, 'kid')).status, 403, 'children only take one');
|
||||||
|
assert.equal((await post('/use', { id: fl.id }, 'kid')).status, 409, 'tapping take-one on a pound of flour is not allowed: use an amount');
|
||||||
|
// scanning goes by the size of the package for an item in a unit
|
||||||
|
r = await j(await post('/item', { name: 'Tomatoes', qty: 0, unit: 'oz' })); const tom = r.items.find(x => x.name === 'Tomatoes').id; const tcache = path.join(process.env.DATA_DIR, 'barcode-cache.json'); const cc = JSON.parse(fs.readFileSync(tcache, 'utf8')); cc['0041331000123'] = { found: true, t: Date.now(), name: 'Diced Tomatoes', brand: 'Muir', quantity: '14.5 oz' }; cc['0041331000456'] = { found: true, t: Date.now(), name: 'Tomato Paste', brand: 'Muir', quantity: '1 lb' }; fs.writeFileSync(tcache, JSON.stringify(cc));
|
||||||
|
r = await j(await post('/scan', { code: '0041331000123', itemId: tom })); assert.equal(r.step, 14.5); assert.equal(r.item.qty, 14.5, 'a 14.5 oz can adds 14.5 oz'); r = await j(await post('/scan', { code: '0041331000456', itemId: tom })); assert.equal(r.step, 16, 'a 1 lb tin is 16 oz'); assert.equal(r.item.qty, 30.5); r = await j(await post('/scan', { code: '0041331000123', mode: 'use' })); assert.equal(r.item.qty, 16, 'using one takes the package size back off');
|
||||||
|
r = await j(await post('/scan', { code: '0070470003344', itemId: gb, mode: 'add' })); assert.equal(r.step, 1, 'a counted item goes up by one');
|
||||||
|
// the pantry is shared, and old pantry files (a list of names) still load
|
||||||
|
assert.equal((await j(await get('/', 'bo'))).items.length >= 1, true); fs.writeFileSync(path.join(process.env.DATA_DIR, 'pantry.json'), JSON.stringify(['Flour', 'Salt'])); r = await j(await get('/')); assert.deepEqual(r.items.map(x => x.name), ['Flour', 'Salt']); assert.equal(r.items[0].qty, null);
|
||||||
|
assert.deepEqual(pantry.inPantry('3 cups all-purpose flour', ['Flour', 'Salt']), ['Flour']);
|
||||||
|
console.log('pantry test ok');
|
||||||
|
} catch (e) { console.error(e); process.exitCode = 1; }
|
||||||
|
automations.fireAll = realFireAll; hub.close(); off.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
+10
-9
@@ -62,16 +62,17 @@ const fake = http.createServer((req, res) => {
|
|||||||
j = await (await post('/plan/shop', { from: '2027-03-02', to: '2027-03-08' })).json(); assert.equal(j.ok, true); assert.equal(j.recipes, 1, 'a recipe planned twice is added once, twice over');
|
j = await (await post('/plan/shop', { from: '2027-03-02', to: '2027-03-08' })).json(); assert.equal(j.ok, true); assert.equal(j.recipes, 1, 'a recipe planned twice is added once, twice over');
|
||||||
assert.equal((await post('/plan/shop', { from: '2027-04-01', to: '2027-04-07' })).status, 400, 'nothing planned, nothing to add');
|
assert.equal((await post('/plan/shop', { from: '2027-04-01', to: '2027-04-07' })).status, 400, 'nothing planned, nothing to add');
|
||||||
await post('/plan/remove', { id: (await (await get('/plan?from=2027-03-02&to=2027-03-02')).json())['2027-03-02'][0].id }); assert.deepEqual(await (await get('/plan?from=2027-03-02&to=2027-03-02')).json(), {});
|
await post('/plan/remove', { id: (await (await get('/plan?from=2027-03-02&to=2027-03-02')).json())['2027-03-02'][0].id }); assert.deepEqual(await (await get('/plan?from=2027-03-02&to=2027-03-02')).json(), {});
|
||||||
// the pantry: items with a count and a low level; the plan flags planned ingredients you have ("3 cups flour" is covered by "flour"; butter is not in the pantry)
|
// the pantry check: a planned ingredient the pantry has ("3 cups flour" is covered by "flour"; butter is not in the pantry, and an empty one is not "had")
|
||||||
await post('/plan/add', { date: '2027-05-03', slug: 'bread', name: 'Bread' });
|
await post('/plan/add', { date: '2027-05-03', slug: 'bread', name: 'Bread' }); const pf = path.join(process.env.DATA_DIR, 'pantry.json');
|
||||||
assert.equal((await post('/pantry/item', { name: ' ' })).status, 400, 'an item needs a name');
|
fs.writeFileSync(pf, JSON.stringify([{ id: 'a1', name: 'Flour', qty: 3, low: 1, codes: [] }, { id: 'a2', name: 'Salt', qty: null, low: null, codes: [] }]));
|
||||||
j = await (await post('/pantry/item', { name: 'Flour', qty: 3, low: 1 })).json(); assert.deepEqual(j.items.map(x => [x.name, x.qty, x.low, x.isLow]), [['Flour', 3, 1, false]]); const fid = j.items[0].id;
|
|
||||||
j = await (await post('/pantry/item', { name: 'salt', qty: '', low: '' })).json(); assert.equal(j.items.find(x => x.name === 'salt').qty, null, 'an item need not be counted'); assert.equal(j.items.find(x => x.name === 'salt').isLow, false);
|
|
||||||
j = await (await post('/pantry/item', { name: 'FLOUR', qty: 3, low: 1 })).json(); assert.equal(j.items.filter(x => x.name.toLowerCase() === 'flour').length, 1, 'the same name updates the item');
|
|
||||||
j = await (await get('/plan/pantry?from=2027-05-03&to=2027-05-09')).json(); assert.deepEqual(j.items.map(i => i.text), ['3 cups flour']); assert.equal(j.items[0].have.toLowerCase(), 'flour');
|
j = await (await get('/plan/pantry?from=2027-05-03&to=2027-05-09')).json(); assert.deepEqual(j.items.map(i => i.text), ['3 cups flour']); assert.equal(j.items[0].have.toLowerCase(), 'flour');
|
||||||
j = await (await post('/pantry/adjust', { id: fid, delta: -2 })).json(); assert.equal(j.items[0].qty, 1); assert.equal(j.items[0].isLow, true, 'at the low level counts as running low'); assert.equal(j.items[0].name, 'Flour', 'low ones come first');
|
fs.writeFileSync(pf, JSON.stringify([{ id: 'a1', name: 'Flour', qty: 0, low: 1, codes: [] }])); assert.deepEqual((await (await get('/plan/pantry?from=2027-05-03&to=2027-05-09')).json()).items, [], 'an empty one is not "had"');
|
||||||
j = await (await post('/pantry/adjust', { id: fid, delta: -5 })).json(); assert.equal(j.items[0].qty, 0, 'never below none'); assert.deepEqual((await (await get('/plan/pantry?from=2027-05-03&to=2027-05-09')).json()).items, [], 'an empty one is not "had"');
|
fs.writeFileSync(pf, '[]'); assert.deepEqual((await (await get('/plan/pantry?from=2027-05-03&to=2027-05-09')).json()).items, [], 'an empty pantry flags nothing');
|
||||||
await post('/pantry/delete', { id: fid }); j = await (await get('/pantry')).json(); assert.deepEqual(j.items.map(x => x.name), ['salt']);
|
// what cooking a recipe would take out of the pantry (shown first; nothing changes until it is confirmed in the pantry)
|
||||||
|
fs.writeFileSync(pf, JSON.stringify([{ id: 'fl', name: 'Flour', qty: 10, unit: 'lb', low: 2, codes: [] }, { id: 'bu', name: 'Butter', qty: 1, unit: 'lb', low: null, codes: [] }, { id: 'ca', name: 'Cocoa', qty: null, unit: '', low: null, codes: [] }]));
|
||||||
|
j = await (await get('/cook-plan?slug=bread')).json(); assert.equal(j.name, 'Bread'); assert.deepEqual(j.rows.map(r => [r.item.name, r.ok]), [['Flour', true], ['Butter', true]], 'the glaze heading and anything not in the pantry are left out');
|
||||||
|
assert.ok(Math.abs(j.rows[0].take - 3 * 120 / 453.592) < 0.01, '3 cups of flour in pounds'); assert.equal(j.rows[0].unit, 'lb'); assert.match(j.rows[0].takeLabel, /^(12|13) oz$/); assert.ok(Math.abs(j.rows[1].take - 0.0326) < 0.002, '1 tbsp of butter in pounds (Mealie gave it already split up)');
|
||||||
|
j = await (await get('/cook-plan?slug=bread&scale=2')).json(); assert.ok(Math.abs(j.rows[0].take - 6 * 120 / 453.592) < 0.01, 'doubled'); assert.equal((await get('/cook-plan?slug=..%2Fx')).status, 400);
|
||||||
// a wrong token is explained
|
// a wrong token is explained
|
||||||
process.env.MEALIE_TOKEN = 'bad'; r = await get('/'); assert.equal(r.status, 502); assert.match((await r.json()).error, /token/);
|
process.env.MEALIE_TOKEN = 'bad'; r = await get('/'); assert.equal(r.status, 502); assert.match((await r.json()).error, /token/);
|
||||||
process.env.MEALIE_TOKEN = ''; assert.equal((await get('/')).status, 503);
|
process.env.MEALIE_TOKEN = ''; assert.equal((await get('/')).status, 503);
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
// Units: reading recipe lines, converting (cups of flour to pounds), showing amounts, and working out what a recipe takes out of the pantry.
|
||||||
|
const assert = require('assert'), U = require('../units');
|
||||||
|
const P = U.parseIngredient, near = (a, b, tol = 0.02) => assert.ok(Math.abs(a - b) <= tol * Math.max(1, Math.abs(b)), `${a} is not about ${b}`);
|
||||||
|
// reading lines
|
||||||
|
assert.deepEqual(P('3 cups all-purpose flour'), { amount: 3, unit: 'cup', name: 'all-purpose flour' });
|
||||||
|
assert.deepEqual(P('1 1/2 tsp salt'), { amount: 1.5, unit: 'tsp', name: 'salt' }); assert.deepEqual(P('½ cup sugar'), { amount: 0.5, unit: 'cup', name: 'sugar' }); assert.deepEqual(P('1½ cups milk'), { amount: 1.5, unit: 'cup', name: 'milk' });
|
||||||
|
assert.deepEqual(P('2-3 tbsp olive oil'), { amount: 2.5, unit: 'tbsp', name: 'olive oil' }, 'a range is its middle'); assert.deepEqual(P('1 lb. ground beef, browned'), { amount: 1, unit: 'lb', name: 'ground beef' });
|
||||||
|
assert.deepEqual(P('2 large eggs'), { amount: 2, unit: '', name: 'large eggs' }); assert.deepEqual(P('1 onion, diced'), { amount: 1, unit: '', name: 'onion' }); assert.deepEqual(P('2 (14 oz) cans diced tomatoes'), { amount: 28, unit: 'oz', name: 'diced tomatoes' });
|
||||||
|
assert.deepEqual(P('Salt and pepper to taste'), { amount: null, unit: '', name: 'Salt and pepper to taste' }); assert.deepEqual(P('1 stick butter'), { amount: 1, unit: 'stick', name: 'butter' }); assert.deepEqual(P('8 fl oz cream'), { amount: 8, unit: 'fl oz', name: 'cream' }); assert.deepEqual(P('1 can corn'), { amount: 1, unit: '', name: 'can corn' });
|
||||||
|
assert.deepEqual(P('4 c. flour'), { amount: 4, unit: 'cup', name: 'flour' }); assert.deepEqual(P('2 T sugar'), { amount: 2, unit: 'tbsp', name: 'sugar' }); assert.deepEqual(P('2 cloves garlic'), { amount: 2, unit: '', name: 'cloves garlic' });
|
||||||
|
// converting
|
||||||
|
near(U.convert(1, 'lb', 'oz'), 16); near(U.convert(1, 'cup', 'tbsp'), 16); near(U.convert(1, 'gallon', 'quart'), 4); near(U.convert(1000, 'g', 'kg'), 1); assert.equal(U.convert(2, 'cup', 'lb', 'bananas'), null, 'cups to pounds needs to know the ingredient');
|
||||||
|
near(U.convert(4, 'cup', 'lb', 'all-purpose flour'), 4 * 120 / 453.592, 0.01); near(U.convert(1, 'lb', 'cup', 'flour'), 453.592 / 120, 0.01); near(U.convert(1, 'cup', 'oz', 'brown sugar'), 213 / 28.3495, 0.01); near(U.convert(1, 'stick', 'oz', 'butter'), 4, 0.02); assert.equal(U.convert(1, 'cup', 'lb', 'unobtainium'), null); assert.equal(U.convert(2, '', 'lb', 'flour'), null, 'a count does not become a weight');
|
||||||
|
assert.equal(U.density('light brown sugar, packed'), 213, 'the longest match wins'); assert.equal(U.density('sugar'), 200); assert.equal(U.density('bananas'), 0);
|
||||||
|
// showing amounts
|
||||||
|
assert.equal(U.fmt(8.94, 'lb'), '8 lb 15 oz'); assert.equal(U.fmt(10, 'lb'), '10 lb'); assert.equal(U.fmt(0.94, 'lb'), '15 oz'); assert.equal(U.fmt(2.5, 'cup'), '2 1/2 cups'); assert.equal(U.fmt(1, 'cup'), '1 cup'); assert.equal(U.fmt(12, ''), '12'); assert.equal(U.fmt(null, 'lb'), ''); assert.equal(U.fmt(0.99999, 'lb'), '1 lb'); assert.equal(U.fmt(0.91, 'gallon'), '3 qt 2 1/2 cups'); assert.equal(U.fmt(0.09, 'gallon'), '1 1/2 cups'); assert.equal(U.fmt(1, 'gallon'), '1 gallon'); assert.equal(U.fmt(0.5, 'quart'), '2 cups'); assert.equal(U.fmt(2.25, 'quart'), '2 qt 1 cup');
|
||||||
|
// what cooking takes out of the pantry
|
||||||
|
const items = [{ id: 'f', name: 'Flour', qty: 10, unit: 'lb' }, { id: 'e', name: 'Eggs', qty: 12, unit: '' }, { id: 's', name: 'Salt', qty: null, unit: '' }, { id: 'b', name: 'Butter', qty: 2, unit: 'lb' }, { id: 'm', name: 'Milk', qty: 1, unit: 'gallon' }, { id: 'o', name: 'Onions', qty: 3, unit: 'lb' }, { id: 'bs', name: 'Brown sugar', qty: 2, unit: 'lb' }, { id: 'su', name: 'Sugar', qty: 4, unit: 'lb' }];
|
||||||
|
const pl = U.plan(['4 cups all-purpose flour', '2 large eggs', '1 tsp salt', '1 stick butter', '2 cups milk', '1 onion, diced', '1 cup packed brown sugar', 'pinch of nutmeg', 'Glaze'], items, 1);
|
||||||
|
const by = id => pl.find(r => r.item.id === id);
|
||||||
|
assert.ok(by('f').ok); near(by('f').take, 4 * 120 / 453.592, 0.01); near(by('f').left, 10 - 4 * 120 / 453.592, 0.01, 'flour: 4 cups is about 1 lb 1 oz of the 10 lb');
|
||||||
|
assert.deepEqual([by('e').ok, by('e').take, by('e').left], [true, 2, 10], 'eggs are counted'); assert.equal(by('s').ok, false); assert.match(by('s').why, /not counted/);
|
||||||
|
near(by('b').take, 0.25, 0.02); near(by('m').take, 0.125, 0.01); assert.equal(by('o').ok, false); assert.match(by('o').why, /recipe counts onions/, 'a whole onion cannot come off pounds');
|
||||||
|
near(by('bs').take, 213 / 453.592, 0.01); assert.equal(pl.find(r => r.item.id === 'su'), undefined, '"brown sugar" is not plain sugar... and sugar is not listed for it'); assert.equal(pl.length, 7, 'lines that match nothing are left out');
|
||||||
|
// scaling, and not going below none
|
||||||
|
near(U.plan(['4 cups flour'], items, 2)[0].take, 8 * 120 / 453.592, 0.01); const tiny = U.plan(['4 cups flour'], [{ id: 'f', name: 'Flour', qty: 0.5, unit: 'lb' }])[0]; assert.equal(tiny.left, 0); assert.match(tiny.why, /more than the pantry has/);
|
||||||
|
{ const two = U.plan(['2 cups flour', '1 cup flour'], [{ id: 'f', name: 'Flour', qty: 1, unit: 'lb' }]); near(two[1].left, 1 - 3 * 120 / 453.592, 0.02); /* two lines of the same item add up */ }
|
||||||
|
assert.equal(U.plan(['3 cups flour'], [{ id: 'f', name: 'Flour', qty: 5, unit: 'cup' }])[0].take, 3, 'same unit: no conversion'); near(U.plan(['1 tsp vanilla'], [{ id: 'v', name: 'Vanilla', qty: 4, unit: 'tbsp' }])[0].left, 3.6667, 0.001);
|
||||||
|
console.log('units test ok');
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// Amounts and units for the pantry and recipes: read "1 1/2 cups all-purpose flour" into an amount, a unit and a name; convert between units (cups to pounds needs to know the
|
||||||
|
// ingredient, so there is a table of common ones); show an amount nicely ("8 lb 15 oz"); and work out what cooking a recipe takes out of the pantry. Everything here is an estimate:
|
||||||
|
// it is for keeping count of the flour, not for the lab.
|
||||||
|
const VOL = { ml: 1, l: 1000, tsp: 4.92892, tbsp: 14.7868, 'fl oz': 29.5735, cup: 236.588, pint: 473.176, quart: 946.353, gallon: 3785.41, stick: 118.294 }; // to millilitres (a stick of butter is half a cup)
|
||||||
|
const WT = { g: 1, kg: 1000, oz: 28.3495, lb: 453.592 }; // to grams
|
||||||
|
const ALIAS = { c: 'cup', cups: 'cup', tablespoon: 'tbsp', tablespoons: 'tbsp', tbs: 'tbsp', tbl: 'tbsp', tbsps: 'tbsp', t: 'tsp', teaspoon: 'tsp', teaspoons: 'tsp', tsps: 'tsp', ounce: 'oz', ounces: 'oz', ozs: 'oz', pound: 'lb', pounds: 'lb', lbs: 'lb', gram: 'g', grams: 'g', gr: 'g', kilogram: 'kg', kilograms: 'kg', kgs: 'kg', milliliter: 'ml', milliliters: 'ml', millilitre: 'ml', millilitres: 'ml', liter: 'l', liters: 'l', litre: 'l', litres: 'l', pt: 'pint', pints: 'pint', qt: 'quart', quarts: 'quart', gal: 'gallon', gallons: 'gallon', floz: 'fl oz', 'fl. oz': 'fl oz', 'fl oz.': 'fl oz', sticks: 'stick' };
|
||||||
|
/** The canonical unit for a word ("Cups" -> "cup", "lbs." -> "lb"), or '' when it is not a unit this knows. */
|
||||||
|
function unitOf(w) { const s = String(w || '').toLowerCase().trim().replace(/\.$/, ''); if (VOL[s] || WT[s]) return s; return ALIAS[s] || ''; }
|
||||||
|
const family = u => WT[u] ? 'weight' : VOL[u] ? 'volume' : 'count';
|
||||||
|
const UNITS = ['', 'g', 'kg', 'oz', 'lb', 'ml', 'l', 'tsp', 'tbsp', 'cup', 'fl oz', 'pint', 'quart', 'gallon'];
|
||||||
|
|
||||||
|
// grams in one cup, for the things people bake and cook with (King Arthur, USDA). The longest matching name wins ("brown sugar" before "sugar").
|
||||||
|
const DENSITY = { flour: 120, 'bread flour': 120, 'whole wheat flour': 120, 'almond flour': 96, 'coconut flour': 112, 'rice flour': 158, sugar: 200, 'brown sugar': 213, 'powdered sugar': 120, 'confectioners sugar': 120, 'icing sugar': 120, butter: 227, margarine: 227, shortening: 190, milk: 245, buttermilk: 245, cream: 238, 'heavy cream': 238, 'half and half': 242, water: 237, juice: 248, oil: 218, 'olive oil': 216, 'vegetable oil': 218, 'coconut oil': 218, honey: 340, molasses: 340, 'maple syrup': 322, 'corn syrup': 328, syrup: 322, rice: 185, 'brown rice': 190, quinoa: 170, oats: 90, oatmeal: 90, cornmeal: 157, cornstarch: 128, cocoa: 85, 'cocoa powder': 85, salt: 288, 'baking powder': 230, 'baking soda': 230, yeast: 144, 'peanut butter': 258, 'almond butter': 250, 'cream cheese': 227, 'sour cream': 240, yogurt: 245, 'chocolate chips': 170, raisins: 145, nuts: 120, almonds: 140, walnuts: 117, pecans: 109, cheese: 113, parmesan: 100, breadcrumbs: 108, lentils: 192, beans: 190, pasta: 100, mayonnaise: 220, ketchup: 240, 'tomato sauce': 245, 'chicken broth': 240, broth: 240, stock: 240, vinegar: 239, 'soy sauce': 255, coconut: 80, 'cottage cheese': 226, ricotta: 246, 'peanuts': 146, 'sunflower seeds': 140, 'chia seeds': 170, flaxseed: 168 };
|
||||||
|
const stem = w => w.replace(/(ies)$/, 'y').replace(/(ves)$/, 'f').replace(/(es|s)$/, '');
|
||||||
|
const words = t => (String(t).toLowerCase().replace(/&/g, ' and ').match(/[a-z]+/g) || []).map(stem);
|
||||||
|
/** Grams per cup for a named ingredient, or 0 when it is not in the table. */
|
||||||
|
function density(name) {
|
||||||
|
const have = new Set(words(name)); let best = 0, bestLen = 0;
|
||||||
|
for (const [k, g] of Object.entries(DENSITY)) { const ks = words(k); if (ks.length >= bestLen && ks.every(w => have.has(w)) && (ks.length > bestLen || !best)) { best = g; bestLen = ks.length; } }
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
const FR = { '¼': 0.25, '½': 0.5, '¾': 0.75, '⅓': 1 / 3, '⅔': 2 / 3, '⅛': 0.125, '⅜': 0.375, '⅝': 0.625, '⅞': 0.875, '⅕': 0.2, '⅖': 0.4, '⅗': 0.6, '⅘': 0.8, '⅙': 1 / 6, '⅚': 5 / 6 };
|
||||||
|
/** A leading amount ("1 1/2", "½", "1½", "2-3", "2 to 3", "0.5"): { n, rest } or null. A range counts as its middle. */
|
||||||
|
function leadingNumber(text) {
|
||||||
|
let s = String(text || '').trim().replace(/[¼½¾⅓⅔⅛⅜⅝⅞⅕⅖⅗⅘⅙⅚]/g, m => ' ' + FR[m] + ' ').replace(/\s+/g, ' ').trim();
|
||||||
|
const one = /^(\d+\s+\d+\/\d+|\d+\/\d+|\d+\.\d+|\d+\s+0?\.\d+|\d+|0?\.\d+)/.exec(s); if (!one) return null;
|
||||||
|
const val = t => { t = t.trim(); let m; if ((m = /^(\d+)\s+(\d+)\/(\d+)$/.exec(t))) return +m[1] + +m[2] / +m[3]; if ((m = /^(\d+)\/(\d+)$/.exec(t))) return +m[1] / +m[2]; if ((m = /^(\d+)\s+(0?\.\d+)$/.exec(t))) return +m[1] + +m[2]; return parseFloat(t); };
|
||||||
|
let n = val(one[1]), rest = s.slice(one[0].length).trim(); const range = /^(?:-|–|to)\s*(\d+\s+\d+\/\d+|\d+\/\d+|\d+\.\d+|\d+|0?\.\d+)/i.exec(rest); if (range) { n = (n + val(range[1])) / 2; rest = rest.slice(range[0].length).trim(); }
|
||||||
|
return isFinite(n) ? { n, rest } : null;
|
||||||
|
}
|
||||||
|
/** One recipe line -> { amount (number or null), unit ('' for a count), name }. "2 (14 oz) cans tomatoes" is 28 oz of tomatoes. */
|
||||||
|
function parseIngredient(text) {
|
||||||
|
const t = String(text || '').trim(), q = leadingNumber(t); if (!q) return { amount: null, unit: '', name: t };
|
||||||
|
let amount = q.n, rest = q.rest, unit = '', m;
|
||||||
|
if ((m = /^\(\s*([\d./\s]+)\s*([a-z. ]+?)\s*\)\s*/i.exec(rest)) && unitOf(m[2])) { const inner = leadingNumber(m[1]); if (inner) { amount = q.n * inner.n; unit = unitOf(m[2]); rest = rest.slice(m[0].length).replace(/^(cans?|jars?|packages?|pkgs?|bags?|boxes|box|bottles?|containers?)\b\s*/i, '').trim(); } }
|
||||||
|
else { const two = /^(fl\.?\s?oz\.?)\b/i.exec(rest); if (two) { unit = 'fl oz'; rest = rest.slice(two[0].length).trim(); } else if ((m = /^T(\s|$)/.exec(rest))) { unit = 'tbsp'; rest = rest.slice(m[0].length).trim(); } // (a capital T is a tablespoon, a small t a teaspoon)
|
||||||
|
else if ((m = /^([a-zA-Z]+\.?)(\s|$)/.exec(rest)) && unitOf(m[1]) && !(m[1].length === 1 && /^[a-z]$/.test(m[1]) && !/^[ctT]$/.test(m[1]))) { unit = unitOf(m[1]); rest = rest.slice(m[0].length).trim(); } }
|
||||||
|
rest = rest.replace(/^of\s+/i, '').replace(/\(.*?\)/g, ' ').replace(/,.*$/, '').replace(/\s+/g, ' ').trim();
|
||||||
|
return { amount, unit, name: rest || t };
|
||||||
|
}
|
||||||
|
/** Convert an amount between units. Weight and volume need the ingredient (a name, or grams per cup); a count converts only to a count. Returns null when it cannot. */
|
||||||
|
function convert(amount, from, to, name, gPerCup) {
|
||||||
|
if (from === to) return amount; const ff = family(from), tf = family(to);
|
||||||
|
if (ff === 'count' || tf === 'count') return null;
|
||||||
|
if (ff === tf) { const t = ff === 'weight' ? WT : VOL; return amount * t[from] / t[to]; }
|
||||||
|
const g = gPerCup || density(name); if (!g) return null; const gPerMl = g / VOL.cup;
|
||||||
|
return ff === 'volume' ? amount * VOL[from] * gPerMl / WT[to] : amount * WT[from] / gPerMl / VOL[to];
|
||||||
|
}
|
||||||
|
const r2 = n => Math.round(n * 100) / 100, r4 = n => Math.round(n * 10000) / 10000; // (amounts keep four decimals: a spoonful of butter is a few hundredths of a pound)
|
||||||
|
/** An amount to show: "8 lb 15 oz", "2 1/2 cups", "12". */
|
||||||
|
function fmt(qty, unit) {
|
||||||
|
if (qty == null) return ''; const q = Math.round(qty * 100) / 100;
|
||||||
|
if (unit === 'lb' && q % 1) { let lb = Math.floor(q), oz = Math.round((q - lb) * 16); if (oz === 16) { lb++; oz = 0; } return oz ? `${lb ? lb + ' lb ' : ''}${oz} oz` : lb + ' lb'; }
|
||||||
|
if ((unit === 'gallon' || unit === 'quart') && q % 1) { // a fraction of a gallon or quart is easier to picture in smaller measures: "3 qt 2 1/2 cups"
|
||||||
|
let cups = Math.round(q * (unit === 'gallon' ? 16 : 4) * 4) / 4; const parts = []; if (unit === 'gallon') { const g = Math.floor(cups / 16); if (g) parts.push(g + ' gal'); cups -= g * 16; } const qt = Math.floor(cups / 4); if (qt) parts.push(qt + ' qt'); cups -= qt * 4;
|
||||||
|
if (cups) { const w = Math.floor(cups), f = { 0.25: '1/4', 0.5: '1/2', 0.75: '3/4' }[cups - w]; parts.push(`${w ? w + ' ' : ''}${f || ''}`.trim() + (cups > 1 ? ' cups' : ' cup')); } return parts.join(' ') || '0';
|
||||||
|
}
|
||||||
|
const frac = q % 1, whole = Math.floor(q), nice = { 0.25: '1/4', 0.33: '1/3', 0.5: '1/2', 0.67: '2/3', 0.75: '3/4' }[r2(frac)];
|
||||||
|
const num = ['cup', 'tbsp', 'tsp', 'quart', 'pint', 'gallon'].includes(unit) && nice ? `${whole ? whole + ' ' : ''}${nice}` : String(q);
|
||||||
|
return unit ? `${num} ${unit === 'cup' && q > 1 ? 'cups' : unit}` : num;
|
||||||
|
}
|
||||||
|
const aboutWords = (a, b) => { const ws = new Set(words(a)); return words(b).length > 0 && words(b).every(w => ws.has(w)); };
|
||||||
|
/** What cooking `ingredients` (lines, or { amount, unit, name }) takes out of the pantry `items` (each { id, name, qty, unit }), times `scale`.
|
||||||
|
* Returns [{ line, item, take (in the item's own unit), unit, left, ok, why }]. Lines that match nothing in the pantry are not listed. */
|
||||||
|
function plan(ingredients, items, scale = 1) {
|
||||||
|
const out = [], left = new Map(items.map(x => [x.id, x.qty]));
|
||||||
|
for (const raw of ingredients) {
|
||||||
|
const ing = typeof raw === 'string' ? { ...parseIngredient(raw), line: raw } : { ...raw, line: raw.line || [raw.amount, raw.unit, raw.name].filter(x => x != null && x !== '').join(' ') };
|
||||||
|
let best = null; for (const it of items) if (aboutWords(ing.name, it.name) && (!best || words(it.name).length > words(best.name).length)) best = it; if (!best) continue;
|
||||||
|
const row = { line: ing.line, item: { id: best.id, name: best.name }, unit: best.unit || '', ok: false, take: 0, left: null, why: '' };
|
||||||
|
if (best.qty == null) { row.why = 'not counted'; out.push(row); continue; }
|
||||||
|
if (ing.amount == null) { row.why = 'no amount in the recipe (“to taste”)'; out.push(row); continue; }
|
||||||
|
const a = ing.amount * (scale || 1), fromU = ing.unit, toU = best.unit || '';
|
||||||
|
let take = fromU === '' && toU === '' ? a : fromU !== '' && toU !== '' ? convert(a, fromU, toU, best.name + ' ' + ing.name) : null;
|
||||||
|
if (take == null) row.why = fromU === '' ? `the recipe counts ${best.name.toLowerCase()} but the pantry has it in ${toU}` : toU === '' ? `the recipe uses ${fromU} but the pantry counts ${best.name.toLowerCase()}` : `cannot turn ${fromU} into ${toU} for ${best.name.toLowerCase()}`;
|
||||||
|
else { take = r4(take); const now = left.get(best.id); row.ok = true; row.take = take; row.left = Math.max(0, r4(now - take)); left.set(best.id, row.left); if (take > now) row.why = 'more than the pantry has'; }
|
||||||
|
out.push(row);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
module.exports = { UNITS, unitOf, family, density, leadingNumber, parseIngredient, convert, fmt, plan, words };
|
||||||
Reference in new issue
Block a user