Escape and fold the iCal export, serve it as text/calendar, add subscription links
- iCal export: RFC 5545 text escaping for SUMMARY, DESCRIPTION and LOCATION,
line folding at 75 octets (UTF-8 aware), CRLF line endings, and
Content-Type text/calendar instead of the inferred text/html. A line break
in a description used to end the property early; the new calendar
frontend has a multi-line description field.
- formatDate no longer shifts the event's end date in place.
- GET /calendar/events/subscriptions: the iCal URL of every calendar, with
its shared password where needed, for the calendar app's "Abonnieren"
dialog. Editors only (requireAppAccess('calendar')), the shared password
is not accepted there, never cached; calendars without a configured
credential are left out.
- Tests for both; documented in docs/calendar-ical.md.
Backwards compatible with the current Angular calendar app.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
6 files changed
+355
-8
No files matched your search
@@ -21,7 +21,13 @@ dotenv.config();
|
||||
* test/calendar/credentials.service.test.ts.
|
||||
*/
|
||||
|
||||
const credentialFor = (calendarName: string): string | undefined => {
|
||||
/**
|
||||
* The shared password for a calendar, or undefined for `public` (which needs
|
||||
* none), an unknown calendar, or one whose credential is not configured.
|
||||
* Exported for the subscriptions endpoint, which hands signed-in editors the
|
||||
* ready-made iCal URLs - see GET /calendar/events/subscriptions.
|
||||
*/
|
||||
export const credentialFor = (calendarName: string): string | undefined => {
|
||||
switch (calendarName) {
|
||||
case 'members':
|
||||
return process.env.MEMBER_CREDENTIAL;
|
||||
|
||||
@@ -8,6 +8,7 @@ import * as EventService from './events.service.js';
|
||||
import * as iCalService from './icalgenerator.service.js';
|
||||
import * as CredentialService from './credentials.service.js';
|
||||
import {requireAppAccess, resolveAccess, AdminAccess} from '../../admin/admin.middleware.js';
|
||||
import {API_BASE_URL} from '../../admin/admin.config.js';
|
||||
import {Guid} from 'guid-typescript';
|
||||
import logger from '../../../middleware/logger.js';
|
||||
|
||||
@@ -423,7 +424,12 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => {
|
||||
let file = await iCalService.convertToIcal(events);
|
||||
|
||||
// Send the ical file back
|
||||
res.set({'Content-Disposition': 'attachment; filename=' + fileName + '.ics'});
|
||||
// text/calendar, not the text/html that send() infers from a string - calendar apps
|
||||
// coped with the wrong type, but it was wrong (RFC 5545 §8.1).
|
||||
res.set({
|
||||
'Content-Type': 'text/calendar; charset=utf-8',
|
||||
'Content-Disposition': 'attachment; filename=' + fileName + '.ics'
|
||||
});
|
||||
res.status(200).send(file);
|
||||
} catch (e: any) {
|
||||
let errorGuid = Guid.create().toString();
|
||||
@@ -436,6 +442,59 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /calendar/events/subscriptions:
|
||||
* get:
|
||||
* summary: The iCal subscription URL of every calendar
|
||||
* description: >
|
||||
* Ready-to-use iCal URLs for each calendar, with the calendar's shared password
|
||||
* already in the query string where it needs one - for the calendar app's
|
||||
* "Abonnieren" dialog. A calendar whose password is not configured is left out
|
||||
* rather than listed with a URL that cannot work. Requires a signed-in account
|
||||
* with the calendar permission: those editors can read every event anyway, so the
|
||||
* passwords tell them nothing new. Never cached.
|
||||
* tags:
|
||||
* - calendar
|
||||
* security:
|
||||
* - AdminSessionCookie: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Success
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* calendar:
|
||||
* type: string
|
||||
* example: members
|
||||
* icalUrl:
|
||||
* type: string
|
||||
* example: https://api.nachklang.art/calendar/events/members/ical?password=…
|
||||
* 401:
|
||||
* description: Unauthorized - not signed in
|
||||
* 403:
|
||||
* description: Forbidden - the account lacks the calendar permission
|
||||
*/
|
||||
eventsRouter.get('/subscriptions', requireCalendarAccess, (req: Request, res: Response) => {
|
||||
const base = API_BASE_URL.replace(/\/+$/, '');
|
||||
const subscriptions = Array.from(calendarNames.keys()).flatMap((calendar) => {
|
||||
const url = `${base}/calendar/events/${calendar}/ical`;
|
||||
if (calendar === 'public') {
|
||||
return [{calendar, icalUrl: url}];
|
||||
}
|
||||
const password = CredentialService.credentialFor(calendar);
|
||||
return password ? [{calendar, icalUrl: `${url}?password=${encodeURIComponent(password)}`}] : [];
|
||||
});
|
||||
|
||||
// These URLs carry the shared passwords; keep them out of every cache on the way.
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.status(200).send(subscriptions);
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /calendar/events:
|
||||
|
||||
@@ -13,7 +13,7 @@ export const convertToIcal = async (events: Event[]): Promise<string> => {
|
||||
addEventToFile(ical, event);
|
||||
}
|
||||
|
||||
return serializeIcalFile(ical);
|
||||
return toContentLines(serializeIcalFile(ical));
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
@@ -116,9 +116,11 @@ const addEventToFile = (ical: iCalFile, event: Event) => {
|
||||
* @param event
|
||||
*/
|
||||
const createIcalEvent = (event: Event): iCalEvent => {
|
||||
let description = event.description ? event.description + '\n' : '';
|
||||
let location = event.location ? event.location + '\n' : '';
|
||||
let url = event.url ? event.url + '\n' : '';
|
||||
// Free text is escaped (see escapeText); the URL is a URI value, which has
|
||||
// no escapes - it only must not break the line.
|
||||
let description = event.description ? escapeText(event.description) + '\n' : '';
|
||||
let location = event.location ? escapeText(event.location) + '\n' : '';
|
||||
let url = event.url ? event.url.replace(/[\r\n]+/g, '') + '\n' : '';
|
||||
|
||||
return {
|
||||
header: 'BEGIN:VEVENT\n',
|
||||
@@ -128,7 +130,7 @@ const createIcalEvent = (event: Event): iCalEvent => {
|
||||
start: formatDate(event.startDateTime, event.wholeDay) + '\n',
|
||||
end: formatDate(event.endDateTime, event.wholeDay, true) + '\n',
|
||||
repeatFrequency: event.repeatFrequency ? event.repeatFrequency + '\n' : '',
|
||||
summary: event.name + '\n',
|
||||
summary: escapeText(event.name) + '\n',
|
||||
description: description,
|
||||
location: location,
|
||||
url: url,
|
||||
@@ -143,8 +145,11 @@ const createIcalEvent = (event: Event): iCalEvent => {
|
||||
* @param wholeDayFormat
|
||||
* @param isEndDate
|
||||
*/
|
||||
const formatDate = (date: Date, wholeDayFormat: boolean = false, isEndDate: boolean = false): string => {
|
||||
const formatDate = (input: Date, wholeDayFormat: boolean = false, isEndDate: boolean = false): string => {
|
||||
let returnString = '';
|
||||
// A copy: this used to shift the caller's Date in place, so the event object
|
||||
// came out of the export with its end a day later than it went in.
|
||||
const date = new Date(input);
|
||||
|
||||
// We need to do this for whole day events as otherwise the event ends one day too early
|
||||
if(wholeDayFormat && isEndDate) date.setDate(date.getDate() + 1)
|
||||
@@ -184,6 +189,58 @@ export interface iCalEvent {
|
||||
footer: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* RFC 5545 §3.3.11 TEXT escaping. Without it a description with a line break
|
||||
* ended the DESCRIPTION property early and the rest of the text was read as a
|
||||
* new (garbage) property, and an unescaped `,` or `;` is invalid in the value.
|
||||
* The backslash goes first, or the escapes added after it would be doubled.
|
||||
*/
|
||||
export const escapeText = (value: string): string =>
|
||||
value
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/;/g, '\\;')
|
||||
.replace(/,/g, '\\,')
|
||||
.replace(/\r\n|\r|\n/g, '\\n');
|
||||
|
||||
const MAX_LINE_OCTETS = 75;
|
||||
|
||||
/**
|
||||
* RFC 5545 §3.1 line folding: no content line longer than 75 octets, a longer
|
||||
* one continues on the next line after a single leading space. Counts UTF-8
|
||||
* octets, not characters, and never splits inside a character - "ü" is two
|
||||
* octets and a fold between them corrupts it.
|
||||
*/
|
||||
export const foldLine = (line: string): string => {
|
||||
const parts: string[] = [];
|
||||
let current = '';
|
||||
let octets = 0;
|
||||
for (const char of line) {
|
||||
const size = Buffer.byteLength(char, 'utf8');
|
||||
// A continuation line's leading space counts towards its 75.
|
||||
const limit = parts.length === 0 ? MAX_LINE_OCTETS : MAX_LINE_OCTETS - 1;
|
||||
if (octets + size > limit) {
|
||||
parts.push(current);
|
||||
current = '';
|
||||
octets = 0;
|
||||
}
|
||||
current += char;
|
||||
octets += size;
|
||||
}
|
||||
parts.push(current);
|
||||
return parts.join('\r\n ');
|
||||
};
|
||||
|
||||
/**
|
||||
* The generator builds the file with bare `\n` line ends; the format wants
|
||||
* every content line folded and terminated by CRLF (RFC 5545 §3.1).
|
||||
*/
|
||||
const toContentLines = (ical: string): string =>
|
||||
ical
|
||||
.split('\n')
|
||||
.filter((line) => line !== '')
|
||||
.map(foldLine)
|
||||
.join('\r\n') + '\r\n';
|
||||
|
||||
/**
|
||||
* Checks if a given string is null, undefined or blank
|
||||
* @param str The string to check
|
||||
|
||||
Reference in new issue
Block a user