Family bookkeeping PWA modelled on 木木记账
Hono + SQLite server and a React/shadcn PWA with two-level categories, who-spent/who-paid splits, settlement, one-line and voice entry, budget alerts (Web Push and Bark), monthly/annual reports, and 木木 import tools. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
import webpush from 'web-push';
|
||||
import { kvGet, kvSet, type DB } from './db.js';
|
||||
|
||||
// VAPID keys are generated once and kept in the database.
|
||||
export function vapidKeys(db: DB) {
|
||||
let pub = kvGet(db, 'vapid_public');
|
||||
let priv = kvGet(db, 'vapid_private');
|
||||
if (!pub || !priv) {
|
||||
const keys = webpush.generateVAPIDKeys();
|
||||
pub = keys.publicKey;
|
||||
priv = keys.privateKey;
|
||||
kvSet(db, 'vapid_public', pub);
|
||||
kvSet(db, 'vapid_private', priv);
|
||||
}
|
||||
return { publicKey: pub, privateKey: priv };
|
||||
}
|
||||
|
||||
export function saveSubscription(db: DB, userId: number, sub: { endpoint: string }) {
|
||||
db.prepare(
|
||||
`INSERT INTO push_subscriptions (endpoint, user_id, data) VALUES (?, ?, ?)
|
||||
ON CONFLICT(endpoint) DO UPDATE SET user_id = excluded.user_id, data = excluded.data`,
|
||||
).run(sub.endpoint, userId, JSON.stringify(sub));
|
||||
}
|
||||
|
||||
export function removeSubscription(db: DB, endpoint: string) {
|
||||
db.prepare('DELETE FROM push_subscriptions WHERE endpoint = ?').run(endpoint);
|
||||
}
|
||||
|
||||
// Optional Bark (iOS push app) endpoints, e.g. "https://bark.example.com/<device key>",
|
||||
// comma separated in BARK_URLS. Delivered alongside Web Push.
|
||||
async function pushToBark(payload: { title: string; body: string; url?: string }) {
|
||||
const urls = (process.env.BARK_URLS ?? '').split(',').map((s) => s.trim()).filter(Boolean);
|
||||
const link = process.env.PUBLIC_URL ? new URL(payload.url ?? '/', process.env.PUBLIC_URL).href : undefined;
|
||||
await Promise.all(
|
||||
urls.map(async (base) => {
|
||||
try {
|
||||
const res = await fetch(base.replace(/\/$/, ''), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: payload.title, body: payload.body, group: '记账', url: link }),
|
||||
});
|
||||
if (!res.ok) console.error('bark push failed', res.status);
|
||||
} catch (err) {
|
||||
console.error('bark push failed', err);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function pushToAll(db: DB, payload: { title: string; body: string; url?: string }) {
|
||||
await pushToBark(payload);
|
||||
const subject = process.env.VAPID_SUBJECT ?? 'mailto:admin@example.com';
|
||||
const { publicKey, privateKey } = vapidKeys(db);
|
||||
const subs = db.prepare('SELECT endpoint, data FROM push_subscriptions').all() as { endpoint: string; data: string }[];
|
||||
await Promise.all(
|
||||
subs.map(async (s) => {
|
||||
try {
|
||||
await webpush.sendNotification(JSON.parse(s.data), JSON.stringify(payload), {
|
||||
vapidDetails: { subject, publicKey, privateKey },
|
||||
TTL: 24 * 3600,
|
||||
});
|
||||
} catch (err) {
|
||||
const status = (err as { statusCode?: number }).statusCode;
|
||||
// The browser dropped this subscription; forget it.
|
||||
if (status === 404 || status === 410) removeSubscription(db, s.endpoint);
|
||||
else console.error('push failed', status, err);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user