feat: send calendar event invitations by email or federation
Build & Push Docker Image / build (push) Successful in 4m18s
Build & Push Docker Image / build (push) Successful in 4m18s
- New endpoint POST /api/calendar/events/:id/email sends event invitations with an .ics attachment to external email addresses (rate-limited like room email invites) - Create-event dialog gets an optional invitations section to invite people by email or federation address right away - The "Invite remote" dialog on existing events now accepts email addresses in addition to federation IDs Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -289,6 +289,78 @@ export async function sendCalendarInviteEmail(to, name, fromUser, title, startTi
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a calendar event invitation to an external email address (with ICS attachment).
|
||||
* @param {string} to - recipient email
|
||||
* @param {string} fromUser - sender display name
|
||||
* @param {string} title - event title
|
||||
* @param {string} startTime - ISO start time
|
||||
* @param {string} endTime - ISO end time
|
||||
* @param {string|null} description - optional event description
|
||||
* @param {string|null} joinUrl - direct meeting join URL if a room is linked
|
||||
* @param {string} ics - ICS file content to attach
|
||||
* @param {string} appName - branding app name
|
||||
* @param {string} lang - language code
|
||||
*/
|
||||
export async function sendCalendarEventEmail(to, fromUser, title, startTime, endTime, description, joinUrl, ics, appName = 'Redlight', lang = 'en') {
|
||||
if (!transporter) {
|
||||
throw new Error('SMTP not configured');
|
||||
}
|
||||
|
||||
const from = process.env.SMTP_FROM || process.env.SMTP_USER;
|
||||
const headerAppName = sanitizeHeaderValue(appName);
|
||||
const safeFromUser = escapeHtml(fromUser);
|
||||
const safeTitle = escapeHtml(title);
|
||||
const safeDesc = description ? escapeHtml(description) : null;
|
||||
|
||||
const formatDate = (iso) => {
|
||||
try { return new Date(iso).toLocaleString(lang === 'de' ? 'de-DE' : 'en-GB', { dateStyle: 'full', timeStyle: 'short' }); }
|
||||
catch { return iso; }
|
||||
};
|
||||
|
||||
const introHtml = t(lang, 'email.calendarEventInvite.intro')
|
||||
.replace('{fromUser}', `<strong style="color:#cdd6f4;">${safeFromUser}</strong>`);
|
||||
|
||||
await transporter.sendMail({
|
||||
from: `"${headerAppName}" <${from}>`,
|
||||
to,
|
||||
subject: t(lang, 'email.calendarEventInvite.subject', { appName: headerAppName, title: sanitizeHeaderValue(title) }),
|
||||
html: `
|
||||
<div style="font-family:Arial,sans-serif;max-width:520px;margin:0 auto;padding:32px;background:#1e1e2e;color:#cdd6f4;border-radius:12px;">
|
||||
<h2 style="color:#cba6f7;margin-top:0;">${t(lang, 'email.calendarEventInvite.title')}</h2>
|
||||
<p>${introHtml}</p>
|
||||
<div style="background:#313244;border-radius:8px;padding:16px;margin:20px 0;">
|
||||
<p style="margin:0 0 4px 0;font-size:15px;font-weight:bold;color:#cdd6f4;">${safeTitle}</p>
|
||||
<p style="margin:6px 0 0 0;font-size:13px;color:#a6adc8;">${escapeHtml(formatDate(startTime))} - ${escapeHtml(formatDate(endTime))}</p>
|
||||
${safeDesc ? `<p style="margin:10px 0 0 0;font-size:13px;color:#a6adc8;font-style:italic;">"${safeDesc}"</p>` : ''}
|
||||
</div>
|
||||
${joinUrl ? `
|
||||
<p style="text-align:center;margin:28px 0;">
|
||||
<a href="${joinUrl}"
|
||||
style="display:inline-block;background:#cba6f7;color:#1e1e2e;padding:12px 32px;border-radius:8px;text-decoration:none;font-weight:bold;">
|
||||
${t(lang, 'email.calendarEventInvite.joinButton')}
|
||||
</a>
|
||||
</p>
|
||||
<p style="font-size:13px;color:#7f849c;">
|
||||
${t(lang, 'email.linkHint')}<br/>
|
||||
<a href="${joinUrl}" style="color:#89b4fa;word-break:break-all;">${escapeHtml(joinUrl)}</a>
|
||||
</p>` : ''}
|
||||
<p style="font-size:13px;color:#7f849c;">${t(lang, 'email.calendarEventInvite.icsHint')}</p>
|
||||
<hr style="border:none;border-top:1px solid #313244;margin:24px 0;"/>
|
||||
<p style="font-size:12px;color:#585b70;">${t(lang, 'email.calendarEventInvite.footer', { appName: escapeHtml(appName) })}</p>
|
||||
</div>
|
||||
`,
|
||||
text: `${t(lang, 'email.calendarEventInvite.intro', { fromUser })}\n${title}\n${formatDate(startTime)} – ${formatDate(endTime)}${description ? `\n\n"${description}"` : ''}${joinUrl ? `\n\n${t(lang, 'email.calendarEventInvite.joinButton')}: ${joinUrl}` : ''}\n\n${t(lang, 'email.calendarEventInvite.icsHint')}\n\n– ${appName}`,
|
||||
attachments: [
|
||||
{
|
||||
filename: 'event.ics',
|
||||
content: ics,
|
||||
contentType: 'text/calendar; charset=utf-8; method=PUBLISH',
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify a user that a federated calendar event they received was deleted by the organiser.
|
||||
*/
|
||||
|
||||
@@ -43,6 +43,14 @@
|
||||
"subject": "{appName} - Kalendereinladung von {fromUser}",
|
||||
"intro": "Du hast eine Kalendereinladung von {fromUser} erhalten."
|
||||
},
|
||||
"calendarEventInvite": {
|
||||
"subject": "{appName} - Kalendereinladung: {title}",
|
||||
"title": "Kalendereinladung",
|
||||
"intro": "{fromUser} hat dich zu folgendem Termin eingeladen:",
|
||||
"joinButton": "Meeting beitreten",
|
||||
"icsHint": "Mit der angehängten .ics-Datei kannst du den Termin zu deinem Kalender hinzufügen.",
|
||||
"footer": "Diese Einladung wurde über {appName} versendet."
|
||||
},
|
||||
"calendarDeleted": {
|
||||
"subject": "{appName} - Kalendereintrag abgesagt: {title}",
|
||||
"intro": "Der folgende Kalendereintrag wurde vom Organisator ({fromUser}) gelöscht und ist nicht mehr verfügbar:",
|
||||
|
||||
@@ -43,6 +43,14 @@
|
||||
"subject": "{appName} - Calendar invitation from {fromUser}",
|
||||
"intro": "You have received a calendar invitation from {fromUser}."
|
||||
},
|
||||
"calendarEventInvite": {
|
||||
"subject": "{appName} - Calendar invitation: {title}",
|
||||
"title": "Calendar Invitation",
|
||||
"intro": "{fromUser} has invited you to the following event:",
|
||||
"joinButton": "Join Meeting",
|
||||
"icsHint": "You can add this event to your calendar using the attached .ics file.",
|
||||
"footer": "This invitation was sent via {appName}."
|
||||
},
|
||||
"calendarDeleted": {
|
||||
"subject": "{appName} - Calendar event cancelled: {title}",
|
||||
"intro": "The following calendar event was deleted by the organiser ({fromUser}) and is no longer available:",
|
||||
|
||||
@@ -3,7 +3,7 @@ import crypto from 'crypto';
|
||||
import { getDb } from '../config/database.js';
|
||||
import { authenticateToken, getBaseUrl } from '../middleware/auth.js';
|
||||
import { log } from '../config/logger.js';
|
||||
import { sendCalendarInviteEmail } from '../config/mailer.js';
|
||||
import { sendCalendarInviteEmail, sendCalendarEventEmail } from '../config/mailer.js';
|
||||
import { getAppName } from '../config/appName.js';
|
||||
import {
|
||||
isFederationEnabled,
|
||||
@@ -23,6 +23,16 @@ const SAFE_COLOR_RE = /^(?:#[0-9a-fA-F]{3,8}|hsl\(\d{1,3},\s*\d{1,3}%,\s*\d{1,3}
|
||||
// Allowed reminder intervals in minutes
|
||||
const VALID_REMINDERS = new Set([5, 15, 30, 60, 120, 1440]);
|
||||
|
||||
// Rate limit email invitations: each request may carry up to 50 addresses, so
|
||||
// without a cap any registered account could be abused as an SMTP spam relay.
|
||||
const calendarEmailInviteLimiter = rateLimit({
|
||||
windowMs: 60 * 60 * 1000, // 1 hour
|
||||
max: 10,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many email invitations. Please try again later.' },
|
||||
});
|
||||
|
||||
// Rate limit for federation calendar receive
|
||||
const calendarFederationLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
@@ -581,6 +591,69 @@ router.post('/events/:id/federation', authenticateToken, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ── POST /api/calendar/events/:id/email — Send event invitation by email ────
|
||||
router.post('/events/:id/email', authenticateToken, calendarEmailInviteLimiter, async (req, res) => {
|
||||
try {
|
||||
const { emails } = req.body;
|
||||
if (!emails || !Array.isArray(emails) || !emails.length) {
|
||||
return res.status(400).json({ error: 'At least one email address is required' });
|
||||
}
|
||||
if (emails.length > 50) {
|
||||
return res.status(400).json({ error: 'Maximum 50 email addresses allowed' });
|
||||
}
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
for (const email of emails) {
|
||||
if (typeof email !== 'string' || !emailRegex.test(email) || email.length > 254) {
|
||||
return res.status(400).json({ error: `Invalid email address: ${email}` });
|
||||
}
|
||||
}
|
||||
|
||||
const db = getDb();
|
||||
const event = await db.get(`
|
||||
SELECT ce.*, COALESCE(NULLIF(u.display_name,''), u.name) as organizer_name, u.email as organizer_email
|
||||
FROM calendar_events ce
|
||||
JOIN users u ON ce.user_id = u.id
|
||||
WHERE ce.id = ? AND ce.user_id = ?
|
||||
`, [req.params.id, req.user.id]);
|
||||
if (!event) return res.status(404).json({ error: 'Event not found or no permission' });
|
||||
|
||||
const baseUrl = getBaseUrl(req);
|
||||
let joinUrl = null;
|
||||
if (event.room_uid) {
|
||||
joinUrl = `${baseUrl}/join/${event.room_uid}`;
|
||||
}
|
||||
|
||||
const ics = generateICS(event, joinUrl || '', baseUrl);
|
||||
const appName = await getAppName();
|
||||
const fromUser = req.user.display_name || req.user.name;
|
||||
const lang = req.user.language || 'en';
|
||||
|
||||
// Send emails (in parallel but collect errors)
|
||||
const results = await Promise.allSettled(
|
||||
emails.map(email =>
|
||||
sendCalendarEventEmail(
|
||||
email, fromUser, event.title, event.start_time, event.end_time,
|
||||
event.description, joinUrl, ics, appName, lang
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const failed = results.filter(r => r.status === 'rejected');
|
||||
if (failed.length === emails.length) {
|
||||
return res.status(500).json({ error: 'Failed to send all email invitations' });
|
||||
}
|
||||
if (failed.length > 0) {
|
||||
log.server.warn(`${failed.length}/${emails.length} calendar email invitations failed`);
|
||||
}
|
||||
|
||||
res.json({ success: true, sent: emails.length - failed.length, failed: failed.length });
|
||||
} catch (err) {
|
||||
log.server.error(`Calendar email invite error: ${err.message}`);
|
||||
res.status(500).json({ error: err.message || 'Failed to send email invitations' });
|
||||
}
|
||||
});
|
||||
|
||||
// ── POST /receive-event or /calendar-event — Receive calendar event from remote ──
|
||||
// '/receive-event' when mounted at /api/calendar
|
||||
// '/calendar-event' when mounted at /api/federation (for remote instance discovery)
|
||||
|
||||
Reference in New Issue
Block a user