// Notifications center: a short list of what happened for each person (chat messages, reminders, announcements) so nothing depends on a phone buzz being seen. // Each person's list lives in their own folder (inbox.json); a chat conversation keeps one entry that grows a count instead of filling the list. const fs = require('fs'), path = require('path'), crypto = require('crypto'); const atomicWrite = require('./atomic'); const users = require('./users'); const { readBody } = require('./body'); const MAX = 120, json = (res, code, o) => { res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(o)); }; const str = (v, n) => String(v == null ? '' : v).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').slice(0, n); const file = uid => path.join(users.dirOf(uid), 'inbox.json'); const load = uid => { try { const j = JSON.parse(fs.readFileSync(file(uid), 'utf8')); return Array.isArray(j.items) ? j.items : []; } catch { return []; } }; const save = (uid, items) => { try { fs.mkdirSync(path.dirname(file(uid)), { recursive: true }); atomicWrite(file(uid), JSON.stringify({ items }), { mode: 0o600 }); } catch (e) { console.warn('[inbox]', e.message); } }; /** Add something for a person. With a `tag`, a still-unread entry with the same tag is updated (and counted) instead of added again. */ function add(uid, { kind = 'info', title, body = '', url = '', tag = '' }) { if (!users.get(uid)) return; const items = load(uid), now = Date.now(); const old = tag ? items.find(i => i.tag === tag && !i.read) : null; if (old) { old.count = (old.count || 1) + 1; old.title = str(title, 100); old.body = str(body, 200); old.at = now; items.sort((a, b) => b.at - a.at); } else items.unshift({ id: crypto.randomBytes(6).toString('hex'), kind, title: str(title, 100), body: str(body, 200), url: str(url, 200), tag: str(tag, 80), at: now, read: false, count: 1 }); save(uid, items.slice(0, MAX)); } const unread = uid => load(uid).filter(i => !i.read).length; async function handle(req, res) { const p = new URL(req.url, 'http://x').pathname.slice('/api/inbox'.length) || '/', me = users.current(); try { if (p === '/' && req.method === 'GET') { const items = load(me.id); return json(res, 200, { items, unread: items.filter(i => !i.read).length }); } if (p === '/read' && req.method === 'POST') { const b = JSON.parse(await readBody(req, 5e3) || '{}'), items = load(me.id); for (const i of items) if (b.all || i.id === b.id) i.read = true; save(me.id, items); return json(res, 200, { unread: items.filter(i => !i.read).length }); } if (p === '/clear' && req.method === 'POST') { save(me.id, []); return json(res, 200, { unread: 0 }); } return json(res, 404, { error: 'Not found' }); } catch (e) { return json(res, e instanceof SyntaxError ? 400 : 500, { error: e instanceof SyntaxError ? 'Bad request' : e.message }); } } module.exports = { handle, add, unread, load };