Add Svelte web client and service worker
Mobile-first PWA: groups via key-in-fragment links, encrypted outbox and sync over SSE, all split modes, currencies with ECB rate prefill, photos, comments, history and rewind, stats, recurring expenses, CSV and backup, EN/CS, dark/light theme, Web Push decrypted in the service worker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
This commit is contained in:
parent
f67add3660
commit
8fbbb4933e
53 changed files with 4558 additions and 37 deletions
90
apps/web/src/lib/api.ts
Normal file
90
apps/web/src/lib/api.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
// Thin wrappers around the server API (SPEC.md §8.1).
|
||||
import type { StoredEvent } from './idb.ts';
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/** True for errors that mean "try again later" rather than "this is wrong". */
|
||||
export const isOffline = (e: unknown) => !(e instanceof ApiError) || e.status >= 500 || e.status === 429;
|
||||
|
||||
async function req<T>(method: string, path: string, opts: { token?: string; json?: unknown; body?: BodyInit; signal?: AbortSignal } = {}): Promise<T> {
|
||||
const headers: Record<string, string> = {};
|
||||
if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
|
||||
if (opts.json !== undefined) headers['Content-Type'] = 'application/json';
|
||||
const res = await fetch(path, {
|
||||
method,
|
||||
headers,
|
||||
body: opts.json !== undefined ? JSON.stringify(opts.json) : opts.body,
|
||||
signal: opts.signal,
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (!res.ok) {
|
||||
let msg = res.statusText;
|
||||
try {
|
||||
msg = (await res.json()).error ?? msg;
|
||||
} catch { /* not JSON */ }
|
||||
throw new ApiError(res.status, msg);
|
||||
}
|
||||
const type = res.headers.get('content-type') ?? '';
|
||||
return (type.includes('application/json') ? res.json() : res.arrayBuffer()) as Promise<T>;
|
||||
}
|
||||
|
||||
export interface ServerConfig {
|
||||
vapidPublicKey: string | null;
|
||||
maxPhotoBytes: number;
|
||||
maxGroupBytes: number;
|
||||
}
|
||||
|
||||
let configP: Promise<ServerConfig> | null = null;
|
||||
export function serverConfig(): Promise<ServerConfig> {
|
||||
configP ??= req<ServerConfig>('GET', '/api/config').catch((e) => {
|
||||
configP = null;
|
||||
throw e;
|
||||
});
|
||||
return configP;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
createGroup: (id: string, authHash: string) => req('POST', '/api/groups', { json: { id, authHash } }),
|
||||
deleteGroup: (id: string, token: string) => req('DELETE', `/api/groups/${id}`, { token }),
|
||||
events: (id: string, token: string, after: number) =>
|
||||
req<{ events: Omit<StoredEvent, 'g'>[]; latest: number }>('GET', `/api/groups/${id}/events?after=${after}&limit=500`, { token }),
|
||||
append: (id: string, token: string, events: Omit<StoredEvent, 'g' | 'seq'>[]) =>
|
||||
req<{ seqs: number[] }>('POST', `/api/groups/${id}/events`, { token, json: { events } }),
|
||||
putBlob: (id: string, token: string, blobId: string, data: ArrayBuffer) =>
|
||||
req('PUT', `/api/groups/${id}/blobs/${blobId}`, { token, body: data }),
|
||||
getBlob: (id: string, token: string, blobId: string) => req<ArrayBuffer>('GET', `/api/groups/${id}/blobs/${blobId}`, { token }),
|
||||
pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) =>
|
||||
req('POST', `/api/groups/${id}/push`, { token, json: { ...sub, deviceId } }),
|
||||
pushUnsubscribe: (id: string, token: string, endpoint: string) => req('DELETE', `/api/groups/${id}/push`, { token, json: { endpoint } }),
|
||||
rates: (date: string) => req<{ base: string; date: string; rates: Record<string, string> }>('GET', `/api/rates?date=${date}`),
|
||||
};
|
||||
|
||||
/**
|
||||
* Listen for "new seq" pings on the group's SSE stream. EventSource can't
|
||||
* send an Authorization header, so this reads the stream with fetch.
|
||||
* Resolves when the stream ends; throws on errors.
|
||||
*/
|
||||
export async function listen(id: string, token: string, signal: AbortSignal, onSeq: (seq: number) => void): Promise<void> {
|
||||
const res = await fetch(`/api/groups/${id}/stream`, { headers: { Authorization: `Bearer ${token}` }, signal, cache: 'no-store' });
|
||||
if (!res.ok || !res.body) throw new ApiError(res.status, 'stream failed');
|
||||
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
||||
let buf = '';
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) return;
|
||||
buf += value;
|
||||
let i: number;
|
||||
while ((i = buf.indexOf('\n\n')) >= 0) {
|
||||
const msg = buf.slice(0, i);
|
||||
buf = buf.slice(i + 2);
|
||||
const m = /^data: (\d+)$/m.exec(msg);
|
||||
if (m) onSeq(Number(m[1]));
|
||||
}
|
||||
}
|
||||
}
|
||||
84
apps/web/src/lib/backup.ts
Normal file
84
apps/web/src/lib/backup.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
// Backup file (SPEC.md §7.6): the encrypted event log and photos plus the
|
||||
// group secret, so the group can be restored even if every link is lost.
|
||||
// Events and photos stay encrypted inside; the secret makes the file as
|
||||
// sensitive as the link.
|
||||
import type { GroupEvent } from '@oweme/core';
|
||||
import { api, ApiError } from './api.ts';
|
||||
import { b64uDecode, b64uEncode, deriveKeys, isGroupId, isGroupSecret, sha256hex } from './crypto.ts';
|
||||
import { get, put, type StoredBlob } from './idb.ts';
|
||||
import { decryptEvent } from './events.ts';
|
||||
import { addGroup, type GroupSession } from './session.svelte.ts';
|
||||
|
||||
interface BackupFile {
|
||||
format: 'oweme-backup';
|
||||
v: 1;
|
||||
groupId: string;
|
||||
secret: string;
|
||||
createdAt: string;
|
||||
events: { id: string; deviceId: string; iv: string; ct: string }[];
|
||||
blobs: { id: string; data: string }[];
|
||||
}
|
||||
|
||||
function photoIds(events: GroupEvent[]): string[] {
|
||||
const ids = new Set<string>();
|
||||
for (const e of events) {
|
||||
if ((e.type === 'expense.created' || e.type === 'expense.updated') && e.data?.photo) {
|
||||
ids.add(e.data.photo.blobId);
|
||||
ids.add(e.data.photo.thumbBlobId);
|
||||
}
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
export async function makeBackup(s: GroupSession): Promise<string> {
|
||||
await s.sync();
|
||||
const raw = await s.rawEvents();
|
||||
const blobs: BackupFile['blobs'] = [];
|
||||
for (const id of photoIds(s.synced)) {
|
||||
let rec = await get<StoredBlob>('blobs', [s.id, id]);
|
||||
if (!rec) {
|
||||
try {
|
||||
rec = { g: s.id, id, data: await api.getBlob(s.id, s.keys.authToken, id), uploaded: true };
|
||||
await put('blobs', rec);
|
||||
} catch {
|
||||
continue; // missing photo shouldn't block the rest of the backup
|
||||
}
|
||||
}
|
||||
blobs.push({ id, data: b64uEncode(new Uint8Array(rec.data)) });
|
||||
}
|
||||
const file: BackupFile = {
|
||||
format: 'oweme-backup', v: 1, groupId: s.id, secret: s.local.secret, createdAt: new Date().toISOString(),
|
||||
events: raw.map(({ id, deviceId, iv, ct }) => ({ id, deviceId, iv, ct })),
|
||||
blobs,
|
||||
};
|
||||
return JSON.stringify(file);
|
||||
}
|
||||
|
||||
/** Restore a backup to this server. Returns the group id and whether it already existed. */
|
||||
export async function restoreBackup(text: string): Promise<{ id: string; existed: boolean }> {
|
||||
let f: BackupFile;
|
||||
try {
|
||||
f = JSON.parse(text);
|
||||
} catch {
|
||||
throw new Error('bad file');
|
||||
}
|
||||
if (f?.format !== 'oweme-backup' || !isGroupId(f.groupId) || !isGroupSecret(f.secret) || !Array.isArray(f.events) || !f.events.length)
|
||||
throw new Error('bad file');
|
||||
const keys = await deriveKeys(f.secret);
|
||||
// Make sure the key really opens this data before uploading anything.
|
||||
if (!(await decryptEvent(keys, f.groupId, { ...f.events[0], seq: 0 }))) throw new Error('bad file');
|
||||
|
||||
let existed = false;
|
||||
try {
|
||||
await api.createGroup(f.groupId, await sha256hex(keys.authToken));
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 409) existed = true;
|
||||
else throw e;
|
||||
}
|
||||
// Uploads are idempotent (by event and blob id), so this also completes
|
||||
// an interrupted restore, and is harmless for a group that already exists.
|
||||
for (const b of f.blobs ?? []) await api.putBlob(f.groupId, keys.authToken, b.id, b64uDecode(b.data).buffer);
|
||||
for (let i = 0; i < f.events.length; i += 200) await api.append(f.groupId, keys.authToken, f.events.slice(i, i + 200));
|
||||
await addGroup(f.groupId, f.secret);
|
||||
return { id: f.groupId, existed };
|
||||
}
|
||||
77
apps/web/src/lib/crypto.ts
Normal file
77
apps/web/src/lib/crypto.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
// Client-side encryption (SPEC.md §3.1, §11). WebCrypto only:
|
||||
// AES-256-GCM for data, HKDF-SHA-256 to derive keys from the group secret.
|
||||
|
||||
const te = new TextEncoder();
|
||||
const td = new TextDecoder();
|
||||
|
||||
export function b64uEncode(bytes: Uint8Array): string {
|
||||
let s = '';
|
||||
for (const b of bytes) s += String.fromCharCode(b);
|
||||
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
export function b64uDecode(str: string): Uint8Array<ArrayBuffer> {
|
||||
const s = atob(str.replace(/-/g, '+').replace(/_/g, '/'));
|
||||
const out = new Uint8Array(s.length);
|
||||
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function randomBytes(n: number): Uint8Array<ArrayBuffer> {
|
||||
return crypto.getRandomValues(new Uint8Array(n));
|
||||
}
|
||||
|
||||
/** Random base64url id; 16 bytes → 22 chars. */
|
||||
export function randomId(bytes = 16): string {
|
||||
return b64uEncode(randomBytes(bytes));
|
||||
}
|
||||
|
||||
export const isGroupId = (s: string) => /^[A-Za-z0-9_-]{22}$/.test(s);
|
||||
export const isGroupSecret = (s: string) => /^[A-Za-z0-9_-]{43}$/.test(s);
|
||||
|
||||
export interface GroupKeys {
|
||||
encKey: CryptoKey;
|
||||
/** bearer token for the API; the server only stores its SHA-256 */
|
||||
authToken: string;
|
||||
}
|
||||
|
||||
export async function deriveKeys(secret: string): Promise<GroupKeys> {
|
||||
const ikm = await crypto.subtle.importKey('raw', b64uDecode(secret), 'HKDF', false, ['deriveKey', 'deriveBits']);
|
||||
const params = (info: string) => ({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: te.encode(info) });
|
||||
const encKey = await crypto.subtle.deriveKey(params('oweme/enc/v1'), ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
||||
const auth = new Uint8Array(await crypto.subtle.deriveBits(params('oweme/auth/v1'), ikm, 256));
|
||||
return { encKey, authToken: b64uEncode(auth) };
|
||||
}
|
||||
|
||||
export async function sha256hex(s: string): Promise<string> {
|
||||
const d = new Uint8Array(await crypto.subtle.digest('SHA-256', te.encode(s)));
|
||||
return [...d].map((b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
/** Encrypt JSON for an event. `aad` binds the ciphertext to its group and id,
|
||||
* so the server can't swap events between groups or ids. */
|
||||
export async function encryptJson(key: CryptoKey, value: unknown, aad: string): Promise<{ iv: string; ct: string }> {
|
||||
const iv = randomBytes(12);
|
||||
const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: te.encode(aad) }, key, te.encode(JSON.stringify(value)));
|
||||
return { iv: b64uEncode(iv), ct: b64uEncode(new Uint8Array(ct)) };
|
||||
}
|
||||
|
||||
export async function decryptJson<T>(key: CryptoKey, iv: string, ct: string, aad: string): Promise<T> {
|
||||
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b64uDecode(iv), additionalData: te.encode(aad) }, key, b64uDecode(ct));
|
||||
return JSON.parse(td.decode(pt));
|
||||
}
|
||||
|
||||
/** Encrypt bytes for a blob: output is iv (12 bytes) || ciphertext. */
|
||||
export async function encryptBytes(key: CryptoKey, data: ArrayBuffer, aad: string): Promise<ArrayBuffer> {
|
||||
const iv = randomBytes(12);
|
||||
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: te.encode(aad) }, key, data));
|
||||
const out = new Uint8Array(12 + ct.length);
|
||||
out.set(iv);
|
||||
out.set(ct, 12);
|
||||
return out.buffer;
|
||||
}
|
||||
|
||||
export async function decryptBytes(key: CryptoKey, data: ArrayBuffer, aad: string): Promise<ArrayBuffer> {
|
||||
const bytes = new Uint8Array(data);
|
||||
return crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes.subarray(0, 12), additionalData: te.encode(aad) }, key, bytes.subarray(12));
|
||||
}
|
||||
17
apps/web/src/lib/events.ts
Normal file
17
apps/web/src/lib/events.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// Decrypting a stored event. Plain module (no runes) so the service worker
|
||||
// can use it too.
|
||||
import type { EventPlaintext, GroupEvent } from '@oweme/core';
|
||||
import { decryptJson, type GroupKeys } from './crypto.ts';
|
||||
|
||||
export async function decryptEvent(
|
||||
keys: GroupKeys,
|
||||
groupId: string,
|
||||
e: { id: string; seq: number | null; deviceId: string; iv: string; ct: string },
|
||||
): Promise<GroupEvent | null> {
|
||||
try {
|
||||
const p = await decryptJson<EventPlaintext>(keys.encKey, e.iv, e.ct, `${groupId}|${e.id}`);
|
||||
return { ...p, id: e.id, seq: e.seq, deviceId: e.deviceId };
|
||||
} catch {
|
||||
return null; // wrong key or tampered: skip it
|
||||
}
|
||||
}
|
||||
87
apps/web/src/lib/format.ts
Normal file
87
apps/web/src/lib/format.ts
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import { exponent, toDecimalString } from '@oweme/core';
|
||||
import { settings } from './settings.svelte.ts';
|
||||
|
||||
const cache = new Map<string, Intl.NumberFormat>();
|
||||
|
||||
/** Format minor units as money in the current locale ("1 234,50 Kč"). */
|
||||
export function money(minor: number, currency: string, opts: { sign?: boolean } = {}): string {
|
||||
const key = `${settings.locale}|${currency}|${opts.sign ? 1 : 0}`;
|
||||
let f = cache.get(key);
|
||||
if (!f) {
|
||||
const e = exponent(currency);
|
||||
try {
|
||||
f = new Intl.NumberFormat(settings.locale, {
|
||||
style: 'currency', currency, minimumFractionDigits: e, maximumFractionDigits: e,
|
||||
signDisplay: opts.sign ? 'exceptZero' : 'auto',
|
||||
});
|
||||
} catch {
|
||||
f = new Intl.NumberFormat(settings.locale, { minimumFractionDigits: e, maximumFractionDigits: e });
|
||||
}
|
||||
cache.set(key, f);
|
||||
}
|
||||
return f.format(minor / 10 ** exponent(currency));
|
||||
}
|
||||
|
||||
/** Editable amount text for an input, in the user's decimal style. */
|
||||
export function amountInput(minor: number, currency: string): string {
|
||||
const s = toDecimalString(minor, currency);
|
||||
return settings.lang === 'cs' ? s.replace('.', ',') : s;
|
||||
}
|
||||
|
||||
export function fmtDate(d: string, style: 'short' | 'long' = 'short'): string {
|
||||
const date = new Date(`${d}T12:00:00`);
|
||||
return date.toLocaleDateString(settings.locale, style === 'long'
|
||||
? { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' }
|
||||
: { day: 'numeric', month: 'short', year: date.getFullYear() === new Date().getFullYear() ? undefined : 'numeric' });
|
||||
}
|
||||
|
||||
export function fmtDateTime(iso: string): string {
|
||||
return new Date(iso).toLocaleString(settings.locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
export function fmtMonth(ym: string): string {
|
||||
return new Date(`${ym}-15T12:00:00`).toLocaleDateString(settings.locale, { month: 'short', year: '2-digit' });
|
||||
}
|
||||
|
||||
/** Today as YYYY-MM-DD in local time. */
|
||||
export function today(): string {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function addDays(d: string, n: number): string {
|
||||
const x = new Date(`${d}T12:00:00`);
|
||||
x.setDate(x.getDate() + n);
|
||||
return `${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, '0')}-${String(x.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function currencyName(code: string): string {
|
||||
try {
|
||||
return new Intl.DisplayNames(settings.locale, { type: 'currency' }).of(code) ?? code;
|
||||
} catch {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
export const CATEGORY_ICONS: Record<string, string> = {
|
||||
food: '🍽️', groceries: '🛒', transport: '🚕', accommodation: '🏨', entertainment: '🎟️',
|
||||
shopping: '🛍️', utilities: '💡', rent: '🏠', travel: '✈️', gifts: '🎁', health: '💊',
|
||||
other: '🧾', transfer: '💸',
|
||||
};
|
||||
|
||||
export const MEMBER_COLORS = ['#3DDC97', '#F2A65A', '#6CB4EE', '#E879A6', '#C9A227', '#9B8CF2', '#4FD1C5', '#F87171', '#A3E635', '#FB923C'];
|
||||
|
||||
export function download(filename: string, content: BlobPart, type: string) {
|
||||
const url = URL.createObjectURL(new Blob([content], { type }));
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.append(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
||||
}
|
||||
|
||||
export function slug(s: string): string {
|
||||
return s.normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^A-Za-z0-9]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'group';
|
||||
}
|
||||
25
apps/web/src/lib/i18n.ts
Normal file
25
apps/web/src/lib/i18n.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
// Tiny i18n. English is the default; Czech is used when the browser's
|
||||
// preferred language is Czech, unless the user picks one in settings
|
||||
// (SPEC.md §10.3). Plain module (no runes) so the service worker can use it.
|
||||
import cs from './locales/cs.ts';
|
||||
import en, { type Messages, type Plural } from './locales/en.ts';
|
||||
|
||||
export type Lang = 'en' | 'cs';
|
||||
export type MsgKey = keyof Messages;
|
||||
const dicts: Record<Lang, Messages> = { en, cs };
|
||||
|
||||
export function detectLang(languages: readonly string[] = navigator.languages ?? [navigator.language]): Lang {
|
||||
const first = (languages[0] ?? '').toLowerCase();
|
||||
return first === 'cs' || first.startsWith('cs-') ? 'cs' : 'en';
|
||||
}
|
||||
|
||||
export const localeOf = (lang: Lang) => (lang === 'cs' ? 'cs-CZ' : 'en');
|
||||
|
||||
export function translate(lang: Lang, key: MsgKey, vars: Record<string, string | number> = {}): string {
|
||||
let msg: string | Plural = dicts[lang][key] ?? en[key];
|
||||
if (typeof msg !== 'string') {
|
||||
const form = new Intl.PluralRules(localeOf(lang)).select(Number(vars.n ?? 0));
|
||||
msg = form === 'one' ? msg.one : form === 'few' ? msg.few : msg.other;
|
||||
}
|
||||
return msg.replace(/\{(\w+)\}/g, (_, k) => (k in vars ? String(vars[k]) : `{${k}}`));
|
||||
}
|
||||
150
apps/web/src/lib/idb.ts
Normal file
150
apps/web/src/lib/idb.ts
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
// IndexedDB storage, shared by the page and the service worker.
|
||||
// Events are kept as the server's ciphertext and decrypted when loaded.
|
||||
|
||||
export interface LocalGroup {
|
||||
id: string;
|
||||
/** the key from the link; anyone with this has full access */
|
||||
secret: string;
|
||||
name: string;
|
||||
icon: string;
|
||||
baseCurrency: string;
|
||||
/** "who am I" on this device */
|
||||
me: string | null;
|
||||
/** my balance in base minor units, cached for the home screen */
|
||||
myBalance: number | null;
|
||||
lastSeq: number;
|
||||
lastOpened: number;
|
||||
push: boolean;
|
||||
/** highest seq the service worker has notified about */
|
||||
notifiedSeq: number;
|
||||
/** set when the server says the group no longer exists */
|
||||
gone?: boolean;
|
||||
}
|
||||
|
||||
export interface StoredEvent {
|
||||
g: string;
|
||||
seq: number;
|
||||
id: string;
|
||||
deviceId: string;
|
||||
iv: string;
|
||||
ct: string;
|
||||
}
|
||||
|
||||
export interface OutboxItem {
|
||||
n?: number;
|
||||
g: string;
|
||||
id: string;
|
||||
deviceId: string;
|
||||
iv: string;
|
||||
ct: string;
|
||||
}
|
||||
|
||||
export interface StoredBlob {
|
||||
g: string;
|
||||
id: string;
|
||||
/** encrypted bytes */
|
||||
data: ArrayBuffer;
|
||||
uploaded: boolean;
|
||||
}
|
||||
|
||||
let dbp: Promise<IDBDatabase> | null = null;
|
||||
|
||||
export function openDb(): Promise<IDBDatabase> {
|
||||
if (dbp) return dbp;
|
||||
dbp = new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open('oweme', 1);
|
||||
req.onupgradeneeded = () => {
|
||||
const db = req.result;
|
||||
db.createObjectStore('groups', { keyPath: 'id' });
|
||||
db.createObjectStore('events', { keyPath: ['g', 'seq'] });
|
||||
db.createObjectStore('outbox', { keyPath: 'n', autoIncrement: true }).createIndex('g', 'g');
|
||||
db.createObjectStore('blobs', { keyPath: ['g', 'id'] });
|
||||
db.createObjectStore('kv');
|
||||
};
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
return dbp;
|
||||
}
|
||||
|
||||
type StoreName = 'groups' | 'events' | 'outbox' | 'blobs' | 'kv';
|
||||
|
||||
function wrap<T>(req: IDBRequest<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
}
|
||||
|
||||
async function store(name: StoreName, mode: IDBTransactionMode = 'readonly'): Promise<IDBObjectStore> {
|
||||
return (await openDb()).transaction(name, mode).objectStore(name);
|
||||
}
|
||||
|
||||
export async function get<T>(name: StoreName, key: IDBValidKey): Promise<T | undefined> {
|
||||
return wrap((await store(name)).get(key));
|
||||
}
|
||||
export async function put(name: StoreName, value: unknown, key?: IDBValidKey): Promise<void> {
|
||||
await wrap((await store(name, 'readwrite')).put(value, key));
|
||||
}
|
||||
export async function del(name: StoreName, key: IDBValidKey | IDBKeyRange): Promise<void> {
|
||||
await wrap((await store(name, 'readwrite')).delete(key));
|
||||
}
|
||||
export async function getAll<T>(name: StoreName, query?: IDBKeyRange): Promise<T[]> {
|
||||
return wrap((await store(name)).getAll(query)) as Promise<T[]>;
|
||||
}
|
||||
|
||||
export const groupRange = (g: string) => IDBKeyRange.bound([g, -Infinity], [g, Infinity]);
|
||||
export const groupBlobRange = (g: string) => IDBKeyRange.bound([g, ''], [g, '']);
|
||||
|
||||
export async function putEvents(events: StoredEvent[]): Promise<void> {
|
||||
if (!events.length) return;
|
||||
const tx = (await openDb()).transaction('events', 'readwrite');
|
||||
for (const e of events) tx.objectStore('events').put(e);
|
||||
await new Promise<void>((res, rej) => ((tx.oncomplete = () => res()), (tx.onerror = () => rej(tx.error))));
|
||||
}
|
||||
|
||||
export async function outboxFor(g: string): Promise<OutboxItem[]> {
|
||||
const s = await store('outbox');
|
||||
return wrap(s.index('g').getAll(g)) as Promise<OutboxItem[]>;
|
||||
}
|
||||
|
||||
export async function updateGroup(id: string, patch: Partial<LocalGroup>): Promise<LocalGroup | undefined> {
|
||||
const tx = (await openDb()).transaction('groups', 'readwrite');
|
||||
const s = tx.objectStore('groups');
|
||||
const g = (await wrap(s.get(id))) as LocalGroup | undefined;
|
||||
if (!g) return undefined;
|
||||
const next = { ...g, ...patch };
|
||||
s.put(next);
|
||||
await new Promise<void>((res, rej) => ((tx.oncomplete = () => res()), (tx.onerror = () => rej(tx.error))));
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Remove a group and everything cached for it from this device. */
|
||||
export async function forgetGroup(id: string): Promise<void> {
|
||||
const db = await openDb();
|
||||
const tx = db.transaction(['groups', 'events', 'outbox', 'blobs'], 'readwrite');
|
||||
tx.objectStore('groups').delete(id);
|
||||
tx.objectStore('events').delete(groupRange(id));
|
||||
tx.objectStore('blobs').delete(groupBlobRange(id));
|
||||
const ob = tx.objectStore('outbox');
|
||||
const keys = await wrap(ob.index('g').getAllKeys(id));
|
||||
for (const k of keys) ob.delete(k);
|
||||
await new Promise<void>((res, rej) => ((tx.oncomplete = () => res()), (tx.onerror = () => rej(tx.error))));
|
||||
}
|
||||
|
||||
export async function kvGet<T>(k: string): Promise<T | undefined> {
|
||||
return get<T>('kv', k);
|
||||
}
|
||||
export async function kvSet(k: string, v: unknown): Promise<void> {
|
||||
await put('kv', v, k);
|
||||
}
|
||||
|
||||
/** Stable random id for this browser, so it can skip notifying itself. */
|
||||
export async function deviceId(): Promise<string> {
|
||||
let id = await kvGet<string>('deviceId');
|
||||
if (!id) {
|
||||
id = Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(36).padStart(2, '0')).join('');
|
||||
await kvSet('deviceId', id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
253
apps/web/src/lib/locales/cs.ts
Normal file
253
apps/web/src/lib/locales/cs.ts
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
import type { Messages } from './en.ts';
|
||||
|
||||
const cs: Messages = {
|
||||
app_name: 'OweMe',
|
||||
tagline: 'Dělte společné výdaje. Šifrováno end-to-end.',
|
||||
|
||||
your_groups: 'Vaše skupiny',
|
||||
no_groups: 'Na tomto zařízení zatím nejsou žádné skupiny. Vytvořte novou, nebo otevřete odkaz, který vám někdo poslal.',
|
||||
new_group: 'Nová skupina',
|
||||
open_link: 'Otevřít odkaz na skupinu',
|
||||
restore_backup: 'Obnovit zálohu',
|
||||
paste_link: 'Vložte odkaz na skupinu',
|
||||
open: 'Otevřít',
|
||||
invalid_link: 'Tohle nevypadá jako úplný odkaz na skupinu OweMe.',
|
||||
you_are_owed: 'dluží vám {amount}',
|
||||
you_owe: 'dlužíte {amount}',
|
||||
settled: 'vyrovnáno',
|
||||
pick_identity_hint: 'vyberte, kdo jste',
|
||||
group_gone: 'smazáno',
|
||||
e2e_note: 'Vše se šifruje přímo ve vašem zařízení. Server ukládá jen data, která nedokáže přečíst. Odkazy na skupiny si proto dobře uschovejte: ztracený odkaz nelze obnovit.',
|
||||
|
||||
settings: 'Nastavení',
|
||||
app_settings: 'Nastavení aplikace',
|
||||
language: 'Jazyk',
|
||||
lang_auto: 'Automaticky',
|
||||
theme: 'Vzhled',
|
||||
theme_system: 'Podle systému',
|
||||
theme_dark: 'Tmavý',
|
||||
theme_light: 'Světlý',
|
||||
|
||||
create_group: 'Vytvořit skupinu',
|
||||
group_name: 'Název skupiny',
|
||||
group_name_ph: 'Výlet do Prahy',
|
||||
base_currency: 'Hlavní měna',
|
||||
base_currency_hint: 'V této měně se zobrazují zůstatky. Jakmile má skupina výdaje, nelze ji změnit.',
|
||||
base_currency_locked: 'Uzamčeno, protože skupina už má výdaje.',
|
||||
icon: 'Ikona',
|
||||
your_name: 'Vaše jméno',
|
||||
other_members: 'Další členové',
|
||||
add_member: 'Přidat člena',
|
||||
member_name: 'Jméno',
|
||||
creating: 'Vytvářím…',
|
||||
|
||||
share_group: 'Sdílet skupinu',
|
||||
share_intro: 'Kdokoli s tímto odkazem může skupinu vidět i upravovat. Posílejte ho jen členům.',
|
||||
save_link_warning: 'Uložte si tento odkaz na bezpečné místo. Pokud se ztratí všechny kopie, skupinu nepůjde obnovit.',
|
||||
copy_link: 'Kopírovat odkaz',
|
||||
copied: 'Zkopírováno',
|
||||
share: 'Sdílet…',
|
||||
done: 'Hotovo',
|
||||
|
||||
who_are_you: 'Kdo jste?',
|
||||
who_are_you_hint: 'Zapamatuje se na tomto zařízení, takže výdaje budou předvyplněné na vás.',
|
||||
im_new: 'Nejsem v seznamu',
|
||||
just_looking: 'Přeskočit',
|
||||
change_identity: 'Nejsem {name}',
|
||||
you: 'vy',
|
||||
|
||||
expenses: 'Výdaje',
|
||||
balances: 'Zůstatky',
|
||||
stats: 'Statistiky',
|
||||
activity: 'Aktivita',
|
||||
add_expense: 'Přidat výdaj',
|
||||
no_expenses: 'Zatím žádné výdaje. Klepněte na + a přidejte první.',
|
||||
total_spent: 'Celkem utraceno',
|
||||
paid_by: 'Platil(a) {name}',
|
||||
paid_by_many: 'Platilo {n} lidí',
|
||||
your_share: 'váš podíl {amount}',
|
||||
you_lent: 'půjčili jste {amount}',
|
||||
you_borrowed: 'dlužíte {amount}',
|
||||
not_involved: 'netýká se vás',
|
||||
transfer_line: '{from} → {to}',
|
||||
offline: 'Jste offline. Změny se uloží v zařízení a synchronizují se později.',
|
||||
pending: { one: '{n} změna čeká na synchronizaci', few: '{n} změny čekají na synchronizaci', other: '{n} změn čeká na synchronizaci' },
|
||||
rollback_warning: 'Server vrátil starší data, než toto zařízení už vidělo. Mohl s nimi někdo manipulovat, nebo byla obnovena ze zálohy.',
|
||||
not_found_group: 'Tato skupina už na serveru neexistuje.',
|
||||
remove_from_device: 'Odebrat z tohoto zařízení',
|
||||
group_not_on_device: 'Tato skupina není uložená v tomto zařízení. Otevřete celý odkaz (včetně části za #).',
|
||||
loading: 'Načítám…',
|
||||
search: 'Hledat',
|
||||
|
||||
settle_up: 'Vyrovnání',
|
||||
all_settled: 'Všichni jsou vyrovnaní. 🎉',
|
||||
mark_paid: 'Zaznamenat platbu',
|
||||
show_in: 'Zobrazit v',
|
||||
display_only_rate: 'Přepočteno dnešním kurzem, jen pro zobrazení.',
|
||||
is_owed: 'má dostat {amount}',
|
||||
owes: 'dluží {amount}',
|
||||
|
||||
new_expense: 'Nový výdaj',
|
||||
edit_expense: 'Upravit výdaj',
|
||||
new_transfer: 'Zaznamenat platbu',
|
||||
kind_expense: 'Výdaj',
|
||||
kind_transfer: 'Platba',
|
||||
amount: 'Částka',
|
||||
title: 'Za co?',
|
||||
title_ph: 'Večeře',
|
||||
category: 'Kategorie',
|
||||
date: 'Datum',
|
||||
currency: 'Měna',
|
||||
rate: 'Směnný kurz',
|
||||
rate_source_ecb: 'Kurz ECB ze dne {date}',
|
||||
rate_source_manual: 'Zadáno ručně',
|
||||
rate_unavailable: 'Pro tuto měnu není kurz k dispozici, zadejte ho prosím.',
|
||||
paid_by_label: 'Platil(a)',
|
||||
multiple_payers: 'Platilo více lidí',
|
||||
from_label: 'Od',
|
||||
to_label: 'Komu',
|
||||
split: 'Rozdělení',
|
||||
split_equal: 'Rovným dílem',
|
||||
split_shares: 'Podíly',
|
||||
split_exact: 'Částky',
|
||||
split_percent: 'Procenta',
|
||||
remaining: 'Zbývá: {amount}',
|
||||
over_by: 'Přebývá: {amount}',
|
||||
select_all: 'Všichni',
|
||||
select_none: 'Nikdo',
|
||||
note: 'Poznámka',
|
||||
photo: 'Fotka',
|
||||
add_photo: 'Přidat fotku',
|
||||
replace_photo: 'Vyměnit',
|
||||
remove_photo: 'Odebrat',
|
||||
processing_photo: 'Zpracovávám fotku…',
|
||||
photo_too_large: 'Fotka je i po zmenšení příliš velká.',
|
||||
repeat: 'Opakovat',
|
||||
repeat_none: 'Nikdy',
|
||||
repeat_weekly: 'Každý týden',
|
||||
repeat_monthly: 'Každý měsíc',
|
||||
repeat_yearly: 'Každý rok',
|
||||
save: 'Uložit',
|
||||
cancel: 'Zrušit',
|
||||
invalid_amount: 'Zadejte platnou částku.',
|
||||
invalid_split: 'Rozdělení nesedí.',
|
||||
invalid_payers: 'Platby nedávají dohromady celou částku.',
|
||||
need_title: 'Doplňte popis.',
|
||||
need_members: 'Nejdřív do skupiny přidejte členy.',
|
||||
|
||||
delete: 'Smazat',
|
||||
restore: 'Obnovit',
|
||||
edit: 'Upravit',
|
||||
deleted_banner: 'Tento výdaj byl smazán.',
|
||||
split_details: 'Rozdělení',
|
||||
paid: 'zaplatil(a) {amount}',
|
||||
owes_share: 'podíl {amount}',
|
||||
converted: '{amount} při kurzu {rate}',
|
||||
comments: 'Komentáře',
|
||||
add_comment: 'Napište komentář…',
|
||||
send: 'Odeslat',
|
||||
history: 'Historie',
|
||||
restore_version: 'Obnovit tuto verzi',
|
||||
current_version: 'Aktuální verze',
|
||||
recurring_badge: 'Opakuje se',
|
||||
confirm_delete: 'Smazat tento výdaj? Později ho můžete obnovit z historie.',
|
||||
|
||||
rewind_here: 'Vrátit skupinu sem',
|
||||
undo_rewind: 'Zrušit toto vrácení',
|
||||
confirm_rewind: 'Vrátit celou skupinu do stavu po této změně? Nic se neztratí: vrácení lze zase zrušit.',
|
||||
act_group_created: '{actor} vytvořil(a) skupinu',
|
||||
act_group_updated: '{actor} změnil(a) nastavení skupiny',
|
||||
act_member_added: '{actor} přidal(a) člena {name}',
|
||||
act_member_updated: '{actor} přejmenoval(a) {old} na {name}',
|
||||
act_member_archived: '{actor} archivoval(a) člena {name}',
|
||||
act_member_restored: '{actor} obnovil(a) člena {name}',
|
||||
act_expense_created: '{actor} přidal(a) {title}',
|
||||
act_expense_updated: '{actor} upravil(a) {title}',
|
||||
act_expense_deleted: '{actor} smazal(a) {title}',
|
||||
act_expense_restored: '{actor} obnovil(a) {title}',
|
||||
act_comment_added: '{actor} okomentoval(a) {title}',
|
||||
act_comment_deleted: '{actor} smazal(a) komentář u {title}',
|
||||
act_recurring_created: '{actor} nastavil(a) opakování {title}',
|
||||
act_recurring_updated: '{actor} změnil(a) opakování {title}',
|
||||
act_recurring_deleted: '{actor} zrušil(a) opakování {title}',
|
||||
act_revert: '{actor} vrátil(a) skupinu do stavu z {time}',
|
||||
someone: 'Někdo',
|
||||
changed_fields: 'Změněno: {fields}',
|
||||
no_activity: 'Zatím žádná aktivita.',
|
||||
|
||||
range_all: 'Celé období',
|
||||
range_month: 'Tento měsíc',
|
||||
range_30: 'Posledních 30 dní',
|
||||
range_year: 'Tento rok',
|
||||
by_category: 'Podle kategorie',
|
||||
by_month: 'Podle měsíce',
|
||||
per_member: 'Zaplaceno vs. podíl',
|
||||
legend_paid: 'Zaplaceno',
|
||||
legend_share: 'Podíl',
|
||||
my_spending: 'Můj podíl na útratě',
|
||||
no_data: 'Za toto období tu nic není.',
|
||||
|
||||
group_settings: 'Nastavení skupiny',
|
||||
members: 'Členové',
|
||||
rename: 'Přejmenovat',
|
||||
archive: 'Archivovat',
|
||||
archived: 'archivován(a)',
|
||||
unarchive: 'Obnovit',
|
||||
archive_needs_zero: 'Archivovat lze jen členy s nulovým zůstatkem.',
|
||||
identity: 'Jste',
|
||||
not_set: 'Nenastaveno',
|
||||
change: 'Změnit',
|
||||
notifications: 'Oznámení',
|
||||
notifications_hint: 'Dostanete oznámení, když skupinu změní někdo jiný.',
|
||||
notifications_ios: 'Na iPhonu a iPadu nejdřív přidejte OweMe na plochu (Sdílet → Přidat na plochu).',
|
||||
notifications_denied: 'Oznámení jsou pro tento web zablokovaná v nastavení prohlížeče.',
|
||||
notifications_unavailable: 'Oznámení nejsou na tomto serveru nebo v tomto prohlížeči k dispozici.',
|
||||
recurring: 'Opakované výdaje',
|
||||
no_recurring: 'Žádné. Při přidání výdaje zvolte „Opakovat“.',
|
||||
next_on: 'příště {date}',
|
||||
stop: 'Zrušit',
|
||||
export: 'Export',
|
||||
export_expenses: 'Výdaje (CSV)',
|
||||
export_balances: 'Zůstatky (CSV)',
|
||||
backup: 'Soubor se zálohou',
|
||||
backup_hint: 'Obsahuje klíč skupiny: kdokoli se souborem skupinu otevře. Uložte ho bezpečně.',
|
||||
danger_zone: 'Nebezpečná zóna',
|
||||
remove_from_device_hint: 'Skupina zůstane na serveru i v ostatních zařízeních.',
|
||||
delete_group: 'Smazat skupinu pro všechny',
|
||||
delete_group_hint: 'Smaže ze serveru všechny výdaje a fotky. Pro potvrzení napište název skupiny.',
|
||||
confirm: 'Potvrdit',
|
||||
saved: 'Uloženo',
|
||||
|
||||
restore_title: 'Obnovit zálohu',
|
||||
restore_pick: 'Vyberte soubor se zálohou OweMe (.json).',
|
||||
restore_bad_file: 'Tohle není platná záloha OweMe.',
|
||||
restore_exists: 'Tato skupina na serveru už existuje, takže byla jen přidána do tohoto zařízení.',
|
||||
restoring: 'Obnovuji…',
|
||||
|
||||
back: 'Zpět',
|
||||
close: 'Zavřít',
|
||||
error_generic: 'Něco se pokazilo: {msg}',
|
||||
update_available: 'Je k dispozici nová verze.',
|
||||
reload: 'Načíst znovu',
|
||||
today: 'Dnes',
|
||||
yesterday: 'Včera',
|
||||
n_members: { one: '{n} člen', few: '{n} členové', other: '{n} členů' },
|
||||
|
||||
cat_food: 'Jídlo a pití',
|
||||
cat_groceries: 'Potraviny',
|
||||
cat_transport: 'Doprava',
|
||||
cat_accommodation: 'Ubytování',
|
||||
cat_entertainment: 'Zábava',
|
||||
cat_shopping: 'Nákupy',
|
||||
cat_utilities: 'Energie a služby',
|
||||
cat_rent: 'Nájem',
|
||||
cat_travel: 'Cestování',
|
||||
cat_gifts: 'Dárky',
|
||||
cat_health: 'Zdraví',
|
||||
cat_other: 'Ostatní',
|
||||
cat_transfer: 'Platba',
|
||||
|
||||
notif_new_activity: { one: '{n} nová změna', few: '{n} nové změny', other: '{n} nových změn' },
|
||||
};
|
||||
|
||||
export default cs;
|
||||
270
apps/web/src/lib/locales/en.ts
Normal file
270
apps/web/src/lib/locales/en.ts
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
// English strings. `{name}` placeholders are filled by t(); entries with
|
||||
// one/few/other are plural forms chosen by Intl.PluralRules on `{n}`.
|
||||
const en = {
|
||||
app_name: 'OweMe',
|
||||
tagline: 'Split group expenses. End-to-end encrypted.',
|
||||
|
||||
// home
|
||||
your_groups: 'Your groups',
|
||||
no_groups: 'No groups on this device yet. Create one, or open a group link someone sent you.',
|
||||
new_group: 'New group',
|
||||
open_link: 'Open a group link',
|
||||
restore_backup: 'Restore a backup',
|
||||
paste_link: 'Paste the group link',
|
||||
open: 'Open',
|
||||
invalid_link: "That doesn't look like a complete OweMe group link.",
|
||||
you_are_owed: 'you are owed {amount}',
|
||||
you_owe: 'you owe {amount}',
|
||||
settled: 'settled up',
|
||||
pick_identity_hint: 'choose who you are',
|
||||
group_gone: 'deleted',
|
||||
e2e_note: 'Everything is encrypted on your device. The server only stores data it cannot read, so keep your group links safe: lost links cannot be recovered.',
|
||||
|
||||
// settings
|
||||
settings: 'Settings',
|
||||
app_settings: 'App settings',
|
||||
language: 'Language',
|
||||
lang_auto: 'Automatic',
|
||||
theme: 'Theme',
|
||||
theme_system: 'System',
|
||||
theme_dark: 'Dark',
|
||||
theme_light: 'Light',
|
||||
|
||||
// new group
|
||||
create_group: 'Create group',
|
||||
group_name: 'Group name',
|
||||
group_name_ph: 'Prague trip',
|
||||
base_currency: 'Main currency',
|
||||
base_currency_hint: 'Balances are shown in this currency. It can’t be changed once the group has expenses.',
|
||||
base_currency_locked: 'Locked because the group has expenses.',
|
||||
icon: 'Icon',
|
||||
your_name: 'Your name',
|
||||
other_members: 'Other members',
|
||||
add_member: 'Add member',
|
||||
member_name: 'Name',
|
||||
creating: 'Creating…',
|
||||
|
||||
// share
|
||||
share_group: 'Share group',
|
||||
share_intro: 'Anyone with this link can see and edit the group. Send it only to group members.',
|
||||
save_link_warning: 'Save this link somewhere safe. If every copy is lost, the group can’t be recovered.',
|
||||
copy_link: 'Copy link',
|
||||
copied: 'Copied',
|
||||
share: 'Share…',
|
||||
done: 'Done',
|
||||
|
||||
// identity
|
||||
who_are_you: 'Who are you?',
|
||||
who_are_you_hint: 'This is remembered on this device, so expenses default to you.',
|
||||
im_new: 'I’m not on the list',
|
||||
just_looking: 'Skip',
|
||||
change_identity: 'I’m not {name}',
|
||||
you: 'you',
|
||||
|
||||
// group tabs
|
||||
expenses: 'Expenses',
|
||||
balances: 'Balances',
|
||||
stats: 'Stats',
|
||||
activity: 'Activity',
|
||||
add_expense: 'Add expense',
|
||||
no_expenses: 'No expenses yet. Tap + to add the first one.',
|
||||
total_spent: 'Total spent',
|
||||
paid_by: 'Paid by {name}',
|
||||
paid_by_many: 'Paid by {n} people',
|
||||
your_share: 'your share {amount}',
|
||||
you_lent: 'you lent {amount}',
|
||||
you_borrowed: 'you borrowed {amount}',
|
||||
not_involved: 'not involved',
|
||||
transfer_line: '{from} → {to}',
|
||||
offline: 'Offline. Changes are saved on this device and will sync later.',
|
||||
pending: { one: '{n} change waiting to sync', few: '{n} changes waiting to sync', other: '{n} changes waiting to sync' },
|
||||
rollback_warning: 'The server returned older data than this device has seen. Someone may have tampered with it, or it was restored from a backup.',
|
||||
not_found_group: 'This group no longer exists on the server.',
|
||||
remove_from_device: 'Remove from this device',
|
||||
group_not_on_device: 'This group isn’t saved on this device. Open the full link (with the part after #) to add it.',
|
||||
loading: 'Loading…',
|
||||
search: 'Search',
|
||||
|
||||
// balances
|
||||
settle_up: 'Settle up',
|
||||
all_settled: 'Everyone is settled up. 🎉',
|
||||
mark_paid: 'Record payment',
|
||||
show_in: 'Show in',
|
||||
display_only_rate: 'Converted at today’s rate, for display only.',
|
||||
is_owed: 'is owed {amount}',
|
||||
owes: 'owes {amount}',
|
||||
|
||||
// expense editor
|
||||
new_expense: 'New expense',
|
||||
edit_expense: 'Edit expense',
|
||||
new_transfer: 'Record payment',
|
||||
kind_expense: 'Expense',
|
||||
kind_transfer: 'Payment',
|
||||
amount: 'Amount',
|
||||
title: 'What was it for?',
|
||||
title_ph: 'Dinner',
|
||||
category: 'Category',
|
||||
date: 'Date',
|
||||
currency: 'Currency',
|
||||
rate: 'Exchange rate',
|
||||
rate_source_ecb: 'ECB rate from {date}',
|
||||
rate_source_manual: 'Entered manually',
|
||||
rate_unavailable: 'No rate available for this currency, please enter it.',
|
||||
paid_by_label: 'Paid by',
|
||||
multiple_payers: 'Several people paid',
|
||||
from_label: 'From',
|
||||
to_label: 'To',
|
||||
split: 'Split',
|
||||
split_equal: 'Equally',
|
||||
split_shares: 'Shares',
|
||||
split_exact: 'Amounts',
|
||||
split_percent: 'Percent',
|
||||
remaining: 'Remaining: {amount}',
|
||||
over_by: 'Over by: {amount}',
|
||||
select_all: 'All',
|
||||
select_none: 'None',
|
||||
note: 'Note',
|
||||
photo: 'Photo',
|
||||
add_photo: 'Add photo',
|
||||
replace_photo: 'Replace',
|
||||
remove_photo: 'Remove',
|
||||
processing_photo: 'Processing photo…',
|
||||
photo_too_large: 'The photo is too large even after compressing.',
|
||||
repeat: 'Repeat',
|
||||
repeat_none: 'Never',
|
||||
repeat_weekly: 'Every week',
|
||||
repeat_monthly: 'Every month',
|
||||
repeat_yearly: 'Every year',
|
||||
save: 'Save',
|
||||
cancel: 'Cancel',
|
||||
invalid_amount: 'Enter a valid amount.',
|
||||
invalid_split: 'The split doesn’t add up.',
|
||||
invalid_payers: 'The payers don’t add up to the amount.',
|
||||
need_title: 'Add a description.',
|
||||
need_members: 'Add members to the group first.',
|
||||
|
||||
// expense detail
|
||||
delete: 'Delete',
|
||||
restore: 'Restore',
|
||||
edit: 'Edit',
|
||||
deleted_banner: 'This expense was deleted.',
|
||||
split_details: 'Split',
|
||||
paid: 'paid {amount}',
|
||||
owes_share: 'share {amount}',
|
||||
converted: '{amount} at {rate}',
|
||||
comments: 'Comments',
|
||||
add_comment: 'Write a comment…',
|
||||
send: 'Send',
|
||||
history: 'History',
|
||||
restore_version: 'Restore this version',
|
||||
current_version: 'Current version',
|
||||
recurring_badge: 'Repeats',
|
||||
confirm_delete: 'Delete this expense? You can restore it later from its history.',
|
||||
|
||||
// activity
|
||||
rewind_here: 'Rewind group to here',
|
||||
undo_rewind: 'Undo this rewind',
|
||||
confirm_rewind: 'Restore the whole group to how it was after this change? Nothing is lost: the rewind itself can be undone.',
|
||||
act_group_created: '{actor} created the group',
|
||||
act_group_updated: '{actor} changed group settings',
|
||||
act_member_added: '{actor} added {name}',
|
||||
act_member_updated: '{actor} renamed {old} to {name}',
|
||||
act_member_archived: '{actor} archived {name}',
|
||||
act_member_restored: '{actor} restored {name}',
|
||||
act_expense_created: '{actor} added {title}',
|
||||
act_expense_updated: '{actor} edited {title}',
|
||||
act_expense_deleted: '{actor} deleted {title}',
|
||||
act_expense_restored: '{actor} restored {title}',
|
||||
act_comment_added: '{actor} commented on {title}',
|
||||
act_comment_deleted: '{actor} deleted a comment on {title}',
|
||||
act_recurring_created: '{actor} set up repeating {title}',
|
||||
act_recurring_updated: '{actor} changed repeating {title}',
|
||||
act_recurring_deleted: '{actor} stopped repeating {title}',
|
||||
act_revert: '{actor} rewound the group to {time}',
|
||||
someone: 'Someone',
|
||||
changed_fields: 'Changed: {fields}',
|
||||
no_activity: 'No activity yet.',
|
||||
|
||||
// stats
|
||||
range_all: 'All time',
|
||||
range_month: 'This month',
|
||||
range_30: 'Last 30 days',
|
||||
range_year: 'This year',
|
||||
by_category: 'By category',
|
||||
by_month: 'By month',
|
||||
per_member: 'Paid vs. share',
|
||||
legend_paid: 'Paid',
|
||||
legend_share: 'Share',
|
||||
my_spending: 'My share of spending',
|
||||
no_data: 'Nothing to show for this period.',
|
||||
|
||||
// group settings
|
||||
group_settings: 'Group settings',
|
||||
members: 'Members',
|
||||
rename: 'Rename',
|
||||
archive: 'Archive',
|
||||
archived: 'archived',
|
||||
unarchive: 'Restore',
|
||||
archive_needs_zero: 'Only members with a zero balance can be archived.',
|
||||
identity: 'You are',
|
||||
not_set: 'Not set',
|
||||
change: 'Change',
|
||||
notifications: 'Notifications',
|
||||
notifications_hint: 'Get a notification when someone else changes this group.',
|
||||
notifications_ios: 'On iPhone and iPad, add OweMe to your home screen first (Share → Add to Home Screen).',
|
||||
notifications_denied: 'Notifications are blocked for this site in your browser settings.',
|
||||
notifications_unavailable: 'Notifications aren’t available on this server or in this browser.',
|
||||
recurring: 'Repeating expenses',
|
||||
no_recurring: 'None. Choose “Repeat” when adding an expense.',
|
||||
next_on: 'next on {date}',
|
||||
stop: 'Stop',
|
||||
export: 'Export',
|
||||
export_expenses: 'Expenses (CSV)',
|
||||
export_balances: 'Balances (CSV)',
|
||||
backup: 'Backup file',
|
||||
backup_hint: 'Contains the group key: anyone with the file can open the group. Store it safely.',
|
||||
danger_zone: 'Danger zone',
|
||||
remove_from_device_hint: 'The group stays on the server and on other devices.',
|
||||
delete_group: 'Delete group for everyone',
|
||||
delete_group_hint: 'Deletes all expenses and photos from the server. Type the group name to confirm.',
|
||||
confirm: 'Confirm',
|
||||
saved: 'Saved',
|
||||
|
||||
// backup restore
|
||||
restore_title: 'Restore a backup',
|
||||
restore_pick: 'Choose an OweMe backup file (.json).',
|
||||
restore_bad_file: 'That isn’t a valid OweMe backup.',
|
||||
restore_exists: 'This group already exists on the server, so it was added to this device.',
|
||||
restoring: 'Restoring…',
|
||||
|
||||
// misc
|
||||
back: 'Back',
|
||||
close: 'Close',
|
||||
error_generic: 'Something went wrong: {msg}',
|
||||
update_available: 'A new version is available.',
|
||||
reload: 'Reload',
|
||||
today: 'Today',
|
||||
yesterday: 'Yesterday',
|
||||
n_members: { one: '{n} member', few: '{n} members', other: '{n} members' },
|
||||
|
||||
cat_food: 'Food & drink',
|
||||
cat_groceries: 'Groceries',
|
||||
cat_transport: 'Transport',
|
||||
cat_accommodation: 'Accommodation',
|
||||
cat_entertainment: 'Entertainment',
|
||||
cat_shopping: 'Shopping',
|
||||
cat_utilities: 'Utilities',
|
||||
cat_rent: 'Rent',
|
||||
cat_travel: 'Travel',
|
||||
cat_gifts: 'Gifts',
|
||||
cat_health: 'Health',
|
||||
cat_other: 'Other',
|
||||
cat_transfer: 'Payment',
|
||||
|
||||
// notifications (service worker)
|
||||
notif_new_activity: { one: '{n} new change', few: '{n} new changes', other: '{n} new changes' },
|
||||
};
|
||||
|
||||
export type Plural = { one: string; few: string; other: string };
|
||||
export type Messages = { [K in keyof typeof en]: (typeof en)[K] extends string ? string : Plural };
|
||||
export default en satisfies Messages as Messages;
|
||||
49
apps/web/src/lib/photo.ts
Normal file
49
apps/web/src/lib/photo.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
// Receipt photos (SPEC.md §9): shrink and re-encode on the device, which
|
||||
// also strips EXIF metadata including GPS location, then encrypt.
|
||||
|
||||
export interface ProcessedPhoto {
|
||||
full: Blob;
|
||||
thumb: Blob;
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
async function encode(canvas: HTMLCanvasElement, quality: number): Promise<Blob> {
|
||||
const webp = await new Promise<Blob | null>((r) => canvas.toBlob(r, 'image/webp', quality));
|
||||
// Browsers that can't encode WebP silently return PNG; use JPEG instead.
|
||||
if (webp && webp.type === 'image/webp') return webp;
|
||||
const jpeg = await new Promise<Blob | null>((r) => canvas.toBlob(r, 'image/jpeg', quality));
|
||||
if (!jpeg) throw new Error('could not encode image');
|
||||
return jpeg;
|
||||
}
|
||||
|
||||
function draw(img: ImageBitmap, maxEdge: number): HTMLCanvasElement {
|
||||
const scale = Math.min(1, maxEdge / Math.max(img.width, img.height));
|
||||
const c = document.createElement('canvas');
|
||||
c.width = Math.round(img.width * scale);
|
||||
c.height = Math.round(img.height * scale);
|
||||
c.getContext('2d')!.drawImage(img, 0, 0, c.width, c.height);
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Photo + thumbnail, together under `maxBytes` (minus encryption overhead).
|
||||
* Tries lower quality, then smaller sizes, before giving up.
|
||||
*/
|
||||
export async function processPhoto(file: Blob, maxBytes: number): Promise<ProcessedPhoto> {
|
||||
const img = await createImageBitmap(file, { imageOrientation: 'from-image' });
|
||||
try {
|
||||
const thumb = await encode(draw(img, 320), 0.7);
|
||||
const budget = maxBytes - thumb.size - 1024;
|
||||
for (const edge of [1600, 1280, 1024, 800]) {
|
||||
const canvas = draw(img, edge);
|
||||
for (const q of [0.82, 0.7, 0.55]) {
|
||||
const full = await encode(canvas, q);
|
||||
if (full.size <= budget) return { full, thumb, w: canvas.width, h: canvas.height };
|
||||
}
|
||||
}
|
||||
throw new Error('too large');
|
||||
} finally {
|
||||
img.close();
|
||||
}
|
||||
}
|
||||
52
apps/web/src/lib/push.ts
Normal file
52
apps/web/src/lib/push.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
// Web Push opt-in per group (SPEC.md §7.7). One browser subscription is
|
||||
// shared by all groups; each group registers it with the server separately.
|
||||
import { api, serverConfig } from './api.ts';
|
||||
import { b64uDecode } from './crypto.ts';
|
||||
import { deviceId, getAll, updateGroup, type LocalGroup } from './idb.ts';
|
||||
import type { GroupSession } from './session.svelte.ts';
|
||||
|
||||
export type PushSupport = 'ok' | 'unsupported' | 'needs-install' | 'denied' | 'no-server';
|
||||
|
||||
export async function pushSupport(): Promise<PushSupport> {
|
||||
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
|
||||
const standalone = matchMedia('(display-mode: standalone)').matches || (navigator as { standalone?: boolean }).standalone === true;
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) {
|
||||
return ios && !standalone ? 'needs-install' : 'unsupported';
|
||||
}
|
||||
if (Notification.permission === 'denied') return 'denied';
|
||||
try {
|
||||
if (!(await serverConfig()).vapidPublicKey) return 'no-server';
|
||||
} catch {
|
||||
return 'no-server';
|
||||
}
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
async function subscription(create: boolean): Promise<PushSubscription | null> {
|
||||
const reg = await navigator.serviceWorker.ready;
|
||||
const existing = await reg.pushManager.getSubscription();
|
||||
if (existing || !create) return existing;
|
||||
const key = (await serverConfig()).vapidPublicKey;
|
||||
if (!key) throw new Error('push not configured');
|
||||
return reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64uDecode(key) });
|
||||
}
|
||||
|
||||
export async function enablePush(s: GroupSession): Promise<boolean> {
|
||||
if ((await Notification.requestPermission()) !== 'granted') return false;
|
||||
const sub = await subscription(true);
|
||||
if (!sub) return false;
|
||||
await api.pushSubscribe(s.id, s.keys.authToken, sub.toJSON(), await deviceId());
|
||||
// Don't notify about everything that happened before opting in.
|
||||
s.local = { ...s.local, push: true, notifiedSeq: s.local.lastSeq };
|
||||
await updateGroup(s.id, { push: true, notifiedSeq: s.local.lastSeq });
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function disablePush(s: GroupSession): Promise<void> {
|
||||
const sub = await subscription(false);
|
||||
if (sub) await api.pushUnsubscribe(s.id, s.keys.authToken, sub.endpoint).catch(() => {});
|
||||
s.local = { ...s.local, push: false };
|
||||
await updateGroup(s.id, { push: false });
|
||||
const others = (await getAll<LocalGroup>('groups')).filter((g) => g.push && g.id !== s.id);
|
||||
if (sub && others.length === 0) await sub.unsubscribe();
|
||||
}
|
||||
68
apps/web/src/lib/rates.ts
Normal file
68
apps/web/src/lib/rates.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
// Exchange rates from our own server (ECB daily, EUR-based). Cached in
|
||||
// IndexedDB so prefilling still works offline (SPEC.md §5.2, §8.2).
|
||||
import { rateToString } from '@oweme/core';
|
||||
import { api } from './api.ts';
|
||||
import { kvGet, kvSet } from './idb.ts';
|
||||
import { today } from './format.ts';
|
||||
|
||||
export interface RatesDay {
|
||||
date: string;
|
||||
rates: Record<string, string>;
|
||||
}
|
||||
|
||||
const memory = new Map<string, Promise<RatesDay | null>>();
|
||||
|
||||
/** Rates for a date (the latest published on or before it). */
|
||||
export function ratesOn(date: string): Promise<RatesDay | null> {
|
||||
let p = memory.get(date);
|
||||
if (!p) {
|
||||
p = (async () => {
|
||||
const key = `rates:${date}`;
|
||||
const cached = await kvGet<RatesDay>(key);
|
||||
// A past date's rates never change; today's might still be published.
|
||||
if (cached && date < today()) return cached;
|
||||
try {
|
||||
const r = await api.rates(date);
|
||||
const day = { date: r.date, rates: r.rates };
|
||||
await kvSet(key, day);
|
||||
await kvSet('rates:latest', day);
|
||||
return day;
|
||||
} catch {
|
||||
memory.delete(date);
|
||||
return cached ?? (await kvGet<RatesDay>('rates:latest')) ?? null;
|
||||
}
|
||||
})();
|
||||
memory.set(date, p);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Suggested rate string for 1 `from` = x `to`, or null if unknown. */
|
||||
export async function suggestRate(from: string, to: string, date: string): Promise<{ rate: string; source: string } | null> {
|
||||
if (from === to) return { rate: '1', source: 'same' };
|
||||
const day = await ratesOn(date);
|
||||
const f = Number(day?.rates[from]);
|
||||
const tt = Number(day?.rates[to]);
|
||||
if (!day || !(f > 0) || !(tt > 0)) return null;
|
||||
return { rate: rateToString(tt / f), source: `ecb:${day.date}` };
|
||||
}
|
||||
|
||||
/** Float conversion for display only (never stored). */
|
||||
export async function displayRate(from: string, to: string): Promise<number | null> {
|
||||
if (from === to) return 1;
|
||||
const day = await ratesOn(today());
|
||||
const f = Number(day?.rates[from]);
|
||||
const tt = Number(day?.rates[to]);
|
||||
return f > 0 && tt > 0 ? tt / f : null;
|
||||
}
|
||||
|
||||
/** Currencies with ECB rates first, then every other ISO currency. */
|
||||
export async function currencyList(): Promise<{ ecb: string[]; other: string[] }> {
|
||||
const day = await ratesOn(today());
|
||||
const ecb = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).sort();
|
||||
let all: string[] = [];
|
||||
try {
|
||||
all = Intl.supportedValuesOf('currency');
|
||||
} catch { /* old browser */ }
|
||||
return { ecb, other: all.filter((c) => !ecb.includes(c)) };
|
||||
}
|
||||
66
apps/web/src/lib/router.svelte.ts
Normal file
66
apps/web/src/lib/router.svelte.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
// Minimal history-API router. The group secret lives only in the URL
|
||||
// fragment and is stripped from the address bar as soon as it's saved.
|
||||
|
||||
export type Route =
|
||||
| { name: 'home' }
|
||||
| { name: 'new' }
|
||||
| { name: 'settings' }
|
||||
| { name: 'restore' }
|
||||
| { name: 'group'; id: string; tab: 'expenses' | 'balances' | 'stats' | 'activity' }
|
||||
| { name: 'group-settings'; id: string }
|
||||
| { name: 'expense'; id: string; eid: string }
|
||||
| { name: 'expense-edit'; id: string; eid: string | null; params: URLSearchParams }
|
||||
| { name: 'notfound' };
|
||||
|
||||
function parse(path: string, search: string): Route {
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
if (parts.length === 0) return { name: 'home' };
|
||||
if (parts[0] === 'new' && parts.length === 1) return { name: 'new' };
|
||||
if (parts[0] === 'settings' && parts.length === 1) return { name: 'settings' };
|
||||
if (parts[0] === 'restore' && parts.length === 1) return { name: 'restore' };
|
||||
if (parts[0] === 'g' && parts[1]) {
|
||||
const id = parts[1];
|
||||
const rest = parts.slice(2);
|
||||
if (rest.length === 0) return { name: 'group', id, tab: 'expenses' };
|
||||
if (rest.length === 1 && ['balances', 'stats', 'activity'].includes(rest[0]))
|
||||
return { name: 'group', id, tab: rest[0] as 'balances' | 'stats' | 'activity' };
|
||||
if (rest.length === 1 && rest[0] === 'settings') return { name: 'group-settings', id };
|
||||
if (rest[0] === 'e' && rest[1] === 'new' && rest.length === 2)
|
||||
return { name: 'expense-edit', id, eid: null, params: new URLSearchParams(search) };
|
||||
if (rest[0] === 'e' && rest[1] && rest.length === 2) return { name: 'expense', id, eid: rest[1] };
|
||||
if (rest[0] === 'e' && rest[1] && rest[2] === 'edit') return { name: 'expense-edit', id, eid: rest[1], params: new URLSearchParams(search) };
|
||||
}
|
||||
return { name: 'notfound' };
|
||||
}
|
||||
|
||||
class Router {
|
||||
route = $state<Route>(parse(location.pathname, location.search));
|
||||
/** how many entries we pushed, so "back" can stay inside the app */
|
||||
private depth = 0;
|
||||
|
||||
constructor() {
|
||||
addEventListener('popstate', () => {
|
||||
this.depth = Math.max(0, this.depth - 1);
|
||||
this.route = parse(location.pathname, location.search);
|
||||
});
|
||||
}
|
||||
|
||||
go(path: string, opts: { replace?: boolean } = {}) {
|
||||
const url = new URL(path, location.origin);
|
||||
if (opts.replace) history.replaceState(null, '', url.pathname + url.search);
|
||||
else {
|
||||
history.pushState(null, '', url.pathname + url.search);
|
||||
this.depth += 1;
|
||||
}
|
||||
this.route = parse(url.pathname, url.search);
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
|
||||
/** Back within the app, or to `fallback` if this is the first page. */
|
||||
back(fallback: string) {
|
||||
if (this.depth > 0) history.back();
|
||||
else this.go(fallback, { replace: true });
|
||||
}
|
||||
}
|
||||
|
||||
export const router = new Router();
|
||||
296
apps/web/src/lib/session.svelte.ts
Normal file
296
apps/web/src/lib/session.svelte.ts
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
// One open group: its keys, decrypted log, derived state, and sync with the
|
||||
// server. Changes are encrypted, written to the local outbox first, then
|
||||
// uploaded, so the app works offline (SPEC.md §4.1, §10.1).
|
||||
import {
|
||||
balances, dueOccurrences, logOrder, replay, SCHEMA_VERSION,
|
||||
type Activity, type EventBody, type GroupEvent, type GroupState, type EventPlaintext,
|
||||
} from '@oweme/core';
|
||||
import { decryptEvent } from './events.ts';
|
||||
import { api, ApiError, isOffline, listen } from './api.ts';
|
||||
import { decryptBytes, deriveKeys, encryptBytes, encryptJson, randomId, type GroupKeys } from './crypto.ts';
|
||||
import {
|
||||
del, deviceId, get, getAll, groupRange, outboxFor, put, putEvents, updateGroup,
|
||||
type LocalGroup, type OutboxItem, type StoredBlob, type StoredEvent,
|
||||
} from './idb.ts';
|
||||
import { today } from './format.ts';
|
||||
|
||||
export type Status = 'loading' | 'online' | 'offline' | 'gone' | 'error';
|
||||
|
||||
export class GroupSession {
|
||||
readonly id: string;
|
||||
local = $state<LocalGroup>() as LocalGroup;
|
||||
status = $state<Status>('loading');
|
||||
/** seq rollback detected: server is behind what we've seen */
|
||||
rollback = $state(false);
|
||||
synced = $state.raw<GroupEvent[]>([]);
|
||||
pending = $state.raw<GroupEvent[]>([]);
|
||||
state = $state.raw<GroupState>({ group: null, members: [], expenses: {}, comments: {}, recurring: {} });
|
||||
activity = $state.raw<Activity[]>([]);
|
||||
balances = $state.raw<Record<string, number>>({});
|
||||
|
||||
keys!: GroupKeys;
|
||||
private device = '';
|
||||
private abort = new AbortController();
|
||||
private syncing: Promise<void> | null = null;
|
||||
private resync = false;
|
||||
private generatedRecurring = false;
|
||||
private retryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
constructor(local: LocalGroup) {
|
||||
this.id = local.id;
|
||||
this.local = local;
|
||||
}
|
||||
|
||||
/** Load from IndexedDB, then start syncing in the background. */
|
||||
async open(): Promise<void> {
|
||||
this.keys = await deriveKeys(this.local.secret);
|
||||
this.device = await deviceId();
|
||||
const stored = await getAll<StoredEvent>('events', groupRange(this.id));
|
||||
const out = await outboxFor(this.id);
|
||||
this.synced = (await Promise.all(stored.map((e) => decryptEvent(this.keys, this.id, e)))).filter((e): e is GroupEvent => !!e);
|
||||
this.pending = (await Promise.all(out.map((e) => decryptEvent(this.keys, this.id, { ...e, seq: null })))).filter((e): e is GroupEvent => !!e);
|
||||
this.recompute();
|
||||
if (this.local.gone) {
|
||||
this.status = 'gone';
|
||||
return;
|
||||
}
|
||||
addEventListener('online', this.onOnline);
|
||||
void this.sync();
|
||||
void this.stream();
|
||||
}
|
||||
|
||||
close() {
|
||||
this.abort.abort();
|
||||
clearTimeout(this.retryTimer);
|
||||
removeEventListener('online', this.onOnline);
|
||||
}
|
||||
|
||||
private onOnline = () => void this.sync();
|
||||
|
||||
get me(): string | null {
|
||||
const me = this.local.me;
|
||||
return me && this.state.members.some((m) => m.id === me) ? me : null;
|
||||
}
|
||||
|
||||
get base(): string {
|
||||
return this.state.group?.baseCurrency ?? this.local.baseCurrency;
|
||||
}
|
||||
|
||||
memberName(id: string | null | undefined): string {
|
||||
return this.state.members.find((m) => m.id === id)?.name ?? '?';
|
||||
}
|
||||
|
||||
private recompute() {
|
||||
const r = replay(logOrder(this.synced, this.pending));
|
||||
this.state = r.state;
|
||||
this.activity = r.activity;
|
||||
this.balances = balances(r.state);
|
||||
const g = r.state.group;
|
||||
if (g) {
|
||||
const myBalance = this.local.me ? (this.balances[this.local.me] ?? null) : null;
|
||||
const patch = { name: g.name, icon: g.icon, baseCurrency: g.baseCurrency, myBalance };
|
||||
if (Object.entries(patch).some(([k, v]) => this.local[k as keyof LocalGroup] !== v)) {
|
||||
this.local = { ...this.local, ...patch };
|
||||
void updateGroup(this.id, patch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async setMe(memberId: string | null) {
|
||||
this.local = { ...this.local, me: memberId };
|
||||
await updateGroup(this.id, { me: memberId });
|
||||
this.recompute();
|
||||
}
|
||||
|
||||
/** Record a change: encrypt → outbox → apply locally → upload. */
|
||||
async emit(...bodies: EventBody[]): Promise<void> {
|
||||
const items: OutboxItem[] = [];
|
||||
const evs: GroupEvent[] = [];
|
||||
for (const body of bodies) {
|
||||
const id = randomId(16);
|
||||
const plain = { ...body, v: SCHEMA_VERSION, actor: this.me, at: new Date().toISOString() } as EventPlaintext;
|
||||
const { iv, ct } = await encryptJson(this.keys.encKey, plain, `${this.id}|${id}`);
|
||||
items.push({ g: this.id, id, deviceId: this.device, iv, ct });
|
||||
evs.push({ ...plain, id, seq: null, deviceId: this.device } as GroupEvent);
|
||||
}
|
||||
for (const it of items) await put('outbox', it);
|
||||
this.pending = [...this.pending, ...evs];
|
||||
this.recompute();
|
||||
void this.sync();
|
||||
}
|
||||
|
||||
/** Encrypt a photo blob and queue it for upload. Returns its id. */
|
||||
async addBlob(data: ArrayBuffer): Promise<string> {
|
||||
const id = randomId(18);
|
||||
const enc = await encryptBytes(this.keys.encKey, data, `${this.id}|${id}`);
|
||||
await put('blobs', { g: this.id, id, data: enc, uploaded: false } satisfies StoredBlob);
|
||||
return id;
|
||||
}
|
||||
|
||||
private blobUrls = new Map<string, Promise<string>>();
|
||||
|
||||
/** Object URL for a photo blob (from the local cache or the server). */
|
||||
blobUrl(blobId: string, type = 'image/webp'): Promise<string> {
|
||||
let p = this.blobUrls.get(blobId);
|
||||
if (!p) {
|
||||
p = (async () => {
|
||||
let rec = await get<StoredBlob>('blobs', [this.id, blobId]);
|
||||
if (!rec) {
|
||||
const data = await api.getBlob(this.id, this.keys.authToken, blobId);
|
||||
rec = { g: this.id, id: blobId, data, uploaded: true };
|
||||
await put('blobs', rec);
|
||||
}
|
||||
const plain = await decryptBytes(this.keys.encKey, rec.data, `${this.id}|${blobId}`);
|
||||
return URL.createObjectURL(new Blob([plain], { type }));
|
||||
})();
|
||||
p.catch(() => this.blobUrls.delete(blobId));
|
||||
this.blobUrls.set(blobId, p);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Upload outbox, then pull new events. Coalesces concurrent calls. */
|
||||
sync(): Promise<void> {
|
||||
if (this.syncing) {
|
||||
this.resync = true;
|
||||
return this.syncing;
|
||||
}
|
||||
this.syncing = (async () => {
|
||||
try {
|
||||
do {
|
||||
this.resync = false;
|
||||
await this.flush();
|
||||
await this.pull();
|
||||
} while (this.resync);
|
||||
this.status = 'online';
|
||||
await this.generateRecurring();
|
||||
} catch (e) {
|
||||
this.handleError(e);
|
||||
} finally {
|
||||
this.syncing = null;
|
||||
}
|
||||
})();
|
||||
return this.syncing;
|
||||
}
|
||||
|
||||
private handleError(e: unknown) {
|
||||
if (e instanceof ApiError && e.status === 404) {
|
||||
this.status = 'gone';
|
||||
void updateGroup(this.id, { gone: true });
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
if (this.abort.signal.aborted) return;
|
||||
this.status = isOffline(e) ? 'offline' : 'error';
|
||||
if (!(e instanceof ApiError)) console.warn('sync failed', e);
|
||||
clearTimeout(this.retryTimer);
|
||||
this.retryTimer = setTimeout(() => void this.sync(), 15_000);
|
||||
}
|
||||
|
||||
private async flush() {
|
||||
// Photos first, so no event ever references a blob the server lacks.
|
||||
const blobs = (await getAll<StoredBlob>('blobs')).filter((b) => b.g === this.id && !b.uploaded);
|
||||
for (const b of blobs) {
|
||||
await api.putBlob(this.id, this.keys.authToken, b.id, b.data);
|
||||
await put('blobs', { ...b, uploaded: true });
|
||||
}
|
||||
const out = await outboxFor(this.id);
|
||||
for (let i = 0; i < out.length; i += 100) {
|
||||
const chunk = out.slice(i, i + 100);
|
||||
await api.append(this.id, this.keys.authToken, chunk.map(({ id, deviceId, iv, ct }) => ({ id, deviceId, iv, ct })));
|
||||
// The pull that follows stores them with their seqs.
|
||||
for (const it of chunk) await del('outbox', it.n!);
|
||||
}
|
||||
}
|
||||
|
||||
private async pull() {
|
||||
for (;;) {
|
||||
const { events, latest } = await api.events(this.id, this.keys.authToken, this.local.lastSeq);
|
||||
if (latest < this.local.lastSeq) this.rollback = true;
|
||||
if (events.length === 0) break;
|
||||
const stored = events.map((e) => ({ ...e, g: this.id }));
|
||||
await putEvents(stored);
|
||||
const dec = (await Promise.all(stored.map((e) => decryptEvent(this.keys, this.id, e)))).filter((e): e is GroupEvent => !!e);
|
||||
const lastSeq = stored[stored.length - 1].seq;
|
||||
this.local = { ...this.local, lastSeq };
|
||||
await updateGroup(this.id, { lastSeq });
|
||||
const ids = new Set(dec.map((e) => e.id));
|
||||
this.synced = [...this.synced, ...dec];
|
||||
this.pending = this.pending.filter((e) => !ids.has(e.id));
|
||||
this.recompute();
|
||||
if (lastSeq >= latest) break;
|
||||
}
|
||||
}
|
||||
|
||||
/** Create due recurring occurrences, once per open, after a full sync. */
|
||||
private async generateRecurring() {
|
||||
if (this.generatedRecurring) return;
|
||||
this.generatedRecurring = true;
|
||||
await this.createDueOccurrences();
|
||||
}
|
||||
|
||||
/** Emit any recurring occurrences that are due but missing. */
|
||||
async createDueOccurrences() {
|
||||
const due = dueOccurrences(this.state, today());
|
||||
if (due.length) await this.emit(...due.map((e) => ({ type: 'expense.created' as const, data: e })));
|
||||
}
|
||||
|
||||
/** Keep an SSE stream open; reconnect with backoff. */
|
||||
private async stream() {
|
||||
let delay = 1000;
|
||||
while (!this.abort.signal.aborted) {
|
||||
try {
|
||||
await listen(this.id, this.keys.authToken, this.abort.signal, (seq) => {
|
||||
delay = 1000;
|
||||
if (seq !== this.local.lastSeq) void this.sync();
|
||||
});
|
||||
} catch (e) {
|
||||
if (this.abort.signal.aborted) return;
|
||||
if (e instanceof ApiError && e.status === 404) return this.handleError(e);
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
delay = Math.min(delay * 2, 60_000);
|
||||
}
|
||||
}
|
||||
|
||||
/** Every event in log order, as stored (for backups). */
|
||||
async rawEvents(): Promise<StoredEvent[]> {
|
||||
return (await getAll<StoredEvent>('events', groupRange(this.id))).sort((a, b) => a.seq - b.seq);
|
||||
}
|
||||
}
|
||||
|
||||
let current: GroupSession | null = null;
|
||||
|
||||
/** The session for a group id, opening it (and closing any other). */
|
||||
export async function openSession(id: string): Promise<GroupSession | null> {
|
||||
if (current?.id === id) return current;
|
||||
current?.close();
|
||||
current = null;
|
||||
const local = await get<LocalGroup>('groups', id);
|
||||
if (!local) return null;
|
||||
await updateGroup(id, { lastOpened: Date.now() });
|
||||
const s = new GroupSession(local);
|
||||
current = s;
|
||||
await s.open();
|
||||
return s;
|
||||
}
|
||||
|
||||
export function closeSession(id: string) {
|
||||
if (current?.id === id) {
|
||||
current.close();
|
||||
current = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Save a group (from a link) on this device. */
|
||||
export async function addGroup(id: string, secret: string, extra: Partial<LocalGroup> = {}): Promise<void> {
|
||||
const existing = await get<LocalGroup>('groups', id);
|
||||
if (existing) {
|
||||
if (existing.secret !== secret) await updateGroup(id, { secret, gone: false });
|
||||
return;
|
||||
}
|
||||
await put('groups', {
|
||||
id, secret, name: '', icon: '', baseCurrency: 'EUR', me: null, myBalance: null,
|
||||
lastSeq: 0, lastOpened: Date.now(), push: false, notifiedSeq: 0, ...extra,
|
||||
} satisfies LocalGroup);
|
||||
}
|
||||
58
apps/web/src/lib/settings.svelte.ts
Normal file
58
apps/web/src/lib/settings.svelte.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
// App-wide, per-device preferences: language and theme. Stored in
|
||||
// localStorage (a per-device convenience; failures just mean defaults).
|
||||
import { detectLang, localeOf, translate, type Lang, type MsgKey } from './i18n.ts';
|
||||
import { kvSet } from './idb.ts';
|
||||
|
||||
type LangPref = 'auto' | Lang;
|
||||
type ThemePref = 'system' | 'dark' | 'light';
|
||||
|
||||
function load<T extends string>(key: string, allowed: readonly T[], def: T): T {
|
||||
try {
|
||||
const v = localStorage.getItem(key) as T | null;
|
||||
return v && allowed.includes(v) ? v : def;
|
||||
} catch {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
function save(key: string, v: string) {
|
||||
try {
|
||||
localStorage.setItem(key, v);
|
||||
} catch { /* private mode etc. */ }
|
||||
}
|
||||
|
||||
class Settings {
|
||||
langPref = $state<LangPref>(load('oweme.lang', ['auto', 'en', 'cs'], 'auto'));
|
||||
themePref = $state<ThemePref>(load('oweme.theme', ['system', 'dark', 'light'], 'system'));
|
||||
|
||||
lang = $derived<Lang>(this.langPref === 'auto' ? detectLang() : this.langPref);
|
||||
locale = $derived(localeOf(this.lang));
|
||||
|
||||
setLang(v: LangPref) {
|
||||
this.langPref = v;
|
||||
save('oweme.lang', v);
|
||||
document.documentElement.lang = this.lang;
|
||||
// the service worker reads this to localise notifications
|
||||
void kvSet('lang', this.lang).catch(() => {});
|
||||
}
|
||||
|
||||
setTheme(v: ThemePref) {
|
||||
this.themePref = v;
|
||||
save('oweme.theme', v);
|
||||
this.applyTheme();
|
||||
}
|
||||
|
||||
applyTheme() {
|
||||
const root = document.documentElement;
|
||||
if (this.themePref === 'system') delete root.dataset.theme;
|
||||
else root.dataset.theme = this.themePref;
|
||||
const dark = this.themePref === 'dark' || (this.themePref === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
document.querySelector('meta[name=theme-color]')?.setAttribute('content', dark ? '#0B2E22' : '#F2F7F4');
|
||||
}
|
||||
}
|
||||
|
||||
export const settings = new Settings();
|
||||
|
||||
/** Translate in the current language. Reactive inside components. */
|
||||
export function t(key: MsgKey, vars?: Record<string, string | number>): string {
|
||||
return translate(settings.lang, key, vars);
|
||||
}
|
||||
14
apps/web/src/lib/ui.svelte.ts
Normal file
14
apps/web/src/lib/ui.svelte.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
// Small bits of global UI state: toasts and the "new version" prompt.
|
||||
class Ui {
|
||||
toast = $state<string | null>(null);
|
||||
updateReady = $state(false);
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
show(msg: string, ms = 2500) {
|
||||
this.toast = msg;
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => (this.toast = null), ms);
|
||||
}
|
||||
}
|
||||
|
||||
export const ui = new Ui();
|
||||
Loading…
Add table
Add a link
Reference in a new issue