Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 54 additions & 39 deletions backend/src/calendar/cardInvite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { confirmedTitle, isPodcastInviteTitle, parseHoldDocumentUrl, podcastInvi
import { listPodcastEpisodes, type PodcastEpisode } from '../db/podcastEpisodes';
import { recordTemplateTypes } from '../cards/cardTitlePattern';
import { deleteHoldGoogleEvents, fetchGoogleEvent, findGoneGoogleEvents, mergeHoldGoogleResults, syncLumaCalendarEvents, syncSilentGoogleCopies, type HoldGoogleDeps, type HoldGoogleResult } from './holdGoogleSync';
import { lumaUrlForEventCard } from './lumaEvents';
import { lumaEventSubtitle, lumaUrlForEventCard } from './lumaEvents';
import { PUBLIC_DTC_EVENTS_CALENDAR, resolveHoldGoogleCalendars } from './dapierBroker';
import { decryptSponsorDocAccessCode, getSponsorDocWithAuthMaterial } from '../db/sponsorDocs';

Expand Down Expand Up @@ -293,10 +293,14 @@ export async function syncCardInvite(
linkedHold = active[0] || null;
}
const eventKey = card.eventTime?.eventKey || linkedHold?.id || `card:${card.id}`;
const eventIds = {
const recordedEventIds = {
...(card.eventTime?.googleEventIds || {}),
...(linkedHold?.googleEventIds || {}),
};
// The standalone public entry is recorded on the Card only, so a rerun or a
// move updates that same entry instead of leaving the old one behind.
const publicCopyIds: Record<string, string> = Object.fromEntries(Object.entries(recordedEventIds).filter(([calendar]) => calendar === PUBLIC_DTC_EVENTS_CALENDAR));
const eventIds = { ...recordedEventIds };
// A legacy public-calendar attendee copy is never part of the guest invite.
delete eventIds[PUBLIC_DTC_EVENTS_CALENDAR];
// Podcast SOP: the confirmed invite is named for the guest, not the topic.
Expand Down Expand Up @@ -336,59 +340,68 @@ export async function syncCardInvite(
expectedVersion: card.version,
patch: { eventTime: pending, guestEmails: silentLumaEvent ? [] : guests },
});
// A silent Luma event (a course cohort Q&A or Launch and every other
// Luma-linked Card) gets the full SOP calendar set: the standalone public
// entry on the DTC events calendar plus the same content as silent
// organizer + personal hold copies (attendee-free, no email). Each leg is
// idempotent and recovers its partial writes on retry.
const publicCopyIds = { ...(eventIds[PUBLIC_DTC_EVENTS_CALENDAR] ? { [PUBLIC_DTC_EVENTS_CALENDAR]: eventIds[PUBLIC_DTC_EVENTS_CALENDAR] } : {}) };
// Every Luma-linked Card owns one standalone public entry on the DTC events
// calendar beside its guest invite or silent copies (SOP
// `sop.events.luma.creating-events-on-google-calendar`): attendee-free,
// Zoom-free, at the real event time. A silent Luma event (a course cohort
// Q&A or Launch) adds the same content as silent organizer + personal hold
// copies. Each leg is idempotent and recovers its partial writes on retry;
// the hold itself carries the invitation only, never the public entry.
const personalCopyIds = Object.fromEntries(Object.entries(eventIds).filter(([calendar]) => calendar !== PUBLIC_DTC_EVENTS_CALENDAR));
const lumaEvent = {
eventKey,
summary: card.title || 'DataTalks.Club event',
subtitle: card.description || undefined,
startIso: interval.startIso,
endIso: interval.endIso,
timeZone: interval.timeZone,
lumaUrl: lumaUrl!,
};
let sync: HoldGoogleResult;
/** The standalone public entry; a guest invite waits while Luma gives no subtitle. */
const syncPublicEntry = async (): Promise<HoldGoogleResult> => {
// A silent Card's description is its public subtitle. A guest invite
// Card's description holds internal scheduling notes and never goes
// public: its subtitle is the Luma event's own.
const subtitle = silentLumaEvent ? card.description || undefined : await lumaEventSubtitle(lumaUrl!, deps.fetchImpl);
return subtitle === undefined && !silentLumaEvent
? { state: 'deferred', reason: 'The public DTC events entry needs the event subtitle, and the Luma page did not provide one. Check that the Luma event is public, then rerun.', eventIds: { ...publicCopyIds } }
: syncLumaCalendarEvents({ ...lumaEvent, subtitle }, deps, publicCopyIds);
};
// One result per Google leg: the public entry first (when the Card has a
// Luma link), then the invitation or the silent copies.
const legs: HoldGoogleResult[] = [];
try {
sync = silentLumaEvent
? mergeHoldGoogleResults(
await syncLumaCalendarEvents(lumaEvent, deps, publicCopyIds),
await syncSilentGoogleCopies(lumaEvent, deps, personalCopyIds),
)
: await writeGuestInvite(invite!, eventIds, deps);
if (lumaUrl) legs.push(await syncPublicEntry());
legs.push(await (silentLumaEvent ? syncSilentGoogleCopies(lumaEvent, deps, personalCopyIds) : writeGuestInvite(invite!, eventIds, deps)));
} catch (error) {
if (error instanceof GuestInviteValidationError) await reportGuestInviteFailure(client, error, { cardId: card.id, actorId });
throw error;
}
const sync = mergeHoldGoogleResults(...legs);
// Each leg links the entries it wrote and read back, so a partial sync shows
// exactly what is live. The Card is synced, and its invite Tasks close, only
// when every leg is.
const linkedEventIds = legs.filter((leg) => leg.state === 'synced').flatMap((leg) => Object.entries(leg.eventIds));
const publicEntryLive = Boolean(lumaUrl) && legs[0].state === 'synced';
const updated = await updateCardAdditive(client, reserved, current => {
const invites = [...(current.calendarInvites || [])];
if (sync.state === 'synced') {
// Silent Luma events link every calendar copy they own (public entry,
// organizer and personal copies); guest invites never link the public
// calendar — its standalone entries are never invite copies.
const linkedEventIds = Object.entries(sync.eventIds).filter(([calendar]) =>
silentLumaEvent || calendar !== PUBLIC_DTC_EVENTS_CALENDAR);
if (silentLumaEvent && sync.state === 'synced') {
for (let index = invites.length - 1; index >= 0; index--) {
if (invites[index].calendar === PUBLIC_DTC_EVENTS_CALENDAR) invites.splice(index, 1);
}
if (publicEntryLive) {
// Exactly one DTC events row: the standalone entry the public leg owns.
for (let index = invites.length - 1; index >= 0; index--) {
if (invites[index].calendar === PUBLIC_DTC_EVENTS_CALENDAR) invites.splice(index, 1);
}
for (const [calendar, eventId] of linkedEventIds) {
const index = invites.findIndex(entry => entry.calendar === calendar && entry.eventId === eventId);
const entry = {
calendar, eventId, url: calendarInviteUrl(calendar, eventId), createdAt: new Date().toISOString(), createdBy: actorId,
...(silentLumaEvent ? { label: card.title || 'Luma event' } : {}),
};
if (index < 0) invites.push(entry);
else {
const refreshed = { ...invites[index] };
delete refreshed.staleAt;
invites[index] = { ...refreshed, ...entry };
}
}
for (const [calendar, eventId] of linkedEventIds) {
const index = invites.findIndex(entry => entry.calendar === calendar && entry.eventId === eventId);
const entry = {
calendar, eventId, url: calendarInviteUrl(calendar, eventId), createdAt: new Date().toISOString(), createdBy: actorId,
// Silent copies and the public entry are named for the event.
...(silentLumaEvent || calendar === PUBLIC_DTC_EVENTS_CALENDAR ? { label: card.title || 'Luma event' } : {}),
};
if (index < 0) invites.push(entry);
else {
const refreshed = { ...invites[index] };
delete refreshed.staleAt;
invites[index] = { ...refreshed, ...entry };
}
}
return {
Expand All @@ -399,11 +412,13 @@ export async function syncCardInvite(
let storedHold: CalendarHold | undefined;
if (linkedHold) {
const preservedTopic = linkedHold.topic || (podcastTitle && linkedHold.title && !isPodcastInviteTitle(linkedHold.title) ? confirmedTitle(linkedHold.title) : undefined);
// The public entry belongs to the Card, so releasing the hold never has to touch it.
const inviteEventIds = Object.fromEntries(Object.entries(sync.eventIds).filter(([calendar]) => calendar !== PUBLIC_DTC_EVENTS_CALENDAR));
storedHold = {
...linkedHold, ...interval, cardId: card.id, title: confirmedTitle(inviteTitle), ...(preservedTopic ? { topic: preservedTopic } : {}), date: todayIn(interval.timeZone, new Date(interval.startIso)),
googleTitle: confirmedTitle(inviteTitle), guestRef: guests[0], ...(documentUrl ? { documentUrl } : {}),
status: 'confirmed', confirmedAt: linkedHold.confirmedAt || new Date().toISOString(),
googleEventIds: sync.eventIds, googleSync: { state: sync.state, ...(sync.state === 'deferred' ? { reason: sync.reason } : {}) },
googleEventIds: inviteEventIds, googleSync: { state: sync.state, ...(sync.state === 'deferred' ? { reason: sync.reason } : {}) },
updatedAt: new Date().toISOString(), version: linkedHold.version + 1,
};
await putCalendarHold(client, storedHold);
Expand Down
12 changes: 10 additions & 2 deletions backend/src/calendar/holdGoogleSync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,8 @@ export function mergeHoldGoogleResults(...results: HoldGoogleResult[]): HoldGoog
* Public event copy rules. This path writes one standalone event owned by the
* public calendar, without attendees or conference data. Existing manual SOP
* entries are adopted by matching title, time and Luma URL before insertion.
* A recorded entry id is updated in place, so a rerun or a move never leaves
* the previous entry behind.
*/
export async function syncLumaCalendarEvents(
event: LumaCalendarEvent,
Expand Down Expand Up @@ -397,14 +399,20 @@ export async function syncLumaCalendarEvents(
if (PRIVATE_DETAIL_PATTERN.test(body.description)) {
return deferred('Public calendar entry contains private meeting or document details.');
}
// Attendees or private meeting details never belong on a public entry.
const unsafe = (event: any) => Boolean(event && (event.attendees?.length || event.conferenceData
|| /zoom\.us|ops\.dtcdev\.click/i.test(`${event.description || ''}\n${event.location || ''}`)));
try {
let current: any;
if (eventIds[PUBLIC_DTC_EVENTS_CALENDAR]) {
try { current = await request(`${url}/${encodeURIComponent(eventIds[PUBLIC_DTC_EVENTS_CALENDAR])}`); }
catch (error) {
if (!(error instanceof Error) || !/HTTP (404|410)/.test(error.message)) throw error;
}
if (current?.status === 'cancelled') current = undefined;
// Gone, cancelled, or not a standalone entry: a recorded id may point at
// a legacy attendee copy of the guest invite, which is never reused or
// edited, so the entry below is matched or created as if none was recorded.
if (current?.status === 'cancelled' || unsafe(current)) current = undefined;
}
if (!current) {
const found = await request(`${url}?timeMin=${encodeURIComponent(event.startIso)}&timeMax=${encodeURIComponent(event.endIso)}&singleEvents=true&maxResults=250`);
Expand All @@ -417,7 +425,7 @@ export async function syncLumaCalendarEvents(
if (matches.length > 1) return deferred('Multiple matching public Luma entries exist; reconcile them before syncing.');
current = matches[0];
}
if (current?.attendees?.length || current?.conferenceData || /zoom\.us|ops\.dtcdev\.click/i.test(`${current?.description || ''}\n${current?.location || ''}`)) {
if (unsafe(current)) {
return deferred('The public calendar event has attendees or private meeting details; it was left untouched.');
}
const saved = current?.id
Expand Down
48 changes: 48 additions & 0 deletions backend/src/calendar/lumaEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,51 @@ export async function lumaUrlForEventCard(
}
return null;
}

const LUMA_PAGE_LIMIT = 1024 * 1024;
const LUMA_SUBTITLE_LIMIT = 300;
const LUMA_FETCH_USER_AGENT = 'DataOps/1.0 (DataTalks.Club operations portal)';

const NAMED_ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };

/** Luma HTML-escapes its meta content (`&#x27;`, `&quot;`, `&amp;`). */
function decodeHtmlEntities(text: string): string {
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, body: string) => {
if (!body.startsWith('#')) return NAMED_ENTITIES[body.toLowerCase()] ?? entity;
const code = body[1].toLowerCase() === 'x' ? parseInt(body.slice(2), 16) : Number(body.slice(1));
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : entity;
});
}

/** The decoded `content` of the first `<meta property|name="<name>">` tag, in either attribute order. */
function metaContent(html: string, name: string): string | undefined {
for (const [tag] of html.matchAll(/<meta\s[^>]*>/gi)) {
if (/\b(?:property|name)\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1] !== name) continue;
const content = /\bcontent\s*=\s*"([^"]*)"/i.exec(tag)?.[1];
if (content !== undefined) return decodeHtmlEntities(content);
}
return undefined;
}

/**
* The Luma event's own subtitle: the first line of its public `og:description`
* (`<subtitle> - <speakers>`). Undefined when Luma gives none (a missing,
* non-public or changed page); the caller decides what a missing subtitle means.
* Never throws.
*/
export async function lumaEventSubtitle(lumaUrl: string, fetchImpl?: typeof fetch): Promise<string | undefined> {
try {
const response = await (fetchImpl || fetch)(lumaUrl, {
headers: { 'User-Agent': LUMA_FETCH_USER_AGENT, Accept: 'text/html' },
signal: AbortSignal.timeout(10000),
});
if (!response.ok) return undefined;
const declared = Number(response.headers.get('content-length') || 0);
if (declared > LUMA_PAGE_LIMIT) return undefined;
const raw = metaContent((await response.text()).slice(0, LUMA_PAGE_LIMIT), 'og:description')?.split(/\r?\n/)[0];
const subtitle = raw?.replace(/\s+/g, ' ').trim().slice(0, LUMA_SUBTITLE_LIMIT);
return subtitle || undefined;
} catch {
return undefined;
}
}
Loading