Skip to content

Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.

Calendar link: a big feed no longer freezes the app (#79): parsed once per fetch, without ical.js scanning the whole feed per event, and a week of occurrences kept for the next reads

christianmat1a91926c03da
diff --git a/app/src/main/calendarLink/ics.ts b/app/src/main/calendarLink/ics.ts
index f094a7bf..9cbeb927 100644
--- a/app/src/main/calendarLink/ics.ts
+++ b/app/src/main/calendarLink/ics.ts
@@ -53,48 +53,84 @@ function people(c: ICAL.Component, me: string | null): RawEvent['attendees'] {
return out
}
-/** Events that overlap [fromMs, toMs), all-day and cancelled ones left out. A feed that isn't iCal throws. */
-export function icsEvents(text: string, fromMs: number, toMs: number, link: LinkRef): RawEvent[] {
+/** how far either side of a read the occurrences are worked out at once, so the next reads (each minute) reuse them */
+const SPAN_MS = 7 * 86_400_000
+
+/**
+ * A feed parsed once (#79: parsing it on every read froze the app with a years-long work calendar). Its events between
+ * two times; occurrences are worked out for a week either side and kept, so call detection and the agenda read from
+ * memory. Throws when the text isn't iCal.
+ */
+export function icsFeed(text: string, link: LinkRef) {
const root = parse(text)
- const { me } = icsName(text)
+ const name = prop(root, 'x-wr-calname')
+ const me = name && /^[^\s@]+@[^\s@]+$/.test(name) ? name.toLowerCase() : null
const masters = new Map<string, ICAL.Event>()
const exceptions: ICAL.Component[] = []
for (const v of root.getAllSubcomponents('vevent')) {
const uid = prop(v, 'uid')
if (!uid) continue
+ // exceptions: [] stops ical.js looking through the whole feed for each event's moved copies (quadratic: thousands of
+ // events took seconds); they're tied to their event just below
if (v.hasProperty('recurrence-id')) exceptions.push(v)
- else masters.set(uid, new ICAL.Event(v))
+ else masters.set(uid, new ICAL.Event(v, { exceptions: [] }))
}
// a moved or changed occurrence belongs to its recurring event; one whose event isn't in the feed stands alone
const lone: ICAL.Event[] = []
for (const x of exceptions) {
const master = masters.get(prop(x, 'uid')!)
if (master) master.relateException(x)
- else lone.push(new ICAL.Event(x))
+ else lone.push(new ICAL.Event(x, { exceptions: [] }))
}
+ const items = [...masters.values(), ...lone]
- const out: RawEvent[] = []
- const add = (item: ICAL.Event, start: ICAL.Time, end: ICAL.Time) => {
- if (start.isDate) return
- if ((prop(item.component, 'status') ?? '').toUpperCase() === 'CANCELLED') return
- const s = start.toJSDate().getTime(), e = end.toJSDate().getTime()
- if (!(s < toMs && e > fromMs)) return
- const uid = item.uid
- out.push({
- id: `${uid}|${new Date(s).toISOString()}`, externalId: uid, title: item.summary ?? '',
- start: new Date(s).toISOString(), end: new Date(e).toISOString(), attendees: people(item.component, me),
- url: prop(item.component, 'url') ?? prop(item.component, 'x-google-conference'), location: item.location || null, notes: item.description || null,
- calendarId: link.id, calendar: link.name, calendarSource: 'Calendar link', me,
- })
- }
- for (const ev of [...masters.values(), ...lone]) {
- if (!ev.isRecurring()) { add(ev, ev.startDate, ev.endDate); continue }
- const it = ev.iterator()
- for (let i = 0, next = it.next(); next && i < MAX_STEPS; i++, next = it.next()) {
- if (next.toJSDate().getTime() >= toMs) break
- const d = ev.getOccurrenceDetails(next)
- add(d.item, d.startDate, d.endDate)
+ function expand(fromMs: number, toMs: number): RawEvent[] {
+ const out: RawEvent[] = []
+ const add = (item: ICAL.Event, start: ICAL.Time, end: ICAL.Time) => {
+ if (start.isDate) return
+ if ((prop(item.component, 'status') ?? '').toUpperCase() === 'CANCELLED') return
+ const s = start.toJSDate().getTime(), e = end.toJSDate().getTime()
+ if (!(s < toMs && e > fromMs)) return
+ const uid = item.uid
+ out.push({
+ id: `${uid}|${new Date(s).toISOString()}`, externalId: uid, title: item.summary ?? '',
+ start: new Date(s).toISOString(), end: new Date(e).toISOString(), attendees: people(item.component, me),
+ url: prop(item.component, 'url') ?? prop(item.component, 'x-google-conference'), location: item.location || null, notes: item.description || null,
+ calendarId: link.id, calendar: link.name, calendarSource: 'Calendar link', me,
+ })
}
+ for (const ev of items) {
+ if (!ev.isRecurring()) { add(ev, ev.startDate, ev.endDate); continue }
+ // working out an occurrence (its moved copy, its end) is the slow part: only for ones that can reach the window
+ const lasts = ev.duration.toSeconds() * 1000
+ const moved = new Set(Object.keys(ev.exceptions))
+ const it = ev.iterator()
+ for (let i = 0, next = it.next(); next && i < MAX_STEPS; i++, next = it.next()) {
+ const at = next.toJSDate().getTime()
+ if (at >= toMs && !moved.has(next.toString())) break
+ if (at + lasts <= fromMs && !moved.has(next.toString())) continue
+ const d = ev.getOccurrenceDetails(next)
+ add(d.item, d.startDate, d.endDate)
+ }
+ }
+ return out
+ }
+
+ let kept: { fromMs: number; toMs: number; events: RawEvent[] } | null = null
+ return {
+ /** Events that overlap [fromMs, toMs), all-day and cancelled ones left out */
+ events(fromMs: number, toMs: number): RawEvent[] {
+ if (!kept || fromMs < kept.fromMs || toMs > kept.toMs) {
+ const from = fromMs - SPAN_MS, to = toMs + SPAN_MS
+ kept = { fromMs: from, toMs: to, events: expand(from, to) }
+ }
+ return kept.events.filter((e) => Date.parse(e.start) < toMs && Date.parse(e.end) > fromMs).sort((a, b) => a.start.localeCompare(b.start))
+ },
}
- return out.sort((a, b) => a.start.localeCompare(b.start))
+}
+export type IcsFeed = ReturnType<typeof icsFeed>
+
+/** Events that overlap [fromMs, toMs), all-day and cancelled ones left out. A feed that isn't iCal throws. */
+export function icsEvents(text: string, fromMs: number, toMs: number, link: LinkRef): RawEvent[] {
+ return icsFeed(text, link).events(fromMs, toMs)
}
diff --git a/app/src/main/calendarLink/index.ts b/app/src/main/calendarLink/index.ts
index 011578ff..e9cfde4d 100644
--- a/app/src/main/calendarLink/index.ts
+++ b/app/src/main/calendarLink/index.ts
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto'
import { loadSettings, updateSettings } from '../settings'
-import { icsEvents, icsName, type RawEvent } from './ics'
+import { icsFeed, icsName, type IcsFeed, type RawEvent } from './ics'
/**
* Calendar links: Windows and Linux have no system calendar Yogurt can read, so the person pastes their calendar's
@@ -34,24 +34,27 @@ export function createCalendarLinks(d: {
now?: () => number
}) {
const now = d.now ?? Date.now
- const cache = new Map<string, { text: string; at: number }>()
+ // the feed is kept parsed with its text (#79: parsing it on every read, each minute, froze the app)
+ const cache = new Map<string, { text: string; at: number; feed?: IcsFeed }>()
const stored = (): Stored[] => loadSettings(d.file).calendarLinks ?? []
const urlOf = (l: Stored) => { try { return d.open(l.url) } catch { return null } }
/** the feed's text: the cached copy for five minutes, a fresh one after, the last good copy when that fails */
- async function text(l: Stored): Promise<string | null> {
+ async function feed(l: Stored): Promise<IcsFeed | null> {
const hit = cache.get(l.id)
- if (hit && now() - hit.at < REFRESH_MS) return hit.text
+ const parsed = (c: { text: string; feed?: IcsFeed }) => (c.feed ??= icsFeed(c.text, { id: l.id, name: l.name }))
+ if (hit && now() - hit.at < REFRESH_MS) return parsed(hit)
const url = urlOf(l)
- if (!url) return hit?.text ?? null
+ const last = () => (hit ? parsed(hit) : null)
+ if (!url) return last()
try {
const t = await d.get(url)
- icsName(t)
- cache.set(l.id, { text: t, at: now() })
- return t
+ const entry = { text: t, at: now(), feed: icsFeed(t, { id: l.id, name: l.name }) }
+ cache.set(l.id, entry)
+ return entry.feed
} catch (e) {
console.warn('calendar link: could not read', l.host, e instanceof Error ? e.message : e)
- return hit?.text ?? null
+ return last()
}
}
@@ -84,9 +87,10 @@ export function createCalendarLinks(d: {
/** every link's events between two times; a link that can't be read gives none, never an error */
async events(fromMs: number, toMs: number): Promise<RawEvent[]> {
const all = await Promise.all(stored().map(async (l) => {
- const t = await text(l)
- if (!t) return []
- try { return icsEvents(t, fromMs, toMs, { id: l.id, name: l.name }) } catch { return [] }
+ try {
+ const f = await feed(l)
+ return f ? f.events(fromMs, toMs) : []
+ } catch { return [] }
}))
return all.flat()
},
diff --git a/app/test/calendarLinkIcs.test.ts b/app/test/calendarLinkIcs.test.ts
index d2a15deb..cee81114 100644
--- a/app/test/calendarLinkIcs.test.ts
+++ b/app/test/calendarLinkIcs.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from 'vitest'
-import { icsEvents, icsName } from '../src/main/calendarLink/ics'
+import ICAL from 'ical.js'
+import { describe, expect, it, vi } from 'vitest'
+import { icsEvents, icsFeed, icsName } from '../src/main/calendarLink/ics'
// A made-up feed in the shape Google's "Secret address in iCal format" gives: its own time zone, attendees, a Meet link
const feed = (events: string) => `BEGIN:VCALENDAR
@@ -106,4 +107,43 @@ describe('a calendar link: events from an iCal feed, in the shape the Mac helper
it('a feed that is not a calendar is an error, not an empty week', () => {
expect(() => icsEvents('<html>Sign in</html>', 0, 1, link)).toThrow()
})
+
+ // #79: a work calendar with years of recurring meetings froze the app, every read walking each series from its start
+ const years = `BEGIN:VEVENT
+SUMMARY:Standup
+DTSTART:20190107T170000Z
+DTEND:20190107T171500Z
+RRULE:FREQ=DAILY
+END:VEVENT
+BEGIN:VEVENT
+RECURRENCE-ID:20261116T170000Z
+SUMMARY:Standup (moved)
+DTSTART:20261117T190000Z
+DTEND:20261117T191500Z
+END:VEVENT`
+ it('a series that has run for years: occurrences long before the window are not worked out one by one, and one moved into it still shows', () => {
+ const details = vi.spyOn(ICAL.Event.prototype, 'getOccurrenceDetails')
+ const got = icsEvents(feed(years), at('2026-11-17T00:00:00Z'), at('2026-11-18T00:00:00Z'), link)
+ expect(got.map((e) => [e.title, e.start])).toEqual([['Standup', '2026-11-17T17:00:00.000Z'], ['Standup (moved)', '2026-11-17T19:00:00.000Z']])
+ // the window and a week either side (kept for the next reads): about 15 of a daily series, not all ~2,900 since 2019
+ expect(details.mock.calls.length).toBeLessThan(20)
+ details.mockRestore()
+ })
+ it('building a feed of many events does not look through the whole feed once per event (thousands of events took seconds)', () => {
+ const many = Array.from({ length: 50 }, (_, i) => `BEGIN:VEVENT\nUID:one-${i}@example.com\nSUMMARY:One ${i}\nDTSTART:20190101T1000${String(i).padStart(2, '0')}Z\nDTEND:20190101T1100${String(i).padStart(2, '0')}Z\nEND:VEVENT`).join('\n')
+ const scans = vi.spyOn(ICAL.Component.prototype, 'getAllSubcomponents')
+ icsFeed(feed(`${years}\n${many}`), link)
+ expect(scans.mock.calls.length).toBeLessThan(10)
+ scans.mockRestore()
+ })
+ it('a feed is parsed once, however many windows are read from it', () => {
+ const parse = vi.spyOn(ICAL, 'parse')
+ const f = icsFeed(feed(years), link)
+ for (let d = 15; d <= 19; d++) f.events(at(`2026-11-${d}T00:00:00Z`), at(`2026-11-${d + 1}T00:00:00Z`))
+ expect(f.events(at('2026-11-17T00:00:00Z'), at('2026-11-18T00:00:00Z')).map((e) => e.title)).toEqual(['Standup', 'Standup (moved)'])
+ expect(parse).toHaveBeenCalledTimes(1)
+ parse.mockRestore()
+ })
})
diff --git a/app/test/calendarLinks.test.ts b/app/test/calendarLinks.test.ts
index 45632759..0a68e665 100644
--- a/app/test/calendarLinks.test.ts
+++ b/app/test/calendarLinks.test.ts
@@ -1,7 +1,8 @@
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { afterEach, describe, expect, it } from 'vitest'
+import ICAL from 'ical.js'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { createCalendarLinks } from '../src/main/calendarLink'
const ics = (name: string) => `BEGIN:VCALENDAR\nVERSION:2.0\nX-WR-CALNAME:${name}\nBEGIN:VEVENT\nUID:[email protected]\nSUMMARY:Standup\nDTSTART:20261117T170000Z\nDTEND:20261117T171500Z\nEND:VEVENT\nEND:VCALENDAR\n`
@@ -61,6 +62,14 @@ describe('calendar links (Windows and Linux): a private calendar address, kept o
expect((await r.links.events(...day)).map((e) => e.title)).toEqual(['Standup'])
expect(r.fetched).toHaveLength(2)
})
+ it('reading the calendar again and again (call detection, the agenda) reuses the parsed feed until it is fetched again', async () => {
+ const r = rig(() => ics('Team'))
+ await r.links.add('https://calendar.google.com/calendar/ical/team/private-x/basic.ics')
+ const parse = vi.spyOn(ICAL, 'parse')
+ for (let i = 0; i < 5; i++) await r.links.events(...day)
+ expect(parse.mock.calls.length).toBeLessThanOrEqual(1)
+ parse.mockRestore()
+ })
it('removing the last address leaves no calendar', async () => {
const r = rig(() => ics('Work'))
const got = await r.links.add('https://example.com/cal.ics')