summaryrefslogtreecommitdiff
path: root/src/routes/event.ts
blob: 6be5ff8384990a24e20269ef525ea754b489a144 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
import { Router, Response, Request } from "express";
import multer from "multer";
import Jimp from "jimp";
import moment from "moment-timezone";
import {
    generateEditToken,
    generateEventID,
    generateRSAKeypair,
} from "../util/generator.js";
import { validateEventData } from "../util/validation.js";
import { addToLog } from "../helpers.js";
import Event from "../models/Event.js";
import EventGroup from "../models/EventGroup.js";
import {
    broadcastCreateMessage,
    broadcastUpdateMessage,
    createActivityPubActor,
    createActivityPubEvent,
    createFeaturedPost,
    sendDirectMessage,
    updateActivityPubActor,
    updateActivityPubEvent,
} from "../activitypub.js";
import getConfig from "../lib/config.js";
import { sendEmailFromTemplate } from "../lib/email.js";
import crypto from "crypto";
import ical from "ical";
import { markdownToSanitizedHTML } from "../util/markdown.js";
import { checkMagicLink } from "../lib/middleware.js";

const config = getConfig();

const storage = multer.memoryStorage();
// Accept only JPEG, GIF or PNG images, up to 10MB
const upload = multer({
    storage: storage,
    limits: { fileSize: 10 * 1024 * 1024 },
    fileFilter: function (_, file, cb) {
        const filetypes = /jpeg|jpg|png|gif/;
        const mimetype = filetypes.test(file.mimetype);
        if (!mimetype) {
            return cb(new Error("Only JPEG, PNG and GIF images are allowed."));
        }
        cb(null, true);
    },
});
const icsUpload = multer({
    storage: storage,
    limits: { fileSize: 10 * 1024 * 1024 },
    fileFilter: function (_, file, cb) {
        const filetype = "text/calendar";
        if (file.mimetype !== filetype) {
            return cb(new Error("Only ICS files are allowed."));
        }
        cb(null, true);
    },
});

const router = Router();

router.post(
    "/event",
    upload.single("imageUpload"),
    checkMagicLink,
    async (req: Request, res: Response) => {
        const { data: eventData, errors } = validateEventData(req.body);
        if (errors && errors.length > 0) {
            return res.status(400).json({ errors });
        }
        if (!eventData) {
            return res.status(400).json({
                errors: [
                    {
                        message: "No event data was provided.",
                    },
                ],
            });
        }

        let eventID = generateEventID();
        let editToken = generateEditToken();
        let eventImageFilename;
        let isPartOfEventGroup = false;

        if (req.file?.buffer) {
            eventImageFilename = await Jimp.read(req.file.buffer)
                .then((img) => {
                    img.resize(920, Jimp.AUTO) // resize
                        .quality(80) // set JPEG quality
                        .write("./public/events/" + eventID + ".jpg"); // save
                    return eventID + ".jpg";
                })
                .catch((err) => {
                    addToLog(
                        "Jimp",
                        "error",
                        "Attempt to edit image failed with error: " + err,
                    );
                });
        }

        const startUTC = moment.tz(eventData.eventStart, eventData.timezone);
        const endUTC = moment.tz(eventData.eventEnd, eventData.timezone);
        let eventGroup;
        if (eventData?.eventGroupBoolean) {
            try {
                eventGroup = await EventGroup.findOne({
                    id: eventData.eventGroupID,
                    editToken: eventData.eventGroupEditToken,
                });
                if (eventGroup) {
                    isPartOfEventGroup = true;
                }
            } catch (err) {
                console.error(err);
                addToLog(
                    "createEvent",
                    "error",
                    "Attempt to find event group failed with error: " + err,
                );
            }
        }

        // generate RSA keypair for ActivityPub
        let { publicKey, privateKey } = generateRSAKeypair();

        const event = new Event({
            id: eventID,
            type: "public", // This is for backwards compatibility
            name: eventData.eventName,
            location: eventData.eventLocation,
            start: startUTC,
            end: endUTC,
            timezone: eventData.timezone,
            description: eventData.eventDescription,
            image: eventImageFilename,
            creatorEmail: eventData.creatorEmail,
            url: eventData.eventURL,
            hostName: eventData.hostName,
            viewPassword: "", // Backwards compatibility
            editPassword: "", // Backwards compatibility
            editToken: editToken,
            showOnPublicList: eventData?.publicBoolean,
            eventGroup: isPartOfEventGroup ? eventGroup?._id : null,
            usersCanAttend: eventData.joinBoolean ? true : false,
            showUsersList: false, // Backwards compatibility
            usersCanComment: eventData.interactionBoolean ? true : false,
            maxAttendees: eventData.maxAttendees,
            firstLoad: true,
            activityPubActor: createActivityPubActor(
                eventID,
                config.general.domain,
                publicKey,
                markdownToSanitizedHTML(eventData.eventDescription),
                eventData.eventName,
                eventData.eventLocation,
                eventImageFilename,
                startUTC,
                endUTC,
                eventData.timezone,
            ),
            activityPubEvent: createActivityPubEvent(
                eventData.eventName,
                startUTC,
                endUTC,
                eventData.timezone,
                eventData.eventDescription,
                eventData.eventLocation,
            ),
            activityPubMessages: [
                {
                    id: `https://${config.general.domain}/${eventID}/m/featuredPost`,
                    content: JSON.stringify(
                        createFeaturedPost(
                            eventID,
                            eventData.eventName,
                            startUTC,
                            endUTC,
                            eventData.timezone,
                            eventData.eventDescription,
                            eventData.eventLocation,
                        ),
                    ),
                },
            ],
            publicKey,
            privateKey,
        });
        try {
            const savedEvent = await event.save();
            addToLog("createEvent", "success", "Event " + eventID + "created");
            // Send email with edit link
            if (eventData.creatorEmail && req.app.locals.sendEmails) {
                sendEmailFromTemplate(
                    eventData.creatorEmail,
                    `${eventData.eventName}`,
                    "createEvent",
                    {
                        eventID,
                        editToken,
                        siteName: config.general.site_name,
                        siteLogo: config.general.email_logo_url,
                        domain: config.general.domain,
                    },
                    req,
                );
            }
            // If the event was added to a group, send an email to any group
            // subscribers
            if (event.eventGroup && req.app.locals.sendEmails) {
                try {
                    const eventGroup = await EventGroup.findOne({
                        _id: event.eventGroup.toString(),
                    });
                    if (!eventGroup) {
                        throw new Error(
                            "Event group not found for event " + eventID,
                        );
                    }
                    const subscribers = eventGroup?.subscribers?.reduce(
                        (acc: string[], current) => {
                            if (current.email && !acc.includes(current.email)) {
                                return [current.email, ...acc];
                            }
                            return acc;
                        },
                        [] as string[],
                    );
                    subscribers?.forEach((emailAddress) => {
                        sendEmailFromTemplate(
                            emailAddress,
                            `New event in ${eventGroup.name}`,
                            "eventGroupUpdated",
                            {
                                siteName: config.general.site_name,
                                siteLogo: config.general.email_logo_url,
                                domain: config.general.domain,
                                eventGroupName: eventGroup.name,
                                eventName: event.name,
                                eventID: event.id,
                                eventGroupID: eventGroup.id,
                                emailAddress: encodeURIComponent(emailAddress),
                            },
                            req,
                        );
                    });
                } catch (err) {
                    console.error(err);
                    addToLog(
                        "createEvent",
                        "error",
                        "Attempt to send event group emails failed with error: " +
                            err,
                    );
                }
            }
            return res.json({
                eventID: eventID,
                editToken: editToken,
                url: `/${eventID}?e=${editToken}`,
            });
        } catch (err) {
            console.error(err);
            addToLog(
                "createEvent",
                "error",
                "Attempt to create event failed with error: " + err,
            );
            return res.status(500).json({
                errors: [
                    {
                        message: err,
                    },
                ],
            });
        }
    },
);

router.put(
    "/event/:eventID",
    upload.single("imageUpload"),
    async (req: Request, res: Response) => {
        const { data: eventData, errors } = validateEventData(req.body);
        if (errors && errors.length > 0) {
            return res.status(400).json({ errors });
        }
        if (!eventData) {
            return res.status(400).json({
                errors: [
                    {
                        message: "No event data was provided.",
                    },
                ],
            });
        }

        try {
            const submittedEditToken = req.body.editToken;
            const event = await Event.findOne({
                id: req.params.eventID,
            });
            if (!event) {
                return res.status(404).json({
                    errors: [
                        {
                            message: "Event not found.",
                        },
                    ],
                });
            }
            if (event.editToken !== submittedEditToken) {
                // Token doesn't match
                addToLog(
                    "editEvent",
                    "error",
                    `Attempt to edit event ${req.params.eventID} failed with error: token does not match`,
                );
                return res.status(403).json({
                    errors: [
                        {
                            message: "Edit token is invalid.",
                        },
                    ],
                });
            }
            // Token matches
            // If there is a new image, upload that first
            let eventID = req.params.eventID;
            let eventImageFilename = event.image;
            if (req.file?.buffer) {
                Jimp.read(req.file.buffer)
                    .then((img) => {
                        img.resize(920, Jimp.AUTO) // resize
                            .quality(80) // set JPEG quality
                            .write(`./public/events/${eventID}.jpg`); // save
                    })
                    .catch((err) => {
                        addToLog(
                            "Jimp",
                            "error",
                            "Attempt to edit image failed with error: " + err,
                        );
                    });
                eventImageFilename = eventID + ".jpg";
            }

            const startUTC = moment.tz(
                eventData.eventStart,
                eventData.timezone,
            );
            const endUTC = moment.tz(eventData.eventEnd, eventData.timezone);

            let isPartOfEventGroup = false;
            let eventGroup;
            if (eventData.eventGroupBoolean) {
                eventGroup = await EventGroup.findOne({
                    id: eventData.eventGroupID,
                    editToken: eventData.eventGroupEditToken,
                });
                if (eventGroup) {
                    isPartOfEventGroup = true;
                }
            }
            const updatedEvent = {
                name: eventData.eventName,
                location: eventData.eventLocation,
                start: startUTC.toDate(),
                end: endUTC.toDate(),
                timezone: eventData.timezone,
                description: eventData.eventDescription,
                url: eventData.eventURL,
                hostName: eventData.hostName,
                image: eventImageFilename,
                showOnPublicList: eventData.publicBoolean,
                usersCanAttend: eventData.joinBoolean,
                showUsersList: false, // Backwards compatibility
                usersCanComment: eventData.interactionBoolean,
                maxAttendees: eventData.maxAttendeesBoolean
                    ? eventData.maxAttendees
                    : undefined,
                eventGroup: isPartOfEventGroup ? eventGroup?._id : null,
                activityPubActor: event.activityPubActor
                    ? updateActivityPubActor(
                          JSON.parse(event.activityPubActor),
                          eventData.eventDescription,
                          eventData.eventName,
                          eventData.eventLocation,
                          eventImageFilename,
                          startUTC,
                          endUTC,
                          eventData.timezone,
                      )
                    : undefined,
                activityPubEvent: event.activityPubEvent
                    ? updateActivityPubEvent(
                          JSON.parse(event.activityPubEvent),
                          eventData.eventName,
                          startUTC,
                          endUTC,
                          eventData.timezone,
                      )
                    : undefined,
            };
            let diffText =
                "<p>This event was just updated with new information.</p><ul>";
            let displayDate;
            if (event.name !== updatedEvent.name) {
                diffText += `<li>the event name changed to ${updatedEvent.name}</li>`;
            }
            if (event.location !== updatedEvent.location) {
                diffText += `<li>the location changed to ${updatedEvent.location}</li>`;
            }
            if (
                event.start.toISOString() !== updatedEvent.start.toISOString()
            ) {
                displayDate = moment
                    .tz(updatedEvent.start, updatedEvent.timezone)
                    .format("dddd D MMMM YYYY h:mm a");
                diffText += `<li>the start time changed to ${displayDate}</li>`;
            }
            if (event.end.toISOString() !== updatedEvent.end.toISOString()) {
                displayDate = moment
                    .tz(updatedEvent.end, updatedEvent.timezone)
                    .format("dddd D MMMM YYYY h:mm a");
                diffText += `<li>the end time changed to ${displayDate}</li>`;
            }
            if (event.timezone !== updatedEvent.timezone) {
                diffText += `<li>the time zone changed to ${updatedEvent.timezone}</li>`;
            }
            if (event.description !== updatedEvent.description) {
                diffText += `<li>the event description changed</li>`;
            }
            diffText += `</ul>`;
            const updatedEventObject = await Event.findOneAndUpdate(
                { id: req.params.eventID },
                updatedEvent,
                { new: true },
            );
            if (!updatedEventObject) {
                throw new Error("Event not found");
            }
            addToLog(
                "editEvent",
                "success",
                "Event " + req.params.eventID + " edited",
            );
            // send update to ActivityPub subscribers
            let attendees = updatedEventObject.attendees?.filter((el) => el.id);
            // broadcast an identical message to all followers, will show in home timeline
            const guidObject = crypto.randomBytes(16).toString("hex");
            const jsonObject = {
                "@context": "https://www.w3.org/ns/activitystreams",
                id: `https://${config.general.domain}/${req.params.eventID}/m/${guidObject}`,
                name: `RSVP to ${event.name}`,
                type: "Note",
                cc: "https://www.w3.org/ns/activitystreams#Public",
                content: `${diffText} See here: <a href="https://${config.general.domain}/${req.params.eventID}">https://${config.general.domain}/${req.params.eventID}</a>`,
            };
            broadcastCreateMessage(jsonObject, event.followers, eventID);
            // also broadcast an Update profile message to all followers so that at least Mastodon servers will update the local profile information
            const jsonUpdateObject = JSON.parse(event.activityPubActor || "{}");
            broadcastUpdateMessage(jsonUpdateObject, event.followers, eventID);
            // also broadcast an Update/Event for any calendar apps that are consuming our Events
            const jsonEventObject = JSON.parse(event.activityPubEvent || "{}");
            broadcastUpdateMessage(jsonEventObject, event.followers, eventID);

            // DM to attendees
            if (attendees?.length) {
                for (const attendee of attendees) {
                    const jsonObject = {
                        "@context": "https://www.w3.org/ns/activitystreams",
                        name: `RSVP to ${event.name}`,
                        type: "Note",
                        content: `<span class=\"h-card\"><a href="${attendee.id}" class="u-url mention">@<span>${attendee.name}</span></a></span> ${diffText} See here: <a href="https://${config.general.domain}/${req.params.eventID}">https://${config.general.domain}/${req.params.eventID}</a>`,
                        tag: [
                            {
                                type: "Mention",
                                href: attendee.id,
                                name: attendee.name,
                            },
                        ],
                    };
                    // send direct message to user
                    sendDirectMessage(jsonObject, attendee.id, eventID);
                }
            }
            // Send update to all attendees
            if (req.app.locals.sendEmails) {
                const attendeeEmails = event.attendees
                    ?.filter((o) => o.status === "attending" && o.email)
                    .map((o) => o.email);
                if (attendeeEmails?.length) {
                    sendEmailFromTemplate(
                        attendeeEmails.join(","),
                        `${event.name} was just edited`,
                        "editEvent",
                        {
                            diffText,
                            eventID: req.params.eventID,
                            siteName: config.general.site_name,
                            siteLogo: config.general.email_logo_url,
                            domain: config.general.domain,
                        },
                        req,
                    );
                }
            }
            res.sendStatus(200);
        } catch (err) {
            console.error(err);
            addToLog(
                "editEvent",
                "error",
                "Attempt to edit event " +
                    req.params.eventID +
                    " failed with error: " +
                    err,
            );
            return res.status(500).json({
                errors: [
                    {
                        message: err,
                    },
                ],
            });
        }
    },
);

router.post(
    "/import/event",
    icsUpload.single("icsImportControl"),
    checkMagicLink,
    async (req: Request, res: Response) => {
        if (!req.file) {
            return res.status(400).json({
                errors: [
                    {
                        message: "No file was provided.",
                    },
                ],
            });
        }

        let eventID = generateEventID();
        let editToken = generateEditToken();

        let iCalObject = ical.parseICS(req.file.buffer.toString("utf8"));

        let importedEventData = iCalObject[Object.keys(iCalObject)[0]];

        let creatorEmail: string | undefined;
        if (req.body.creatorEmail) {
            creatorEmail = req.body.creatorEmail;
        } else if (importedEventData.organizer) {
            if (typeof importedEventData.organizer === "string") {
                creatorEmail = importedEventData.organizer.replace(
                    "MAILTO:",
                    "",
                );
            } else {
                creatorEmail = importedEventData.organizer.val.replace(
                    "MAILTO:",
                    "",
                );
            }
        }

        let hostName: string | undefined;
        if (importedEventData.organizer) {
            if (typeof importedEventData.organizer === "string") {
                hostName = importedEventData.organizer.replace(/["]+/g, "");
            } else {
                hostName = importedEventData.organizer.params.CN.replace(
                    /["]+/g,
                    "",
                );
            }
        }

        const event = new Event({
            id: eventID,
            type: "public",
            name: importedEventData.summary,
            location: importedEventData.location,
            start: importedEventData.start,
            end: importedEventData.end,
            timezone: "Etc/UTC", // TODO: get timezone from ics file
            description: importedEventData.description,
            image: "",
            creatorEmail,
            url: "",
            hostName,
            viewPassword: "",
            editPassword: "",
            editToken: editToken,
            usersCanAttend: false,
            showUsersList: false,
            usersCanComment: false,
            firstLoad: true,
        });
        try {
            await event.save();
            addToLog("createEvent", "success", `Event ${eventID} created`);
            // Send email with edit link
            if (creatorEmail && req.app.locals.sendEmails) {
                sendEmailFromTemplate(
                    creatorEmail,
                    `${importedEventData.summary}`,
                    "createEvent",
                    {
                        eventID,
                        editToken,
                        siteName: config.general.site_name,
                        siteLogo: config.general.email_logo_url,
                        domain: config.general.domain,
                    },
                    req,
                );
            }
            return res.json({
                eventID: eventID,
                editToken: editToken,
                url: `/${eventID}?e=${editToken}`,
            });
        } catch (err) {
            console.error(err);
            addToLog(
                "createEvent",
                "error",
                "Attempt to create event failed with error: " + err,
            );
            return res.status(500).json({
                errors: [
                    {
                        message: err,
                    },
                ],
            });
        }
    },
);

export default router;