diff --git a/cypress/e2e/event.cy.ts b/cypress/e2e/event.cy.ts index 3536806..cf0a1e6 100644 --- a/cypress/e2e/event.cy.ts +++ b/cypress/e2e/event.cy.ts @@ -4,7 +4,6 @@ const eventData = { timezone: "Europe/London", eventDescription: "Event Description", eventURL: "https://example.com", - imagePath: "path/to/your/image.jpg", // If you have an image to upload hostName: "Your Name", creatorEmail: "test@example.com", eventGroupCheckbox: false, @@ -14,40 +13,25 @@ const eventData = { joinCheckbox: true, maxAttendeesCheckbox: true, maxAttendees: 10, - eventStart: "", - eventEnd: "", + eventStart: "2030-01-01T00:00", + eventEnd: "2030-01-01T01:00", }; describe("Events", () => { beforeEach(() => { - cy.clearLocalStorage(); - cy.visit("/new"); cy.get("#showNewEventFormButton").click(); cy.get("#eventName").type(eventData.eventName); cy.get("#eventLocation").type(eventData.eventLocation); - cy.get("#eventStart").click(); - // This opens a datepicker, so find the first non-disabled day and click it - cy.get(".datepicker--cell-day:not(.-disabled-)").first().click(); - cy.get("#eventStart").invoke("val").as("eventStart"); - // Click away from the datepicker to close it - cy.get("#eventName").click(); - cy.get("#eventEnd").click(); - // This opens a datepicker, so find the last non-disabled day and click it - cy.get(".datepicker--cell-day:not(.-disabled-)").last().click(); - cy.get("#eventEnd").invoke("val").as("eventEnd"); - // Click away from the datepicker to close it - cy.get("#eventName").click(); + // These are datetime-local inputs + cy.get("#eventStart").type(eventData.eventStart); + cy.get("#eventEnd").type(eventData.eventEnd); // #timezone is a Select2 dropdown, so select the option you want cy.get("#timezone").select(eventData.timezone, { force: true }); cy.get("#eventDescription").type(eventData.eventDescription); cy.get("#eventURL").type(eventData.eventURL); - // Upload an image - // if (eventData.imagePath) { - // cy.get("#eventImageUpload").attachFile(eventData.imagePath); - // } cy.get("#hostName").type(eventData.hostName); cy.get("#creatorEmail").type(eventData.creatorEmail); @@ -74,6 +58,16 @@ describe("Events", () => { // Submit the form cy.get("#newEventFormSubmit").click(); + + // Wait for the new page to load + cy.url().should("not.include", "/new"); + + // Get the new event ID from the URL + cy.url().then((url) => { + const [eventID, editToken] = url.split("/").pop().split("?"); + cy.wrap(eventID).as("eventID"); + cy.wrap(editToken).as("editToken"); + }); }); it("creates a new event", function () { // Check that all the data is correct @@ -82,18 +76,13 @@ describe("Events", () => { cy.get(".p-summary").should("contain.text", eventData.eventDescription); cy.get("#hosted-by").should( "contain.text", - `Hosted by ${eventData.hostName}` + `Hosted by ${eventData.hostName}`, ); cy.get("#attendees-alert").should("contain.text", "10 spots remaining"); - let [startDate, startTime] = this.eventStart.split(", "); - let [endDate, endTime] = this.eventEnd.split(", "); - // Remove leading zeroes from the times - startTime = startTime.replace(/^0+/, ""); - endTime = endTime.replace(/^0+/, ""); - cy.get(".dt-duration").should("contain.text", startDate); - cy.get(".dt-duration").should("contain.text", endDate); - cy.get(".dt-duration").should("contain.text", startTime); - cy.get(".dt-duration").should("contain.text", endTime); + cy.get(".dt-duration").should( + "contain.text", + "Tuesday 1 January 2030 from 12:00 am to 1:00 am (GMT)", + ); }); it("allows you to attend an event", function () { @@ -105,7 +94,7 @@ describe("Events", () => { cy.get("#attendees-alert").should("contain.text", "8 spots remaining"); cy.get(".attendeesList").should( "contain.text", - "Test Attendee (2 people)" + "Test Attendee (2 people)", ); }); @@ -116,4 +105,109 @@ describe("Events", () => { cy.get(".comment").should("contain.text", "Test Author"); cy.get(".comment").should("contain.text", "Test Comment"); }); + + it("displays the ActivityPub featured post", function () { + cy.log(this.eventID); + + cy.request({ + url: `/${this.eventID}/featured`, + headers: { + Accept: "application/activity+json", + }, + }).then((response) => { + expect(response.body).to.have.property("@context"); + expect(response.body).to.have.property("id"); + expect(response.body).to.have.property("type"); + expect(response.body).to.have.property("orderedItems"); + expect(response.body.orderedItems) + .to.be.an("array") + .and.to.have.lengthOf(1); + const featuredPost = response.body.orderedItems[0]; + expect(featuredPost).to.have.property("@context"); + expect(featuredPost).to.have.property("id"); + expect(featuredPost).to.have.property("type"); + expect(featuredPost).to.have.property("name"); + expect(featuredPost).to.have.property("content"); + expect(featuredPost).to.have.property("attributedTo"); + }); + }); + + it("responds correctly to ActivityPub webfinger requests", function () { + cy.request({ + url: `/.well-known/webfinger?resource=acct:${ + this.eventID + }@${Cypress.env("CYPRESS_DOMAIN")}`, + headers: { + Accept: "application/activity+json", + }, + }).then((response) => { + expect(response.body).to.have.property("subject"); + expect(response.body).to.have.property("links"); + expect(response.body.links) + .to.be.an("array") + .and.to.have.lengthOf(1); + const link = response.body.links[0]; + expect(link).to.have.property("rel"); + expect(link).to.have.property("type"); + expect(link).to.have.property("href"); + }); + }); + + it("edits an event", function () { + cy.get("#editEvent").click(); + + // The edit form is the same as the new form, so we can just re-use the same selectors + // but we need to clear the fields first + cy.get("#editEventForm #eventName").clear(); + cy.get("#editEventForm #eventLocation").clear(); + cy.get("#editEventForm #eventStart").clear(); + cy.get("#editEventForm #eventEnd").clear(); + cy.get("#editEventForm #eventDescription").clear(); + cy.get("#editEventForm #eventURL").clear(); + cy.get("#editEventForm #hostName").clear(); + cy.get("#editEventForm #creatorEmail").clear(); + cy.get("#editEventForm #maxAttendees").clear(); + + cy.get("#editEventForm #eventName").type("Edited Event Name"); + cy.get("#editEventForm #eventLocation").type("Edited Event Location"); + // These are datetime-local inputs + cy.get("#editEventForm #eventStart").type("2030-12-01T00:00"); + cy.get("#editEventForm #eventEnd").type("2030-12-01T01:00"); + // #timezone is a Select2 dropdown, so select the option you want + cy.get("#editEventForm #timezone").select("Australia/Sydney", { + force: true, + }); + cy.get("#editEventForm #eventDescription").type( + "Edited Event Description", + ); + cy.get("#editEventForm #eventURL").type("https://edited.example.com"); + cy.get("#editEventForm #hostName").type("Edited Name"); + cy.get("#editEventForm #creatorEmail").type("edited@example.com"); + + cy.get("#editEventForm #maxAttendeesCheckbox").uncheck(); + + cy.get("#editEventForm #interactionCheckbox").uncheck(); + + cy.get("#editEventForm #joinCheckbox").uncheck(); + + // Submit the form + cy.get("#editEventForm").submit(); + + // Wait for the modal to not be visible + cy.get("#editModal").should("not.be.visible"); + + // Check that all the data is correct + cy.get(".p-name").should("have.text", "Edited Event Name"); + cy.get(".p-location").should("have.text", "Edited Event Location"); + cy.get(".p-summary").should("contain.text", "Edited Event Description"); + cy.get("#hosted-by").should("contain.text", "Hosted by Edited Name"); + cy.get(".dt-duration").should( + "contain.text", + "Sunday 1 December 2030 from 12:00 am to 1:00 am", + ); + // Check that the comment form is not visible + cy.get("#postComment").should("not.exist"); + // Check that the attendee form is not visible + cy.get("#attendEvent").should("not.exist"); + }); }); diff --git a/public/css/style.css b/public/css/style.css index 93789b7..a312587 100755 --- a/public/css/style.css +++ b/public/css/style.css @@ -305,17 +305,6 @@ body, html { margin-top: 0.5rem; } -#maxAttendeesContainer { - display: none; -} -/* #maxAttendeesCheckboxContainer { - display: none; -} */ - -#eventGroupData { - display: none; -} - .edit-buttons { text-align: right; } diff --git a/public/js/generate-timezones.js b/public/js/generate-timezones.js index 01c9989..02607a9 100644 --- a/public/js/generate-timezones.js +++ b/public/js/generate-timezones.js @@ -373,6 +373,4 @@ const timezones = [ document.querySelector("#timezone").innerHTML = selectorOptions; document.querySelector("#timezone").value = moment.tz.guess(); - - $("#timezone").select2(); \ No newline at end of file diff --git a/src/app.ts b/src/app.ts index 5b01b3c..30cf02d 100755 --- a/src/app.ts +++ b/src/app.ts @@ -3,9 +3,15 @@ import hbs from "express-handlebars"; import routes from "./routes.js"; import frontend from "./routes/frontend.js"; +import activitypub from "./routes/activitypub.js"; +import event from "./routes/event.js"; + +import { initEmailService } from "./lib/email.js"; const app = express(); +app.locals.sendEmails = initEmailService(); + // View engine // const hbsInstance = hbs.create({ defaultLayout: "main", @@ -37,11 +43,15 @@ app.set("hbsInstance", hbsInstance); app.use(express.static("public")); // Body parser // -app.use(express.json({ type: "application/activity+json" })); // support json encoded bodies +app.use(express.json({ type: "application/activity+json" })); +app.use(express.json({ type: "application/ld+json" })); +app.use(express.json({ type: "application/json" })); app.use(express.urlencoded({ extended: true })); // Router // app.use("/", frontend); +app.use("/", activitypub); +app.use("/", event); app.use("/", routes); export default app; diff --git a/src/lib/activitypub.ts b/src/lib/activitypub.ts new file mode 100644 index 0000000..0a3db7b --- /dev/null +++ b/src/lib/activitypub.ts @@ -0,0 +1,9 @@ +import { Request } from "express"; + +export const acceptsActivityPub = (req: Request) => { + return ( + req.headers.accept && + (req.headers.accept.includes("application/activity+json") || + req.headers.accept.includes("application/ld+json")) + ); +}; diff --git a/src/lib/config.ts b/src/lib/config.ts index 9577fd6..7b35b98 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -1,5 +1,6 @@ import fs from "fs"; import toml from "toml"; +import { exitWithError } from "./process.js"; interface GathioConfig { general: { @@ -46,8 +47,8 @@ export const getConfig = (): GathioConfig => { ) as GathioConfig; return config; } catch { - console.error( - "\x1b[31mConfiguration file not found! Have you renamed './config/config-example.toml' to './config/config.toml'?", + exitWithError( + "Configuration file not found! Have you renamed './config/config-example.toml' to './config/config.toml'?", ); return process.exit(1); } diff --git a/src/lib/email.ts b/src/lib/email.ts new file mode 100644 index 0000000..f55fa3b --- /dev/null +++ b/src/lib/email.ts @@ -0,0 +1,145 @@ +import { Request } from "express"; +import sgMail from "@sendgrid/mail"; +import nodemailer, { TransportOptions } from "nodemailer"; +import { getConfig } from "./config.js"; +import SMTPTransport from "nodemailer/lib/smtp-transport/index.js"; +import { exitWithError } from "./process.js"; +import { renderTemplate } from "./handlebars.js"; +const config = getConfig(); + +type EmailTemplate = + | "addEventAttendee" + | "addEventComment" + | "createEvent" + | "createEventGroup" + | "deleteEvent" + | "editEvent" + | "eventGroupUpdated" + | "subscribed" + | "unattendEvent"; + +export const initEmailService = async (): Promise => { + switch (config.general.mail_service) { + case "sendgrid": + if (!config.sendgrid?.api_key) { + return exitWithError( + "Sendgrid is configured as the email service, but no API key is provided. Please provide an API key in the config file.", + ); + } + sgMail.setApiKey(config.sendgrid.api_key); + console.log("Sendgrid is ready to send emails."); + return true; + case "nodemailer": + if ( + !config.nodemailer?.smtp_server || + !config.nodemailer?.smtp_port || + !config.nodemailer?.smtp_username || + !config.nodemailer?.smtp_password + ) { + return exitWithError( + "Nodemailer is configured as the email service, but not all required fields are provided. Please provide all required fields in the config file.", + ); + } + const nodemailerConfig = { + host: config.nodemailer?.smtp_server, + port: Number(config.nodemailer?.smtp_port) || 587, + auth: { + user: config.nodemailer?.smtp_username, + pass: config.nodemailer?.smtp_password, + }, + } as SMTPTransport.Options; + const nodemailerTransporter = + nodemailer.createTransport(nodemailerConfig); + const nodemailerVerified = await nodemailerTransporter.verify(); + if (nodemailerVerified) { + console.log("Nodemailer is ready to send emails."); + return true; + } else { + return exitWithError( + "Error verifying Nodemailer transporter. Please check your Nodemailer configuration.", + ); + } + default: + console.warn( + "You have not configured this Gathio instance to send emails! This means that event creators will not receive emails when their events are created, which means they may end up locked out of editing events. Consider setting up an email service.", + ); + return false; + } +}; + +export const sendEmail = async ( + to: string, + subject: string, + text: string, + html?: string, +): Promise => { + switch (config.general.mail_service) { + case "sendgrid": + try { + await sgMail.send({ + to, + from: config.general.email, + subject: `${config.general.site_name}: ${subject}`, + text, + html, + }); + return true; + } catch (e: any) { + if (e.response) { + console.error(e.response.body); + } else { + console.error(e); + } + return false; + } + case "nodemailer": + try { + const nodemailerConfig = { + host: config.nodemailer?.smtp_server, + port: Number(config.nodemailer?.smtp_port) || 587, + auth: { + user: config.nodemailer?.smtp_username, + pass: config.nodemailer?.smtp_password, + }, + } as SMTPTransport.Options; + const nodemailerTransporter = + nodemailer.createTransport(nodemailerConfig); + await nodemailerTransporter.sendMail({ + from: config.general.email, + to, + subject, + text, + html, + }); + return true; + } catch (e) { + console.error(e); + return false; + } + default: + return false; + } +}; + +export const sendEmailFromTemplate = async ( + to: string, + subject: string, + template: EmailTemplate, + templateData: Record, + req: Request, +): Promise => { + const html = await renderTemplate(req, `${template}/${template}Html`, { + siteName: config.general.site_name, + siteLogo: config.general.email_logo_url, + domain: config.general.domain, + cache: true, + layout: "email.handlebars", + ...templateData, + }); + const text = await renderTemplate( + req, + `${template}/${template}Text`, + templateData, + ); + return await sendEmail(to, subject, text, html); +}; diff --git a/src/lib/handlebars.ts b/src/lib/handlebars.ts new file mode 100644 index 0000000..d5a8b6e --- /dev/null +++ b/src/lib/handlebars.ts @@ -0,0 +1,23 @@ +import { Request } from "express"; + +export const renderTemplate = async ( + req: Request, + templateName: string, + data: Record, +): Promise => { + return new Promise((resolve, reject) => { + req.app + .get("hbsInstance") + .renderView( + `./views/emails/${templateName}.handlebars`, + data, + (err: any, html: string) => { + if (err) { + console.error(err); + reject(err); + } + resolve(html); + }, + ); + }); +}; diff --git a/src/lib/process.ts b/src/lib/process.ts new file mode 100644 index 0000000..d43b3c7 --- /dev/null +++ b/src/lib/process.ts @@ -0,0 +1,4 @@ +export const exitWithError = (message: string) => { + console.error(`\x1b[31m${message}`); + process.exit(1); +}; diff --git a/src/routes.js b/src/routes.js index 7257bdb..94b7477 100755 --- a/src/routes.js +++ b/src/routes.js @@ -6,7 +6,6 @@ import { getConfig } from "./lib/config.js"; import { addToLog, exportIcal } from "./helpers.js"; import moment from "moment-timezone"; import { marked } from "marked"; -import generateRSAKeypair from "generate-rsa-keypair"; import crypto from "crypto"; import request from "request"; import niceware from "niceware"; @@ -17,21 +16,14 @@ import fileUpload from "express-fileupload"; import Jimp from "jimp"; import schedule from "node-schedule"; import { - createActivityPubActor, - createActivityPubEvent, - createFeaturedPost, - createWebfinger, - updateActivityPubActor, - updateActivityPubEvent, broadcastCreateMessage, - broadcastUpdateMessage, broadcastDeleteMessage, - sendDirectMessage, processInbox, } from "./activitypub.js"; import Event from "./models/Event.js"; import EventGroup from "./models/EventGroup.js"; import path from "path"; +import { renderPlain } from "./util/markdown.js"; const config = getConfig(); const domain = config.general.domain; @@ -40,7 +32,6 @@ const siteName = config.general.site_name; const mailService = config.general.mail_service; const siteLogo = config.general.email_logo_url; const isFederated = config.general.is_federated || true; -const showKofi = config.general.show_kofi; // This alphabet (used to generate all event, group, etc. IDs) is missing '-' // because ActivityPub doesn't like it in IDs @@ -193,180 +184,6 @@ schedule.scheduleJob("59 23 * * *", function (fireDate) { // old (they're not going to become active) }); -// return the JSON for the featured/pinned post for this event -router.get("/:eventID/featured", (req, res) => { - if (!isFederated) return res.sendStatus(404); - const { eventID } = req.params; - const guidObject = crypto.randomBytes(16).toString("hex"); - const featured = { - "@context": "https://www.w3.org/ns/activitystreams", - id: `https://${domain}/${eventID}/featured`, - type: "OrderedCollection", - orderedItems: [createFeaturedPost(eventID)], - }; - if ( - req.headers.accept && - (req.headers.accept.includes("application/activity+json") || - req.headers.accept.includes("application/ld+json")) - ) { - res.header("Content-Type", "application/activity+json").send(featured); - } else { - res.header("Content-Type", "application/json").send(featured); - } -}); - -// return the JSON for a given activitypub message -router.get("/:eventID/m/:hash", (req, res) => { - if (!isFederated) return res.sendStatus(404); - const { hash, eventID } = req.params; - const id = `https://${domain}/${eventID}/m/${hash}`; - - Event.findOne({ - id: eventID, - }) - .then((event) => { - if (!event) { - res.status(404); - res.render("404", { url: req.url }); - } else { - const message = event.activityPubMessages.find( - (el) => el.id === id, - ); - if (message) { - if ( - req.headers.accept && - (req.headers.accept.includes( - "application/activity+json", - ) || - req.headers.accept.includes("application/ld+json")) - ) { - res.header( - "Content-Type", - "application/activity+json", - ).send(JSON.parse(message.content)); - } else { - res.header("Content-Type", "application/json").send( - JSON.parse(message.content), - ); - } - } else { - res.status(404); - return res.render("404", { url: req.url }); - } - } - }) - .catch((err) => { - addToLog( - "getActivityPubMessage", - "error", - "Attempt to get Activity Pub Message for " + - id + - " failed with error: " + - err, - ); - res.status(404); - res.render("404", { url: req.url }); - return; - }); -}); - -// return the webfinger record required for the initial activitypub handshake -router.get("/.well-known/webfinger", (req, res) => { - if (!isFederated) return res.sendStatus(404); - let resource = req.query.resource; - if (!resource || !resource.includes("acct:")) { - return res - .status(400) - .send( - 'Bad request. Please make sure "acct:USER@DOMAIN" is what you are sending as the "resource" query parameter.', - ); - } else { - // "foo@domain" - let activityPubAccount = resource.replace("acct:", ""); - // "foo" - let eventID = activityPubAccount.replace(/@.*/, ""); - Event.findOne({ - id: eventID, - }) - .then((event) => { - if (!event) { - res.status(404); - res.render("404", { url: req.url }); - } else { - if ( - req.headers.accept && - (req.headers.accept.includes( - "application/activity+json", - ) || - req.headers.accept.includes("application/ld+json")) - ) { - res.header( - "Content-Type", - "application/activity+json", - ).send(createWebfinger(eventID, domain)); - } else { - res.header("Content-Type", "application/json").send( - createWebfinger(eventID, domain), - ); - } - } - }) - .catch((err) => { - addToLog( - "renderWebfinger", - "error", - "Attempt to render webfinger for " + - req.params.eventID + - " failed with error: " + - err, - ); - res.status(404); - res.render("404", { url: req.url }); - return; - }); - } -}); - -router.get("/:eventID/followers", (req, res) => { - if (!isFederated) return res.sendStatus(404); - const eventID = req.params.eventID; - Event.findOne({ - id: eventID, - }).then((event) => { - if (event) { - const followers = event.followers.map((el) => el.actorId); - let followersCollection = { - type: "OrderedCollection", - totalItems: followers.length, - id: `https://${domain}/${eventID}/followers`, - first: { - type: "OrderedCollectionPage", - totalItems: followers.length, - partOf: `https://${domain}/${eventID}/followers`, - orderedItems: followers, - id: `https://${domain}/${eventID}/followers?page=1`, - }, - "@context": ["https://www.w3.org/ns/activitystreams"], - }; - if ( - req.headers.accept && - (req.headers.accept.includes("application/activity+json") || - req.headers.accept.includes("application/ld+json")) - ) { - return res - .header("Content-Type", "application/activity+json") - .send(followersCollection); - } else { - return res - .header("Content-Type", "application/json") - .send(followersCollection); - } - } else { - return res.status(400).send("Bad request."); - } - }); -}); - router.get("/group/:eventGroupID", (req, res) => { EventGroup.findOne({ id: req.params.eventGroupID, @@ -467,7 +284,7 @@ router.get("/group/:eventGroupID", (req, res) => { title: eventGroup.name, description: marked .parse(eventGroup.description, { - renderer: render_plain(), + renderer: renderPlain(), }) .split(" ") .splice(0, 40) @@ -603,243 +420,6 @@ router.get("/exportgroup/:eventGroupID", (req, res) => { }); // BACKEND ROUTES - -router.post("/newevent", async (req, res) => { - let eventID = nanoid(); - let editToken = randomstring.generate(); - let eventImageFilename = ""; - let isPartOfEventGroup = false; - if (req.files && Object.keys(req.files).length !== 0) { - let eventImageBuffer = req.files.imageUpload.data; - eventImageFilename = await Jimp.read(eventImageBuffer) - .then((img) => { - img.resize(920, Jimp.AUTO) // resize - .quality(80) // set JPEG quality - .write("./public/events/" + eventID + ".jpg"); // save - const filename = eventID + ".jpg"; - return filename; - }) - .catch((err) => { - addToLog( - "Jimp", - "error", - "Attempt to edit image failed with error: " + err, - ); - }); - } - let startUTC = moment.tz( - req.body.eventStart, - "D MMMM YYYY, hh:mm a", - req.body.timezone, - ); - let endUTC = moment.tz( - req.body.eventEnd, - "D MMMM YYYY, hh:mm a", - req.body.timezone, - ); - let eventGroup; - if (req.body.eventGroupCheckbox) { - eventGroup = await EventGroup.findOne({ - id: req.body.eventGroupID, - editToken: req.body.eventGroupEditToken, - }); - if (eventGroup) { - isPartOfEventGroup = true; - } - } - - // generate RSA keypair for ActivityPub - let pair = generateRSAKeypair(); - - const event = new Event({ - id: eventID, - type: "public", // This is for backwards compatibility - name: req.body.eventName, - location: req.body.eventLocation, - start: startUTC, - end: endUTC, - timezone: req.body.timezone, - description: req.body.eventDescription, - image: eventImageFilename, - creatorEmail: req.body.creatorEmail, - url: req.body.eventURL, - hostName: req.body.hostName, - viewPassword: req.body.viewPassword, - editPassword: req.body.editPassword, - editToken: editToken, - eventGroup: isPartOfEventGroup ? eventGroup._id : null, - usersCanAttend: req.body.joinCheckbox ? true : false, - showUsersList: req.body.guestlistCheckbox ? true : false, - usersCanComment: req.body.interactionCheckbox ? true : false, - maxAttendees: req.body.maxAttendees, - firstLoad: true, - activityPubActor: createActivityPubActor( - eventID, - domain, - pair.public, - marked.parse(req.body.eventDescription), - req.body.eventName, - req.body.eventLocation, - eventImageFilename, - startUTC, - endUTC, - req.body.timezone, - ), - activityPubEvent: createActivityPubEvent( - req.body.eventName, - startUTC, - endUTC, - req.body.timezone, - req.body.eventDescription, - req.body.eventLocation, - ), - activityPubMessages: [ - { - id: `https://${domain}/${eventID}/m/featuredPost`, - content: JSON.stringify( - createFeaturedPost( - eventID, - req.body.eventName, - startUTC, - endUTC, - req.body.timezone, - req.body.eventDescription, - req.body.eventLocation, - ), - ), - }, - ], - publicKey: pair.public, - privateKey: pair.private, - }); - event - .save() - .then((event) => { - addToLog("createEvent", "success", "Event " + eventID + "created"); - // Send email with edit link - if (req.body.creatorEmail && sendEmails) { - req.app.get("hbsInstance").renderView( - "./views/emails/createevent.handlebars", - { - eventID, - editToken, - siteName, - siteLogo, - domain, - cache: true, - layout: "email.handlebars", - }, - function (err, html) { - const msg = { - to: req.body.creatorEmail, - from: { - name: siteName, - email: contactEmail, - address: contactEmail, - }, - subject: `${siteName}: ${req.body.eventName}`, - html, - }; - switch (mailService) { - case "sendgrid": - sgMail.send(msg).catch((e) => { - console.error(e.toString()); - res.status(500).end(); - }); - break; - case "nodemailer": - nodemailerTransporter - .sendMail(msg) - .catch((e) => { - console.error(e.toString()); - res.status(500).end(); - }); - break; - } - }, - ); - } - // If the event was added to a group, send an email to any group - // subscribers - if (event.eventGroup && sendEmails) { - EventGroup.findOne({ _id: event.eventGroup._id }).then( - (eventGroup) => { - const subscribers = eventGroup.subscribers.reduce( - (acc, current) => { - if (acc.includes(current.email)) { - return acc; - } - return [current.email, ...acc]; - }, - [], - ); - subscribers.forEach((emailAddress) => { - req.app.get("hbsInstance").renderView( - "./views/emails/eventgroupupdated.handlebars", - { - siteName, - siteLogo, - domain, - eventID: req.params.eventID, - eventGroupName: eventGroup.name, - eventName: event.name, - eventID: event.id, - eventGroupID: eventGroup.id, - emailAddress: - encodeURIComponent(emailAddress), - cache: true, - layout: "email.handlebars", - }, - function (err, html) { - const msg = { - to: emailAddress, - from: { - name: siteName, - email: contactEmail, - }, - subject: `${siteName}: New event in ${eventGroup.name}`, - html, - }; - switch (mailService) { - case "sendgrid": - sgMail.send(msg).catch((e) => { - console.error(e.toString()); - res.status(500).end(); - }); - break; - case "nodemailer": - nodemailerTransporter - .sendMail(msg) - .catch((e) => { - console.error(e.toString()); - res.status(500).end(); - }); - break; - } - }, - ); - }); - }, - ); - } - res.writeHead(302, { - Location: "/" + eventID + "?e=" + editToken, - }); - res.end(); - }) - .catch((err) => { - console.error(err); - res.status(500).send( - "Database error, please try again :( - " + err, - ); - addToLog( - "createEvent", - "error", - "Attempt to create event failed with error: " + err, - ); - }); -}); - router.post("/importevent", (req, res) => { let eventID = nanoid(); let editToken = randomstring.generate(); @@ -1071,338 +651,6 @@ router.post("/verifytoken/group/:eventGroupID", (req, res) => { }); }); -router.post("/editevent/:eventID/:editToken", (req, res) => { - let submittedEditToken = req.params.editToken; - Event.findOne({ - id: req.params.eventID, - }) - .then(async (event) => { - if (event.editToken === submittedEditToken) { - // Token matches - - // If there is a new image, upload that first - let eventID = req.params.eventID; - let eventImageFilename = event.image; - if (req.files && Object.keys(req.files).length !== 0) { - let eventImageBuffer = req.files.imageUpload.data; - Jimp.read(eventImageBuffer, (err, img) => { - if (err) throw err; - img.resize(920, Jimp.AUTO) // resize - .quality(80) // set JPEG - .write("./public/events/" + eventID + ".jpg"); // save - }); - eventImageFilename = eventID + ".jpg"; - } - let startUTC = moment.tz( - req.body.eventStart, - "D MMMM YYYY, hh:mm a", - req.body.timezone, - ); - let endUTC = moment.tz( - req.body.eventEnd, - "D MMMM YYYY, hh:mm a", - req.body.timezone, - ); - - let isPartOfEventGroup = false; - let eventGroup; - if (req.body.eventGroupCheckbox) { - eventGroup = await EventGroup.findOne({ - id: req.body.eventGroupID, - editToken: req.body.eventGroupEditToken, - }); - if (eventGroup) { - isPartOfEventGroup = true; - } - } - const updatedEvent = { - name: req.body.eventName, - location: req.body.eventLocation, - start: startUTC, - end: endUTC, - timezone: req.body.timezone, - description: req.body.eventDescription, - url: req.body.eventURL, - hostName: req.body.hostName, - image: eventImageFilename, - usersCanAttend: req.body.joinCheckbox ? true : false, - showUsersList: req.body.guestlistCheckbox ? true : false, - usersCanComment: req.body.interactionCheckbox - ? true - : false, - maxAttendees: req.body.maxAttendeesCheckbox - ? req.body.maxAttendees - : null, - eventGroup: isPartOfEventGroup ? eventGroup._id : null, - activityPubActor: event.activityPubActor - ? updateActivityPubActor( - JSON.parse(event.activityPubActor), - req.body.eventDescription, - req.body.eventName, - req.body.eventLocation, - eventImageFilename, - startUTC, - endUTC, - req.body.timezone, - ) - : null, - activityPubEvent: event.activityPubEvent - ? updateActivityPubEvent( - JSON.parse(event.activityPubEvent), - req.body.eventName, - req.body.startUTC, - req.body.endUTC, - req.body.timezone, - ) - : null, - }; - let diffText = - "

This event was just updated with new information.

    "; - let displayDate; - if (event.name !== updatedEvent.name) { - diffText += `
  • the event name changed to ${updatedEvent.name}
  • `; - } - if (event.location !== updatedEvent.location) { - diffText += `
  • the location changed to ${updatedEvent.location}
  • `; - } - if ( - event.start.toISOString() !== - updatedEvent.start.toISOString() - ) { - displayDate = moment - .tz(updatedEvent.start, updatedEvent.timezone) - .format("dddd D MMMM YYYY h:mm a"); - diffText += `
  • the start time changed to ${displayDate}
  • `; - } - if ( - event.end.toISOString() !== updatedEvent.end.toISOString() - ) { - displayDate = moment - .tz(updatedEvent.end, updatedEvent.timezone) - .format("dddd D MMMM YYYY h:mm a"); - diffText += `
  • the end time changed to ${displayDate}
  • `; - } - if (event.timezone !== updatedEvent.timezone) { - diffText += `
  • the time zone changed to ${updatedEvent.timezone}
  • `; - } - if (event.description !== updatedEvent.description) { - diffText += `
  • the event description changed
  • `; - } - diffText += `
`; - Event.findOneAndUpdate( - { id: req.params.eventID }, - updatedEvent, - function (err, raw) { - if (err) { - addToLog( - "editEvent", - "error", - "Attempt to edit event " + - req.params.eventID + - " failed with error: " + - err, - ); - res.send(err); - } - }, - ) - .then(() => { - addToLog( - "editEvent", - "success", - "Event " + req.params.eventID + " edited", - ); - // send update to ActivityPub subscribers - Event.findOne( - { id: req.params.eventID }, - function (err, event) { - if (!event) return; - let attendees = event.attendees.filter( - (el) => el.id, - ); - if (!err) { - // 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://${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: https://${domain}/${req.params.eventID}`, - }; - 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 - for (const attendee of attendees) { - const jsonObject = { - "@context": - "https://www.w3.org/ns/activitystreams", - name: `RSVP to ${event.name}`, - type: "Note", - content: `@${attendee.name} ${diffText} See here: https://${domain}/${req.params.eventID}`, - 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 (sendEmails) { - Event.findOne({ id: req.params.eventID }).then( - (event) => { - const attendeeEmails = event.attendees - .filter( - (o) => - o.status === "attending" && - o.email, - ) - .map((o) => o.email); - if (attendeeEmails.length) { - console.log( - "Sending emails to: " + - attendeeEmails, - ); - req.app.get("hbsInstance").renderView( - "./views/emails/editevent.handlebars", - { - diffText, - eventID: req.params.eventID, - siteName, - siteLogo, - domain, - cache: true, - layout: "email.handlebars", - }, - function (err, html) { - const msg = { - to: attendeeEmails, - from: { - name: siteName, - email: contactEmail, - address: contactEmail, - }, - subject: `${siteName}: ${event.name} was just edited`, - html, - }; - switch (mailService) { - case "sendgrid": - sgMail - .sendMultiple(msg) - .catch((e) => { - console.error( - e.toString(), - ); - res.status( - 500, - ).end(); - }); - break; - case "nodemailer": - nodemailerTransporter - .sendMail(msg) - .catch((e) => { - console.error( - e.toString(), - ); - res.status( - 500, - ).end(); - }); - break; - } - }, - ); - } else { - console.log("Nothing to send!"); - } - }, - ); - } - res.writeHead(302, { - Location: - "/" + - req.params.eventID + - "?e=" + - req.params.editToken, - }); - res.end(); - }) - .catch((err) => { - console.error(err); - res.send("Sorry! Something went wrong!"); - addToLog( - "editEvent", - "error", - "Attempt to edit event " + - req.params.eventID + - " failed with error: " + - err, - ); - }); - } else { - // Token doesn't match - res.send("Sorry! Something went wrong"); - addToLog( - "editEvent", - "error", - "Attempt to edit event " + - req.params.eventID + - " failed with error: token does not match", - ); - } - }) - .catch((err) => { - console.error(err); - res.send("Sorry! Something went wrong!"); - addToLog( - "editEvent", - "error", - "Attempt to edit event " + - req.params.eventID + - " failed with error: " + - err, - ); - }); -}); - router.post("/editeventgroup/:eventGroupID/:editToken", (req, res) => { let submittedEditToken = req.params.editToken; EventGroup.findOne({ @@ -1506,6 +754,7 @@ router.post("/editeventgroup/:eventGroupID/:editToken", (req, res) => { router.post("/deleteimage/:eventID/:editToken", (req, res) => { let submittedEditToken = req.params.editToken; + let eventImage; Event.findOne({ id: req.params.eventID, }).then((event) => { diff --git a/src/routes/activitypub.ts b/src/routes/activitypub.ts new file mode 100644 index 0000000..2c4231a --- /dev/null +++ b/src/routes/activitypub.ts @@ -0,0 +1,174 @@ +import { Router, Request, Response, NextFunction } from "express"; +import { createFeaturedPost, createWebfinger } from "../activitypub.js"; +import { acceptsActivityPub } from "../lib/activitypub.js"; +import getConfig from "../lib/config.js"; +import Event from "../models/Event.js"; +import { addToLog } from "../helpers.js"; + +const config = getConfig(); + +const router = Router(); + +const send404IfNotFederated = ( + req: Request, + res: Response, + next: NextFunction, +) => { + if (!config.general.is_federated) { + res.status(404).render("404", { url: req.url }); + return; + } + next(); +}; + +router.use(send404IfNotFederated); + +// return the JSON for the featured/pinned post for this event +router.get("/:eventID/featured", (req: Request, res: Response) => { + const { eventID } = req.params; + const featured = { + "@context": "https://www.w3.org/ns/activitystreams", + id: `https://${config.general.domain}/${eventID}/featured`, + type: "OrderedCollection", + orderedItems: [createFeaturedPost(eventID)], + }; + if (acceptsActivityPub(req)) { + res.header("Content-Type", "application/activity+json").send(featured); + } else { + res.header("Content-Type", "application/json").send(featured); + } +}); + +// return the JSON for a given activitypub message +router.get("/:eventID/m/:hash", async (req: Request, res: Response) => { + const { hash, eventID } = req.params; + const id = `https://${config.general.domain}/${eventID}/m/${hash}`; + + try { + const event = await Event.findOne({ + id: eventID, + }); + if (!event) { + return res.status(404).render("404", { url: req.url }); + } else { + if (!event.activityPubMessages) { + return res.status(404).render("404", { url: req.url }); + } + const message = event.activityPubMessages.find( + (el) => el.id === id, + ); + if (message) { + if (acceptsActivityPub(req)) { + res.header( + "Content-Type", + "application/activity+json", + ).send(JSON.parse(message.content || "{}")); + } else { + res.header("Content-Type", "application/json").send( + JSON.parse(message.content || "{}"), + ); + } + } else { + return res.status(404).render("404", { url: req.url }); + } + } + } catch (err) { + addToLog( + "getActivityPubMessage", + "error", + "Attempt to get Activity Pub Message for " + + id + + " failed with error: " + + err, + ); + return res.status(404).render("404", { url: req.url }); + } +}); + +router.get("/.well-known/webfinger", async (req, res) => { + let resource = req.query.resource as string; + if (!resource || !resource.includes("acct:")) { + return res + .status(400) + .send( + 'Bad request. Please make sure "acct:USER@DOMAIN" is what you are sending as the "resource" query parameter.', + ); + } else { + // "foo@domain" + let activityPubAccount = resource.replace("acct:", ""); + // "foo" + let eventID = activityPubAccount.replace(/@.*/, ""); + + try { + const event = await Event.findOne({ id: eventID }); + + if (!event) { + return res.status(404).render("404", { url: req.url }); + } else { + if (acceptsActivityPub(req)) { + res.header( + "Content-Type", + "application/activity+json", + ).send(createWebfinger(eventID, config.general.domain)); + } else { + res.header("Content-Type", "application/json").send( + createWebfinger(eventID, config.general.domain), + ); + } + } + } catch (err) { + addToLog( + "renderWebfinger", + "error", + `Attempt to render webfinger for ${resource} failed with error: ${err}`, + ); + return res.status(404).render("404", { url: req.url }); + } + } +}); + +router.get("/:eventID/followers", async (req, res) => { + const eventID = req.params.eventID; + + try { + const event = await Event.findOne({ id: eventID }); + + if (event && event.followers) { + const followers = event.followers.map((el) => el.actorId); + let followersCollection = { + type: "OrderedCollection", + totalItems: followers.length, + id: `https://${config.general.domain}/${eventID}/followers`, + first: { + type: "OrderedCollectionPage", + totalItems: followers.length, + partOf: `https://${config.general.domain}/${eventID}/followers`, + orderedItems: followers, + id: `https://${config.general.domain}/${eventID}/followers?page=1`, + }, + "@context": ["https://www.w3.org/ns/activitystreams"], + }; + + if (acceptsActivityPub(req)) { + return res + .header("Content-Type", "application/activity+json") + .send(followersCollection); + } else { + return res + .header("Content-Type", "application/json") + .send(followersCollection); + } + } else { + return res.status(400).send("Bad request."); + } + } catch (err) { + addToLog( + "renderFollowers", + "error", + `Attempt to render followers for ${eventID} failed with error: ${err}`, + ); + return res.status(404).render("404", { url: req.url }); + } +}); + +export default router; diff --git a/src/routes/event.ts b/src/routes/event.ts new file mode 100644 index 0000000..c418893 --- /dev/null +++ b/src/routes/event.ts @@ -0,0 +1,519 @@ +import { Router, Response, Request } from "express"; +import { customAlphabet } from "nanoid"; +import multer from "multer"; +import Jimp from "jimp"; +import moment from "moment-timezone"; +import { marked } from "marked"; +import { generateEditToken, 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"; + +const config = getConfig(); + +// This alphabet (used to generate all event, group, etc. IDs) is missing '-' +// because ActivityPub doesn't like it in IDs +const nanoid = customAlphabet( + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_", + 21, +); + +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 router = Router(); + +router.post( + "/event", + 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.", + }, + ], + }); + } + + let eventID = nanoid(); + 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 + const filename = eventID + ".jpg"; + return filename; + }) + .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, + 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, + marked.parse(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.", + }, + ], + }); + } + + let submittedEditToken = req.body.editToken; + try { + 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, + 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 = + "

This event was just updated with new information.

    "; + let displayDate; + if (event.name !== updatedEvent.name) { + diffText += `
  • the event name changed to ${updatedEvent.name}
  • `; + } + if (event.location !== updatedEvent.location) { + diffText += `
  • the location changed to ${updatedEvent.location}
  • `; + } + if ( + event.start.toISOString() !== updatedEvent.start.toISOString() + ) { + displayDate = moment + .tz(updatedEvent.start, updatedEvent.timezone) + .format("dddd D MMMM YYYY h:mm a"); + diffText += `
  • the start time changed to ${displayDate}
  • `; + } + if (event.end.toISOString() !== updatedEvent.end.toISOString()) { + displayDate = moment + .tz(updatedEvent.end, updatedEvent.timezone) + .format("dddd D MMMM YYYY h:mm a"); + diffText += `
  • the end time changed to ${displayDate}
  • `; + } + if (event.timezone !== updatedEvent.timezone) { + diffText += `
  • the time zone changed to ${updatedEvent.timezone}
  • `; + } + if (event.description !== updatedEvent.description) { + diffText += `
  • the event description changed
  • `; + } + diffText += `
`; + 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: https://${config.general.domain}/${req.params.eventID}`, + }; + 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: `@${attendee.name} ${diffText} See here: https://${config.general.domain}/${req.params.eventID}`, + 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, + }, + ], + }); + } + }, +); + +export default router; diff --git a/src/routes/frontend.ts b/src/routes/frontend.ts index 71984ec..d24210f 100644 --- a/src/routes/frontend.ts +++ b/src/routes/frontend.ts @@ -69,6 +69,13 @@ router.get("/:eventID", async (req: Request, res: Response) => { let parsedEnd = moment .tz(event.end, event.timezone) .format("YYYYMMDD[T]HHmmss"); + // See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local + const parsedStartForDateInput = moment + .tz(event.start, event.timezone) + .format("YYYY-MM-DDTHH:mm"); + const parsedEndForDateInput = moment + .tz(event.end, event.timezone) + .format("YYYY-MM-DDTHH:mm"); let eventHasConcluded = false; if ( moment @@ -194,6 +201,8 @@ router.get("/:eventID", async (req: Request, res: Response) => { parsedLocation: parsedLocation, parsedStart: parsedStart, parsedEnd: parsedEnd, + parsedStartForDateInput, + parsedEndForDateInput, displayDate: displayDate, fromNow: fromNow, timezone: event.timezone, diff --git a/src/util/config.ts b/src/util/config.ts index c65fdb0..d1fd05b 100644 --- a/src/util/config.ts +++ b/src/util/config.ts @@ -7,6 +7,7 @@ interface FrontendConfig { email: string; siteName: string; showKofi: boolean; + isFederated: boolean; } export const frontendConfig = (): FrontendConfig => ({ @@ -14,4 +15,5 @@ export const frontendConfig = (): FrontendConfig => ({ email: config.general.email, siteName: config.general.site_name, showKofi: config.general.show_kofi, + isFederated: config.general.is_federated, }); diff --git a/src/util/generator.ts b/src/util/generator.ts new file mode 100644 index 0000000..c3712c1 --- /dev/null +++ b/src/util/generator.ts @@ -0,0 +1,24 @@ +import crypto from "crypto"; + +const generateAlphanumericString = (length: number) => { + return Array(length) + .fill(0) + .map((x) => Math.random().toString(36).charAt(2)) + .join(""); +}; + +export const generateEditToken = () => generateAlphanumericString(32); + +export const generateRSAKeypair = () => { + return crypto.generateKeyPairSync("rsa", { + modulusLength: 4096, + publicKeyEncoding: { + type: "spki", + format: "pem", + }, + privateKeyEncoding: { + type: "pkcs8", + format: "pem", + }, + }); +}; diff --git a/src/util/validation.ts b/src/util/validation.ts new file mode 100644 index 0000000..3cd349a --- /dev/null +++ b/src/util/validation.ts @@ -0,0 +1,192 @@ +import moment from "moment"; + +type Error = { + message?: string; + field?: string; +}; + +type ValidationResponse = { + data?: ValidatedEventData; + errors?: Error[]; +}; + +interface EventData { + eventName: string; + eventLocation: string; + eventStart: string; + eventEnd: string; + timezone: string; + eventDescription: string; + eventURL: string; + imagePath: string; + hostName: string; + creatorEmail: string; + eventGroupCheckbox: string; + eventGroupID: string; + eventGroupEditToken: string; + interactionCheckbox: string; + joinCheckbox: string; + maxAttendeesCheckbox: string; + maxAttendees: number; +} + +// EventData without the 'checkbox' fields +export type ValidatedEventData = Omit< + EventData, + | "eventGroupCheckbox" + | "interactionCheckbox" + | "joinCheckbox" + | "maxAttendeesCheckbox" +> & { + eventGroupBoolean: boolean; + interactionBoolean: boolean; + joinBoolean: boolean; + maxAttendeesBoolean: boolean; +}; + +const validateEmail = (email: string) => { + if (!email || email.length === 0 || typeof email !== "string") { + return false; + } + var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return re.test(email); +}; + +export const validateEventTime = (start: Date, end: Date): Error | boolean => { + if (moment(start).isAfter(moment(end))) { + return { + message: "Start time must be before end time.", + field: "eventStart", + }; + } + if (moment(start).isBefore(moment())) { + return { + message: "Start time must be in the future.", + field: "eventStart", + }; + } + if (moment(end).isBefore(moment())) { + return { + message: "End time must be in the future.", + field: "eventEnd", + }; + } + // Duration cannot be longer than 1 year + if (moment(end).diff(moment(start), "years") > 1) { + return { + message: "Event duration cannot be longer than 1 year.", + field: "eventEnd", + }; + } + return true; +}; + +export const validateEventData = (eventData: EventData): ValidationResponse => { + const validatedData: ValidatedEventData = { + eventName: eventData.eventName, + eventLocation: eventData.eventLocation, + eventStart: eventData.eventStart, + eventEnd: eventData.eventEnd, + timezone: eventData.timezone, + eventDescription: eventData.eventDescription, + eventURL: eventData.eventURL, + imagePath: eventData.imagePath, + hostName: eventData.hostName, + creatorEmail: eventData.creatorEmail, + eventGroupBoolean: eventData.eventGroupCheckbox === "true", + interactionBoolean: eventData.interactionCheckbox === "true", + joinBoolean: eventData.joinCheckbox === "true", + maxAttendeesBoolean: eventData.maxAttendeesCheckbox === "true", + eventGroupID: eventData.eventGroupID, + eventGroupEditToken: eventData.eventGroupEditToken, + maxAttendees: eventData.maxAttendees, + }; + console.log(validatedData); + const errors: Error[] = []; + if (!validatedData.eventName) { + errors.push({ + message: "Event name is required.", + field: "eventName", + }); + } + if (!validatedData.eventLocation) { + errors.push({ + message: "Event location is required.", + field: "eventLocation", + }); + } + if (!validatedData.eventStart) { + errors.push({ + message: "Event start time is required.", + field: "eventStart", + }); + } + if (!validatedData.eventEnd) { + errors.push({ + message: "Event end time is required.", + field: "eventEnd", + }); + } + const timeValidation = validateEventTime( + new Date(validatedData.eventStart), + new Date(validatedData.eventEnd), + ); + if (timeValidation !== true && timeValidation !== false) { + errors.push({ + message: timeValidation.message, + }); + } + if (!validatedData.timezone) { + errors.push({ + message: "Event timezone is required.", + field: "timezone", + }); + } + if (!validatedData.eventDescription) { + errors.push({ + message: "Event description is required.", + field: "eventDescription", + }); + } + if (validatedData.eventGroupBoolean) { + if (!validatedData.eventGroupID) { + errors.push({ + message: "Event group ID is required.", + field: "eventGroupID", + }); + } + if (!validatedData.eventGroupEditToken) { + errors.push({ + message: "Event group edit token is required.", + field: "eventGroupEditToken", + }); + } + } + if (validatedData.maxAttendeesBoolean) { + if (!validatedData.maxAttendees) { + errors.push({ + message: "Max number of attendees is required.", + field: "maxAttendees", + }); + } + if (isNaN(validatedData.maxAttendees)) { + errors.push({ + message: "Max number of attendees must be a number.", + field: "maxAttendees", + }); + } + } + if (validatedData.creatorEmail) { + if (!validateEmail(validatedData.creatorEmail)) { + errors.push({ + message: "Email address is invalid.", + field: "creatorEmail", + }); + } + } + + return { + data: validatedData, + errors: errors, + }; +}; diff --git a/views/event.handlebars b/views/event.handlebars index 1576647..41e3591 100755 --- a/views/event.handlebars +++ b/views/event.handlebars @@ -136,7 +136,7 @@ {{#unless noMoreSpots}} {{/unless}} - +
@@ -397,18 +397,7 @@ {{/if}} -{{#unless eventHasConcluded}} -{{#if editingEnabled}} - -{{/if}} -{{/unless}} + + diff --git a/views/newevent.handlebars b/views/newevent.handlebars index 5e7752f..76b6a17 100755 --- a/views/newevent.handlebars +++ b/views/newevent.handlebars @@ -24,7 +24,20 @@
- {{>neweventform}} +

Create an event

+
+ {{>eventForm}} +
+
+ +
+
+
@@ -36,34 +49,11 @@
+ + + + \ No newline at end of file diff --git a/views/partials/editeventmodal.handlebars b/views/partials/editeventmodal.handlebars index b4b0ea6..2572cbb 100644 --- a/views/partials/editeventmodal.handlebars +++ b/views/partials/editeventmodal.handlebars @@ -8,140 +8,21 @@