Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234/** * Decides who to notify, and when. * * - Live triggers come from the appview's change log (polled every 15s): * rsvp → the host: "Alex is going to X" * event_created → people subscribed to the host: "Alex is hosting X" * event_updated → attendees: "X was updated" (description changes) * - Scheduled (every 5 min, in each user's own time zone): * 09:00 → "Today: X" for events you're attending * 17:00 → at most weekly, only if you've had no other pushes: "An event you might like" */import { appview, bskyProfile, type Profile } from './appview.ts'import { pushTo, type Push } from './apns.ts'import { devices, hostSubs, hides, kvStore, notifLog, notifPrefs, type NotifKind } from './db.ts'
const HOUR = 3600_000const DAY = 24 * HOURconst cursorStore = kvStore<number>('notifier')
// ---------- helpers ----------
const profileCache = new Map<string, { p: Profile; at: number }>()async function profile(did: string) { const hit = profileCache.get(did) if (hit && Date.now() - hit.at < 6 * HOUR) return hit.p const p = await bskyProfile(did).catch(() => ({ did }) as Profile) profileCache.set(did, { p, at: Date.now() }) return p}const nameOf = (p: Profile) => p.displayName || (p.handle ? `@${p.handle}` : 'Someone')
/** Local calendar date + hour for a time zone. */function localParts(date: Date, tz: string) { try { const parts = Object.fromEntries( new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', hourCycle: 'h23' }) .formatToParts(date) .map((p) => [p.type, p.value]), ) return { day: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour) } } catch { return localParts(date, 'UTC') }}
function when(iso: string | undefined, tz: string, withDay = true) { if (!iso) return '' try { return new Intl.DateTimeFormat('en-GB', { timeZone: tz, ...(withDay ? { weekday: 'short', day: 'numeric', month: 'short' } : {}), hour: '2-digit', minute: '2-digit', }).format(new Date(iso)) } catch { return '' }}
const tzOf = (did: string) => devices.forDid(did)[0]?.tz ?? 'UTC'const upcoming = (e: { startsAt?: string }) => !!e.startsAt && Date.parse(e.startsAt) > Date.now()
function hidden(viewer: string, event: { uri: string; did: string }) { const h = hides.list(viewer) return h.events.includes(event.uri) || h.actors.includes(event.did)}
/** Send if the user has a device, wants this kind, and hasn't had this exact push before. */async function notify(did: string, kind: NotifKind, key: string, push: Push) { if (!devices.forDid(did).length) return if (!notifPrefs.get(did)[kind]) return if (!notifLog.claim(did, kind, key)) return await pushTo(did, push)}
// ---------- live triggers ----------
type Change = { id: number; kind: 'rsvp' | 'event_created' | 'event_updated'; uri: string; did: string; subject_uri?: string; status?: string }
async function onRsvp(c: Change) { const eventUri = c.subject_uri! const host = eventUri.split('/')[2] if (!host || host === c.did || !devices.forDid(host).length) return // Popular event? Cap at 10 RSVP pushes per event per hour. if (notifLog.countKeyPrefixSince(host, 'rsvps', `${eventUri}|`, Date.now() - HOUR) >= 10) return const [event, who] = await Promise.all([appview.event(eventUri, host).catch(() => undefined), profile(c.did)]) if (!event) return await notify(host, 'rsvps', `${eventUri}|${c.did}`, { title: event.name, body: `${nameOf(who)} ${c.status === 'interested' ? 'might come' : 'is going'}`, threadId: eventUri, data: { eventUri }, })}
async function onEventCreated(c: Change) { const subscribers = hostSubs.subscribersOf(c.did) if (!subscribers.length) return const [event, host] = await Promise.all([appview.event(c.uri, c.did).catch(() => undefined), profile(c.did)]) if (!event || !upcoming(event)) return for (const viewer of subscribers) { if (hidden(viewer, event)) continue // Bulk importers: at most 2 "new event" pushes per host per day. if (notifLog.countKeyPrefixSince(viewer, 'newEvents', `${c.did}|`, Date.now() - DAY) >= 2) continue await notify(viewer, 'newEvents', `${c.did}|${c.uri}`, { title: `${nameOf(host)} is hosting`, body: [event.name, when(event.startsAt, tzOf(viewer))].filter(Boolean).join(' · '), threadId: c.uri, data: { eventUri: c.uri }, }) }}
async function onEventUpdated(c: Change) { const event = await appview.event(c.uri, c.did).catch(() => undefined) if (!event || !upcoming(event)) return const { attendees } = await appview.attendees(c.uri) const snippet = (event.description ?? '').replace(/\s+/g, ' ').trim().slice(0, 140) // Several edits in a row become one push per hour. const bucket = Math.floor(Date.now() / HOUR) for (const a of attendees) { if (a.did === c.did) continue await notify(a.did, 'updates', `${c.uri}|${bucket}`, { title: `${event.name} was updated`, body: snippet || 'The host changed the details.', threadId: c.uri, data: { eventUri: c.uri }, }) }}
async function pollChanges() { let cursor = await cursorStore.get('cursor') const res = await appview.changes(cursor ?? 0) if (cursor === undefined) { // First run: start from now rather than replaying the log. await cursorStore.set('cursor', res.latest) return } for (const c of res.changes as Change[]) { try { if (c.kind === 'rsvp') await onRsvp(c) else if (c.kind === 'event_created') await onEventCreated(c) else if (c.kind === 'event_updated') await onEventUpdated(c) } catch (err) { console.warn('notify failed', c.kind, c.uri, err) } cursor = c.id await cursorStore.set('cursor', cursor) }}
// ---------- scheduled ----------
async function morningReminders(did: string, tz: string, today: string) { const { attending } = await appview.actorEvents(did, did) for (const e of attending as any[]) { if (!e.startsAt || e.status === 'cancelled' || localParts(new Date(e.startsAt), tz).day !== today) continue if (!upcoming(e) && Date.parse(e.startsAt) < Date.now() - HOUR) continue const place = e.locations?.find((l: any) => l.kind !== 'uri')?.name await notify(did, 'reminders', `${e.uri}|${today}`, { title: `Today: ${e.name}`, body: [`Starts at ${when(e.startsAt, tz, false)}`, place].filter(Boolean).join(' · '), threadId: e.uri, data: { eventUri: e.uri }, }) }}
async function weeklySuggestion(did: string, tz: string) { // Only if they've had no pushes at all this week. if (notifLog.countSince(did, Date.now() - 7 * DAY) > 0) return const feed = await appview.feed(did) const h = hides.list(did) const pick = (feed.following ?? []).find( (e: any) => !e.viewerRsvp && e.did !== did && upcoming(e) && Date.parse(e.startsAt) < Date.now() + 14 * DAY && !h.events.includes(e.uri) && !h.actors.includes(e.did), ) if (!pick) return const friend = pick.friends?.[0] const others = (pick.friendsCount ?? 1) - 1 const who = friend ? `${nameOf(friend)}${others > 0 ? ` and ${others} other${others > 1 ? 's' : ''} you know` : ''} ${others > 0 ? 'are' : 'is'} going` : `Hosted by ${nameOf(pick.host ?? { did: pick.did })}` await notify(did, 'suggestions', `week-${Math.floor(Date.now() / (7 * DAY))}`, { title: 'An event you might like', body: `${pick.name} · ${when(pick.startsAt, tz)} — ${who}`, threadId: pick.uri, data: { eventUri: pick.uri }, })}
async function runSchedule() { const now = new Date() for (const { did, tz } of devices.users()) { const { day, hour } = localParts(now, tz) try { if (hour === 9) await morningReminders(did, tz, day) if (hour === 17) await weeklySuggestion(did, tz) } catch (err) { console.warn('schedule failed', did, err) } }}
// ---------- loop ----------
export function startNotifier() { const loop = (fn: () => Promise<void>, every: number, name: string) => { let running = false const tick = async () => { if (running) return running = true try { await fn() } catch (err) { console.warn(`${name} failed`, (err as Error).message) } finally { running = false } } void tick() setInterval(tick, every).unref() } loop(pollChanges, 15_000, 'notifier poll') loop(runSchedule, 5 * 60_000, 'notifier schedule')}
/** Exposed for local testing (/debug routes). */export const _internal = { pollChanges, runSchedule, morningReminders, weeklySuggestion }