Skip to content

A platform for community discussion. Free, open, simple.

FIX: Add VTIMEZONE definitions to ICS downloads (#43168)

Ethan Md9d228a96c0f
diff --git a/frontend/discourse/app/lib/download-calendar.js b/frontend/discourse/app/lib/download-calendar.js
index 93a540e86cc..a155f0ee143 100644
--- a/frontend/discourse/app/lib/download-calendar.js
+++ b/frontend/discourse/app/lib/download-calendar.js
@@ -194,6 +194,161 @@ function _allDayMoments(date) {
return { startDate, endDate };
}
+const ICAL_WEEKDAYS = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
+
+function _formatIcsUtcOffset(offsetMinutes) {
+ const totalSeconds = Math.round(offsetMinutes * 60);
+ const sign = totalSeconds < 0 ? "-" : "+";
+ const absoluteSeconds = Math.abs(totalSeconds);
+ const hours = Math.floor(absoluteSeconds / 3600);
+ const minutes = Math.floor((absoluteSeconds % 3600) / 60);
+ const seconds = absoluteSeconds % 60;
+
+ return (
+ sign +
+ String(hours).padStart(2, "0") +
+ String(minutes).padStart(2, "0") +
+ (seconds ? String(seconds).padStart(2, "0") : "")
+ );
+}
+
+function _vTimezoneTransition(zone, index) {
+ const transitionAt = zone.untils[index];
+ const offsetFrom = -zone.offsets[index];
+ const offsetTo = -zone.offsets[index + 1];
+ const localStart = moment.utc(transitionAt).utcOffset(offsetFrom);
+ const day = localStart.date();
+ const ordinal = day + 7 > localStart.daysInMonth() ? -1 : Math.ceil(day / 7);
+
+ return {
+ localStart: localStart.format("YYYYMMDDTHHmmss"),
+ month: localStart.month() + 1,
+ byDay: `${ordinal}${ICAL_WEEKDAYS[localStart.day()]}`,
+ offsetFrom,
+ offsetTo,
+ name: zone.abbrs[index + 1],
+ };
+}
+
+function _sameVTimezoneRule(a, b) {
+ return (
+ a.month === b.month &&
+ a.byDay === b.byDay &&
+ a.localStart.slice(8) === b.localStart.slice(8) &&
+ a.offsetFrom === b.offsetFrom &&
+ a.offsetTo === b.offsetTo
+ );
+}
+
+function _renderVTimezoneObservance(observance) {
+ const type =
+ observance.offsetTo > observance.offsetFrom ? "DAYLIGHT" : "STANDARD";
+ const lines = [
+ `BEGIN:${type}`,
+ `DTSTART:${observance.localStart}`,
+ `RRULE:FREQ=YEARLY;BYMONTH=${observance.month};BYDAY=${observance.byDay}`,
+ `TZOFFSETFROM:${_formatIcsUtcOffset(observance.offsetFrom)}`,
+ `TZOFFSETTO:${_formatIcsUtcOffset(observance.offsetTo)}`,
+ ];
+
+ if (observance.name) {
+ lines.push(`TZNAME:${_escapeIcsValue(observance.name)}`);
+ }
+
+ lines.push(`END:${type}`);
+
+ return lines.map(_foldLine).join("\r\n") + "\r\n";
+}
+
+function _fixedVTimezone(timezone, referenceMs) {
+ const reference = moment.tz(referenceMs, timezone);
+ const offset = reference.utcOffset();
+ const start = reference
+ .clone()
+ .subtract(1, "year")
+ .startOf("year")
+ .format("YYYYMMDDTHHmmss");
+
+ return (
+ "BEGIN:VTIMEZONE\r\n" +
+ _foldLine(`TZID:${timezone}`) +
+ "\r\n" +
+ "BEGIN:STANDARD\r\n" +
+ `DTSTART:${start}\r\n` +
+ `TZOFFSETFROM:${_formatIcsUtcOffset(offset)}\r\n` +
+ `TZOFFSETTO:${_formatIcsUtcOffset(offset)}\r\n` +
+ _foldLine(`TZNAME:${_escapeIcsValue(reference.zoneAbbr())}`) +
+ "\r\n" +
+ "END:STANDARD\r\n" +
+ "END:VTIMEZONE\r\n"
+ );
+}
+
+function _generateVTimezone(timezone, referenceMs) {
+ const zone = moment.tz.zone(timezone);
+
+ if (!zone) {
+ return "";
+ }
+
+ let previousIndex = -1;
+ let nextIndex = -1;
+
+ for (let i = 0; i < zone.untils.length - 1; i++) {
+ const transitionAt = zone.untils[i];
+
+ if (!Number.isFinite(transitionAt)) {
+ break;
+ }
+
+ if (transitionAt <= referenceMs) {
+ previousIndex = i;
+ } else {
+ nextIndex = i;
+ break;
+ }
+ }
+
+ if (previousIndex === -1 || nextIndex === -1) {
+ return _fixedVTimezone(timezone, referenceMs);
+ }
+
+ const previous = _vTimezoneTransition(zone, previousIndex);
+ const next = _vTimezoneTransition(zone, nextIndex);
+ const followingPreviousIndex = previousIndex + 2;
+ const followingNextIndex = nextIndex + 2;
+
+ // A current seasonal pair reverses the same two UTC offsets and repeats
+ // the same calendar rules in the following cycle. Otherwise, use the
+ // current fixed offset rather than inventing an open-ended yearly rule.
+ if (
+ previous.offsetFrom !== next.offsetTo ||
+ previous.offsetTo !== next.offsetFrom ||
+ followingNextIndex >= zone.untils.length - 1
+ ) {
+ return _fixedVTimezone(timezone, referenceMs);
+ }
+
+ const followingPrevious = _vTimezoneTransition(zone, followingPreviousIndex);
+ const followingNext = _vTimezoneTransition(zone, followingNextIndex);
+
+ if (
+ !_sameVTimezoneRule(previous, followingPrevious) ||
+ !_sameVTimezoneRule(next, followingNext)
+ ) {
+ return _fixedVTimezone(timezone, referenceMs);
+ }
+
+ return (
+ "BEGIN:VTIMEZONE\r\n" +
+ _foldLine(`TZID:${timezone}`) +
+ "\r\n" +
+ _renderVTimezoneObservance(previous) +
+ _renderVTimezoneObservance(next) +
+ "END:VTIMEZONE\r\n"
+ );
+}
+
/**
* Generate ICS calendar data for the given dates
*
@@ -205,6 +360,37 @@ function _allDayMoments(date) {
export function generateIcsData(title, dates, options = {}) {
let data = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Discourse//EN\r\n";
const parsedRrule = _parseRRule(options.rrule);
+
+ const timezoneStarts = new Map();
+
+ for (const date of dates) {
+ if (date.allDay) {
+ continue;
+ }
+
+ const timezone = date.timezone || options.timezone;
+
+ if (!timezone || !moment.tz.zone(timezone)) {
+ continue;
+ }
+
+ const startsAt = moment.tz(date.startsAt, timezone);
+
+ if (!startsAt.isValid()) {
+ continue;
+ }
+
+ const existing = timezoneStarts.get(timezone);
+
+ if (existing === undefined || startsAt.valueOf() < existing) {
+ timezoneStarts.set(timezone, startsAt.valueOf());
+ }
+ }
+
+ for (const [timezone, startsAt] of timezoneStarts) {
+ data += _generateVTimezone(timezone, startsAt);
+ }
+
dates.forEach((date) => {
let rrule = parsedRrule;
diff --git a/frontend/discourse/tests/unit/lib/download-calendar-test.js b/frontend/discourse/tests/unit/lib/download-calendar-test.js
index 629be4019ce..c825c490e84 100644
--- a/frontend/discourse/tests/unit/lib/download-calendar-test.js
+++ b/frontend/discourse/tests/unit/lib/download-calendar-test.js
@@ -51,6 +51,178 @@ module("Unit | Utility | download-calendar", function (hooks) {
assert.true(data.includes("END:VCALENDAR"));
});
+ test("timezone ICS includes a VTIMEZONE definition", function (assert) {
+ const data = generateIcsData("testevent 2", [
+ {
+ startsAt: "2026-08-11T15:00:00.000Z",
+ endsAt: "2026-08-11T17:15:00.000Z",
+ timezone: "Europe/Berlin",
+ },
+ ]);
+
+ assert.true(
+ data.includes(
+ [
+ "BEGIN:VTIMEZONE",
+ "TZID:Europe/Berlin",
+ "BEGIN:DAYLIGHT",
+ "DTSTART:20260329T020000",
+ "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU",
+ "TZOFFSETFROM:+0100",
+ "TZOFFSETTO:+0200",
+ "TZNAME:CEST",
+ "END:DAYLIGHT",
+ ].join("\r\n")
+ ),
+ "includes the Berlin daylight-saving observance"
+ );
+ assert.true(
+ data.includes(
+ [
+ "BEGIN:STANDARD",
+ "DTSTART:20261025T030000",
+ "RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU",
+ "TZOFFSETFROM:+0200",
+ "TZOFFSETTO:+0100",
+ "TZNAME:CET",
+ "END:STANDARD",
+ "END:VTIMEZONE",
+ ].join("\r\n")
+ ),
+ "includes the Berlin standard-time observance"
+ );
+ assert.true(data.includes("DTSTART;TZID=Europe/Berlin:20260811T170000"));
+ assert.true(data.includes("DTEND;TZID=Europe/Berlin:20260811T191500"));
+ });
+
+ test("VTIMEZONE supports North American DST rules", function (assert) {
+ const data = generateIcsData("New York event", [
+ {
+ startsAt: "2026-07-15T16:00:00.000Z",
+ endsAt: "2026-07-15T17:00:00.000Z",
+ timezone: "America/New_York",
+ },
+ ]);
+
+ assert.true(
+ data.includes(
+ [
+ "BEGIN:DAYLIGHT",
+ "DTSTART:20260308T020000",
+ "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU",
+ "TZOFFSETFROM:-0500",
+ "TZOFFSETTO:-0400",
+ "TZNAME:EDT",
+ "END:DAYLIGHT",
+ ].join("\r\n")
+ ),
+ "includes the New York daylight-saving observance"
+ );
+ assert.true(
+ data.includes(
+ [
+ "BEGIN:STANDARD",
+ "DTSTART:20261101T020000",
+ "RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU",
+ "TZOFFSETFROM:-0400",
+ "TZOFFSETTO:-0500",
+ "TZNAME:EST",
+ "END:STANDARD",
+ ].join("\r\n")
+ ),
+ "includes the New York standard-time observance"
+ );
+ assert.true(data.includes("DTSTART;TZID=America/New_York:20260715T120000"));
+ });
+
+ test("VTIMEZONE supports zones with a stable current offset", function (assert) {
+ const data = generateIcsData("Kolkata event", [
+ {
+ startsAt: "2026-08-11T12:00:00.000Z",
+ endsAt: "2026-08-11T13:00:00.000Z",
+ timezone: "Asia/Kolkata",
+ },
+ ]);
+
+ assert.true(data.includes("BEGIN:VTIMEZONE"));
+ assert.true(data.includes("TZID:Asia/Kolkata"));
+ assert.true(data.includes("BEGIN:STANDARD"));
+ assert.true(data.includes("TZOFFSETTO:+0530"));
+ assert.true(data.includes("TZNAME:IST"));
+ assert.false(data.includes("BEGIN:DAYLIGHT"));
+ assert.true(data.includes("DTSTART;TZID=Asia/Kolkata:20260811T173000"));
+ });
+
+ test("VTIMEZONE supports a zero standard UTC offset", function (assert) {
+ const data = generateIcsData("London event", [
+ {
+ startsAt: "2026-08-11T12:00:00.000Z",
+ endsAt: "2026-08-11T13:00:00.000Z",
+ timezone: "Europe/London",
+ },
+ ]);
+
+ assert.true(
+ data.includes(
+ [
+ "BEGIN:DAYLIGHT",
+ "DTSTART:20260329T010000",
+ "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU",
+ "TZOFFSETFROM:+0000",
+ "TZOFFSETTO:+0100",
+ "TZNAME:BST",
+ "END:DAYLIGHT",
+ ].join("\r\n")
+ ),
+ "includes the London daylight-saving observance"
+ );
+ assert.true(
+ data.includes(
+ [
+ "BEGIN:STANDARD",
+ "DTSTART:20261025T020000",
+ "RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU",
+ "TZOFFSETFROM:+0100",
+ "TZOFFSETTO:+0000",
+ "TZNAME:GMT",
+ "END:STANDARD",
+ ].join("\r\n")
+ ),
+ "includes the London standard-time observance"
+ );
+ assert.true(data.includes("DTSTART;TZID=Europe/London:20260811T130000"));
+ });
+
+ test("VTIMEZONE falls back to a fixed offset for irregular seasonal zones", function (assert) {
+ // Morocco's transitions follow Ramadan, so the calendar rule differs every
+ // year. There is no stable RRULE to emit; the current offset is used instead.
+ const data = generateIcsData("Casablanca event", [
+ {
+ startsAt: "2025-08-11T12:00:00.000Z",
+ endsAt: "2025-08-11T13:00:00.000Z",
+ timezone: "Africa/Casablanca",
+ },
+ ]);
+
+ assert.true(data.includes("TZID:Africa/Casablanca"));
+ assert.strictEqual(
+ data.match(/BEGIN:STANDARD/g).length,
+ 1,
+ "emits exactly one STANDARD observance"
+ );
+ assert.false(data.includes("BEGIN:DAYLIGHT"), "no DAYLIGHT observance");
+ assert.false(
+ /^RRULE:/m.test(data.split("BEGIN:VEVENT")[0]),
+ "no recurrence rule inside the VTIMEZONE"
+ );
+ assert.true(data.includes("TZOFFSETFROM:+0100"));
+ assert.true(data.includes("TZOFFSETTO:+0100"));
+ assert.true(
+ data.includes("DTSTART;TZID=Africa/Casablanca:20250811T130000"),
+ "event local time still uses the named timezone"
+ );
+ });
+
test("correct data for ICS without timezone (UTC)", function (assert) {
const now = moment.tz("2022-04-04 23:15", "Europe/Paris").valueOf();
sinon.useFakeTimers({
diff --git a/plugins/discourse-events/test/javascripts/unit/ics-generation-test.js b/plugins/discourse-events/test/javascripts/unit/ics-generation-test.js
index 00733098715..ded9cb5f08f 100644
--- a/plugins/discourse-events/test/javascripts/unit/ics-generation-test.js
+++ b/plugins/discourse-events/test/javascripts/unit/ics-generation-test.js
@@ -57,7 +57,7 @@ module("Unit | Events | ICS Generation", function () {
icsData.includes("DTEND;TZID=America/Los_Angeles:"),
"contains end time with TZID"
);
- assert.false(icsData.includes("DTSTART:"), "no UTC start time");
+ assert.false(/^DTSTART:\d{8}T\d{6}Z$/m.test(icsData), "no UTC start time");
assert.false(icsData.includes("20251201T120000Z"), "no Z suffix on times");
assert.true(icsData.includes("END:VEVENT"), "closes VEVENT");
assert.true(icsData.includes("END:VCALENDAR"), "closes VCALENDAR");