Skip to content

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

FIX: "add to calendar" not providing correct ics (#35886)

Sam6330409d4470
diff --git a/frontend/discourse/app/components/modal/download-calendar.gjs b/frontend/discourse/app/components/modal/download-calendar.gjs
index 0ecbf8f566e..2b8ca816c50 100644
--- a/frontend/discourse/app/components/modal/download-calendar.gjs
+++ b/frontend/discourse/app/components/modal/download-calendar.gjs
@@ -33,6 +33,7 @@ export default class DownloadCalendar extends Component {
rrule: this.args.model.calendar.rrule,
location: this.args.model.calendar.location,
details: this.args.model.calendar.details,
+ timezone: this.args.model.calendar.timezone,
}
);
} else {
@@ -43,6 +44,7 @@ export default class DownloadCalendar extends Component {
rrule: this.args.model.calendar.rrule,
location: this.args.model.calendar.location,
details: this.args.model.calendar.details,
+ timezone: this.args.model.calendar.timezone,
}
);
}
diff --git a/frontend/discourse/app/lib/bbcode-attributes.js b/frontend/discourse/app/lib/bbcode-attributes.js
new file mode 100644
index 00000000000..7ca08c7cd40
--- /dev/null
+++ b/frontend/discourse/app/lib/bbcode-attributes.js
@@ -0,0 +1,42 @@
+/**
+ * Encodes a string value for safe use in BBCode attributes.
+ *
+ * Converts strings to base64url format, replacing characters that have
+ * special meaning in BBCode ('+', '/', '=') with URL-safe alternatives
+ * ('-', '_', '~').
+ *
+ * @param {string} value - The string value to encode
+ * @returns {string} The base64url-encoded string
+ */
+export function bbcodeAttributeEncode(value) {
+ const utf8Bytes = new TextEncoder().encode(value);
+ const binaryString = Array.from(utf8Bytes, (byte) =>
+ String.fromCharCode(byte)
+ ).join("");
+ const base64 = btoa(binaryString);
+
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "~");
+}
+
+/**
+ * Decodes a base64url-encoded string from a BBCode attribute.
+ *
+ * Reverses the encoding performed by bbcodeAttributeEncode.
+ *
+ * @param {string} encodedValue - The base64url-encoded string to decode
+ * @returns {string} The decoded UTF-8 string
+ */
+export function bbcodeAttributeDecode(encodedValue) {
+ const base64 = encodedValue
+ .replace(/-/g, "+")
+ .replace(/_/g, "/")
+ .replace(/~/g, "=");
+
+ const binaryString = atob(base64);
+ const bytes = new Uint8Array(binaryString.length);
+ for (let i = 0; i < binaryString.length; i++) {
+ bytes[i] = binaryString.charCodeAt(i);
+ }
+
+ return new TextDecoder().decode(bytes);
+}
diff --git a/frontend/discourse/app/lib/download-calendar.js b/frontend/discourse/app/lib/download-calendar.js
index ff7b8d0db2c..6ec5ab60680 100644
--- a/frontend/discourse/app/lib/download-calendar.js
+++ b/frontend/discourse/app/lib/download-calendar.js
@@ -34,7 +34,7 @@ export function downloadIcs(title, dates, options = {}) {
a.href = window.URL.createObjectURL(file);
a.download = `${title.toLowerCase().replace(/[^\w]/g, "-")}.ics`;
a.click();
- setTimeout(() => window.URL.revokeObjectURL(file), REMOVE_FILE_AFTER); //remove file to avoid memory leaks
+ setTimeout(() => window.URL.revokeObjectURL(file), REMOVE_FILE_AFTER);
}
export function downloadGoogle(title, dates, options = {}) {
@@ -67,32 +67,159 @@ export function downloadGoogle(title, dates, options = {}) {
export function formatDates(dates) {
return dates.map((date) => {
- return {
+ const formatted = {
startsAt: date.startsAt,
endsAt: date.endsAt
? date.endsAt
: moment.utc(date.startsAt).add(1, "hours").format(),
};
+
+ // Preserve timezone if present
+ if (date.timezone) {
+ formatted.timezone = date.timezone;
+ }
+
+ return formatted;
});
}
+/**
+ * Escape special characters in ICS field values per RFC 5545
+ * - Backslashes must be escaped as \\
+ * - Newlines (CR, LF, CRLF) must be encoded as \n
+ * - Semicolons must be escaped as \;
+ * - Commas must be escaped as \,
+ *
+ * @param {string} value - The value to escape
+ * @returns {string} - The escaped value
+ */
+function _escapeIcsValue(value) {
+ return value
+ .replace(/\\/g, "\\\\")
+ .replace(/\r\n|\r|\n/g, "\\n")
+ .replace(/;/g, "\\;")
+ .replace(/,/g, "\\,");
+}
+
+/**
+ * Fold a line to comply with RFC 5545 line length limit (75 octets)
+ * Continuation lines start with a space
+ *
+ * @param {string} line - The line to fold
+ * @returns {string} - The folded line
+ */
+function _foldLine(line) {
+ const maxLength = 75;
+ if (line.length <= maxLength) {
+ return line;
+ }
+
+ const result = [];
+ let currentLine = line;
+
+ while (currentLine.length > maxLength) {
+ result.push(currentLine.substring(0, maxLength));
+ currentLine = " " + currentLine.substring(maxLength);
+ }
+ result.push(currentLine);
+
+ return result.join("\r\n");
+}
+
+/**
+ * Parse and extract the RRULE line from a string that may contain
+ * both DTSTART and RRULE (legacy format)
+ *
+ * @param {string} rruleString - The RRULE string (may include DTSTART)
+ * @returns {string|null} - The extracted RRULE value or null if invalid
+ */
+function _parseRRule(rruleString) {
+ if (!rruleString) {
+ return null;
+ }
+
+ const lines = rruleString.split(/\r?\n/);
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith("RRULE:")) {
+ return trimmed.substring(6);
+ } else if (/^FREQ=/i.test(trimmed)) {
+ return trimmed;
+ }
+ }
+
+ if (/^FREQ=/i.test(rruleString.trim())) {
+ return rruleString.trim();
+ }
+
+ return null;
+}
+
+/**
+ * Check if an RRULE string contains the required FREQ parameter
+ *
+ * @param {string} rrule - The RRULE string to check
+ * @returns {boolean} - True if FREQ is present
+ */
+function _hasFreq(rrule) {
+ return /FREQ=/i.test(rrule);
+}
+
+/**
+ * Generate ICS calendar data for the given dates
+ *
+ * @param {string} title - Event title
+ * @param {Array} dates - Array of date objects with startsAt, endsAt, and optional timezone
+ * @param {Object} options - Optional parameters (rrule, location, details, timezone)
+ * @returns {string} - ICS formatted calendar data
+ */
export function generateIcsData(title, dates, options = {}) {
- let data = "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//Discourse//EN\n";
+ let data = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Discourse//EN\r\n";
dates.forEach((date) => {
- const startDate = moment(date.startsAt);
- const endDate = moment(date.endsAt);
+ const timezone = date.timezone || options.timezone;
+ const startDate = timezone
+ ? moment.tz(date.startsAt, timezone)
+ : moment(date.startsAt);
+ const endDate = timezone
+ ? moment.tz(date.endsAt, timezone)
+ : moment(date.endsAt);
+ const rrule = _parseRRule(options.rrule);
+
+ // Format date-time based on whether we have timezone info
+ const formatDateTime = (momentObj) => {
+ return momentObj.format("YYYYMMDDTHHmmss");
+ };
+
+ const dtStartValue = timezone
+ ? `DTSTART;TZID=${timezone}:${formatDateTime(startDate)}`
+ : `DTSTART:${startDate.utc().format("YYYYMMDDTHHmmss")}Z`;
+
+ const dtEndValue = timezone
+ ? `DTEND;TZID=${timezone}:${formatDateTime(endDate)}`
+ : `DTEND:${endDate.utc().format("YYYYMMDDTHHmmss")}Z`;
data = data.concat(
- "BEGIN:VEVENT\n" +
- `UID:${startDate.utc().format("x")}_${endDate.format("x")}\n` +
- `DTSTAMP:${moment().utc().format("YMMDDTHHmmss")}Z\n` +
- `DTSTART:${startDate.utc().format("YMMDDTHHmmss")}Z\n` +
- `DTEND:${endDate.utc().format("YMMDDTHHmmss")}Z\n` +
- (options.rrule ? `RRULE:${options.rrule}\n` : ``) +
- (options.location ? `LOCATION:${options.location}\n` : ``) +
- (options.details ? `DESCRIPTION:${options.details}\n` : ``) +
- `SUMMARY:${title}\n` +
- "END:VEVENT\n"
+ "BEGIN:VEVENT\r\n" +
+ _foldLine(`UID:${startDate.valueOf()}_${endDate.valueOf()}`) +
+ "\r\n" +
+ _foldLine(`DTSTAMP:${moment().utc().format("YYYYMMDDTHHmmss")}Z`) +
+ "\r\n" +
+ _foldLine(dtStartValue) +
+ "\r\n" +
+ _foldLine(dtEndValue) +
+ "\r\n" +
+ (rrule && _hasFreq(rrule) ? _foldLine(`RRULE:${rrule}`) + "\r\n" : ``) +
+ (options.location
+ ? _foldLine(`LOCATION:${_escapeIcsValue(options.location)}`) + "\r\n"
+ : ``) +
+ (options.details
+ ? _foldLine(`DESCRIPTION:${_escapeIcsValue(options.details)}`) +
+ "\r\n"
+ : ``) +
+ _foldLine(`SUMMARY:${_escapeIcsValue(title)}`) +
+ "\r\n" +
+ "END:VEVENT\r\n"
);
});
data = data.concat("END:VCALENDAR");
@@ -109,6 +236,7 @@ function _displayModal(title, dates, options = {}) {
rrule: options.rrule,
location: options.location,
details: options.details,
+ timezone: options.timezone,
},
},
});
diff --git a/frontend/discourse/tests/unit/lib/bbcode-attributes-test.js b/frontend/discourse/tests/unit/lib/bbcode-attributes-test.js
new file mode 100644
index 00000000000..ae25410404f
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/bbcode-attributes-test.js
@@ -0,0 +1,148 @@
+import { module, test } from "qunit";
+import {
+ bbcodeAttributeDecode,
+ bbcodeAttributeEncode,
+} from "discourse/lib/bbcode-attributes";
+
+module("Unit | Utility | bbcode-attributes", function () {
+ test("bbcodeAttributeEncode converts string to base64url format", function (assert) {
+ const input = "Hello World";
+ const encoded = bbcodeAttributeEncode(input);
+
+ assert.true(encoded.length > 0, "produces non-empty output");
+ assert.false(encoded.includes("+"), "does not contain + character");
+ assert.false(encoded.includes("/"), "does not contain / character");
+ assert.false(encoded.includes("="), "does not contain = character");
+ });
+
+ test("bbcodeAttributeDecode reverses the encoding", function (assert) {
+ const original = "Hello World";
+ const encoded = bbcodeAttributeEncode(original);
+ const decoded = bbcodeAttributeDecode(encoded);
+
+ assert.strictEqual(
+ decoded,
+ original,
+ "decoded value matches original string"
+ );
+ });
+
+ test("handles UTF-8 characters correctly", function (assert) {
+ const testCases = [
+ "Hello 世界",
+ "Café ☕",
+ "Testing émojis 🎉🎊",
+ "Special chars: äöüß",
+ "Cyrillic: Привет",
+ "Arabic: مرحبا",
+ ];
+
+ testCases.forEach((testCase) => {
+ const encoded = bbcodeAttributeEncode(testCase);
+ const decoded = bbcodeAttributeDecode(encoded);
+
+ assert.strictEqual(
+ decoded,
+ testCase,
+ `UTF-8 characters preserved: "${testCase}"`
+ );
+ });
+ });
+
+ test("handles ICS calendar data", function (assert) {
+ const icsData = `BEGIN:VCALENDAR
+VERSION:2.0
+PRODID:-//Discourse//EN
+BEGIN:VEVENT
+UID:12345
+SUMMARY:Test Event
+DTSTART:20251201T120000Z
+DTEND:20251201T130000Z
+LOCATION:Test Location
+DESCRIPTION:Test Description
+END:VEVENT
+END:VCALENDAR`;
+
+ const encoded = bbcodeAttributeEncode(icsData);
+ const decoded = bbcodeAttributeDecode(encoded);
+
+ assert.strictEqual(decoded, icsData, "ICS data preserved through encoding");
+ assert.true(decoded.includes("BEGIN:VCALENDAR"), "contains VCALENDAR");
+ assert.true(decoded.includes("Test Event"), "contains event title");
+ });
+
+ test("handles empty strings", function (assert) {
+ const encoded = bbcodeAttributeEncode("");
+ const decoded = bbcodeAttributeDecode(encoded);
+
+ assert.strictEqual(decoded, "", "empty string is preserved");
+ });
+
+ test("handles long strings", function (assert) {
+ const longString = "A".repeat(10000);
+ const encoded = bbcodeAttributeEncode(longString);
+ const decoded = bbcodeAttributeDecode(encoded);
+
+ assert.strictEqual(
+ decoded.length,
+ 10000,
+ "long string length is preserved"
+ );
+ assert.strictEqual(decoded, longString, "long string content is preserved");
+ });
+
+ test("handles strings with special BBCode characters", function (assert) {
+ const testCases = [
+ "Text with [brackets]",
+ "Text with = equals",
+ "Text with + plus",
+ "Text with / slash",
+ "Text with ~tilde~",
+ "Mixed: [tag=value] with+special/chars~",
+ ];
+
+ testCases.forEach((testCase) => {
+ const encoded = bbcodeAttributeEncode(testCase);
+ const decoded = bbcodeAttributeDecode(encoded);
+
+ assert.strictEqual(
+ decoded,
+ testCase,
+ `Special characters preserved: "${testCase}"`
+ );
+ });
+ });
+
+ test("encoded output is URL-safe", function (assert) {
+ const testStrings = [
+ "Test with spaces",
+ "Test+with+plus",
+ "Test/with/slashes",
+ "Test=with=equals",
+ ];
+
+ testStrings.forEach((testString) => {
+ const encoded = bbcodeAttributeEncode(testString);
+
+ assert.false(
+ encoded.includes(" "),
+ `"${testString}" encoded without spaces`
+ );
+ assert.false(encoded.includes("+"), `"${testString}" encoded without +`);
+ assert.false(encoded.includes("/"), `"${testString}" encoded without /`);
+ assert.false(encoded.includes("="), `"${testString}" encoded without =`);
+ });
+ });
+
+ test("handles multiline strings", function (assert) {
+ const multiline = `Line 1
+Line 2
+Line 3`;
+
+ const encoded = bbcodeAttributeEncode(multiline);
+ const decoded = bbcodeAttributeDecode(encoded);
+
+ assert.strictEqual(decoded, multiline, "multiline text preserved");
+ assert.true(decoded.includes("\n"), "newlines preserved");
+ });
+});
diff --git a/frontend/discourse/tests/unit/lib/download-calendar-test.js b/frontend/discourse/tests/unit/lib/download-calendar-test.js
index bb6a1968a86..1908ae521f6 100644
--- a/frontend/discourse/tests/unit/lib/download-calendar-test.js
+++ b/frontend/discourse/tests/unit/lib/download-calendar-test.js
@@ -16,7 +16,42 @@ module("Unit | Utility | download-calendar", function (hooks) {
sinon.stub(win, "focus");
});
- test("correct data for ICS", function (assert) {
+ test("correct data for ICS with timezone", function (assert) {
+ const now = moment.tz("2022-04-04 23:15", "Europe/Paris").valueOf();
+ sinon.useFakeTimers({
+ now,
+ toFake: ["Date"],
+ shouldAdvanceTime: true,
+ shouldClearNativeTimers: true,
+ });
+ const data = generateIcsData(
+ "event test",
+ [
+ {
+ startsAt: "2021-10-12T15:00:00.000Z",
+ endsAt: "2021-10-12T16:00:00.000Z",
+ timezone: "Europe/Paris",
+ },
+ ],
+ {
+ rrule: "FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR",
+ location: "Paris",
+ details: "Good soup",
+ }
+ );
+
+ assert.true(data.includes("BEGIN:VCALENDAR"));
+ assert.true(data.includes("DTSTART;TZID=Europe/Paris:20211012T170000"));
+ assert.true(data.includes("DTEND;TZID=Europe/Paris:20211012T180000"));
+ assert.true(data.includes("RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR"));
+ assert.true(data.includes("LOCATION:Paris"));
+ assert.true(data.includes("DESCRIPTION:Good soup"));
+ assert.true(data.includes("SUMMARY:event test"));
+ assert.true(data.includes("END:VEVENT"));
+ assert.true(data.includes("END:VCALENDAR"));
+ });
+
+ test("correct data for ICS without timezone (UTC)", function (assert) {
const now = moment.tz("2022-04-04 23:15", "Europe/Paris").valueOf();
sinon.useFakeTimers({
now,
@@ -41,24 +76,38 @@ module("Unit | Utility | download-calendar", function (hooks) {
assert.strictEqual(
data,
- `BEGIN:VCALENDAR
-VERSION:2.0
-PRODID:-//Discourse//EN
-BEGIN:VEVENT
-UID:1634050800000_1634054400000
-DTSTAMP:20220404T211500Z
-DTSTART:20211012T150000Z
-DTEND:20211012T160000Z
-RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR
-LOCATION:Paris
-DESCRIPTION:Good soup
-SUMMARY:event test
-END:VEVENT
-END:VCALENDAR`
+ `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Discourse//EN\r\nBEGIN:VEVENT\r\nUID:1634050800000_1634054400000\r\nDTSTAMP:20220404T211500Z\r\nDTSTART:20211012T150000Z\r\nDTEND:20211012T160000Z\r\nRRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\r\nLOCATION:Paris\r\nDESCRIPTION:Good soup\r\nSUMMARY:event test\r\nEND:VEVENT\r\nEND:VCALENDAR`
);
});
- test("correct data for ICS when recurring event", function (assert) {
+ test("correct data for ICS when recurring event with timezone", function (assert) {
+ const now = moment.tz("2022-04-04 23:15", "Europe/Paris").valueOf();
+ sinon.useFakeTimers({
+ now,
+ toFake: ["Date"],
+ shouldAdvanceTime: true,
+ shouldClearNativeTimers: true,
+ });
+ const data = generateIcsData(
+ "event test",
+ [
+ {
+ startsAt: "2021-10-12T15:00:00.000Z",
+ endsAt: "2021-10-12T16:00:00.000Z",
+ timezone: "America/New_York",
+ },
+ ],
+ { rrule: "FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR" }
+ );
+
+ assert.true(data.includes("DTSTART;TZID=America/New_York:20211012T110000"));
+ assert.true(data.includes("DTEND;TZID=America/New_York:20211012T120000"));
+ assert.true(data.includes("RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR"));
+
+ sinon.restore();
+ });
+
+ test("correct data for ICS when recurring event without timezone", function (assert) {
const now = moment.tz("2022-04-04 23:15", "Europe/Paris").valueOf();
sinon.useFakeTimers({
now,
@@ -78,18 +127,7 @@ END:VCALENDAR`
);
assert.strictEqual(
data,
- `BEGIN:VCALENDAR
-VERSION:2.0
-PRODID:-//Discourse//EN
-BEGIN:VEVENT
-UID:1634050800000_1634054400000
-DTSTAMP:20220404T211500Z
-DTSTART:20211012T150000Z
-DTEND:20211012T160000Z
-RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR
-SUMMARY:event test
-END:VEVENT
-END:VCALENDAR`
+ `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Discourse//EN\r\nBEGIN:VEVENT\r\nUID:1634050800000_1634054400000\r\nDTSTAMP:20220404T211500Z\r\nDTSTART:20211012T150000Z\r\nDTEND:20211012T160000Z\r\nRRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\r\nSUMMARY:event test\r\nEND:VEVENT\r\nEND:VCALENDAR`
);
sinon.restore();
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/dates.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/dates.gjs
index f49760be5ca..28519d26a6c 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/dates.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/dates.gjs
@@ -6,6 +6,8 @@ import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import icon from "discourse/helpers/d-icon";
+import { bbcodeAttributeEncode } from "discourse/lib/bbcode-attributes";
+import { generateIcsData } from "discourse/lib/download-calendar";
import discourseLater from "discourse/lib/later";
import { applyLocalDates } from "discourse/lib/local-dates";
import { cook } from "discourse/lib/text";
@@ -99,6 +101,36 @@ export default class DiscoursePostEventDates extends Component {
return date.hour() || date.minute();
}
+ generateIcsForEvent() {
+ const event = this.args.event;
+ if (!event || !this.startsAt) {
+ return null;
+ }
+
+ const title = event.name || event.post?.topic?.title || "Event";
+ const startsAt = this.startsAt.toISOString();
+ const endsAt = this.endsAt
+ ? this.endsAt.toISOString()
+ : moment(this.startsAt).add(1, "hours").toISOString();
+
+ const dates = [{ startsAt, endsAt, timezone: this.timezone }];
+ const options = {};
+
+ if (event.rrule) {
+ options.rrule = event.rrule;
+ }
+
+ if (event.location) {
+ options.location = event.location;
+ }
+
+ if (event.description) {
+ options.details = event.description;
+ }
+
+ return generateIcsData(title, dates, options);
+ }
+
buildDateBBCode({ date, format, range }) {
const bbcode = {
date: date.format("YYYY-MM-DD"),
@@ -116,6 +148,11 @@ export default class DiscoursePostEventDates extends Component {
bbcode.range = range;
}
+ const icsData = this.generateIcsForEvent();
+ if (icsData) {
+ bbcode.ics = bbcodeAttributeEncode(icsData);
+ }
+
const content = Object.entries(bbcode)
.map(([key, value]) => `${key}=${value}`)
.join(" ");
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs
index 82ba0b4b4ff..8e560c5c805 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs
@@ -80,6 +80,7 @@ export default class DiscoursePostEventMoreMenu extends Component {
{
startsAt: event.startsAt,
endsAt: event.endsAt,
+ timezone: event.timezone,
},
],
{
diff --git a/plugins/discourse-calendar/test/javascripts/unit/ics-generation-test.js b/plugins/discourse-calendar/test/javascripts/unit/ics-generation-test.js
new file mode 100644
index 00000000000..b1fd81f5d41
--- /dev/null
+++ b/plugins/discourse-calendar/test/javascripts/unit/ics-generation-test.js
@@ -0,0 +1,621 @@
+import { module, test } from "qunit";
+import {
+ bbcodeAttributeDecode,
+ bbcodeAttributeEncode,
+} from "discourse/lib/bbcode-attributes";
+import { generateIcsData } from "discourse/lib/download-calendar";
+
+module("Unit | Discourse Calendar | ICS Generation", function () {
+ test("generates valid ICS data", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {};
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(icsData.includes("BEGIN:VCALENDAR"), "contains VCALENDAR");
+ assert.true(icsData.includes("VERSION:2.0"), "contains version");
+ assert.true(icsData.includes("BEGIN:VEVENT"), "contains VEVENT");
+ assert.true(icsData.includes("SUMMARY:Test Event"), "contains title");
+ assert.true(icsData.includes("DTSTART:"), "contains start time");
+ assert.true(icsData.includes("DTEND:"), "contains end time");
+ assert.true(icsData.includes("END:VEVENT"), "closes VEVENT");
+ assert.true(icsData.includes("END:VCALENDAR"), "closes VCALENDAR");
+ });
+
+ test("generates ICS data with timezone (TZID)", function (assert) {
+ const title = "Test Event with Timezone";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ timezone: "America/Los_Angeles",
+ },
+ ];
+ const options = {};
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(icsData.includes("BEGIN:VCALENDAR"), "contains VCALENDAR");
+ assert.true(icsData.includes("VERSION:2.0"), "contains version");
+ assert.true(icsData.includes("BEGIN:VEVENT"), "contains VEVENT");
+ assert.true(
+ icsData.includes("SUMMARY:Test Event with Timezone"),
+ "contains title"
+ );
+ assert.true(
+ icsData.includes("DTSTART;TZID=America/Los_Angeles:"),
+ "contains start time with TZID"
+ );
+ assert.true(
+ icsData.includes("DTEND;TZID=America/Los_Angeles:"),
+ "contains end time with TZID"
+ );
+ assert.false(icsData.includes("DTSTART:"), "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");
+ });
+
+ test("includes location when provided", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { location: "Test Location" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("LOCATION:Test Location"),
+ "includes location"
+ );
+ });
+
+ test("includes description when provided", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { details: "Test Description" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("DESCRIPTION:Test Description"),
+ "includes description"
+ );
+ });
+
+ test("includes recurrence rule when provided", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { rrule: "FREQ=WEEKLY;BYDAY=MO" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("RRULE:FREQ=WEEKLY;BYDAY=MO"),
+ "includes rrule"
+ );
+ });
+
+ test("handles multiple dates", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ {
+ startsAt: "2025-12-08T12:00:00Z",
+ endsAt: "2025-12-08T13:00:00Z",
+ },
+ ];
+ const options = {};
+
+ const icsData = generateIcsData(title, dates, options);
+
+ const eventCount = (icsData.match(/BEGIN:VEVENT/g) || []).length;
+ assert.strictEqual(eventCount, 2, "creates two VEVENT blocks");
+ });
+
+ test("handles emoji and special characters in event details", function (assert) {
+ const title = "Test Event ????";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {
+ location: "Caf? ?",
+ details: "Testing ?mojis and sp?cial ?haracters",
+ };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(icsData.includes("??"), "preserves emoji in title");
+ assert.true(icsData.includes("?"), "preserves emoji in location");
+ assert.true(icsData.includes("?mojis"), "preserves accented characters");
+ });
+
+ test("generates valid base64url encoding", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { location: "Test+Location/With=Special" };
+
+ const icsData = generateIcsData(title, dates, options);
+ const base64url = bbcodeAttributeEncode(icsData);
+
+ assert.false(
+ base64url.includes("+"),
+ "base64url encoding replaces + with -"
+ );
+ assert.false(
+ base64url.includes("/"),
+ "base64url encoding replaces / with _"
+ );
+ assert.false(
+ base64url.includes("="),
+ "base64url encoding replaces = with ~"
+ );
+ assert.true(base64url.length > 0, "produces non-empty output");
+
+ const decoded = bbcodeAttributeDecode(base64url);
+ assert.strictEqual(
+ decoded,
+ icsData,
+ "can decode back to original ICS data"
+ );
+ });
+
+ test("uses CRLF line endings", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {};
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(icsData.includes("\r\n"), "contains CRLF line endings");
+ assert.false(/(?<!\r)\n/.test(icsData), "does not contain LF without CR");
+ assert.true(icsData.startsWith("BEGIN:VCALENDAR\r\n"), "starts with CRLF");
+ assert.true(icsData.endsWith("END:VCALENDAR"), "ends correctly");
+ });
+
+ test("folds long lines correctly", function (assert) {
+ const longTitle = "A".repeat(100);
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {};
+
+ const icsData = generateIcsData(longTitle, dates, options);
+
+ const summaryLine = icsData.match(/SUMMARY:[^\r\n]*(?:\r\n [^\r\n]*)*/)[0];
+ const lines = summaryLine.split("\r\n");
+
+ assert.true(lines.length > 1, "long SUMMARY is folded into multiple lines");
+ for (let i = 1; i < lines.length; i++) {
+ assert.true(
+ lines[i].startsWith(" "),
+ `continuation line ${i} starts with space`
+ );
+ }
+ lines.forEach((line, i) => {
+ if (i < lines.length - 1) {
+ assert.true(
+ line.length <= 75,
+ `line ${i} does not exceed 75 characters`
+ );
+ }
+ });
+ });
+
+ test("omits RRULE when FREQ is missing", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { rrule: "BYDAY=MO,TU,WE" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.false(
+ icsData.includes("RRULE:"),
+ "RRULE is omitted when FREQ is missing"
+ );
+ });
+
+ test("includes RRULE when FREQ is present", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { rrule: "FREQ=WEEKLY;BYDAY=MO" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("RRULE:FREQ=WEEKLY;BYDAY=MO"),
+ "RRULE is included when FREQ is present"
+ );
+ });
+
+ test("parses legacy RRULE format with DTSTART", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {
+ rrule: "DTSTART:20251201T120000Z\nRRULE:FREQ=WEEKLY;BYDAY=SU",
+ };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ const rruleCount = (icsData.match(/^RRULE:/gm) || []).length;
+ assert.strictEqual(rruleCount, 1, "only one RRULE line in output");
+
+ assert.true(
+ icsData.includes("RRULE:FREQ=WEEKLY;BYDAY=SU"),
+ "includes RRULE with FREQ"
+ );
+
+ assert.false(
+ icsData.includes("RRULE:DTSTART"),
+ "does not include DTSTART in RRULE line"
+ );
+
+ assert.true(
+ icsData.includes("DTSTART:20251201T120000Z"),
+ "DTSTART is a separate line"
+ );
+ });
+
+ test("handles RRULE with RRULE: prefix", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { rrule: "RRULE:FREQ=DAILY;INTERVAL=2" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ const rruleCount = (icsData.match(/^RRULE:/gm) || []).length;
+ assert.strictEqual(rruleCount, 1, "only one RRULE line in output");
+
+ assert.true(
+ icsData.includes("RRULE:FREQ=DAILY;INTERVAL=2"),
+ "RRULE is properly formatted"
+ );
+ });
+
+ test("omits RRULE when only DTSTART provided", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { rrule: "DTSTART:20251201T120000Z" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.false(
+ icsData.includes("RRULE:"),
+ "RRULE is omitted when no FREQ present"
+ );
+ });
+
+ test("handles long description with folding", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const longDescription =
+ "This is a very long description that exceeds the 75 character limit for ICS files and should be properly folded";
+ const options = { details: longDescription };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(icsData.includes("DESCRIPTION:"), "includes DESCRIPTION field");
+
+ const descriptionLine = icsData.match(
+ /DESCRIPTION:[^\r\n]*(?:\r\n [^\r\n]*)*/
+ )[0];
+ const lines = descriptionLine.split("\r\n");
+
+ assert.true(
+ lines.length > 1,
+ "long DESCRIPTION is folded into multiple lines"
+ );
+ for (let i = 1; i < lines.length; i++) {
+ assert.true(
+ lines[i].startsWith(" "),
+ `continuation line ${i} starts with space`
+ );
+ }
+ });
+
+ test("handles long location with folding", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const longLocation =
+ "A very long location name that will definitely exceed the 75 character limit set by the ICS specification";
+ const options = { location: longLocation };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(icsData.includes("LOCATION:"), "includes LOCATION field");
+
+ const locationLine = icsData.match(
+ /LOCATION:[^\r\n]*(?:\r\n [^\r\n]*)*/
+ )[0];
+ const lines = locationLine.split("\r\n");
+
+ assert.true(
+ lines.length > 1,
+ "long LOCATION is folded into multiple lines"
+ );
+ for (let i = 1; i < lines.length; i++) {
+ assert.true(
+ lines[i].startsWith(" "),
+ `continuation line ${i} starts with space`
+ );
+ }
+ });
+
+ test("escapes newlines in description", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { details: "Line 1\nLine 2\nLine 3" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("DESCRIPTION:Line 1\\nLine 2\\nLine 3"),
+ "newlines are escaped as \\n in description"
+ );
+ assert.false(
+ /DESCRIPTION:[^\r]*\n(?! )/.test(icsData),
+ "no unescaped newlines in description value"
+ );
+ });
+
+ test("escapes newlines in title", function (assert) {
+ const title = "Multi\nLine\nTitle";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {};
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("SUMMARY:Multi\\nLine\\nTitle"),
+ "newlines are escaped as \\n in title"
+ );
+ });
+
+ test("escapes newlines in location", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { location: "Building A\nRoom 101" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("LOCATION:Building A\\nRoom 101"),
+ "newlines are escaped as \\n in location"
+ );
+ });
+
+ test("escapes CRLF newlines", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { details: "Line 1\r\nLine 2\r\nLine 3" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("DESCRIPTION:Line 1\\nLine 2\\nLine 3"),
+ "CRLF newlines are escaped as \\n"
+ );
+ });
+
+ test("escapes CR newlines", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = { details: "Line 1\rLine 2\rLine 3" };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("DESCRIPTION:Line 1\\nLine 2\\nLine 3"),
+ "CR newlines are escaped as \\n"
+ );
+ });
+
+ test("escapes semicolons in field values", function (assert) {
+ const title = "Event; with semicolons;";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {
+ location: "Room; A",
+ details: "Important; details; here",
+ };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("SUMMARY:Event\\; with semicolons\\;"),
+ "semicolons are escaped in title"
+ );
+ assert.true(
+ icsData.includes("LOCATION:Room\\; A"),
+ "semicolons are escaped in location"
+ );
+ assert.true(
+ icsData.includes("DESCRIPTION:Important\\; details\\; here"),
+ "semicolons are escaped in description"
+ );
+ });
+
+ test("escapes commas in field values", function (assert) {
+ const title = "Event, with commas,";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {
+ location: "City, State",
+ details: "Item 1, Item 2, Item 3",
+ };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("SUMMARY:Event\\, with commas\\,"),
+ "commas are escaped in title"
+ );
+ assert.true(
+ icsData.includes("LOCATION:City\\, State"),
+ "commas are escaped in location"
+ );
+ assert.true(
+ icsData.includes("DESCRIPTION:Item 1\\, Item 2\\, Item 3"),
+ "commas are escaped in description"
+ );
+ });
+
+ test("escapes backslashes in field values", function (assert) {
+ const title = "Path\\to\\event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {
+ location: "C:\\Users\\Name",
+ details: "File: C:\\Documents\\file.txt",
+ };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes("SUMMARY:Path\\\\to\\\\event"),
+ "backslashes are escaped in title"
+ );
+ assert.true(
+ icsData.includes("LOCATION:C:\\\\Users\\\\Name"),
+ "backslashes are escaped in location"
+ );
+ assert.true(
+ icsData.includes("DESCRIPTION:File: C:\\\\Documents\\\\file.txt"),
+ "backslashes are escaped in description"
+ );
+ });
+
+ test("handles mixed special characters", function (assert) {
+ const title = "Test Event";
+ const dates = [
+ {
+ startsAt: "2025-12-01T12:00:00Z",
+ endsAt: "2025-12-01T13:00:00Z",
+ },
+ ];
+ const options = {
+ details: "Line 1\\path\nLine 2; with semicolon\nLine 3, with comma",
+ };
+
+ const icsData = generateIcsData(title, dates, options);
+
+ assert.true(
+ icsData.includes(
+ "DESCRIPTION:Line 1\\\\path\\nLine 2\\; with semicolon\\nLine 3\\, wit" +
+ "h comma"
+ ),
+ "multiple special characters are properly escaped"
+ );
+ });
+});
diff --git a/plugins/discourse-local-dates/assets/javascripts/initializers/discourse-local-dates.js b/plugins/discourse-local-dates/assets/javascripts/initializers/discourse-local-dates.js
index 1aa60645049..912403c3b0d 100644
--- a/plugins/discourse-local-dates/assets/javascripts/initializers/discourse-local-dates.js
+++ b/plugins/discourse-local-dates/assets/javascripts/initializers/discourse-local-dates.js
@@ -1,6 +1,7 @@
import { setOwner } from "@ember/owner";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
+import { bbcodeAttributeDecode } from "discourse/lib/bbcode-attributes";
import { bind } from "discourse/lib/decorators";
import { downloadCalendar } from "discourse/lib/download-calendar";
import { iconHTML, renderIcon } from "discourse/lib/icon-library";
@@ -9,6 +10,7 @@ import {
addTagDecorateCallback,
addTextDecorateCallback,
} from "discourse/lib/to-markdown";
+import { slugify } from "discourse/lib/utilities";
import { i18n } from "discourse-i18n";
import generateDateMarkup from "discourse/plugins/discourse-local-dates/lib/local-date-markup-generator";
import LocalDatesCreateModal from "../discourse/components/modal/local-dates-create";
@@ -315,7 +317,18 @@ function _downloadCalendarNode(element) {
if (!startDataset.time && !endDataset) {
node.setAttribute("data-ends-at", startDate.add(24, "hours").toISOString());
}
- node.setAttribute("data-title", startDataset.title);
+ if (startDataset.title) {
+ node.setAttribute("data-title", startDataset.title);
+ }
+ if (startDataset.timezone) {
+ node.setAttribute("data-timezone", startDataset.timezone);
+ }
+
+ // If ics data is available, pass it to the download button
+ if (startDataset.ics) {
+ node.setAttribute("data-ics", startDataset.ics);
+ }
+
return node;
}
@@ -353,12 +366,37 @@ class LocalDatesInit {
showDatePopover(event) {
if (event?.target?.classList?.contains("download-calendar")) {
const dataset = event.target.dataset;
- downloadCalendar(dataset.title, [
- {
- startsAt: dataset.startsAt,
- endsAt: dataset.endsAt,
- },
- ]);
+
+ if (dataset.ics) {
+ const icsData = bbcodeAttributeDecode(dataset.ics);
+
+ let title;
+ if (dataset.title) {
+ title = dataset.title;
+ } else {
+ // Extract event title from ICS SUMMARY field for filename if title missing
+ const summaryMatch = icsData.match(/SUMMARY:(.+?)[\r\n]/);
+ if (summaryMatch && summaryMatch[1]) {
+ title = summaryMatch[1].trim();
+ }
+ }
+
+ this.downloadIcs(title || "event", icsData);
+ } else {
+ const dates = [
+ {
+ startsAt: dataset.startsAt,
+ endsAt: dataset.endsAt,
+ },
+ ];
+
+ // Add timezone if available
+ if (dataset.timezone) {
+ dates[0].timezone = dataset.timezone;
+ }
+
+ downloadCalendar(dataset.title, dates);
+ }
return this.tooltip.close("local-date");
}
@@ -373,6 +411,22 @@ class LocalDatesInit {
});
}
+ downloadIcs(title, icsData) {
+ const blob = new Blob([icsData], { type: "text/calendar;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
+ try {
+ const a = document.createElement("a");
+ a.href = url;
+ const fileName = slugify(title);
+ a.download = `${fileName}.ics`;
+ // Most browsers allow clicking without attaching to DOM.
+ a.click();
+ } finally {
+ // Revoke on next tick so the download can start.
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+ }
+ }
+
teardown() {
window.removeEventListener("click", this.showDatePopover);
}
diff --git a/plugins/discourse-local-dates/assets/javascripts/lib/discourse-markdown/discourse-local-dates.js b/plugins/discourse-local-dates/assets/javascripts/lib/discourse-markdown/discourse-local-dates.js
index 0f6eb51b22a..7844cb91fab 100644
--- a/plugins/discourse-local-dates/assets/javascripts/lib/discourse-markdown/discourse-local-dates.js
+++ b/plugins/discourse-local-dates/assets/javascripts/lib/discourse-markdown/discourse-local-dates.js
@@ -37,7 +37,10 @@ function addLocalDate(attributes, state, buffer, applyDataAttributes) {
let token = new state.Token("span_open", "span", 1);
token.attrs = [["class", "discourse-local-date"]];
+
+ // applyDataAttributes will handle all data-* attributes including data-ics
applyDataAttributes(token, attributes, "date");
+
buffer.push(token);
token = new state.Token("text", "", 0);
@@ -106,6 +109,7 @@ export function setup(helper) {
"span[data-displayed-timezone]",
"span[data-email-preview]",
"span[data-format]",
+ "span[data-ics]",
"span[data-recurring]",
"span[data-time]",
"span[data-timezone]",
diff --git a/plugins/discourse-local-dates/test/javascripts/acceptance/download-calendar-with-ics-test.js b/plugins/discourse-local-dates/test/javascripts/acceptance/download-calendar-with-ics-test.js
new file mode 100644
index 00000000000..ee734bc4219
--- /dev/null
+++ b/plugins/discourse-local-dates/test/javascripts/acceptance/download-calendar-with-ics-test.js
@@ -0,0 +1,111 @@
+import { click, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { bbcodeAttributeEncode } from "discourse/lib/bbcode-attributes";
+import { cloneJSON } from "discourse/lib/object";
+import { fixturesByUrl } from "discourse/tests/helpers/create-pretender";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+acceptance(
+ "Local Dates - Download calendar with embedded ICS data",
+ function (needs) {
+ needs.user({ "user_option.default_calendar": "none_selected" });
+ needs.settings({ discourse_local_dates_enabled: true });
+ needs.pretender((server, helper) => {
+ const response = cloneJSON(fixturesByUrl["/t/281.json"]);
+ const startDate = moment
+ .tz("America/Lima")
+ .add(1, "days")
+ .format("YYYY-MM-DD");
+
+ // Create sample ICS data
+ const icsData = `BEGIN:VCALENDAR
+VERSION:2.0
+PRODID:-//Discourse//EN
+BEGIN:VEVENT
+UID:test123
+DTSTAMP:20251201T000000Z
+DTSTART:20251201T130000Z
+DTEND:20251201T140000Z
+SUMMARY:Test Event from Calendar
+LOCATION:Test Location
+DESCRIPTION:Test Description
+END:VEVENT
+END:VCALENDAR`;
+
+ // Use shared helper to encode ICS payload for data-ics attribute
+ const base64url = bbcodeAttributeEncode(icsData);
+
+ response.post_stream.posts[0].cooked = `<p><span data-date="${startDate}" data-time="13:00:00" class="discourse-local-date" data-timezone="America/Lima" data-ics="${base64url}" data-email-preview="${startDate}T18:00:00Z UTC">${startDate}T18:00:00Z</span></p>`;
+
+ server.get("/t/281.json", () => helper.response(response));
+ });
+
+ test("Downloads ICS file with embedded data", async function (assert) {
+ await visit("/t/local-dates/281");
+ await click(".discourse-local-date");
+
+ assert
+ .dom(".download-calendar")
+ .exists("download calendar button is present");
+
+ // We can't fully test the download without mocking File/Blob APIs
+ // but we can verify the button has the data-ics attribute
+ const downloadButton = document.querySelector(".download-calendar");
+ assert.true(
+ !!downloadButton.dataset.ics,
+ "download button has data-ics attribute"
+ );
+ assert.true(
+ downloadButton.dataset.ics.length > 0,
+ "data-ics attribute is not empty"
+ );
+ assert.false(
+ downloadButton.dataset.ics.includes("+"),
+ "data-ics uses base64url encoding (no +)"
+ );
+ assert.false(
+ downloadButton.dataset.ics.includes("/"),
+ "data-ics uses base64url encoding (no /)"
+ );
+ });
+ }
+);
+
+acceptance(
+ "Local Dates - Falls back to default ICS generation without embedded data",
+ function (needs) {
+ needs.user({ "user_option.default_calendar": "none_selected" });
+ needs.settings({ discourse_local_dates_enabled: true });
+ needs.pretender((server, helper) => {
+ const response = cloneJSON(fixturesByUrl["/t/281.json"]);
+ const startDate = moment
+ .tz("America/Lima")
+ .add(1, "days")
+ .format("YYYY-MM-DD");
+
+ // No data-ics attribute - should fall back to default behavior
+ response.post_stream.posts[0].cooked = `<p><span data-date="${startDate}" data-time="13:00:00" class="discourse-local-date" data-timezone="America/Lima" data-email-preview="${startDate}T18:00:00Z UTC">${startDate}T18:00:00Z</span></p>`;
+
+ server.get("/t/281.json", () => helper.response(response));
+ });
+
+ test("Shows download button without data-ics attribute", async function (assert) {
+ await visit("/t/local-dates/281");
+ await click(".discourse-local-date");
+
+ assert
+ .dom(".download-calendar")
+ .exists("download calendar button is present");
+
+ const downloadButton = document.querySelector(".download-calendar");
+ assert.false(
+ !!downloadButton.dataset.ics,
+ "download button has no data-ics attribute"
+ );
+ assert.true(
+ !!downloadButton.dataset.startsAt,
+ "download button has data-starts-at for fallback"
+ );
+ });
+ }
+);
diff --git a/plugins/discourse-local-dates/test/javascripts/unit/ics-parameter-test.js b/plugins/discourse-local-dates/test/javascripts/unit/ics-parameter-test.js
new file mode 100644
index 00000000000..c289a00a093
--- /dev/null
+++ b/plugins/discourse-local-dates/test/javascripts/unit/ics-parameter-test.js
@@ -0,0 +1,142 @@
+import { module, test } from "qunit";
+import {
+ bbcodeAttributeDecode,
+ bbcodeAttributeEncode,
+} from "discourse/lib/bbcode-attributes";
+
+module("Unit | Local Dates | ICS Parameter", function () {
+ test("encodes and decodes ICS data correctly", function (assert) {
+ const testIcsData = `BEGIN:VCALENDAR
+VERSION:2.0
+PRODID:-//Discourse//EN
+BEGIN:VEVENT
+UID:12345
+SUMMARY:Test Event
+DTSTART:20251201T120000Z
+DTEND:20251201T130000Z
+LOCATION:Test Location
+DESCRIPTION:Test Description
+END:VEVENT
+END:VCALENDAR`;
+
+ const base64url = bbcodeAttributeEncode(testIcsData);
+
+ assert.true(base64url.length > 0, "base64url encoding produces output");
+ assert.false(
+ base64url.includes("+"),
+ "base64url does not contain + character"
+ );
+ assert.false(
+ base64url.includes("/"),
+ "base64url does not contain / character"
+ );
+ assert.false(
+ base64url.includes("="),
+ "base64url does not contain = character"
+ );
+
+ const decodedIcsData = bbcodeAttributeDecode(base64url);
+
+ assert.strictEqual(
+ decodedIcsData,
+ testIcsData,
+ "decoded ICS data matches original"
+ );
+ });
+
+ test("handles UTF-8 characters in ICS data", function (assert) {
+ const testIcsData = `BEGIN:VCALENDAR
+VERSION:2.0
+PRODID:-//Discourse//EN
+BEGIN:VEVENT
+UID:12345
+SUMMARY:Test Event ????
+DTSTART:20251201T120000Z
+DTEND:20251201T130000Z
+LOCATION:Caf? ?
+DESCRIPTION:Testing ?mojis and sp?cial ?haracters
+END:VEVENT
+END:VCALENDAR`;
+
+ const base64url = bbcodeAttributeEncode(testIcsData);
+ const decodedIcsData = bbcodeAttributeDecode(base64url);
+
+ assert.strictEqual(
+ decodedIcsData,
+ testIcsData,
+ "UTF-8 characters are preserved through encoding/decoding"
+ );
+ assert.true(decodedIcsData.includes("??"), "emoji in title is preserved");
+ assert.true(decodedIcsData.includes("?"), "emoji in location is preserved");
+ assert.true(
+ decodedIcsData.includes("?mojis"),
+ "accented characters are preserved"
+ );
+ });
+
+ test("extracts event title from ICS SUMMARY field", function (assert) {
+ const testCases = [
+ {
+ ics: "BEGIN:VEVENT\nSUMMARY:My Event Name\nEND:VEVENT",
+ expected: "My Event Name",
+ },
+ {
+ ics: "BEGIN:VEVENT\nSUMMARY:Event with ?? emoji\nEND:VEVENT",
+ expected: "Event with ?? emoji",
+ },
+ {
+ ics: "BEGIN:VEVENT\nSUMMARY: Trimmed Event \nEND:VEVENT",
+ expected: "Trimmed Event",
+ },
+ ];
+
+ testCases.forEach((testCase) => {
+ const summaryMatch = testCase.ics.match(/SUMMARY:(.+?)[\r\n]/);
+ const title = summaryMatch ? summaryMatch[1].trim() : "event";
+ assert.strictEqual(
+ title,
+ testCase.expected,
+ `extracts "${testCase.expected}"`
+ );
+ });
+ });
+
+ test("cleans filename correctly", function (assert) {
+ const testCases = [
+ { input: "My Event Name", expected: "my-event-name" },
+ { input: "Event with ?? emoji", expected: "event-with-emoji" },
+ {
+ input: "Special!@#$%^&*()chars",
+ expected: "specialchars",
+ },
+ {
+ input: "Multiple Spaces",
+ expected: "multiple-spaces",
+ },
+ {
+ input: "Trailing-Dashes---",
+ expected: "trailing-dashes",
+ },
+ {
+ input:
+ "Very Long Event Name That Exceeds Fifty Characters Total Length Here",
+ expected: "very-long-event-name-that-exceeds-fifty-characters",
+ },
+ ];
+
+ testCases.forEach((testCase) => {
+ const cleaned = testCase.input
+ .toLowerCase()
+ .replace(/[^\w\s-]/g, "")
+ .replace(/[\s_]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .substring(0, 50);
+
+ assert.strictEqual(
+ cleaned,
+ testCase.expected,
+ `"${testCase.input}" -> "${testCase.expected}"`
+ );
+ });
+ });
+});