+
+ {{ ev.name }}
+
+
+ + {{ ev.location }} +
++ {{ ev.description }} +
++ Recurring event +
+Add this calendar to your calendar app:
+{{ calendarUrl }}
+
+ No upcoming events.
++ {{ ev.location }} +
++ {{ ev.description }} +
++ Recurring event +
+Calendar not found.
++ Loading... +
+ + +Subscribe to this URL in your calendar app:
+{{ calendarUrl }}
+
+ Connected: {{ guild.atprotoDid }}
+
Events will be published to this AT Protocol account.
+
+ Previously connected to {{ guild.atprotoDid }}, but the session has expired. Please reconnect.
+
+ Connect an AT Protocol account to publish events to the atmosphere. +
+ +No events synced yet. Events will appear after the next sync cycle (up to 5 minutes).
+Guild not found.
+Sign in with Discord to manage your servers.
+ Sign in with Discord ++ Loading your servers... +
+ + +/calendar/{{ guild.calendarSlug }}.ics
+ The discal bot is in these servers. Click to register and create a calendar feed.
++ {{ registerError }} +
++ Add discal bot to a Discord server + + — you manage {{ withoutBot.length }} server{{ withoutBot.length === 1 ? '' : 's' }} that don't have the bot yet + +
+{{ event.description }}
++ You RSVP'd: {{ rsvpStatus }}. Update your response: +
++ RSVP via AT Protocol: +
++ {{ rsvpError }} +
+RSVP will be available once this event is published to AT Protocol.
+Sign in with AT Protocol to RSVP.
+Event not found.
+Subscribe to Discord server events via ICS calendar feeds.
+ +community.lexicon.calendar.event records+ Sign in with Discord + to add your server and get a calendar feed. +
+<{W6G=H!^*!;u3@!%i%<_CY|*&qDl zXa7*g#t*_jY#8MK$S}zNkzla@$G}kkk0GJ{Kf{Or{~3P%|KIrk|Nn#k|NlRX#iIZJ G{{sM%x?{8e diff --git a/public/favicon.svg b/public/favicon.svg new file mode 100644 index 0000000..fe90156 --- /dev/null +++ b/public/favicon.svg @@ -0,0 +1,93 @@ + diff --git a/pwa-assets.config.ts b/pwa-assets.config.ts new file mode 100644 index 0000000..1bf443d --- /dev/null +++ b/pwa-assets.config.ts @@ -0,0 +1,12 @@ +import { + defineConfig, + minimal2023Preset, +} from '@vite-pwa/assets-generator/config' + +export default defineConfig({ + headLinkOptions: { + preset: '2023', + }, + preset: minimal2023Preset, + images: ['public/favicon.svg'], +}) diff --git a/server/api/_cron/sync.ts b/server/api/_cron/sync.ts new file mode 100644 index 0000000..2fcc22d --- /dev/null +++ b/server/api/_cron/sync.ts @@ -0,0 +1,102 @@ +export default defineEventHandler(async (h3Event) => { + const guilds = await getAllGuilds() + const results = { + guilds: guilds.length, + synced: 0, + published: 0, + errors: [] as string[], + } + + for (const guild of guilds) { + try { + const published = await syncGuildEvents(h3Event, guild.id) + results.synced++ + results.published += published + } + catch (error) { + const message = error instanceof Error ? error.message : String(error) + results.errors.push(`Guild ${guild.id}: ${message}`) + console.error(`Sync failed for guild ${guild.id}:`, error) + } + } + + return results +}) + +async function syncGuildEvents(h3Event: Parameters[0], guildId: string): Promise { + const guild = await getGuild(guildId) + if (!guild) return 0 + + let published = 0 + const discordEvents = await fetchGuildEvents(guildId) + const storedEventIndex = await getEventIndex(guildId) + const storedEventIds = new Set(storedEventIndex) + const discordEventIds = new Set(discordEvents.map(e => e.id)) + const now = new Date().toISOString() + + for (const de of discordEvents) { + const stored = await getEvent(guildId, de.id) + const isNew = !stored + const isUpdated = stored && ( + stored.name !== de.name + || stored.description !== de.description + || stored.startTime !== de.scheduled_start_time + || stored.endTime !== de.scheduled_end_time + || stored.status !== de.status + || (stored.location || null) !== (de.entity_metadata?.location || null) + || JSON.stringify(stored.recurrenceRule) !== JSON.stringify(de.recurrence_rule) + ) + const needsRepublish = stored?.atprotoUri + && stored.atprotoRecordVersion !== ATPROTO_RECORD_VERSION + + const eventData: StoredEvent = { + id: de.id, + guildId, + name: de.name, + description: de.description, + location: de.entity_metadata?.location || null, + channelId: de.channel_id, + startTime: de.scheduled_start_time, + endTime: de.scheduled_end_time, + entityType: de.entity_type, + status: de.status, + recurrenceRule: de.recurrence_rule, + imageHash: de.image, + userCount: de.user_count || 0, + atprotoUri: stored?.atprotoUri || null, + atprotoCid: stored?.atprotoCid || null, + atprotoRecordVersion: stored?.atprotoRecordVersion || null, + lastSyncedAt: now, + } + + await setEvent(eventData) + + if (guild.atprotoDid && (isNew || isUpdated || needsRepublish)) { + const result = await publishEventToAtproto(h3Event, eventData, guild) + if (result) { + eventData.atprotoUri = result.uri + eventData.atprotoCid = result.cid + eventData.atprotoRecordVersion = ATPROTO_RECORD_VERSION + await setEvent(eventData) + published++ + } + } + } + + for (const storedId of storedEventIds) { + if (!discordEventIds.has(storedId)) { + const stored = await getEvent(guildId, storedId) + if (stored && (stored.status === 1 || stored.status === 2)) { + stored.status = 4 + stored.lastSyncedAt = now + await setEvent(stored) + + if (guild.atprotoDid && stored.atprotoUri) { + await publishEventToAtproto(h3Event, stored, guild) + } + } + } + } + + return published +} diff --git a/server/api/calendar/[slug].get.ts b/server/api/calendar/[slug].get.ts new file mode 100644 index 0000000..68f9ed0 --- /dev/null +++ b/server/api/calendar/[slug].get.ts @@ -0,0 +1,26 @@ +export default defineEventHandler(async (event) => { + const slug = getRouterParam(event, 'slug') + if (!slug) { + throw createError({ statusCode: 400, message: 'Missing calendar slug' }) + } + + const guild = await getGuildBySlug(slug) + if (!guild) { + throw createError({ statusCode: 404, message: 'Calendar not found' }) + } + + const events = await getGuildEvents(guild.id) + + return { + guild: { + id: guild.id, + name: guild.name, + icon: guild.icon, + timezone: guild.timezone, + calendarSlug: guild.calendarSlug, + }, + events: events + .filter(e => e.status === 1 || e.status === 2) + .sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime()), + } +}) diff --git a/server/api/events/[id].get.ts b/server/api/events/[id].get.ts new file mode 100644 index 0000000..dab4118 --- /dev/null +++ b/server/api/events/[id].get.ts @@ -0,0 +1,28 @@ +export default defineEventHandler(async (event) => { + const eventId = getRouterParam(event, 'id') + if (!eventId) { + throw createError({ statusCode: 400, message: 'Missing event ID' }) + } + + for (const guildId of await getGuildIndex()) { + const storedEvent = await getEvent(guildId, eventId) + if (!storedEvent) continue + + const guild = await getGuild(guildId) + if (!guild) continue + + return { + event: storedEvent, + guild: { + id: guild.id, + name: guild.name, + icon: guild.icon, + timezone: guild.timezone, + calendarSlug: guild.calendarSlug, + atprotoDid: guild.atprotoDid, + }, + } + } + + throw createError({ statusCode: 404, message: 'Event not found' }) +}) diff --git a/server/api/events/[id]/rsvps.get.ts b/server/api/events/[id]/rsvps.get.ts new file mode 100644 index 0000000..3715ac8 --- /dev/null +++ b/server/api/events/[id]/rsvps.get.ts @@ -0,0 +1,71 @@ +export default defineEventHandler(async (event) => { + const eventId = getRouterParam(event, 'id') + if (!eventId) { + throw createError({ statusCode: 400, message: 'Missing event ID' }) + } + + let storedEvent: StoredEvent | null = null + for (const guildId of await getGuildIndex()) { + storedEvent = await getEvent(guildId, eventId) + if (storedEvent) break + } + + if (!storedEvent) { + throw createError({ statusCode: 404, message: 'Event not found' }) + } + + if (!storedEvent.atprotoUri) { + return { rsvps: [], total: 0, currentUserRsvp: null } + } + + // Fetch RSVPs from Constellation (network-wide) + const { rsvps, total } = await fetchEventRsvps(storedEvent.atprotoUri) + + // Check if the current user has an RSVP (directly from their PDS, not Constellation) + let currentUserRsvp: { status: string } | null = null + try { + const session = await getUserSession(event) + const did = session.secure?.atprotoDid + if (did) { + const agent = await getAtprotoAgent(event, did) + const { data } = await agent.com.atproto.repo.listRecords({ + repo: did, + collection: 'community.lexicon.calendar.rsvp', + limit: 100, + }) + const existing = data.records.find((r) => { + const val = r.value as { subject?: { uri?: string } } + return val.subject?.uri === storedEvent!.atprotoUri + }) + if (existing) { + const val = existing.value as { status?: string } + currentUserRsvp = { status: val.status || 'unknown' } + + // Ensure the user appears in the RSVP list even if Constellation hasn't indexed it yet + if (!rsvps.some(r => r.did === did)) { + let handle: string | undefined + let displayName: string | undefined + let avatar: string | undefined + try { + const profile = await $fetch<{ handle: string, displayName?: string, avatar?: string }>( + 'https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile', + { query: { actor: did } }, + ) + handle = profile.handle + displayName = profile.displayName + avatar = profile.avatar + } + catch { + // best-effort + } + rsvps.unshift({ did, rkey: existing.uri.split('/').pop()!, handle, displayName, avatar }) + } + } + } + } + catch { + // User not logged in with AT Proto, or session invalid — that's fine + } + + return { rsvps, total: Math.max(total, rsvps.length), currentUserRsvp } +}) diff --git a/server/api/guilds/[guildId]/index.get.ts b/server/api/guilds/[guildId]/index.get.ts new file mode 100644 index 0000000..75ae55d --- /dev/null +++ b/server/api/guilds/[guildId]/index.get.ts @@ -0,0 +1,23 @@ +export default defineEventHandler(async (event) => { + const guildId = getRouterParam(event, 'guildId') + if (!guildId) { + throw createError({ statusCode: 400, message: 'Missing guild ID' }) + } + + const guild = await getGuild(guildId) + if (!guild) { + throw createError({ statusCode: 404, message: 'Guild not found' }) + } + + let atprotoSessionValid = false + if (guild.atprotoDid) { + const session = await useStorage('kv').getItem(`atproto:session:${guild.atprotoDid}`) + atprotoSessionValid = !!session + } + + return { + guild, + events: await getGuildEvents(guildId), + atprotoSessionValid, + } +}) diff --git a/server/api/guilds/[guildId]/settings.put.ts b/server/api/guilds/[guildId]/settings.put.ts new file mode 100644 index 0000000..bf8fe83 --- /dev/null +++ b/server/api/guilds/[guildId]/settings.put.ts @@ -0,0 +1,33 @@ +export default defineEventHandler(async (event) => { + const { user } = await requireUserSession(event) + if (!user.discordId) { + throw createError({ statusCode: 403, message: 'Discord login required' }) + } + + const guildId = getRouterParam(event, 'guildId') + if (!guildId) { + throw createError({ statusCode: 400, message: 'Missing guild ID' }) + } + + const guild = await getGuild(guildId) + if (!guild) { + throw createError({ statusCode: 404, message: 'Guild not found' }) + } + if (guild.addedBy !== user.discordId) { + throw createError({ statusCode: 403, message: 'Not authorized' }) + } + + const body = await readBody<{ timezone?: string }>(event) + if (body.timezone) { + try { + Intl.DateTimeFormat(undefined, { timeZone: body.timezone }) + guild.timezone = body.timezone + } + catch { + throw createError({ statusCode: 400, message: 'Invalid timezone' }) + } + } + + await setGuild(guild) + return guild +}) diff --git a/server/api/guilds/available.get.ts b/server/api/guilds/available.get.ts new file mode 100644 index 0000000..2b73dc9 --- /dev/null +++ b/server/api/guilds/available.get.ts @@ -0,0 +1,46 @@ +export default defineEventHandler(async (event) => { + const { user, secure } = await requireUserSession(event) + if (!user.discordId || !secure?.discordAccessToken) { + throw createError({ statusCode: 403, message: 'Discord login required' }) + } + + let discordGuilds + try { + discordGuilds = await $fetch >('https://discord.com/api/v10/users/@me/guilds', { + headers: { Authorization: `Bearer ${secure.discordAccessToken}` }, + }) + } + catch (error: unknown) { + if ((error as { statusCode?: number }).statusCode === 401) { + throw createError({ statusCode: 401, message: 'Discord token expired. Please sign in again.' }) + } + throw error + } + + const MANAGE_GUILD = 0x20n + const manageable = discordGuilds.filter((g) => { + const perms = BigInt(g.permissions) + return g.owner || (perms & MANAGE_GUILD) === MANAGE_GUILD + }) + + const results = [] + for (const g of manageable) { + const registered = await getGuild(g.id) + results.push({ + id: g.id, + name: g.name, + icon: g.icon, + registered: !!registered, + botPresent: registered ? false : await checkBotInGuild(g.id), + calendarSlug: registered?.calendarSlug ?? null, + }) + } + + return results +}) diff --git a/server/api/guilds/index.get.ts b/server/api/guilds/index.get.ts new file mode 100644 index 0000000..4d94224 --- /dev/null +++ b/server/api/guilds/index.get.ts @@ -0,0 +1,9 @@ +export default defineEventHandler(async (event) => { + const { user } = await requireUserSession(event) + if (!user.discordId) { + throw createError({ statusCode: 403, message: 'Discord login required' }) + } + + const allGuilds = await getAllGuilds() + return allGuilds.filter(g => g.addedBy === user.discordId) +}) diff --git a/server/api/guilds/register.post.ts b/server/api/guilds/register.post.ts new file mode 100644 index 0000000..66a6907 --- /dev/null +++ b/server/api/guilds/register.post.ts @@ -0,0 +1,37 @@ +export default defineEventHandler(async (event) => { + const { user } = await requireUserSession(event) + if (!user.discordId) { + throw createError({ statusCode: 403, message: 'Discord login required' }) + } + + const body = await readBody<{ guildId: string, guildName?: string }>(event) + if (!body.guildId) { + throw createError({ statusCode: 400, message: 'Missing guildId' }) + } + + const existing = await getGuild(body.guildId) + if (existing) return existing + + if (!await checkBotInGuild(body.guildId)) { + throw createError({ + statusCode: 400, + message: 'Cannot access this guild. Make sure the discal bot has been added to the server first.', + }) + } + + const guild: StoredGuild = { + id: body.guildId, + name: body.guildName || `Guild ${body.guildId}`, + icon: null, + addedBy: user.discordId, + atprotoDid: null, + timezone: 'UTC', + calendarSlug: generateSlug(body.guildName || body.guildId), + createdAt: new Date().toISOString(), + } + + await setGuild(guild) + fetchGuildEvents(body.guildId).catch(() => {}) + + return guild +}) diff --git a/server/api/rsvp.post.ts b/server/api/rsvp.post.ts new file mode 100644 index 0000000..d6acdf2 --- /dev/null +++ b/server/api/rsvp.post.ts @@ -0,0 +1,31 @@ +export default defineEventHandler(async (event) => { + const { user, secure } = await requireUserSession(event) + if (!user.blueskyDid || !secure?.atprotoDid) { + throw createError({ statusCode: 401, message: 'AT Protocol login required' }) + } + + const body = await readBody<{ + eventId: string + guildId: string + status: 'going' | 'interested' | 'notgoing' + }>(event) + + if (!body.eventId || !body.guildId || !body.status) { + throw createError({ statusCode: 400, message: 'Missing required fields' }) + } + + const storedEvent = await getEvent(body.guildId, body.eventId) + if (!storedEvent) { + throw createError({ statusCode: 404, message: 'Event not found' }) + } + if (!storedEvent.atprotoUri || !storedEvent.atprotoCid) { + throw createError({ statusCode: 400, message: 'Event is not published to AT Protocol yet' }) + } + + const result = await createAtprotoRsvp(event, secure.atprotoDid, storedEvent.atprotoUri, storedEvent.atprotoCid, body.status) + if (!result) { + throw createError({ statusCode: 500, message: 'Failed to create RSVP' }) + } + + return result +}) diff --git a/server/routes/auth/bluesky.get.ts b/server/routes/auth/bluesky.get.ts new file mode 100644 index 0000000..3e09cbd --- /dev/null +++ b/server/routes/auth/bluesky.get.ts @@ -0,0 +1,80 @@ +export default defineEventHandler(async (event) => { + const query = getQuery(event) + const client = getAtprotoClient(event) + + // Step 1: No code = initial request, start the OAuth flow + if (!query.code) { + const handle = query.handle?.toString() + if (!handle) { + throw createError({ statusCode: 400, message: 'Missing handle parameter' }) + } + + // Stash the guild ID in a cookie before redirecting + if (query.guild) { + setCookie(event, 'oauth-bluesky-guild', String(query.guild), { + httpOnly: true, + secure: !import.meta.dev, + sameSite: 'lax', + maxAge: 600, + path: '/', + }) + } + + const url = await client.authorize(handle, { + scope: 'atproto repo:community.lexicon.calendar.event repo:community.lexicon.calendar.rsvp', + }) + return sendRedirect(event, url.toString()) + } + + // Step 2: Callback with code, complete the OAuth flow + const params = new URLSearchParams() + for (const [key, value] of Object.entries(query)) { + if (typeof value === 'string') params.set(key, value) + } + + const { session } = await client.callback(params) + const did = session.did + + // Fetch profile (public, no auth needed) + let blueskyHandle: string | undefined + try { + const profile = await $fetch<{ handle: string, displayName?: string }>( + `https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(did)}`, + ) + blueskyHandle = profile.handle + } + catch { + // best-effort + } + + // Merge into existing session + const existing = await getUserSession(event) + await setUserSession(event, { + user: { + ...existing?.user, + discordId: existing?.user?.discordId || '', + name: existing?.user?.name || blueskyHandle || did, + blueskyDid: did, + blueskyHandle, + }, + secure: { + ...existing?.secure, + atprotoDid: did, + }, + }) + + // Link to guild if applicable + const guildId = getCookie(event, 'oauth-bluesky-guild') + deleteCookie(event, 'oauth-bluesky-guild', { path: '/' }) + + if (guildId) { + const guild = await getGuild(guildId) + if (guild) { + guild.atprotoDid = did + await setGuild(guild) + } + return sendRedirect(event, `/dashboard/${guildId}`) + } + + return sendRedirect(event, '/dashboard') +}) diff --git a/server/routes/auth/discord.get.ts b/server/routes/auth/discord.get.ts new file mode 100644 index 0000000..de6a3cc --- /dev/null +++ b/server/routes/auth/discord.get.ts @@ -0,0 +1,28 @@ +export default defineOAuthDiscordEventHandler({ + config: { + scope: ['identify', 'guilds'], + }, + async onSuccess(event, { user, tokens }) { + const existing = await getUserSession(event) + + await setUserSession(event, { + user: { + ...existing?.user, + discordId: String(user.id), + name: user.global_name || user.username, + avatar: user.avatar + ? `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png` + : undefined, + }, + secure: { + ...existing?.secure, + discordAccessToken: tokens.access_token, + }, + }) + return sendRedirect(event, '/dashboard') + }, + onError(event, error) { + console.error('Discord OAuth error:', error) + return sendRedirect(event, '/?error=discord') + }, +}) diff --git a/server/routes/calendar/[slug].ts b/server/routes/calendar/[slug].ts new file mode 100644 index 0000000..136dcf5 --- /dev/null +++ b/server/routes/calendar/[slug].ts @@ -0,0 +1,21 @@ +export default defineEventHandler(async (event) => { + const slug = getRouterParam(event, 'slug')?.replace(/\.ics$/, '') + if (!slug) { + throw createError({ statusCode: 400, message: 'Missing calendar slug' }) + } + + const guild = await getGuildBySlug(slug) + if (!guild) { + throw createError({ statusCode: 404, message: 'Calendar not found' }) + } + + const events = await getGuildEvents(guild.id) + + setResponseHeaders(event, { + 'Content-Type': 'text/calendar; charset=utf-8', + 'Content-Disposition': `inline; filename="${slug}.ics"`, + 'Cache-Control': 'public, max-age=300', + }) + + return generateCalendar(guild, events) +}) diff --git a/server/utils/atproto.ts b/server/utils/atproto.ts new file mode 100644 index 0000000..d1e8bb0 --- /dev/null +++ b/server/utils/atproto.ts @@ -0,0 +1,242 @@ +import { NodeOAuthClient } from '@atproto/oauth-client-node' +import type { NodeSavedSession, NodeSavedSessionStore, NodeSavedStateStore } from '@atproto/oauth-client-node' +import { Agent } from '@atproto/api' +import type { H3Event } from 'h3' + +import type { StoredEvent, StoredGuild } from './types' + +const STATUS_MAP: Record = { + 1: 'community.lexicon.calendar.event#scheduled', + 2: 'community.lexicon.calendar.event#scheduled', + 3: 'community.lexicon.calendar.event#scheduled', + 4: 'community.lexicon.calendar.event#cancelled', +} + +const MODE_MAP: Record = { + 1: 'community.lexicon.calendar.event#virtual', + 2: 'community.lexicon.calendar.event#virtual', + 3: 'community.lexicon.calendar.event#inperson', +} + +// Increment this when the record format changes to force re-publishing +export const ATPROTO_RECORD_VERSION = 3 + +const RSVP_STATUS_MAP: Record = { + going: 'community.lexicon.calendar.rsvp#going', + interested: 'community.lexicon.calendar.rsvp#interested', + notgoing: 'community.lexicon.calendar.rsvp#notgoing', +} + +function kvSessionStore(): NodeSavedSessionStore { + return { + async get(key: string): Promise { + return (await useStorage('kv').getItem(`atproto:session:${key}`) as NodeSavedSession) ?? undefined + }, + async set(key: string, val: NodeSavedSession): Promise { + await useStorage('kv').setItem(`atproto:session:${key}`, val) + }, + async del(key: string): Promise { + await useStorage('kv').removeItem(`atproto:session:${key}`) + }, + } +} + +function kvStateStore(): NodeSavedStateStore { + return { + async get(key: string) { + return (await useStorage('kv').getItem(`atproto:state:${key}`)) as never ?? undefined + }, + async set(key: string, val: Record ): Promise { + await useStorage('kv').setItem(`atproto:state:${key}`, val, { ttl: 600 }) + }, + async del(key: string): Promise { + await useStorage('kv').removeItem(`atproto:state:${key}`) + }, + } +} + +const _locks = new Map >() + +let _client: NodeOAuthClient | null = null + +export function getAtprotoClient(event: H3Event): NodeOAuthClient { + if (_client) return _client + _client = new NodeOAuthClient({ + clientMetadata: getAtprotoClientMetadata(event, 'bluesky', { + scope: [ + 'atproto', + 'repo:community.lexicon.calendar.event', + 'repo:community.lexicon.calendar.rsvp', + ], + }), + sessionStore: kvSessionStore(), + stateStore: kvStateStore(), + requestLock: async (key: string, fn: () => T | PromiseLike ): Promise => { + while (_locks.has(key)) await _locks.get(key) + const promise = Promise.resolve(fn()).finally(() => _locks.delete(key)) + _locks.set(key, promise) + return promise + }, + }) + return _client +} + +export async function getAtprotoAgent(event: H3Event, did: string): Promise { + const client = getAtprotoClient(event) + try { + const session = await client.restore(did) + return new Agent(session) + } + catch (error) { + // If the session is invalid (wrong client, expired refresh token, etc.), + // clear it so the user can re-authenticate + const message = String(error) + if (message.includes('not issued to this client') || message.includes('deleted by another process')) { + await useStorage('kv').removeItem(`atproto:session:${did}`) + } + throw error + } +} + +function buildLocations(event: StoredEvent): Record [] | undefined { + if (!event.location) return undefined + + if (/^https?:\/\//.test(event.location)) { + return [{ $type: 'community.lexicon.calendar.event#uri', uri: event.location, name: event.location }] + } + + return [{ $type: 'community.lexicon.location.address', name: event.location, country: '' }] +} + +function buildUris(event: StoredEvent, guild: StoredGuild): { uri: string, name: string }[] { + const uris = [ + { uri: `https://discord.com/events/${guild.id}/${event.id}`, name: 'Discord Event' }, + ] + + // Voice/Stage channel link is more useful as a URI than a location + if (event.channelId && (event.entityType === 1 || event.entityType === 2)) { + uris.push({ + uri: `https://discord.com/channels/${event.guildId}/${event.channelId}`, + name: 'Discord Channel', + }) + } + + return uris +} + +function toUtcZ(datetime: string): string { + return new Date(datetime).toISOString() +} + +export function discordEventToAtprotoRecord(event: StoredEvent, guild: StoredGuild) { + return { + $type: 'community.lexicon.calendar.event', + name: event.name, + description: event.description || '', + createdAt: new Date().toISOString(), + startsAt: toUtcZ(event.startTime), + endsAt: event.endTime ? toUtcZ(event.endTime) : undefined, + status: STATUS_MAP[event.status], + mode: MODE_MAP[event.entityType], + locations: buildLocations(event), + uris: buildUris(event, guild), + } +} + +export async function publishEventToAtproto( + h3Event: H3Event, + event: StoredEvent, + guild: StoredGuild, +): Promise<{ uri: string, cid: string } | null> { + if (!guild.atprotoDid) return null + + try { + const agent = await getAtprotoAgent(h3Event, guild.atprotoDid) + const record = discordEventToAtprotoRecord(event, guild) + + if (event.atprotoUri) { + const rkey = event.atprotoUri.split('/').pop()! + const result = await agent.com.atproto.repo.putRecord({ + repo: guild.atprotoDid, + collection: 'community.lexicon.calendar.event', + rkey, + record, + }) + return { uri: result.data.uri, cid: result.data.cid } + } + + const result = await agent.com.atproto.repo.createRecord({ + repo: guild.atprotoDid, + collection: 'community.lexicon.calendar.event', + record, + }) + return { uri: result.data.uri, cid: result.data.cid } + } + catch (error) { + console.error(`Failed to publish event ${event.id} to AT Proto:`, error) + return null + } +} + +async function findExistingRsvpRkey( + agent: Agent, + userDid: string, + eventUri: string, +): Promise { + try { + const { data } = await agent.com.atproto.repo.listRecords({ + repo: userDid, + collection: 'community.lexicon.calendar.rsvp', + limit: 100, + }) + + const existing = data.records.find((r) => { + const val = r.value as { subject?: { uri?: string } } + return val.subject?.uri === eventUri + }) + return existing?.uri.split('/').pop() ?? null + } + catch { + return null + } +} + +export async function createAtprotoRsvp( + h3Event: H3Event, + userDid: string, + eventUri: string, + eventCid: string, + status: 'going' | 'interested' | 'notgoing', +): Promise<{ uri: string, cid: string } | null> { + try { + const agent = await getAtprotoAgent(h3Event, userDid) + const record = { + $type: 'community.lexicon.calendar.rsvp', + subject: { uri: eventUri, cid: eventCid }, + status: RSVP_STATUS_MAP[status], + createdAt: new Date().toISOString(), + } + + const existingRkey = await findExistingRsvpRkey(agent, userDid, eventUri) + if (existingRkey) { + const result = await agent.com.atproto.repo.putRecord({ + repo: userDid, + collection: 'community.lexicon.calendar.rsvp', + rkey: existingRkey, + record, + }) + return { uri: result.data.uri, cid: result.data.cid } + } + + const result = await agent.com.atproto.repo.createRecord({ + repo: userDid, + collection: 'community.lexicon.calendar.rsvp', + record, + }) + return { uri: result.data.uri, cid: result.data.cid } + } + catch (error) { + console.error(`Failed to create RSVP for ${userDid}:`, error) + return null + } +} diff --git a/server/utils/constellation.ts b/server/utils/constellation.ts new file mode 100644 index 0000000..8524f66 --- /dev/null +++ b/server/utils/constellation.ts @@ -0,0 +1,57 @@ +const CONSTELLATION_API = 'https://constellation.microcosm.blue' + +interface ConstellationBacklink { + did: string + collection: string + rkey: string +} + +interface ConstellationResponse { + total: number + records: ConstellationBacklink[] + cursor: string | null +} + +export interface EventRsvp { + did: string + rkey: string + handle?: string + displayName?: string + avatar?: string +} + +export async function fetchEventRsvps(eventAtUri: string): Promise<{ rsvps: EventRsvp[], total: number }> { + const response = await $fetch ( + `${CONSTELLATION_API}/xrpc/blue.microcosm.links.getBacklinks`, + { + query: { + subject: eventAtUri, + source: 'community.lexicon.calendar.rsvp:subject.uri', + limit: 50, + }, + }, + ) + + const rsvps: EventRsvp[] = await Promise.all( + response.records.map(async (record) => { + const rsvp: EventRsvp = { did: record.did, rkey: record.rkey } + + try { + const profile = await $fetch<{ handle: string, displayName?: string, avatar?: string }>( + `https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile`, + { query: { actor: record.did } }, + ) + rsvp.handle = profile.handle + rsvp.displayName = profile.displayName + rsvp.avatar = profile.avatar + } + catch { + // profile fetch is best-effort + } + + return rsvp + }), + ) + + return { rsvps, total: response.total } +} diff --git a/server/utils/discord.ts b/server/utils/discord.ts new file mode 100644 index 0000000..4c4c468 --- /dev/null +++ b/server/utils/discord.ts @@ -0,0 +1,74 @@ +import type { DiscordScheduledEvent } from './types' + +const DISCORD_API = 'https://discord.com/api/v10' + +async function discordFetch (path: string, options: { + headers: Record + query?: Record +}): Promise { + for (let attempt = 0; attempt < 3; attempt++) { + try { + return await $fetch (`${DISCORD_API}${path}`, options) + } + catch (error: unknown) { + const status = (error as { statusCode?: number }).statusCode + ?? (error as { status?: number }).status + + if (status === 429 && attempt < 2) { + const retryAfter = (error as { data?: { retry_after?: number } }).data?.retry_after ?? 2 + await new Promise(resolve => setTimeout(resolve, Math.min(retryAfter * 1000, 10_000))) + continue + } + throw error + } + } + + throw new Error('Max retries exceeded') +} + +export async function fetchGuildEvents(guildId: string): Promise { + const cacheKey = `cache:events:${guildId}` + const cached = await useStorage('kv').getItem (cacheKey) + if (cached) return cached + + const config = useRuntimeConfig() + const events = await discordFetch ( + `/guilds/${guildId}/scheduled-events`, + { + headers: { Authorization: `Bot ${config.discordBotToken}` }, + query: { with_user_count: true }, + }, + ) + + await useStorage('kv').setItem(cacheKey, events, { ttl: 1 }) + return events +} + +export async function checkBotInGuild(guildId: string): Promise { + const cacheKey = `cache:bot-in-guild:${guildId}` + const cached = await useStorage('kv').getItem (cacheKey) + if (cached !== null) return cached + + try { + const config = useRuntimeConfig() + await discordFetch(`/guilds/${guildId}`, { + headers: { Authorization: `Bot ${config.discordBotToken}` }, + }) + await useStorage('kv').setItem(cacheKey, true, { ttl: 1 }) + return true + } + catch { + return false + } +} + +export function buildBotInviteUrl(guildId?: string): string { + const config = useRuntimeConfig() + const params = new URLSearchParams({ + client_id: config.oauth.discord.clientId, + permissions: '0', + scope: 'bot', + ...(guildId ? { guild_id: guildId } : {}), + }) + return `https://discord.com/oauth2/authorize?${params.toString()}` +} diff --git a/server/utils/ics.ts b/server/utils/ics.ts new file mode 100644 index 0000000..480ff42 --- /dev/null +++ b/server/utils/ics.ts @@ -0,0 +1,55 @@ +import icalGenerator from 'ical-generator' +import type { ICalCalendarData, ICalEventData } from 'ical-generator' +import { getVtimezoneComponent } from '@touch4it/ical-timezones' + +import type { StoredEvent, StoredGuild } from './types' +import { discordRecurrenceToRRule } from './rrule' + +const ENTITY_TYPE_LABELS: Record = { + 1: 'Stage', + 2: 'Voice', + 3: 'External', +} + +export function generateCalendar(guild: StoredGuild, events: StoredEvent[]): string { + const calendarData: ICalCalendarData = { + name: `${guild.name} Events`, + description: `Events from the ${guild.name} Discord server`, + timezone: { name: guild.timezone, generator: getVtimezoneComponent }, + prodId: { company: 'discal.dev', product: 'discal', language: 'EN' }, + ttl: 300, + } + + const calendar = icalGenerator(calendarData) + + for (const event of events) { + if (event.status === 3 || event.status === 4) continue + + const eventData: ICalEventData = { + id: `discord-${event.id}@discal.dev`, + summary: event.name, + description: event.description || undefined, + start: new Date(event.startTime), + end: event.endTime ? new Date(event.endTime) : undefined, + timezone: guild.timezone, + url: `https://discord.com/events/${event.guildId}/${event.id}`, + } + + if (event.location) { + eventData.location = { title: event.location } + } + + const label = ENTITY_TYPE_LABELS[event.entityType] + if (label) { + eventData.categories = [{ name: label }] + } + + const icalEvent = calendar.createEvent(eventData) + + if (event.recurrenceRule) { + icalEvent.repeating(discordRecurrenceToRRule(event.recurrenceRule)) + } + } + + return calendar.toString() +} diff --git a/server/utils/rrule.ts b/server/utils/rrule.ts new file mode 100644 index 0000000..c59a273 --- /dev/null +++ b/server/utils/rrule.ts @@ -0,0 +1,38 @@ +import type { DiscordRecurrenceRule } from './types' + +const WEEKDAY_MAP = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] as const +const FREQ_MAP = ['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY'] as const + +export function discordRecurrenceToRRule(rule: DiscordRecurrenceRule): string { + const parts: string[] = [`FREQ=${FREQ_MAP[rule.frequency]}`] + + if (rule.interval > 1) { + parts.push(`INTERVAL=${rule.interval}`) + } + + if (rule.by_weekday?.length) { + parts.push(`BYDAY=${rule.by_weekday.map(d => WEEKDAY_MAP[d]).join(',')}`) + } + + if (rule.by_n_weekday?.length) { + parts.push(`BYDAY=${rule.by_n_weekday.map(nw => `${nw.n}${WEEKDAY_MAP[nw.day]}`).join(',')}`) + } + + if (rule.by_month?.length) { + parts.push(`BYMONTH=${rule.by_month.join(',')}`) + } + + if (rule.by_month_day?.length) { + parts.push(`BYMONTHDAY=${rule.by_month_day.join(',')}`) + } + + if (rule.count) { + parts.push(`COUNT=${rule.count}`) + } + + if (rule.end) { + parts.push(`UNTIL=${rule.end.replace(/[-:]/g, '').replace(/\.\d+/, '')}`) + } + + return parts.join(';') +} diff --git a/server/utils/storage.ts b/server/utils/storage.ts new file mode 100644 index 0000000..0e88bb8 --- /dev/null +++ b/server/utils/storage.ts @@ -0,0 +1,78 @@ +import type { StoredEvent, StoredGuild } from './types' + +function kv() { + return useStorage('kv') +} + +export async function getGuild(guildId: string): Promise { + return await kv().getItem (`guild:${guildId}`) ?? null +} + +export async function setGuild(guild: StoredGuild): Promise { + await kv().setItem(`guild:${guild.id}`, guild) + + const index = await getGuildIndex() + if (!index.includes(guild.id)) { + index.push(guild.id) + await kv().setItem('guild:index', index) + } + + await kv().setItem(`slug:${guild.calendarSlug}`, guild.id) +} + +export async function getGuildIndex(): Promise { + return await kv().getItem ('guild:index') ?? [] +} + +export async function getGuildBySlug(slug: string): Promise { + const guildId = await kv().getItem (`slug:${slug}`) + if (!guildId) return null + return getGuild(guildId) +} + +export async function getAllGuilds(): Promise { + const index = await getGuildIndex() + const guilds = await Promise.all(index.map(id => getGuild(id))) + return guilds.filter((g): g is StoredGuild => g !== null) +} + +export async function getEvent(guildId: string, eventId: string): Promise { + return await kv().getItem (`event:${guildId}:${eventId}`) ?? null +} + +export async function setEvent(event: StoredEvent): Promise { + await kv().setItem(`event:${event.guildId}:${event.id}`, event) + + const index = await getEventIndex(event.guildId) + if (!index.includes(event.id)) { + index.push(event.id) + await kv().setItem(`events:${event.guildId}`, index) + } +} + +export async function removeEvent(guildId: string, eventId: string): Promise { + await kv().removeItem(`event:${guildId}:${eventId}`) + + const index = await getEventIndex(guildId) + await kv().setItem(`events:${guildId}`, index.filter(id => id !== eventId)) +} + +export async function getEventIndex(guildId: string): Promise { + return await kv().getItem (`events:${guildId}`) ?? [] +} + +export async function getGuildEvents(guildId: string): Promise { + const index = await getEventIndex(guildId) + const events = await Promise.all(index.map(id => getEvent(guildId, id))) + return events.filter((e): e is StoredEvent => e !== null) +} + +export function generateSlug(guildName: string): string { + const base = guildName + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') + .slice(0, 40) + + return `${base}-${Math.random().toString(36).slice(2, 6)}` +} diff --git a/server/utils/types.ts b/server/utils/types.ts new file mode 100644 index 0000000..1e5e402 --- /dev/null +++ b/server/utils/types.ts @@ -0,0 +1,62 @@ +export interface DiscordRecurrenceRule { + start: string + end: string | null + frequency: 0 | 1 | 2 | 3 // 0=YEARLY, 1=MONTHLY, 2=WEEKLY, 3=DAILY + interval: number + by_weekday: number[] | null // 0=Mon...6=Sun + by_n_weekday: { n: number, day: number }[] | null + by_month: number[] | null // 1=Jan...12=Dec + by_month_day: number[] | null + by_year_day: number[] | null + count: number | null +} + +export interface DiscordScheduledEvent { + id: string + guild_id: string + channel_id: string | null + creator_id: string | null + name: string + description: string | null + scheduled_start_time: string + scheduled_end_time: string | null + privacy_level: number + status: 1 | 2 | 3 | 4 // 1=SCHEDULED, 2=ACTIVE, 3=COMPLETED, 4=CANCELED + entity_type: 1 | 2 | 3 // 1=STAGE, 2=VOICE, 3=EXTERNAL + entity_id: string | null + entity_metadata: { location?: string } | null + user_count?: number + image: string | null + recurrence_rule: DiscordRecurrenceRule | null +} + +export interface StoredGuild { + id: string + name: string + icon: string | null + addedBy: string + atprotoDid: string | null + timezone: string + calendarSlug: string + createdAt: string +} + +export interface StoredEvent { + id: string + guildId: string + name: string + description: string | null + location: string | null + channelId: string | null + startTime: string + endTime: string | null + entityType: 1 | 2 | 3 + status: 1 | 2 | 3 | 4 + recurrenceRule: DiscordRecurrenceRule | null + imageHash: string | null + userCount: number + atprotoUri: string | null + atprotoCid: string | null + atprotoRecordVersion: number | null + lastSyncedAt: string +} diff --git a/shared/types/auth.d.ts b/shared/types/auth.d.ts new file mode 100644 index 0000000..3dbac59 --- /dev/null +++ b/shared/types/auth.d.ts @@ -0,0 +1,23 @@ +declare module '#auth-utils' { + interface User { + discordId: string + name: string + avatar?: string + blueskyDid?: string + blueskyHandle?: string + } + + interface UserSession { + /** Guild ID context, if the user came from adding a bot */ + linkedGuildId?: string + } + + interface SecureSessionData { + /** Discord access token for API calls */ + discordAccessToken?: string + /** AT Protocol DID for writing records */ + atprotoDid?: string + } +} + +export {} diff --git a/test/unit/rrule.spec.ts b/test/unit/rrule.spec.ts new file mode 100644 index 0000000..391aebd --- /dev/null +++ b/test/unit/rrule.spec.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { discordRecurrenceToRRule } from '../../server/utils/rrule' +import type { DiscordRecurrenceRule } from '../../server/utils/types' + +function makeRule(overrides: Partial ): DiscordRecurrenceRule { + return { + start: '2026-01-01T00:00:00Z', + end: null, + frequency: 2, + interval: 1, + by_weekday: null, + by_n_weekday: null, + by_month: null, + by_month_day: null, + by_year_day: null, + count: null, + ...overrides, + } +} + +describe('discordRecurrenceToRRule', () => { + it('converts a simple weekly rule', () => { + const rule = makeRule({ frequency: 2, by_weekday: [2] }) + expect(discordRecurrenceToRRule(rule)).toBe('FREQ=WEEKLY;BYDAY=WE') + }) + + it('converts every other week', () => { + const rule = makeRule({ frequency: 2, interval: 2, by_weekday: [2] }) + expect(discordRecurrenceToRRule(rule)).toBe('FREQ=WEEKLY;INTERVAL=2;BYDAY=WE') + }) + + it('converts weekdays (Mon-Fri)', () => { + const rule = makeRule({ frequency: 3, by_weekday: [0, 1, 2, 3, 4] }) + expect(discordRecurrenceToRRule(rule)).toBe('FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR') + }) + + it('converts monthly on nth weekday (4th Wednesday)', () => { + const rule = makeRule({ frequency: 1, by_n_weekday: [{ n: 4, day: 2 }] }) + expect(discordRecurrenceToRRule(rule)).toBe('FREQ=MONTHLY;BYDAY=4WE') + }) + + it('converts yearly on specific date (July 24)', () => { + const rule = makeRule({ frequency: 0, by_month: [7], by_month_day: [24] }) + expect(discordRecurrenceToRRule(rule)).toBe('FREQ=YEARLY;BYMONTH=7;BYMONTHDAY=24') + }) + + it('includes COUNT when present', () => { + const rule = makeRule({ frequency: 2, by_weekday: [0], count: 12 }) + expect(discordRecurrenceToRRule(rule)).toBe('FREQ=WEEKLY;BYDAY=MO;COUNT=12') + }) + + it('includes UNTIL when end is present', () => { + const rule = makeRule({ frequency: 2, by_weekday: [4], end: '2026-12-31T23:59:59.000Z' }) + expect(discordRecurrenceToRRule(rule)).toBe('FREQ=WEEKLY;BYDAY=FR;UNTIL=20261231T235959Z') + }) + + it('handles simple daily with no extra params', () => { + const rule = makeRule({ frequency: 3 }) + expect(discordRecurrenceToRRule(rule)).toBe('FREQ=DAILY') + }) +})