|
| 1 | +import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'; |
| 2 | +import path from 'node:path'; |
| 3 | + |
| 4 | +const GROUPS_FILE = path.join('data', 'meetup_groups.json'); |
| 5 | +const CALENDAR_DIR = path.join('content', 'calendar'); |
| 6 | +const DRY_RUN = process.argv.includes('--dry-run'); |
| 7 | + |
| 8 | +function yaml(value) { |
| 9 | + return JSON.stringify(value ?? ''); |
| 10 | +} |
| 11 | + |
| 12 | +function unescapeIcal(value = '') { |
| 13 | + return value |
| 14 | + .replace(/\\n/gi, '\n') |
| 15 | + .replace(/\\,/g, ',') |
| 16 | + .replace(/\\;/g, ';') |
| 17 | + .replace(/\\\\/g, '\\'); |
| 18 | +} |
| 19 | + |
| 20 | +function property(line) { |
| 21 | + const separator = line.indexOf(':'); |
| 22 | + if (separator < 1) return null; |
| 23 | + const declaration = line.slice(0, separator); |
| 24 | + return { name: declaration.split(';', 1)[0], value: line.slice(separator + 1) }; |
| 25 | +} |
| 26 | + |
| 27 | +function eventsFromIcal(calendar) { |
| 28 | + const events = []; |
| 29 | + let event; |
| 30 | + let groupName; |
| 31 | + |
| 32 | + for (const line of calendar.replace(/\r?\n[ \t]/g, '').split(/\r?\n/)) { |
| 33 | + if (line === 'BEGIN:VEVENT') { |
| 34 | + event = {}; |
| 35 | + continue; |
| 36 | + } |
| 37 | + if (line === 'END:VEVENT') { |
| 38 | + if (event) events.push(event); |
| 39 | + event = undefined; |
| 40 | + continue; |
| 41 | + } |
| 42 | + |
| 43 | + const parsed = property(line); |
| 44 | + if (!parsed) continue; |
| 45 | + if (event) event[parsed.name] = parsed.value; |
| 46 | + if (parsed.name === 'X-WR-CALNAME') groupName = unescapeIcal(parsed.value); |
| 47 | + } |
| 48 | + |
| 49 | + return { events, groupName }; |
| 50 | +} |
| 51 | + |
| 52 | +function date(value, field, url) { |
| 53 | + const match = value?.match(/^(\d{4})(\d{2})(\d{2})/); |
| 54 | + if (!match) throw new Error(`Meetup event ${url} has no valid ${field}.`); |
| 55 | + return `${match[1]}-${match[2]}-${match[3]}`; |
| 56 | +} |
| 57 | + |
| 58 | +function eventId(event, url) { |
| 59 | + const match = event.UID?.match(/^event_(.+?)@meetup\.com$/); |
| 60 | + if (match) return match[1]; |
| 61 | + const urlMatch = url.match(/\/events\/([^/?#]+)/); |
| 62 | + if (urlMatch) return urlMatch[1]; |
| 63 | + throw new Error(`Meetup calendar event has no recognized ID: ${url}`); |
| 64 | +} |
| 65 | + |
| 66 | +function eventSchema(html, url) { |
| 67 | + const scripts = [...html.matchAll(/<script[^>]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi)]; |
| 68 | + for (const [, script] of scripts) { |
| 69 | + const value = JSON.parse(script); |
| 70 | + const candidates = Array.isArray(value) ? value : value['@graph'] ?? [value]; |
| 71 | + const event = candidates.find(({ '@type': type }) => type === 'Event'); |
| 72 | + if (event) return event; |
| 73 | + } |
| 74 | + throw new Error(`Meetup event page has no Event structured data: ${url}`); |
| 75 | +} |
| 76 | + |
| 77 | +function eventMetadata(event) { |
| 78 | + const virtual = /(?:Online|Mixed)EventAttendanceMode$/.test(event.eventAttendanceMode ?? ''); |
| 79 | + const locations = Array.isArray(event.location) ? event.location : [event.location].filter(Boolean); |
| 80 | + const place = locations.find(({ '@type': type }) => type === 'Place'); |
| 81 | + |
| 82 | + if (!place) return { virtual, where: virtual ? 'Online' : '' }; |
| 83 | + |
| 84 | + const address = place.address; |
| 85 | + const addressParts = typeof address === 'string' |
| 86 | + ? [address] |
| 87 | + : [address?.streetAddress, address?.addressLocality, address?.addressRegion, address?.addressCountry]; |
| 88 | + const where = [place.name, ...addressParts].filter(Boolean).reduce( |
| 89 | + (parts, part) => parts.some((existing) => existing.toLowerCase().includes(part.toLowerCase())) ? parts : [...parts, part], |
| 90 | + [], |
| 91 | + ).join(', '); |
| 92 | + return { virtual, where }; |
| 93 | +} |
| 94 | + |
| 95 | +function eventFile(event, metadata, groupName) { |
| 96 | + const url = event.URL; |
| 97 | + if (!url) throw new Error('Meetup calendar event has no URL.'); |
| 98 | + |
| 99 | + const startDate = date(event.DTSTART, 'start date', url); |
| 100 | + const endDate = event.DTEND ? date(event.DTEND, 'end date', url) : undefined; |
| 101 | + const endDateField = endDate && endDate !== startDate ? `endDate: ${yaml(endDate)}\n` : ''; |
| 102 | + const description = unescapeIcal(event.DESCRIPTION).trim(); |
| 103 | + |
| 104 | + return `---\nmeetupEventId: ${yaml(eventId(event, url))}\nmeetupSource: meetup\nstartDate: ${yaml(startDate)}\n${endDateField}title: ${yaml(unescapeIcal(event.SUMMARY))}\nexternalUrl: ${yaml(url)}\nvirtual: ${metadata.virtual}\nwhere: ${yaml(metadata.where || groupName)}\n---\n${description}\n`; |
| 105 | +} |
| 106 | + |
| 107 | +async function groups() { |
| 108 | + const parsed = JSON.parse(await readFile(GROUPS_FILE, 'utf8')); |
| 109 | + if (!Array.isArray(parsed) || !parsed.every((group) => group && typeof group === 'object' && typeof group.urlname === 'string' && group.urlname)) { |
| 110 | + throw new Error(`${GROUPS_FILE} must be an array of Meetup group objects with a urlname.`); |
| 111 | + } |
| 112 | + return parsed; |
| 113 | +} |
| 114 | + |
| 115 | +async function fetchGroupEvents(urlname) { |
| 116 | + const response = await fetch(`https://www.meetup.com/${urlname}/events/ical/`); |
| 117 | + if (!response.ok) throw new Error(`Meetup iCalendar feed returned ${response.status} for ${urlname}.`); |
| 118 | + |
| 119 | + const calendar = eventsFromIcal(await response.text()); |
| 120 | + const events = await Promise.all(calendar.events.map(async (event) => { |
| 121 | + if (event.STATUS === 'CANCELLED') return { event }; |
| 122 | + if (!event.URL || !event.DTSTART || !event.SUMMARY) { |
| 123 | + throw new Error(`Meetup calendar event for ${urlname} is missing required fields.`); |
| 124 | + } |
| 125 | + |
| 126 | + const page = await fetch(event.URL); |
| 127 | + if (!page.ok) throw new Error(`Meetup event page returned ${page.status}: ${event.URL}`); |
| 128 | + return { event, metadata: eventMetadata(eventSchema(await page.text(), event.URL)) }; |
| 129 | + })); |
| 130 | + |
| 131 | + return { events, groupName: calendar.groupName || urlname }; |
| 132 | +} |
| 133 | + |
| 134 | +async function calendarFiles() { |
| 135 | + const names = await readdir(CALENDAR_DIR); |
| 136 | + return Promise.all(names.filter((name) => name.endsWith('.md')).map(async (name) => ({ |
| 137 | + file: path.join(CALENDAR_DIR, name), |
| 138 | + content: await readFile(path.join(CALENDAR_DIR, name), 'utf8'), |
| 139 | + }))); |
| 140 | +} |
| 141 | + |
| 142 | +async function main() { |
| 143 | + const configuredGroups = await groups(); |
| 144 | + const groupEvents = await Promise.all(configuredGroups.map(({ urlname }) => fetchGroupEvents(urlname))); |
| 145 | + await mkdir(CALENDAR_DIR, { recursive: true }); |
| 146 | + |
| 147 | + const calendar = await calendarFiles(); |
| 148 | + const managed = new Set(calendar.filter(({ content }) => content.includes('meetupSource: meetup')).map(({ file }) => file)); |
| 149 | + const manualUrls = new Set(calendar |
| 150 | + .filter(({ content }) => !content.includes('meetupSource: meetup')) |
| 151 | + .map(({ content }) => content.match(/^externalUrl:\s*["']?([^\s"']+)/m)?.[1]) |
| 152 | + .filter(Boolean)); |
| 153 | + const desired = new Map(); |
| 154 | + |
| 155 | + for (const { events, groupName } of groupEvents) { |
| 156 | + for (const { event, metadata } of events) { |
| 157 | + if (event.STATUS === 'CANCELLED' || manualUrls.has(event.URL)) continue; |
| 158 | + desired.set(path.join(CALENDAR_DIR, `meetup-${eventId(event, event.URL)}.md`), eventFile(event, metadata, groupName)); |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + const changes = []; |
| 163 | + for (const [file, content] of desired) { |
| 164 | + const current = calendar.find((entry) => entry.file === file)?.content; |
| 165 | + if (current !== content) { |
| 166 | + changes.push(`${current === undefined ? 'add' : 'update'} ${file}`); |
| 167 | + if (!DRY_RUN) await writeFile(file, content); |
| 168 | + } |
| 169 | + managed.delete(file); |
| 170 | + } |
| 171 | + |
| 172 | + for (const file of managed) { |
| 173 | + changes.push(`remove ${file}`); |
| 174 | + if (!DRY_RUN) await rm(file); |
| 175 | + } |
| 176 | + |
| 177 | + console.log(changes.length ? changes.join('\n') : 'Meetup events are already synchronized.'); |
| 178 | +} |
| 179 | + |
| 180 | +main().catch((error) => { |
| 181 | + console.error(error.message); |
| 182 | + process.exitCode = 1; |
| 183 | +}); |
0 commit comments