diff --git a/server/utils/ics.ts b/server/utils/ics.ts index d02423d..fd62cc7 100644 --- a/server/utils/ics.ts +++ b/server/utils/ics.ts @@ -11,6 +11,46 @@ const ENTITY_TYPE_LABELS: Record = { 3: 'External', } +/** + * Check whether a recurring event's next occurrence has been modified. + * + * Discord updates `scheduled_start_time` when a single occurrence is edited + * but keeps `recurrence_rule.start` as the series anchor. If they represent + * different times-of-day, the next occurrence has been rescheduled. + */ +function getOccurrenceOverride(event: StoredEvent): Date | null { + if (!event.recurrenceRule) return null + + const seriesStart = new Date(event.recurrenceRule.start) + const nextOccurrence = new Date(event.startTime) + + // Compare time-of-day (hours + minutes) in UTC + if ( + seriesStart.getUTCHours() === nextOccurrence.getUTCHours() + && seriesStart.getUTCMinutes() === nextOccurrence.getUTCMinutes() + ) { + return null + } + + return nextOccurrence +} + +/** + * Compute what the original time of a modified occurrence would have been. + * + * Takes the date from the actual occurrence and the time-of-day from the + * series anchor, producing the RECURRENCE-ID value (the occurrence that + * "should have" happened before the edit). + */ +function getOriginalOccurrenceTime(seriesStart: Date, modifiedOccurrence: Date): Date { + const original = new Date(modifiedOccurrence) + original.setUTCHours(seriesStart.getUTCHours()) + original.setUTCMinutes(seriesStart.getUTCMinutes()) + original.setUTCSeconds(seriesStart.getUTCSeconds()) + original.setUTCMilliseconds(0) + return original +} + export function generateCalendar(guild: StoredGuild, events: StoredEvent[]): string { const calendarData: ICalCalendarData = { name: `${guild.name} Events`, @@ -25,11 +65,19 @@ export function generateCalendar(guild: StoredGuild, events: StoredEvent[]): str for (const event of events) { if (event.status === 4) continue + // For recurring events, use the recurrence rule's start as DTSTART (the + // series anchor) rather than scheduled_start_time (the next occurrence). + // Discord updates scheduled_start_time when a single occurrence is modified, + // which would incorrectly shift the entire series in the calendar. + const start = event.recurrenceRule?.start + ? new Date(event.recurrenceRule.start) + : new Date(event.startTime) + const eventData: ICalEventData = { id: `discord-${event.id}@discal.dev`, summary: event.name, description: event.description || undefined, - start: new Date(event.startTime), + start, end: event.endTime ? new Date(event.endTime) : undefined, timezone: guild.timezone, url: `https://discord.com/events/${event.guildId}/${event.id}`, @@ -49,6 +97,34 @@ export function generateCalendar(guild: StoredGuild, events: StoredEvent[]): str if (event.recurrenceRule) { icalEvent.repeating(discordRecurrenceToRRule(event.recurrenceRule)) } + + // If Discord has modified the next occurrence's time, emit an exception + // VEVENT with RECURRENCE-ID so the calendar shows the correct time for + // that specific occurrence without shifting the entire series. + const override = getOccurrenceOverride(event) + if (override && event.recurrenceRule) { + const originalTime = getOriginalOccurrenceTime( + new Date(event.recurrenceRule.start), + override, + ) + + const exceptionData: ICalEventData = { + id: `discord-${event.id}@discal.dev`, + recurrenceId: originalTime, + summary: event.name, + description: event.description || undefined, + start: override, + end: event.endTime ? new Date(event.endTime) : undefined, + timezone: guild.timezone, + url: `https://discord.com/events/${event.guildId}/${event.id}`, + } + + if (event.location) { + exceptionData.location = { title: event.location } + } + + calendar.createEvent(exceptionData) + } } return calendar.toString() diff --git a/test/unit/ics.spec.ts b/test/unit/ics.spec.ts new file mode 100644 index 0000000..cda4ba4 --- /dev/null +++ b/test/unit/ics.spec.ts @@ -0,0 +1,133 @@ +import { describe, expect, it } from 'vite-plus/test' +import { generateCalendar } from '../../server/utils/ics' +import type { StoredEvent, StoredGuild } from '../../server/utils/types' + +function makeGuild(overrides?: Partial): StoredGuild { + return { + id: '123', + name: 'Test Server', + icon: null, + addedBy: 'user1', + atprotoDid: null, + timezone: 'UTC', + calendarSlug: 'test-server-abc', + createdAt: '2026-01-01T00:00:00Z', + ...overrides, + } +} + +function makeEvent(overrides?: Partial): StoredEvent { + return { + id: '456', + guildId: '123', + name: 'Test Event', + description: null, + location: null, + channelId: null, + startTime: '2026-04-01T16:15:00.000Z', + endTime: '2026-04-01T17:15:00.000Z', + entityType: 2, + status: 1, + recurrenceRule: null, + imageHash: null, + userCount: 0, + atprotoUri: null, + atprotoCid: null, + atprotoRecordVersion: null, + lastSyncedAt: '2026-04-01T00:00:00Z', + ...overrides, + } +} + +describe('generateCalendar', () => { + it('generates a basic non-recurring event', () => { + const ics = generateCalendar(makeGuild(), [makeEvent()]) + expect(ics).toContain('SUMMARY:Test Event') + expect(ics).toContain('BEGIN:VEVENT') + expect(ics).not.toContain('RRULE') + expect(ics).not.toContain('RECURRENCE-ID') + }) + + it('generates a recurring event with RRULE', () => { + const event = makeEvent({ + recurrenceRule: { + start: '2026-04-01T16:15:00.000Z', + end: null, + frequency: 2, + interval: 2, + by_weekday: [2], + by_n_weekday: null, + by_month: null, + by_month_day: null, + by_year_day: null, + count: null, + }, + }) + + const ics = generateCalendar(makeGuild(), [event]) + expect(ics).toContain('RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=WE') + expect(ics).not.toContain('RECURRENCE-ID') + }) + + it('emits a RECURRENCE-ID exception when next occurrence time differs from series anchor', () => { + // Series starts at 16:15, but Discord has moved today's occurrence to 15:15 + const event = makeEvent({ + startTime: '2026-04-01T15:15:00.000Z', + endTime: '2026-04-01T16:15:00.000Z', + recurrenceRule: { + start: '2026-03-18T16:15:00.000Z', // original series anchor at 16:15 + end: null, + frequency: 2, + interval: 2, + by_weekday: [2], + by_n_weekday: null, + by_month: null, + by_month_day: null, + by_year_day: null, + count: null, + }, + }) + + const ics = generateCalendar(makeGuild(), [event]) + + // Should have two VEVENTs: the series and the exception + const veventCount = (ics.match(/BEGIN:VEVENT/g) || []).length + expect(veventCount).toBe(2) + + // Series should use recurrence rule start as DTSTART + expect(ics).toContain('RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=WE') + + // Exception should have RECURRENCE-ID pointing to what the original + // occurrence time would have been (Apr 1 at 16:15) + expect(ics).toContain('RECURRENCE-ID') + }) + + it('does not emit exception when occurrence time matches series anchor', () => { + const event = makeEvent({ + startTime: '2026-04-01T16:15:00.000Z', + recurrenceRule: { + start: '2026-03-18T16:15:00.000Z', + end: null, + frequency: 2, + interval: 2, + by_weekday: [2], + by_n_weekday: null, + by_month: null, + by_month_day: null, + by_year_day: null, + count: null, + }, + }) + + const ics = generateCalendar(makeGuild(), [event]) + const veventCount = (ics.match(/BEGIN:VEVENT/g) || []).length + expect(veventCount).toBe(1) + expect(ics).not.toContain('RECURRENCE-ID') + }) + + it('skips cancelled events', () => { + const event = makeEvent({ status: 4 }) + const ics = generateCalendar(makeGuild(), [event]) + expect(ics).not.toContain('BEGIN:VEVENT') + }) +})