From 453c08463bf46e568c8a5018416ad88498a73f29 Mon Sep 17 00:00:00 2001 From: Raphael Kabo Date: Fri, 12 May 2023 16:54:06 +0100 Subject: linting: source files --- src/activitypub.js | 1684 +++++++++++++---------- src/app.js | 65 +- src/config/api-example.js | 10 +- src/config/database-docker.js | 2 +- src/config/database-example.js | 2 +- src/config/domain-example.js | 22 +- src/helpers.js | 30 +- src/models/Event.js | 157 +-- src/models/EventGroup.js | 28 +- src/models/Log.js | 14 +- src/routes.js | 2903 ++++++++++++++++++++++++++-------------- src/start.js | 40 +- 12 files changed, 3107 insertions(+), 1850 deletions(-) (limited to 'src') diff --git a/src/activitypub.js b/src/activitypub.js index 442f03c..c8fc682 100644 --- a/src/activitypub.js +++ b/src/activitypub.js @@ -1,123 +1,168 @@ -const domain = require('./config/domain.js').domain; -const contactEmail = require('./config/domain.js').email; -const siteName = require('./config/domain.js').sitename; -const isFederated = require('./config/domain.js').isFederated; -const request = require('request'); -const addToLog = require('./helpers.js').addToLog; -const crypto = require('crypto'); +const domain = require("./config/domain.js").domain; +const contactEmail = require("./config/domain.js").email; +const siteName = require("./config/domain.js").sitename; +const isFederated = require("./config/domain.js").isFederated; +const request = require("request"); +const addToLog = require("./helpers.js").addToLog; +const crypto = require("crypto"); // This alphabet (used to generate all event, group, etc. IDs) is missing '-' // because ActivityPub doesn't like it in IDs -const { customAlphabet } = require('nanoid'); -const nanoid = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_', 21); -var moment = require('moment-timezone'); -const mongoose = require('mongoose'); -const Event = mongoose.model('Event'); -const EventGroup = mongoose.model('EventGroup'); -var sanitizeHtml = require('sanitize-html'); - -function createActivityPubActor(eventID, domain, pubkey, description, name, location, imageFilename, startUTC, endUTC, timezone) { +const { customAlphabet } = require("nanoid"); +const nanoid = customAlphabet( + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_", + 21 +); +var moment = require("moment-timezone"); +const mongoose = require("mongoose"); +const Event = mongoose.model("Event"); +const EventGroup = mongoose.model("EventGroup"); +var sanitizeHtml = require("sanitize-html"); + +function createActivityPubActor( + eventID, + domain, + pubkey, + description, + name, + location, + imageFilename, + startUTC, + endUTC, + timezone +) { let actor = { - '@context': [ - 'https://www.w3.org/ns/activitystreams', - 'https://w3id.org/security/v1' + "@context": [ + "https://www.w3.org/ns/activitystreams", + "https://w3id.org/security/v1", ], - 'id': `https://${domain}/${eventID}`, - 'type': 'Person', - 'preferredUsername': `${eventID}`, - 'inbox': `https://${domain}/activitypub/inbox`, - 'outbox': `https://${domain}/${eventID}/outbox`, - 'followers': `https://${domain}/${eventID}/followers`, - 'summary': `

${description}

`, - 'name': name, - 'featured': `https://${domain}/${eventID}/featured`, - - 'publicKey': { - 'id': `https://${domain}/${eventID}#main-key`, - 'owner': `https://${domain}/${eventID}`, - 'publicKeyPem': pubkey - } + id: `https://${domain}/${eventID}`, + type: "Person", + preferredUsername: `${eventID}`, + inbox: `https://${domain}/activitypub/inbox`, + outbox: `https://${domain}/${eventID}/outbox`, + followers: `https://${domain}/${eventID}/followers`, + summary: `

${description}

`, + name: name, + featured: `https://${domain}/${eventID}/featured`, + + publicKey: { + id: `https://${domain}/${eventID}#main-key`, + owner: `https://${domain}/${eventID}`, + publicKeyPem: pubkey, + }, }; if (location) { - actor.summary += `

Location: ${location}.

` + actor.summary += `

Location: ${location}.

`; } let displayDate; if (startUTC && timezone) { - displayDate = moment.tz(startUTC, timezone).format('D MMMM YYYY h:mm a'); + displayDate = moment.tz(startUTC, timezone).format("D MMMM YYYY h:mm a"); actor.summary += `

Starting ${displayDate} ${timezone}.

`; } if (imageFilename) { actor.icon = { - 'type': 'Image', - 'mediaType': 'image/jpg', - 'url': `https://${domain}/events/${imageFilename}`, + type: "Image", + mediaType: "image/jpg", + url: `https://${domain}/events/${imageFilename}`, }; } return JSON.stringify(actor); } -function createActivityPubEvent(name, startUTC, endUTC, timezone, description, location) { - const guid = crypto.randomBytes(16).toString('hex'); +function createActivityPubEvent( + name, + startUTC, + endUTC, + timezone, + description, + location +) { + const guid = crypto.randomBytes(16).toString("hex"); let eventObject = { "@context": "https://www.w3.org/ns/activitystreams", - 'id': `https://${domain}/${guid}`, - "name": name, - "type": "Event", - "startTime": moment.tz(startUTC, timezone).format(), - "endTime": moment.tz(endUTC, timezone).format(), - "content": description, - "location": location - } + id: `https://${domain}/${guid}`, + name: name, + type: "Event", + startTime: moment.tz(startUTC, timezone).format(), + endTime: moment.tz(endUTC, timezone).format(), + content: description, + location: location, + }; return JSON.stringify(eventObject); } -function createFeaturedPost(eventID, name, startUTC, endUTC, timezone, description, location) { +function createFeaturedPost( + eventID, + name, + startUTC, + endUTC, + timezone, + description, + location +) { const featured = { "@context": "https://www.w3.org/ns/activitystreams", - "id": `https://${domain}/${eventID}/m/featuredPost`, - "type": "Note", - "name": "Test", - 'cc': 'https://www.w3.org/ns/activitystreams#Public', - "content": `

This is an event that was posted on ${siteName}. If you follow this account, you'll see updates in your timeline about the event. If your software supports polls, you should get a poll in your DMs asking if you want to RSVP. You can reply and RSVP right from there. If your software has an event calendar built in, you should get an event in your inbox that you can RSVP to like you respond to any event.

For more information on how to interact with this, check out this link.

`, - 'attributedTo': `https://${domain}/${eventID}`, - } + id: `https://${domain}/${eventID}/m/featuredPost`, + type: "Note", + name: "Test", + cc: "https://www.w3.org/ns/activitystreams#Public", + content: `

This is an event that was posted on ${siteName}. If you follow this account, you'll see updates in your timeline about the event. If your software supports polls, you should get a poll in your DMs asking if you want to RSVP. You can reply and RSVP right from there. If your software has an event calendar built in, you should get an event in your inbox that you can RSVP to like you respond to any event.

For more information on how to interact with this, check out this link.

`, + attributedTo: `https://${domain}/${eventID}`, + }; return featured; } -function updateActivityPubEvent(oldEvent, name, startUTC, endUTC, timezone, description, location) { +function updateActivityPubEvent( + oldEvent, + name, + startUTC, + endUTC, + timezone, + description, + location +) { // we want to persist the old ID no matter what happens to the Event itself const id = oldEvent.id; let eventObject = { "@context": "https://www.w3.org/ns/activitystreams", - 'id': id, - "name": name, - "type": "Event", - "startTime": moment.tz(startUTC, timezone).format(), - "endTime": moment.tz(endUTC, timezone).format(), - "content": description, - "location": location - } + id: id, + name: name, + type: "Event", + startTime: moment.tz(startUTC, timezone).format(), + endTime: moment.tz(endUTC, timezone).format(), + content: description, + location: location, + }; return JSON.stringify(eventObject); } - -function updateActivityPubActor(actor, description, name, location, imageFilename, startUTC, endUTC, timezone) { +function updateActivityPubActor( + actor, + description, + name, + location, + imageFilename, + startUTC, + endUTC, + timezone +) { if (!actor) return; actor.summary = `

${description}

`; actor.name = name; if (location) { - actor.summary += `

Location: ${location}.

` + actor.summary += `

Location: ${location}.

`; } let displayDate; if (startUTC && timezone) { - displayDate = moment.tz(startUTC, timezone).format('D MMMM YYYY h:mm a'); + displayDate = moment.tz(startUTC, timezone).format("D MMMM YYYY h:mm a"); actor.summary += `

Starting ${displayDate} ${timezone}.

`; } if (imageFilename) { actor.icon = { - 'type': 'Image', - 'mediaType': 'image/jpg', - 'url': `https://${domain}/events/${imageFilename}`, + type: "Image", + mediaType: "image/jpg", + url: `https://${domain}/events/${imageFilename}`, }; } return JSON.stringify(actor); @@ -125,77 +170,95 @@ function updateActivityPubActor(actor, description, name, location, imageFilenam function signAndSend(message, eventID, targetDomain, inbox, callback) { if (!isFederated) return; - let inboxFragment = inbox.replace('https://' + targetDomain, ''); + let inboxFragment = inbox.replace("https://" + targetDomain, ""); // get the private key Event.findOne({ - id: eventID - }) - .then((event) => { - if (event) { - const digest = crypto.createHash('sha256').update(JSON.stringify(message)).digest('base64'); - const privateKey = event.privateKey; - const signer = crypto.createSign('sha256'); - let d = new Date(); - let stringToSign = `(request-target): post ${inboxFragment}\nhost: ${targetDomain}\ndate: ${d.toUTCString()}\ndigest: SHA-256=${digest}`; - signer.update(stringToSign); - signer.end(); - const signature = signer.sign(privateKey); - const signature_b64 = signature.toString('base64'); - const algorithm = 'rsa-sha256'; - let header = `keyId="https://${domain}/${eventID}",algorithm="${algorithm}",headers="(request-target) host date digest",signature="${signature_b64}"`; - request({ + id: eventID, + }).then((event) => { + if (event) { + const digest = crypto + .createHash("sha256") + .update(JSON.stringify(message)) + .digest("base64"); + const privateKey = event.privateKey; + const signer = crypto.createSign("sha256"); + let d = new Date(); + let stringToSign = `(request-target): post ${inboxFragment}\nhost: ${targetDomain}\ndate: ${d.toUTCString()}\ndigest: SHA-256=${digest}`; + signer.update(stringToSign); + signer.end(); + const signature = signer.sign(privateKey); + const signature_b64 = signature.toString("base64"); + const algorithm = "rsa-sha256"; + let header = `keyId="https://${domain}/${eventID}",algorithm="${algorithm}",headers="(request-target) host date digest",signature="${signature_b64}"`; + request( + { url: inbox, headers: { - 'Host': targetDomain, - 'Date': d.toUTCString(), - 'Signature': header, - 'Digest': `SHA-256=${digest}`, - 'Content-Type': 'application/activity+json', - 'Accept': 'application/activity+json' + Host: targetDomain, + Date: d.toUTCString(), + Signature: header, + Digest: `SHA-256=${digest}`, + "Content-Type": "application/activity+json", + Accept: "application/activity+json", }, - method: 'POST', + method: "POST", json: true, - body: message - }, function (error, response) { + body: message, + }, + function (error, response) { if (error) { callback(error, null, 500); - } - else { + } else { // Add the message to the database const messageID = message.id; const newMessage = { id: message.id, - content: JSON.stringify(message) + content: JSON.stringify(message), }; - Event.findOne({ - id: eventID, - }, function (err, event) { - if (!event) return; - event.activityPubMessages.push(newMessage); - // also add the message's object if it has one - if (message.object && message.object.id) { - event.activityPubMessages.push({ - id: message.object.id, - content: JSON.stringify(message.object) - }); + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (!event) return; + event.activityPubMessages.push(newMessage); + // also add the message's object if it has one + if (message.object && message.object.id) { + event.activityPubMessages.push({ + id: message.object.id, + content: JSON.stringify(message.object), + }); + } + event + .save() + .then(() => { + addToLog( + "addActivityPubMessage", + "success", + "ActivityPubMessage added to event " + eventID + ); + callback(null, message.id, 200); + }) + .catch((err) => { + addToLog( + "addActivityPubMessage", + "error", + "Attempt to add ActivityPubMessage to event " + + eventID + + " failed with error: " + + err + ); + callback(err, null, 500); + }); } - event.save() - .then(() => { - addToLog("addActivityPubMessage", "success", "ActivityPubMessage added to event " + eventID); - callback(null, message.id, 200); - }) - .catch((err) => { - addToLog("addActivityPubMessage", "error", "Attempt to add ActivityPubMessage to event " + eventID + " failed with error: " + err); - callback(err, null, 500); - }); - }) + ); } - }); - } - else { - callback(`No record found for ${eventID}.`, null, 404); - } - }); + } + ); + } else { + callback(`No record found for ${eventID}.`, null, 404); + } + }); } // this function sends something to the timeline of every follower in the followers array @@ -203,145 +266,182 @@ function signAndSend(message, eventID, targetDomain, inbox, callback) { // the profile but it doesn't spam federated timelines function broadcastCreateMessage(apObject, followers, eventID) { if (!isFederated) return; - let guidCreate = crypto.randomBytes(16).toString('hex'); - Event.findOne({ - id: eventID, - }, function (err, event) { - if (event) { - // iterate over followers - for (const follower of followers) { - let actorId = follower.actorId; - let myURL = new URL(actorId); - let targetDomain = myURL.hostname; - // get the inbox - const followerFound = event.followers.find(el => el.actorId === actorId); - if (followerFound) { - const actorJson = JSON.parse(follower.actorJson); - const inbox = actorJson.inbox; - const createMessage = { - '@context': ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1'], - 'id': `https://${domain}/${eventID}/m/${guidCreate}`, - 'type': 'Create', - 'actor': `https://${domain}/${eventID}`, - 'to': [actorId], - 'cc': 'https://www.w3.org/ns/activitystreams#Public', - 'object': apObject - }; - signAndSend(createMessage, eventID, targetDomain, inbox, function (err, resp, status) { - if (err) { - console.log(`Didn't send to ${actorId}, status ${status} with error ${err}`); - } - else { - console.log('sent to', actorId); - } - }); - } - else { - console.log(`No follower found with the id ${actorId}`); - } - } // end followers - } // end if event - else { - console.log(`No event found with the id ${eventID}`); + let guidCreate = crypto.randomBytes(16).toString("hex"); + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (event) { + // iterate over followers + for (const follower of followers) { + let actorId = follower.actorId; + let myURL = new URL(actorId); + let targetDomain = myURL.hostname; + // get the inbox + const followerFound = event.followers.find( + (el) => el.actorId === actorId + ); + if (followerFound) { + const actorJson = JSON.parse(follower.actorJson); + const inbox = actorJson.inbox; + const createMessage = { + "@context": [ + "https://www.w3.org/ns/activitystreams", + "https://w3id.org/security/v1", + ], + id: `https://${domain}/${eventID}/m/${guidCreate}`, + type: "Create", + actor: `https://${domain}/${eventID}`, + to: [actorId], + cc: "https://www.w3.org/ns/activitystreams#Public", + object: apObject, + }; + signAndSend( + createMessage, + eventID, + targetDomain, + inbox, + function (err, resp, status) { + if (err) { + console.log( + `Didn't send to ${actorId}, status ${status} with error ${err}` + ); + } else { + console.log("sent to", actorId); + } + } + ); + } else { + console.log(`No follower found with the id ${actorId}`); + } + } // end followers + } // end if event + else { + console.log(`No event found with the id ${eventID}`); + } } - }); + ); } - // sends an Announce for the apObject function broadcastAnnounceMessage(apObject, followers, eventID) { if (!isFederated) return; - let guidUpdate = crypto.randomBytes(16).toString('hex'); - Event.findOne({ - id: eventID, - }, function (err, event) { - if (event) { - // iterate over followers - for (const follower of followers) { - let actorId = follower.actorId; - let myURL = new URL(actorId); - let targetDomain = myURL.hostname; - // get the inbox - const followerFound = event.followers.find(el => el.actorId === actorId); - if (followerFound) { - const actorJson = JSON.parse(follower.actorJson); - const inbox = actorJson.inbox; - const announceMessage = { - '@context': ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1'], - 'id': `https://${domain}/${eventID}/m/${guidUpdate}`, - 'cc': 'https://www.w3.org/ns/activitystreams#Public', - 'type': 'Announce', - 'actor': `https://${domain}/${eventID}`, - 'object': apObject, - 'to': actorId - }; - signAndSend(announceMessage, eventID, targetDomain, inbox, function (err, resp, status) { - if (err) { - console.log(`Didn't send to ${actorId}, status ${status} with error ${err}`); - } - else { - console.log('sent to', actorId); - } - }); - } - else { - console.log(`No follower found with the id ${actorId}`); - } - } // end followers - } // end if event - else { - console.log(`No event found with the id ${eventID}`); + let guidUpdate = crypto.randomBytes(16).toString("hex"); + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (event) { + // iterate over followers + for (const follower of followers) { + let actorId = follower.actorId; + let myURL = new URL(actorId); + let targetDomain = myURL.hostname; + // get the inbox + const followerFound = event.followers.find( + (el) => el.actorId === actorId + ); + if (followerFound) { + const actorJson = JSON.parse(follower.actorJson); + const inbox = actorJson.inbox; + const announceMessage = { + "@context": [ + "https://www.w3.org/ns/activitystreams", + "https://w3id.org/security/v1", + ], + id: `https://${domain}/${eventID}/m/${guidUpdate}`, + cc: "https://www.w3.org/ns/activitystreams#Public", + type: "Announce", + actor: `https://${domain}/${eventID}`, + object: apObject, + to: actorId, + }; + signAndSend( + announceMessage, + eventID, + targetDomain, + inbox, + function (err, resp, status) { + if (err) { + console.log( + `Didn't send to ${actorId}, status ${status} with error ${err}` + ); + } else { + console.log("sent to", actorId); + } + } + ); + } else { + console.log(`No follower found with the id ${actorId}`); + } + } // end followers + } // end if event + else { + console.log(`No event found with the id ${eventID}`); + } } - }); + ); } // sends an Update for the apObject function broadcastUpdateMessage(apObject, followers, eventID) { if (!isFederated) return; - let guidUpdate = crypto.randomBytes(16).toString('hex'); + let guidUpdate = crypto.randomBytes(16).toString("hex"); // iterate over followers - Event.findOne({ - id: eventID, - }, function (err, event) { - if (event) { - for (const follower of followers) { - let actorId = follower.actorId; - let myURL = new URL(actorId); - let targetDomain = myURL.hostname; - // get the inbox - const followerFound = event.followers.find(el => el.actorId === actorId); - if (followerFound) { - const actorJson = JSON.parse(follower.actorJson); - const inbox = actorJson.inbox; - const createMessage = { - '@context': 'https://www.w3.org/ns/activitystreams', - 'id': `https://${domain}/${eventID}/m/${guidUpdate}`, - 'type': 'Update', - 'actor': `https://${domain}/${eventID}`, - 'object': apObject - }; - signAndSend(createMessage, eventID, targetDomain, inbox, function (err, resp, status) { - if (err) { - console.log(`Didn't send to ${actorId}, status ${status} with error ${err}`); - } - else { - console.log('sent to', actorId); - } - }); - } - else { - console.log(`No follower found with the id ${actorId}`); - } - } // end followers - } - else { - console.log(`No event found with the id ${eventID}`); + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (event) { + for (const follower of followers) { + let actorId = follower.actorId; + let myURL = new URL(actorId); + let targetDomain = myURL.hostname; + // get the inbox + const followerFound = event.followers.find( + (el) => el.actorId === actorId + ); + if (followerFound) { + const actorJson = JSON.parse(follower.actorJson); + const inbox = actorJson.inbox; + const createMessage = { + "@context": "https://www.w3.org/ns/activitystreams", + id: `https://${domain}/${eventID}/m/${guidUpdate}`, + type: "Update", + actor: `https://${domain}/${eventID}`, + object: apObject, + }; + signAndSend( + createMessage, + eventID, + targetDomain, + inbox, + function (err, resp, status) { + if (err) { + console.log( + `Didn't send to ${actorId}, status ${status} with error ${err}` + ); + } else { + console.log("sent to", actorId); + } + } + ); + } else { + console.log(`No follower found with the id ${actorId}`); + } + } // end followers + } else { + console.log(`No event found with the id ${eventID}`); + } } - }); + ); } function broadcastDeleteMessage(apObject, followers, eventID, callback) { - callback = callback || function () { }; + callback = callback || function () {}; if (!isFederated) { callback([]); return; @@ -350,54 +450,72 @@ function broadcastDeleteMessage(apObject, followers, eventID, callback) { // per spec, each promise will execute *as it is built*, which is fine, we just need the guarantee that they are all done let promises = []; - let guidUpdate = crypto.randomBytes(16).toString('hex'); + let guidUpdate = crypto.randomBytes(16).toString("hex"); // iterate over followers for (const follower of followers) { - promises.push(new Promise((resolve, reject) => { - let actorId = follower.actorId; - let myURL = new URL(actorId); - let targetDomain = myURL.hostname; - // get the inbox - Event.findOne({ - id: eventID, - }, function (err, event) { - if (event) { - const follower = event.followers.find(el => el.actorId === actorId); - if (follower) { - const actorJson = JSON.parse(follower.actorJson); - const inbox = actorJson.inbox; - const createMessage = { - '@context': 'https://www.w3.org/ns/activitystreams', - 'id': `https://${domain}/${eventID}/m/${guidUpdate}`, - 'type': 'Delete', - 'actor': `https://${domain}/${eventID}`, - 'object': apObject - }; - signAndSend(createMessage, eventID, targetDomain, inbox, function (err, resp, status) { - if (err) { - console.log(`Didn't send to ${actorId}, status ${status} with error ${err}`); - reject(`Didn't send to ${actorId}, status ${status} with error ${err}`); - } - else { - console.log('sent to', actorId); - resolve('sent to', actorId); + promises.push( + new Promise((resolve, reject) => { + let actorId = follower.actorId; + let myURL = new URL(actorId); + let targetDomain = myURL.hostname; + // get the inbox + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (event) { + const follower = event.followers.find( + (el) => el.actorId === actorId + ); + if (follower) { + const actorJson = JSON.parse(follower.actorJson); + const inbox = actorJson.inbox; + const createMessage = { + "@context": "https://www.w3.org/ns/activitystreams", + id: `https://${domain}/${eventID}/m/${guidUpdate}`, + type: "Delete", + actor: `https://${domain}/${eventID}`, + object: apObject, + }; + signAndSend( + createMessage, + eventID, + targetDomain, + inbox, + function (err, resp, status) { + if (err) { + console.log( + `Didn't send to ${actorId}, status ${status} with error ${err}` + ); + reject( + `Didn't send to ${actorId}, status ${status} with error ${err}` + ); + } else { + console.log("sent to", actorId); + resolve("sent to", actorId); + } + } + ); + } else { + console.log( + `No follower found with the id ${actorId}`, + null, + 404 + ); + reject(`No follower found with the id ${actorId}`, null, 404); } - }); - } - else { - console.log(`No follower found with the id ${actorId}`, null, 404); - reject(`No follower found with the id ${actorId}`, null, 404); + } else { + console.log(`No event found with the id ${eventID}`, null, 404); + reject(`No event found with the id ${eventID}`, null, 404); + } } - } - else { - console.log(`No event found with the id ${eventID}`, null, 404); - reject(`No event found with the id ${eventID}`, null, 404); - } - }); // end event - })); + ); // end event + }) + ); } // end followers - Promise.all(promises.map(p => p.catch(e => e))).then(statuses => { + Promise.all(promises.map((p) => p.catch((e) => e))).then((statuses) => { callback(statuses); }); } @@ -405,469 +523,664 @@ function broadcastDeleteMessage(apObject, followers, eventID, callback) { // this sends a message "to:" an individual fediverse user function sendDirectMessage(apObject, actorId, eventID, callback) { if (!isFederated) return; - callback = callback || function () { }; - const guidCreate = crypto.randomBytes(16).toString('hex'); - const guidObject = crypto.randomBytes(16).toString('hex'); + callback = callback || function () {}; + const guidCreate = crypto.randomBytes(16).toString("hex"); + const guidObject = crypto.randomBytes(16).toString("hex"); let d = new Date(); apObject.published = d.toISOString(); apObject.attributedTo = `https://${domain}/${eventID}`; apObject.to = actorId; apObject.id = `https://${domain}/${eventID}/m/${guidObject}`; - apObject.content = unescape(apObject.content) + apObject.content = unescape(apObject.content); let createMessage = { - '@context': 'https://www.w3.org/ns/activitystreams', - 'id': `https://${domain}/${eventID}/m/${guidCreate}`, - 'type': 'Create', - 'actor': `https://${domain}/${eventID}`, - 'to': [actorId], - 'object': apObject + "@context": "https://www.w3.org/ns/activitystreams", + id: `https://${domain}/${eventID}/m/${guidCreate}`, + type: "Create", + actor: `https://${domain}/${eventID}`, + to: [actorId], + object: apObject, }; let myURL = new URL(actorId); let targetDomain = myURL.hostname; // get the inbox - Event.findOne({ - id: eventID, - }, function (err, event) { - if (event) { - const follower = event.followers.find(el => el.actorId === actorId); - if (follower) { - const actorJson = JSON.parse(follower.actorJson); - const inbox = actorJson.inbox; - signAndSend(createMessage, eventID, targetDomain, inbox, callback); - } - else { - callback(`No follower found with the id ${actorId}`, null, 404); + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (event) { + const follower = event.followers.find((el) => el.actorId === actorId); + if (follower) { + const actorJson = JSON.parse(follower.actorJson); + const inbox = actorJson.inbox; + signAndSend(createMessage, eventID, targetDomain, inbox, callback); + } else { + callback(`No follower found with the id ${actorId}`, null, 404); + } + } else { + callback(`No event found with the id ${eventID}`, null, 404); } } - else { - callback(`No event found with the id ${eventID}`, null, 404); - } - }); + ); } function sendAcceptMessage(thebody, eventID, targetDomain, callback) { if (!isFederated) return; - callback = callback || function () { }; - const guid = crypto.randomBytes(16).toString('hex'); + callback = callback || function () {}; + const guid = crypto.randomBytes(16).toString("hex"); const actorId = thebody.actor; let message = { - '@context': 'https://www.w3.org/ns/activitystreams', - 'id': `https://${domain}/${guid}`, - 'type': 'Accept', - 'actor': `https://${domain}/${eventID}`, - 'object': thebody, + "@context": "https://www.w3.org/ns/activitystreams", + id: `https://${domain}/${guid}`, + type: "Accept", + actor: `https://${domain}/${eventID}`, + object: thebody, }; // get the inbox - Event.findOne({ - id: eventID, - }, function (err, event) { - if (event) { - const follower = event.followers.find(el => el.actorId === actorId); - if (follower) { - const actorJson = JSON.parse(follower.actorJson); - const inbox = actorJson.inbox; - signAndSend(message, eventID, targetDomain, inbox, callback); + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (event) { + const follower = event.followers.find((el) => el.actorId === actorId); + if (follower) { + const actorJson = JSON.parse(follower.actorJson); + const inbox = actorJson.inbox; + signAndSend(message, eventID, targetDomain, inbox, callback); + } + } else { + callback(`Could not find event ${eventID}`, null, 404); } } - else { - callback(`Could not find event ${eventID}`, null, 404); - } - }); + ); } function _handleFollow(req, res) { const myURL = new URL(req.body.actor); let targetDomain = myURL.hostname; - let eventID = req.body.object.replace(`https://${domain}/`, ''); + let eventID = req.body.object.replace(`https://${domain}/`, ""); // Add the user to the DB of accounts that follow the account // get the follower's username - request({ - url: req.body.actor, - headers: { - 'Accept': 'application/activity+json', - 'Content-Type': 'application/activity+json' - } - }, function (error, response, body) { - body = JSON.parse(body) - const name = body.preferredUsername || body.name || body.attributedTo; - const newFollower = { - actorId: req.body.actor, - followId: req.body.id, - name: name, - actorJson: JSON.stringify(body) - }; - Event.findOne({ - id: eventID, - }, function (err, event) { - // if this account is NOT already in our followers list, add it - if (event && !event.followers.map(el => el.actorId).includes(req.body.actor)) { - event.followers.push(newFollower); - event.save() - .then(() => { - addToLog("addEventFollower", "success", "Follower added to event " + eventID); - // Accept the follow request - sendAcceptMessage(req.body, eventID, targetDomain, function (err, resp, status) { - if (err) { - console.log(`Didn't send Accept to ${req.body.actor}, status ${status} with error ${err}`); - } - else { - console.log('sent Accept to', req.body.actor); - // ALSO send an ActivityPub Event activity since this person is "interested" in the event, as indicated by the Follow - const jsonEventObject = JSON.parse(event.activityPubEvent); - // send direct message to user - sendDirectMessage(jsonEventObject, newFollower.actorId, event.id); - - // if users can self-RSVP, send a Question to the new follower - if (event.usersCanAttend) { - const jsonObject = { - "@context": "https://www.w3.org/ns/activitystreams", - "name": `RSVP to ${event.name}`, - "type": "Question", - "content": `@${name} Will you attend ${event.name}? (If you reply "Yes", you'll be listed as an attendee on the event page.)`, - "oneOf": [ - { "type": "Note", "name": "Yes" }, - ], - "endTime": event.start.toISOString(), - "tag": [{ "type": "Mention", "href": req.body.actor, "name": name }] - } - // send direct message to user - sendDirectMessage(jsonObject, req.body.actor, eventID, function (error, response, statuscode) { - if (error) { - console.log('Error sending direct message:', error); - return res.status(statuscode).json(error); - } - else { - return res.status(statuscode).json({ messageid: response }); + request( + { + url: req.body.actor, + headers: { + Accept: "application/activity+json", + "Content-Type": "application/activity+json", + }, + }, + function (error, response, body) { + body = JSON.parse(body); + const name = body.preferredUsername || body.name || body.attributedTo; + const newFollower = { + actorId: req.body.actor, + followId: req.body.id, + name: name, + actorJson: JSON.stringify(body), + }; + Event.findOne( + { + id: eventID, + }, + function (err, event) { + // if this account is NOT already in our followers list, add it + if ( + event && + !event.followers.map((el) => el.actorId).includes(req.body.actor) + ) { + event.followers.push(newFollower); + event + .save() + .then(() => { + addToLog( + "addEventFollower", + "success", + "Follower added to event " + eventID + ); + // Accept the follow request + sendAcceptMessage( + req.body, + eventID, + targetDomain, + function (err, resp, status) { + if (err) { + console.log( + `Didn't send Accept to ${req.body.actor}, status ${status} with error ${err}` + ); + } else { + console.log("sent Accept to", req.body.actor); + // ALSO send an ActivityPub Event activity since this person is "interested" in the event, as indicated by the Follow + const jsonEventObject = JSON.parse( + event.activityPubEvent + ); + // send direct message to user + sendDirectMessage( + jsonEventObject, + newFollower.actorId, + event.id + ); + + // if users can self-RSVP, send a Question to the new follower + if (event.usersCanAttend) { + const jsonObject = { + "@context": "https://www.w3.org/ns/activitystreams", + name: `RSVP to ${event.name}`, + type: "Question", + content: `@${name} Will you attend ${event.name}? (If you reply "Yes", you'll be listed as an attendee on the event page.)`, + oneOf: [{ type: "Note", name: "Yes" }], + endTime: event.start.toISOString(), + tag: [ + { + type: "Mention", + href: req.body.actor, + name: name, + }, + ], + }; + // send direct message to user + sendDirectMessage( + jsonObject, + req.body.actor, + eventID, + function (error, response, statuscode) { + if (error) { + console.log( + "Error sending direct message:", + error + ); + return res.status(statuscode).json(error); + } else { + return res + .status(statuscode) + .json({ messageid: response }); + } + } + ); + } } - }); - } - } - }); - }) - .catch((err) => { - addToLog("addEventFollower", "error", "Attempt to add follower to event " + eventID + " failed with error: " + err); - return res.status(500).send('Database error, please try again :('); - }); - } - else { - // this person is already a follower so just say "ok" - return res.status(200); - } - }) - }) //end request + } + ); + }) + .catch((err) => { + addToLog( + "addEventFollower", + "error", + "Attempt to add follower to event " + + eventID + + " failed with error: " + + err + ); + return res + .status(500) + .send("Database error, please try again :("); + }); + } else { + // this person is already a follower so just say "ok" + return res.status(200); + } + } + ); + } + ); //end request } function _handleUndoFollow(req, res) { // get the record of all followers for this account - const eventID = req.body.object.object.replace(`https://${domain}/`, ''); - Event.findOne({ - id: eventID, - }, function (err, event) { - if (!event) return; - // check to see if the Follow object's id matches the id we have on record - // is this even someone who follows us - const indexOfFollower = event.followers.findIndex(el => el.actorId === req.body.object.actor); - if (indexOfFollower !== -1) { - // does the id we have match the id we are being given - if (event.followers[indexOfFollower].followId === req.body.object.id) { - // we have a match and can trust the Undo! remove this person from the followers list - event.followers.splice(indexOfFollower, 1); - event.save() - .then(() => { - addToLog("removeEventFollower", "success", "Follower removed from event " + eventID); - return res.sendStatus(200); - }) - .catch((err) => { - addToLog("removeEventFollower", "error", "Attempt to remove follower from event " + eventID + " failed with error: " + err); - return res.send('Database error, please try again :('); - }); - } - } - }); -} - -function _handleAcceptEvent(req, res) { - let { name, attributedTo, inReplyTo, to, actor } = req.body; - if (Array.isArray(to)) { - to = to[0]; - } - const eventID = to.replace(`https://${domain}/`, ''); - Event.findOne({ - id: eventID, - }, function (err, event) { - if (!event) return; - // does the id we got match the id of a thing we sent out - const message = event.activityPubMessages.find(el => el.id === req.body.object); - if (message) { - // it's a match - request({ - url: actor, - headers: { - 'Accept': 'application/activity+json', - 'Content-Type': 'application/activity+json' - } - }, function (error, response, body) { - body = JSON.parse(body) - // if this account is NOT already in our attendees list, add it - if (!event.attendees.map(el => el.id).includes(actor)) { - const attendeeName = body.preferredUsername || body.name || actor; - const newAttendee = { - name: attendeeName, - status: 'attending', - id: actor, - number: 1, - }; - event.attendees.push(newAttendee); - event.save() - .then((fullEvent) => { - addToLog("addEventAttendee", "success", "Attendee added to event " + req.params.eventID); - // get the new attendee with its hidden id from the full event - let fullAttendee = fullEvent.attendees.find(el => el.id === actor); - // send a "click here to remove yourself" link back to the user as a DM - const jsonObject = { - "@context": "https://www.w3.org/ns/activitystreams", - "name": `RSVP to ${event.name}`, - "type": "Note", - "content": `@${newAttendee.name} Thanks for RSVPing! You can remove yourself from the RSVP list by clicking here: https://${domain}/oneclickunattendevent/${event.id}/${fullAttendee._id}`, - "tag": [{ "type": "Mention", "href": newAttendee.id, "name": newAttendee.name }] - } - // send direct message to user - sendDirectMessage(jsonObject, newAttendee.id, event.id); + const eventID = req.body.object.object.replace(`https://${domain}/`, ""); + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (!event) return; + // check to see if the Follow object's id matches the id we have on record + // is this even someone who follows us + const indexOfFollower = event.followers.findIndex( + (el) => el.actorId === req.body.object.actor + ); + if (indexOfFollower !== -1) { + // does the id we have match the id we are being given + if (event.followers[indexOfFollower].followId === req.body.object.id) { + // we have a match and can trust the Undo! remove this person from the followers list + event.followers.splice(indexOfFollower, 1); + event + .save() + .then(() => { + addToLog( + "removeEventFollower", + "success", + "Follower removed from event " + eventID + ); return res.sendStatus(200); }) .catch((err) => { - addToLog("addEventAttendee", "error", "Attempt to add attendee to event " + req.params.eventID + " failed with error: " + err); - return res.status(500).send('Database error, please try again :('); + addToLog( + "removeEventFollower", + "error", + "Attempt to remove follower from event " + + eventID + + " failed with error: " + + err + ); + return res.send("Database error, please try again :("); }); } - else { - // it's a duplicate and this person is already rsvped so just say OK - return res.status(200).send("Attendee is already registered."); - } - }); + } } - }); + ); } -function _handleUndoAcceptEvent(req, res) { +function _handleAcceptEvent(req, res) { let { name, attributedTo, inReplyTo, to, actor } = req.body; if (Array.isArray(to)) { to = to[0]; } - const eventID = to.replace(`https://${domain}/`, ''); - Event.findOne({ - id: eventID, - }, function (err, event) { - if (!event) return; - // does the id we got match the id of a thing we sent out - const message = event.activityPubMessages.find(el => el.id === req.body.object.object); - if (message) { - // it's a match - Event.update( - { id: eventID }, - { $pull: { attendees: { id: actor } } } - ) - .then(response => { - addToLog("oneClickUnattend", "success", "Attendee removed via one click unattend " + req.params.eventID); - }); - } - }); -} - -function _handleCreateNote(req, res) { - // figure out what this is in reply to -- it should be addressed specifically to us - let { name, attributedTo, inReplyTo, to } = req.body.object; - // if it's an array just grab the first element, since a poll should only broadcast back to the pollster - if (Array.isArray(to)) { - to = to[0]; - } - const eventID = to.replace(`https://${domain}/`, ''); - // make sure this person is actually a follower - Event.findOne({ - id: eventID, - }, function (err, event) { - if (!event) return; - // is this even someone who follows us - const indexOfFollower = event.followers.findIndex(el => el.actorId === req.body.object.attributedTo); - if (indexOfFollower !== -1) { - // compare the inReplyTo to its stored message, if it exists and it's going to the right follower then this is a valid reply - const message = event.activityPubMessages.find(el => { - const content = JSON.parse(el.content); - return inReplyTo === (content.object && content.object.id); - }); + const eventID = to.replace(`https://${domain}/`, ""); + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (!event) return; + // does the id we got match the id of a thing we sent out + const message = event.activityPubMessages.find( + (el) => el.id === req.body.object + ); if (message) { - const content = JSON.parse(message.content); - // check if the message we sent out was sent to the actor this incoming message is attributedTo - if (content.to[0] === attributedTo) { - // it's a match, this is a valid poll response, add RSVP to database - // fetch the profile information of the user - request({ - url: attributedTo, + // it's a match + request( + { + url: actor, headers: { - 'Accept': 'application/activity+json', - 'Content-Type': 'application/activity+json' - } - }, function (error, response, body) { - body = JSON.parse(body) + Accept: "application/activity+json", + "Content-Type": "application/activity+json", + }, + }, + function (error, response, body) { + body = JSON.parse(body); // if this account is NOT already in our attendees list, add it - if (!event.attendees.map(el => el.id).includes(attributedTo)) { - const attendeeName = body.preferredUsername || body.name || attributedTo; + if (!event.attendees.map((el) => el.id).includes(actor)) { + const attendeeName = body.preferredUsername || body.name || actor; const newAttendee = { name: attendeeName, - status: 'attending', - id: attributedTo, + status: "attending", + id: actor, number: 1, }; event.attendees.push(newAttendee); - event.save() + event + .save() .then((fullEvent) => { - addToLog("addEventAttendee", "success", "Attendee added to event " + req.params.eventID); + addToLog( + "addEventAttendee", + "success", + "Attendee added to event " + req.params.eventID + ); // get the new attendee with its hidden id from the full event - let fullAttendee = fullEvent.attendees.find(el => el.id === attributedTo); + let fullAttendee = fullEvent.attendees.find( + (el) => el.id === actor + ); // send a "click here to remove yourself" link back to the user as a DM const jsonObject = { "@context": "https://www.w3.org/ns/activitystreams", - "name": `RSVP to ${event.name}`, - "type": "Note", - "content": `@${newAttendee.name} Thanks for RSVPing! You can remove yourself from the RSVP list by clicking here: https://${domain}/oneclickunattendevent/${event.id}/${fullAttendee._id}`, - "tag": [{ "type": "Mention", "href": newAttendee.id, "name": newAttendee.name }] - } + name: `RSVP to ${event.name}`, + type: "Note", + content: `@${newAttendee.name} Thanks for RSVPing! You can remove yourself from the RSVP list by clicking here: https://${domain}/oneclickunattendevent/${event.id}/${fullAttendee._id}`, + tag: [ + { + type: "Mention", + href: newAttendee.id, + name: newAttendee.name, + }, + ], + }; // send direct message to user sendDirectMessage(jsonObject, newAttendee.id, event.id); return res.sendStatus(200); }) .catch((err) => { - addToLog("addEventAttendee", "error", "Attempt to add attendee to event " + req.params.eventID + " failed with error: " + err); - return res.status(500).send('Database error, please try again :('); + addToLog( + "addEventAttendee", + "error", + "Attempt to add attendee to event " + + req.params.eventID + + " failed with error: " + + err + ); + return res + .status(500) + .send("Database error, please try again :("); }); - } - else { + } else { // it's a duplicate and this person is already rsvped so just say OK return res.status(200).send("Attendee is already registered."); } - }); + } + ); + } + } + ); +} + +function _handleUndoAcceptEvent(req, res) { + let { name, attributedTo, inReplyTo, to, actor } = req.body; + if (Array.isArray(to)) { + to = to[0]; + } + const eventID = to.replace(`https://${domain}/`, ""); + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (!event) return; + // does the id we got match the id of a thing we sent out + const message = event.activityPubMessages.find( + (el) => el.id === req.body.object.object + ); + if (message) { + // it's a match + Event.update( + { id: eventID }, + { $pull: { attendees: { id: actor } } } + ).then((response) => { + addToLog( + "oneClickUnattend", + "success", + "Attendee removed via one click unattend " + req.params.eventID + ); + }); + } + } + ); +} + +function _handleCreateNote(req, res) { + // figure out what this is in reply to -- it should be addressed specifically to us + let { name, attributedTo, inReplyTo, to } = req.body.object; + // if it's an array just grab the first element, since a poll should only broadcast back to the pollster + if (Array.isArray(to)) { + to = to[0]; + } + const eventID = to.replace(`https://${domain}/`, ""); + // make sure this person is actually a follower + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (!event) return; + // is this even someone who follows us + const indexOfFollower = event.followers.findIndex( + (el) => el.actorId === req.body.object.attributedTo + ); + if (indexOfFollower !== -1) { + // compare the inReplyTo to its stored message, if it exists and it's going to the right follower then this is a valid reply + const message = event.activityPubMessages.find((el) => { + const content = JSON.parse(el.content); + return inReplyTo === (content.object && content.object.id); + }); + if (message) { + const content = JSON.parse(message.content); + // check if the message we sent out was sent to the actor this incoming message is attributedTo + if (content.to[0] === attributedTo) { + // it's a match, this is a valid poll response, add RSVP to database + // fetch the profile information of the user + request( + { + url: attributedTo, + headers: { + Accept: "application/activity+json", + "Content-Type": "application/activity+json", + }, + }, + function (error, response, body) { + body = JSON.parse(body); + // if this account is NOT already in our attendees list, add it + if ( + !event.attendees.map((el) => el.id).includes(attributedTo) + ) { + const attendeeName = + body.preferredUsername || body.name || attributedTo; + const newAttendee = { + name: attendeeName, + status: "attending", + id: attributedTo, + number: 1, + }; + event.attendees.push(newAttendee); + event + .save() + .then((fullEvent) => { + addToLog( + "addEventAttendee", + "success", + "Attendee added to event " + req.params.eventID + ); + // get the new attendee with its hidden id from the full event + let fullAttendee = fullEvent.attendees.find( + (el) => el.id === attributedTo + ); + // send a "click here to remove yourself" link back to the user as a DM + const jsonObject = { + "@context": "https://www.w3.org/ns/activitystreams", + name: `RSVP to ${event.name}`, + type: "Note", + content: `@${newAttendee.name} Thanks for RSVPing! You can remove yourself from the RSVP list by clicking here: https://${domain}/oneclickunattendevent/${event.id}/${fullAttendee._id}`, + tag: [ + { + type: "Mention", + href: newAttendee.id, + name: newAttendee.name, + }, + ], + }; + // send direct message to user + sendDirectMessage(jsonObject, newAttendee.id, event.id); + return res.sendStatus(200); + }) + .catch((err) => { + addToLog( + "addEventAttendee", + "error", + "Attempt to add attendee to event " + + req.params.eventID + + " failed with error: " + + err + ); + return res + .status(500) + .send("Database error, please try again :("); + }); + } else { + // it's a duplicate and this person is already rsvped so just say OK + return res + .status(200) + .send("Attendee is already registered."); + } + } + ); + } } } } - }); + ); } function _handleDelete(req, res) { const deleteObjectId = req.body.object.id; // find all events with comments from the author - Event.find({ - "comments.actorId": req.body.actor - }, function (err, events) { - if (!events) { - return res.sendStatus(404); - } + Event.find( + { + "comments.actorId": req.body.actor, + }, + function (err, events) { + if (!events) { + return res.sendStatus(404); + } - // find the event with THIS comment from the author - let eventWithComment = events.find(event => { - let comments = event.comments; - return comments.find(comment => { - if (!comment.activityJson) { - return false; - } - return JSON.parse(comment.activityJson).object.id === req.body.object.id; - }) - }); + // find the event with THIS comment from the author + let eventWithComment = events.find((event) => { + let comments = event.comments; + return comments.find((comment) => { + if (!comment.activityJson) { + return false; + } + return ( + JSON.parse(comment.activityJson).object.id === req.body.object.id + ); + }); + }); - if (!eventWithComment) { - return res.sendStatus(404); - } + if (!eventWithComment) { + return res.sendStatus(404); + } - // delete the comment - // find the index of the comment, it should have an activityJson field because from an AP server you can only delete an AP-originated comment (and of course it needs to be yours) - let indexOfComment = eventWithComment.comments.findIndex(comment => { - return comment.activityJson && JSON.parse(comment.activityJson).object.id === req.body.object.id; - }); - eventWithComment.comments.splice(indexOfComment, 1); - eventWithComment.save() - .then(() => { - addToLog("deleteComment", "success", "Comment deleted from event " + eventWithComment.id); - return res.sendStatus(200); - }) - .catch((err) => { - addToLog("deleteComment", "error", "Attempt to delete comment " + req.body.object.id + "from event " + eventWithComment.id + " failed with error: " + err); - return res.sendStatus(500); + // delete the comment + // find the index of the comment, it should have an activityJson field because from an AP server you can only delete an AP-originated comment (and of course it needs to be yours) + let indexOfComment = eventWithComment.comments.findIndex((comment) => { + return ( + comment.activityJson && + JSON.parse(comment.activityJson).object.id === req.body.object.id + ); }); - }); + eventWithComment.comments.splice(indexOfComment, 1); + eventWithComment + .save() + .then(() => { + addToLog( + "deleteComment", + "success", + "Comment deleted from event " + eventWithComment.id + ); + return res.sendStatus(200); + }) + .catch((err) => { + addToLog( + "deleteComment", + "error", + "Attempt to delete comment " + + req.body.object.id + + "from event " + + eventWithComment.id + + " failed with error: " + + err + ); + return res.sendStatus(500); + }); + } + ); } function _handleCreateNoteComment(req, res) { // figure out what this is in reply to -- it should be addressed specifically to us let { attributedTo, inReplyTo, to, cc } = req.body.object; // normalize cc into an array - if (typeof cc === 'string') { + if (typeof cc === "string") { cc = [cc]; } // normalize to into an array - if (typeof to === 'string') { + if (typeof to === "string") { to = [to]; } // if this is a public message (in the to or cc fields) - if (to.includes('https://www.w3.org/ns/activitystreams#Public') || (Array.isArray(cc) && cc.includes('https://www.w3.org/ns/activitystreams#Public'))) { + if ( + to.includes("https://www.w3.org/ns/activitystreams#Public") || + (Array.isArray(cc) && + cc.includes("https://www.w3.org/ns/activitystreams#Public")) + ) { // figure out which event(s) of ours it was addressing - let ourEvents = cc.filter(el => el.includes(`https://${domain}/`)) - .map(el => el.replace(`https://${domain}/`, '')); - // comments should only be on one event. if more than one, ignore (spam, probably) + let ourEvents = cc + .filter((el) => el.includes(`https://${domain}/`)) + .map((el) => el.replace(`https://${domain}/`, "")); + // comments should only be on one event. if more than one, ignore (spam, probably) if (ourEvents.length === 1) { let eventID = ourEvents[0]; // add comment let commentID = nanoid(); // get the actor for the commenter - request({ - url: req.body.actor, - headers: { - 'Accept': 'application/activity+json', - 'Content-Type': 'application/activity+json' - } - }, function (error, response, actor) { - if (!error) { - const parsedActor = JSON.parse(actor); - const name = parsedActor.preferredUsername || parsedActor.name || req.body.actor; - const newComment = { - id: commentID, - actorId: req.body.actor, - activityId: req.body.object.id, - author: name, - content: sanitizeHtml(req.body.object.content, { allowedTags: [], allowedAttributes: {} }).replace('@' + eventID, ''), - timestamp: moment(), - activityJson: JSON.stringify(req.body), - actorJson: actor - }; - - Event.findOne({ - id: eventID, - }, function (err, event) { - if (!event) { - return res.sendStatus(404); - } - if (!event.usersCanComment) { - return res.sendStatus(200); - } - event.comments.push(newComment); - event.save() - .then(() => { - addToLog("addEventComment", "success", "Comment added to event " + eventID); - const guidObject = crypto.randomBytes(16).toString('hex'); - const jsonObject = req.body.object; - jsonObject.attributedTo = newComment.actorId; - broadcastAnnounceMessage(jsonObject, event.followers, eventID) - return res.sendStatus(200); - }) - .catch((err) => { - addToLog("addEventComment", "error", "Attempt to add comment to event " + eventID + " failed with error: " + err); - res.status(500).send('Database error, please try again :(' + err); - }); - }); + request( + { + url: req.body.actor, + headers: { + Accept: "application/activity+json", + "Content-Type": "application/activity+json", + }, + }, + function (error, response, actor) { + if (!error) { + const parsedActor = JSON.parse(actor); + const name = + parsedActor.preferredUsername || + parsedActor.name || + req.body.actor; + const newComment = { + id: commentID, + actorId: req.body.actor, + activityId: req.body.object.id, + author: name, + content: sanitizeHtml(req.body.object.content, { + allowedTags: [], + allowedAttributes: {}, + }).replace("@" + eventID, ""), + timestamp: moment(), + activityJson: JSON.stringify(req.body), + actorJson: actor, + }; + + Event.findOne( + { + id: eventID, + }, + function (err, event) { + if (!event) { + return res.sendStatus(404); + } + if (!event.usersCanComment) { + return res.sendStatus(200); + } + event.comments.push(newComment); + event + .save() + .then(() => { + addToLog( + "addEventComment", + "success", + "Comment added to event " + eventID + ); + const guidObject = crypto.randomBytes(16).toString("hex"); + const jsonObject = req.body.object; + jsonObject.attributedTo = newComment.actorId; + broadcastAnnounceMessage( + jsonObject, + event.followers, + eventID + ); + return res.sendStatus(200); + }) + .catch((err) => { + addToLog( + "addEventComment", + "error", + "Attempt to add comment to event " + + eventID + + " failed with error: " + + err + ); + res + .status(500) + .send("Database error, please try again :(" + err); + }); + } + ); + } } - }); + ); } // end ourevent } // end public message } @@ -876,50 +1189,79 @@ function processInbox(req, res) { if (!isFederated) return res.sendStatus(404); try { // if a Follow activity hits the inbox - if (typeof req.body.object === 'string' && req.body.type === 'Follow') { + if (typeof req.body.object === "string" && req.body.type === "Follow") { _handleFollow(req, res); } // if an Undo activity with a Follow object hits the inbox - if (req.body && req.body.type === 'Undo' && req.body.object && req.body.object.type === 'Follow') { + if ( + req.body && + req.body.type === "Undo" && + req.body.object && + req.body.object.type === "Follow" + ) { _handleUndoFollow(req, res); } // if an Accept activity with the id of the Event we sent out hits the inbox, it is an affirmative RSVP - if (req.body && req.body.type === 'Accept' && req.body.object && typeof req.body.object === 'string') { + if ( + req.body && + req.body.type === "Accept" && + req.body.object && + typeof req.body.object === "string" + ) { _handleAcceptEvent(req, res); } // if an Undo activity containing an Accept containing the id of the Event we sent out hits the inbox, it is an undo RSVP - if (req.body && req.body.type === 'Undo' && req.body.object && req.body.object.object && typeof req.body.object.object === 'string' && req.body.object.type === 'Accept') { + if ( + req.body && + req.body.type === "Undo" && + req.body.object && + req.body.object.object && + typeof req.body.object.object === "string" && + req.body.object.type === "Accept" + ) { _handleUndoAcceptEvent(req, res); } // if a Create activity with a Note object hits the inbox, and it's a reply, it might be a vote in a poll - if (req.body && req.body.type === 'Create' && req.body.object && req.body.object.type === 'Note' && req.body.object.inReplyTo && req.body.object.to) { + if ( + req.body && + req.body.type === "Create" && + req.body.object && + req.body.object.type === "Note" && + req.body.object.inReplyTo && + req.body.object.to + ) { _handleCreateNote(req, res); } // if a Delete activity hits the inbox, it might a deletion of a comment - if (req.body && req.body.type === 'Delete') { + if (req.body && req.body.type === "Delete") { _handleDelete(req, res); } // if we are CC'ed on a public or unlisted Create/Note, then this is a comment to us we should boost (Announce) to our followers - if (req.body && req.body.type === 'Create' && req.body.object && req.body.object.type === 'Note' && req.body.object.to) { + if ( + req.body && + req.body.type === "Create" && + req.body.object && + req.body.object.type === "Note" && + req.body.object.to + ) { _handleCreateNoteComment(req, res); } // CC'ed - } - catch (e) { - console.log('Error in processing inbox:', e) + } catch (e) { + console.log("Error in processing inbox:", e); } } function createWebfinger(eventID, domain) { return { - 'subject': `acct:${eventID}@${domain}`, + subject: `acct:${eventID}@${domain}`, - 'links': [ + links: [ { - 'rel': 'self', - 'type': 'application/activity+json', - 'href': `https://${domain}/${eventID}` - } - ] + rel: "self", + type: "application/activity+json", + href: `https://${domain}/${eventID}`, + }, + ], }; } @@ -938,4 +1280,4 @@ module.exports = { updateActivityPubEvent, createFeaturedPost, createWebfinger, -} +}; diff --git a/src/app.js b/src/app.js index cc50593..4a2137e 100755 --- a/src/app.js +++ b/src/app.js @@ -1,10 +1,10 @@ -const express = require('express'); -const path = require('path'); -const session = require('express-session'); -const cors = require('cors'); -const routes = require('./routes'); -const hbs = require('express-handlebars'); -const bodyParser = require('body-parser'); +const express = require("express"); +const path = require("path"); +const session = require("express-session"); +const cors = require("cors"); +const routes = require("./routes"); +const hbs = require("express-handlebars"); +const bodyParser = require("body-parser"); const app = express(); @@ -14,41 +14,40 @@ const app = express(); //app.use(bodyParser.json()); //app.use(session({ secret: 'slartibartfast', cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false })); - // View engine // const hbsInstance = hbs.create({ - defaultLayout: 'main', - partialsDir: ['views/partials/'], - layoutsDir: 'views/layouts/', - helpers: { - plural: function(number, text) { - var singular = number === 1; - // If no text parameter was given, just return a conditional s. - if (typeof text !== 'string') return singular ? '' : 's'; - // Split with regex into group1/group2 or group1(group3) - var match = text.match(/^([^()\/]+)(?:\/(.+))?(?:\((\w+)\))?/); - // If no match, just append a conditional s. - if (!match) return text + (singular ? '' : 's'); - // We have a good match, so fire away - return singular && match[1] // Singular case - || - match[2] // Plural case: 'bagel/bagels' --> bagels - || - match[1] + (match[3] || 's'); // Plural case: 'bagel(s)' or 'bagel' --> bagels - } - } + defaultLayout: "main", + partialsDir: ["views/partials/"], + layoutsDir: "views/layouts/", + helpers: { + plural: function (number, text) { + var singular = number === 1; + // If no text parameter was given, just return a conditional s. + if (typeof text !== "string") return singular ? "" : "s"; + // Split with regex into group1/group2 or group1(group3) + var match = text.match(/^([^()\/]+)(?:\/(.+))?(?:\((\w+)\))?/); + // If no match, just append a conditional s. + if (!match) return text + (singular ? "" : "s"); + // We have a good match, so fire away + return ( + (singular && match[1]) || // Singular case + match[2] || // Plural case: 'bagel/bagels' --> bagels + match[1] + (match[3] || "s") + ); // Plural case: 'bagel(s)' or 'bagel' --> bagels + }, + }, }); -app.engine('handlebars', hbsInstance.engine); -app.set('view engine', 'handlebars'); -app.set('hbsInstance', hbsInstance); +app.engine("handlebars", hbsInstance.engine); +app.set("view engine", "handlebars"); +app.set("hbsInstance", hbsInstance); // Static files // -app.use(express.static('public')); +app.use(express.static("public")); // Router // app.use(bodyParser.json({ type: "application/activity+json" })); // support json encoded bodies app.use(bodyParser.urlencoded({ extended: true })); -app.use('/', routes); +app.use("/", routes); module.exports = app; diff --git a/src/config/api-example.js b/src/config/api-example.js index 9202f0a..493b9d6 100644 --- a/src/config/api-example.js +++ b/src/config/api-example.js @@ -1,8 +1,8 @@ // Which of these fields are used depends on the 'mailService' config entry in config/domain.js module.exports = { - 'sendgrid' : '', // If using SendGrid, the Sendgrid API key goes here - 'smtpServer': '', // If using Nodemailer, your SMTP server hostname goes here - 'smtpPort': '', // If using Nodemailer, your SMTP server port goes here - 'smtpUsername': '', // If using Nodemailer, your SMTP server username goes here - 'smtpPassword': '' // If using Nodemailer, your SMTP password goes here + sendgrid: "", // If using SendGrid, the Sendgrid API key goes here + smtpServer: "", // If using Nodemailer, your SMTP server hostname goes here + smtpPort: "", // If using Nodemailer, your SMTP server port goes here + smtpUsername: "", // If using Nodemailer, your SMTP server username goes here + smtpPassword: "", // If using Nodemailer, your SMTP password goes here }; diff --git a/src/config/database-docker.js b/src/config/database-docker.js index 7847097..96c987d 100644 --- a/src/config/database-docker.js +++ b/src/config/database-docker.js @@ -1,3 +1,3 @@ module.exports = { - 'url' : 'mongodb://mongo:27017/gathio' // For dockerised MongoDB connection + url: "mongodb://mongo:27017/gathio", // For dockerised MongoDB connection }; diff --git a/src/config/database-example.js b/src/config/database-example.js index 4aa4c4d..ca7bdcc 100644 --- a/src/config/database-example.js +++ b/src/config/database-example.js @@ -1,3 +1,3 @@ module.exports = { - 'url' : 'mongodb://localhost:27017/gathio' // For local MongoDB connection + url: "mongodb://localhost:27017/gathio", // For local MongoDB connection }; diff --git a/src/config/domain-example.js b/src/config/domain-example.js index 19c797a..abac094 100644 --- a/src/config/domain-example.js +++ b/src/config/domain-example.js @@ -1,13 +1,13 @@ module.exports = { - // Your domain goes here. If there is a port it should be 'domain:port', but otherwise just 'domain' - 'domain' : 'localhost:3000' , - 'port': '3000', - 'email': 'contact@example.com', - 'mailService': 'nodemailer', // Which mail service to use to send emails to attendees. Options are 'nodemailer' or 'sendgrid'. Configure settings for the mail service in config/api.js.z - 'sitename': 'gathio', - 'isFederated': true, - // If left blank, this defaults to https://yourdomain.com/images/gathio-email-logo.gif. Set a full URL here to change it to your own logo (or just change the file itself) - 'logo_url': '', - // Show a Ko-Fi box to donate money to Raphael Kabo (Gathio's creator) on the front page - 'showKofi': false, + // Your domain goes here. If there is a port it should be 'domain:port', but otherwise just 'domain' + domain: "localhost:3000", + port: "3000", + email: "contact@example.com", + mailService: "nodemailer", // Which mail service to use to send emails to attendees. Options are 'nodemailer' or 'sendgrid'. Configure settings for the mail service in config/api.js.z + sitename: "gathio", + isFederated: true, + // If left blank, this defaults to https://yourdomain.com/images/gathio-email-logo.gif. Set a full URL here to change it to your own logo (or just change the file itself) + logo_url: "", + // Show a Ko-Fi box to donate money to Raphael Kabo (Gathio's creator) on the front page + showKofi: false, }; diff --git a/src/helpers.js b/src/helpers.js index bf95e27..9b7559f 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -1,10 +1,10 @@ -const domain = require('./config/domain.js').domain; -const siteName = require('./config/domain.js').sitename; +const domain = require("./config/domain.js").domain; +const siteName = require("./config/domain.js").sitename; -const mongoose = require('mongoose'); -const Log = mongoose.model('Log'); -var moment = require('moment-timezone'); -const icalGenerator = require('ical-generator'); +const mongoose = require("mongoose"); +const Log = mongoose.model("Log"); +var moment = require("moment-timezone"); +const icalGenerator = require("ical-generator"); // LOGGING @@ -13,9 +13,11 @@ function addToLog(process, status, message) { status: status, process: process, message: message, - timestamp: moment() + timestamp: moment(), + }); + logEntry.save().catch(() => { + console.log("Error saving log entry!"); }); - logEntry.save().catch(() => { console.log("Error saving log entry!") }); } function exportIcal(events, calendarName) { @@ -23,13 +25,13 @@ function exportIcal(events, calendarName) { const cal = icalGenerator({ name: calendarName || siteName, x: { - 'X-WR-CALNAME': calendarName || siteName, + "X-WR-CALNAME": calendarName || siteName, }, }); if (events instanceof Array === false) { - events = [ events ]; + events = [events]; } - events.forEach(event => { + events.forEach((event) => { // Add the event to the generator cal.createEvent({ start: moment.tz(event.start, event.timezone), @@ -40,10 +42,10 @@ function exportIcal(events, calendarName) { description: event.description, organizer: { name: event.hostName || "Anonymous", - email: event.creatorEmail || 'anonymous@anonymous.com', + email: event.creatorEmail || "anonymous@anonymous.com", }, location: event.location, - url: 'https://' + domain + '/' + event.id + url: "https://" + domain + "/" + event.id, }); }); // Stringify it! @@ -54,4 +56,4 @@ function exportIcal(events, calendarName) { module.exports = { addToLog, exportIcal, -} +}; diff --git a/src/models/Event.js b/src/models/Event.js index d800077..234084a 100755 --- a/src/models/Event.js +++ b/src/models/Event.js @@ -1,17 +1,17 @@ -const mongoose = require('mongoose'); +const mongoose = require("mongoose"); const Attendees = new mongoose.Schema({ name: { type: String, - trim: true + trim: true, }, status: { type: String, - trim: true + trim: true, }, email: { type: String, - trim: true + trim: true, }, removalPassword: { type: String, @@ -29,226 +29,231 @@ const Attendees = new mongoose.Schema({ number: { type: Number, trim: true, - default: 1 + default: 1, }, created: Date, -}) +}); -const Followers = new mongoose.Schema({ - // this is the id of the original follow *request*, which we use to validate Undo events - followId: { - type: String, - trim: true - }, - // this is the actual remote user profile id - actorId: { - type: String, - trim: true - }, - // this is the stringified JSON of the entire user profile - actorJson: { - type: String, - trim: true - }, - name: { - type: String, - trim: true - }, -}, { _id: false }) +const Followers = new mongoose.Schema( + { + // this is the id of the original follow *request*, which we use to validate Undo events + followId: { + type: String, + trim: true, + }, + // this is the actual remote user profile id + actorId: { + type: String, + trim: true, + }, + // this is the stringified JSON of the entire user profile + actorJson: { + type: String, + trim: true, + }, + name: { + type: String, + trim: true, + }, + }, + { _id: false } +); const ReplySchema = new mongoose.Schema({ id: { type: String, required: true, unique: true, - sparse: true + sparse: true, }, author: { type: String, trim: true, - required: true + required: true, }, content: { type: String, trim: true, - required: true + required: true, }, timestamp: { type: Date, trim: true, - required: true - } -}) + required: true, + }, +}); const ActivityPubMessages = new mongoose.Schema({ id: { type: String, required: true, unique: true, - sparse: true + sparse: true, }, content: { type: String, trim: true, - required: true - } -}) + required: true, + }, +}); const CommentSchema = new mongoose.Schema({ id: { type: String, required: true, unique: true, - sparse: true + sparse: true, }, author: { type: String, trim: true, - required: true + required: true, }, content: { type: String, trim: true, - required: true + required: true, }, timestamp: { type: Date, trim: true, - required: true + required: true, }, activityJson: { type: String, - trim: true + trim: true, }, actorJson: { type: String, - trim: true + trim: true, }, activityId: { type: String, - trim: true + trim: true, }, actorId: { type: String, - trim: true + trim: true, }, - replies: [ReplySchema] -}) + replies: [ReplySchema], +}); const EventSchema = new mongoose.Schema({ id: { type: String, required: true, - unique: true + unique: true, }, type: { type: String, trim: true, - required: true + required: true, }, name: { type: String, trim: true, - required: true + required: true, }, location: { type: String, trim: true, - required: true + required: true, }, - start: { // Stored as a UTC timestamp + start: { + // Stored as a UTC timestamp type: Date, trim: true, - required: true + required: true, }, - end: { // Stored as a UTC timestamp + end: { + // Stored as a UTC timestamp type: Date, trim: true, - required: true + required: true, }, timezone: { type: String, - default: 'Etc/UTC' + default: "Etc/UTC", }, description: { type: String, trim: true, - required: true + required: true, }, image: { type: String, - trim: true + trim: true, }, url: { type: String, - trim: true + trim: true, }, creatorEmail: { type: String, - trim: true + trim: true, }, hostName: { type: String, - trim: true + trim: true, }, viewPassword: { type: String, - trim: true + trim: true, }, editPassword: { type: String, - trim: true + trim: true, }, editToken: { type: String, trim: true, minlength: 32, - maxlength: 32 + maxlength: 32, }, - eventGroup: { type: mongoose.Schema.Types.ObjectId, ref: 'EventGroup' }, + eventGroup: { type: mongoose.Schema.Types.ObjectId, ref: "EventGroup" }, usersCanAttend: { type: Boolean, trim: true, - default: false + default: false, }, showUsersList: { type: Boolean, trim: true, - default: false + default: false, }, usersCanComment: { type: Boolean, trim: true, - default: false + default: false, }, firstLoad: { type: Boolean, trim: true, - default: true + default: true, }, attendees: [Attendees], maxAttendees: { - type: Number + type: Number, }, comments: [CommentSchema], activityPubActor: { type: String, - trim: true + trim: true, }, activityPubEvent: { type: String, - trim: true + trim: true, }, publicKey: { type: String, - trim: true + trim: true, }, privateKey: { type: String, - trim: true + trim: true, }, followers: [Followers], - activityPubMessages: [ActivityPubMessages] + activityPubMessages: [ActivityPubMessages], }); -module.exports = mongoose.model('Event', EventSchema); +module.exports = mongoose.model("Event", EventSchema); diff --git a/src/models/EventGroup.js b/src/models/EventGroup.js index c70ef95..1a4ac64 100755 --- a/src/models/EventGroup.js +++ b/src/models/EventGroup.js @@ -1,57 +1,57 @@ -const mongoose = require('mongoose'); +const mongoose = require("mongoose"); const Subscriber = new mongoose.Schema({ email: { type: String, - trim: true + trim: true, }, -}) +}); const EventGroupSchema = new mongoose.Schema({ id: { type: String, required: true, - unique: true + unique: true, }, name: { type: String, trim: true, - required: true + required: true, }, description: { type: String, trim: true, - required: true + required: true, }, image: { type: String, - trim: true + trim: true, }, url: { type: String, - trim: true + trim: true, }, creatorEmail: { type: String, - trim: true + trim: true, }, hostName: { type: String, - trim: true + trim: true, }, editToken: { type: String, trim: true, minlength: 32, - maxlength: 32 + maxlength: 32, }, firstLoad: { type: Boolean, trim: true, - default: true + default: true, }, - events: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Event' }], + events: [{ type: mongoose.Schema.Types.ObjectId, ref: "Event" }], subscribers: [Subscriber], }); -module.exports = mongoose.model('EventGroup', EventGroupSchema); +module.exports = mongoose.model("EventGroup", EventGroupSchema); diff --git a/src/models/Log.js b/src/models/Log.js index 95a3ab3..b048a45 100755 --- a/src/models/Log.js +++ b/src/models/Log.js @@ -1,26 +1,26 @@ -const mongoose = require('mongoose'); +const mongoose = require("mongoose"); const LogSchema = new mongoose.Schema({ status: { type: String, trim: true, - required: true + required: true, }, process: { type: String, trim: true, - required: true + required: true, }, message: { type: String, trim: true, - required: true + required: true, }, timestamp: { type: Date, trim: true, - required: true - } + required: true, + }, }); -module.exports = mongoose.model('Log', LogSchema); +module.exports = mongoose.model("Log", LogSchema); diff --git a/src/routes.js b/src/routes.js index c9867e3..052446c 100755 --- a/src/routes.js +++ b/src/routes.js @@ -1,45 +1,48 @@ -const fs = require('fs'); +const fs = require("fs"); -const express = require('express'); +const express = require("express"); -const mongoose = require('mongoose'); +const mongoose = require("mongoose"); // This alphabet (used to generate all event, group, etc. IDs) is missing '-' // because ActivityPub doesn't like it in IDs -const { customAlphabet } = require('nanoid'); -const nanoid = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_', 21); +const { customAlphabet } = require("nanoid"); +const nanoid = customAlphabet( + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_", + 21 +); const randomstring = require("randomstring"); -const { body, validationResult } = require('express-validator'); +const { body, validationResult } = require("express-validator"); const router = express.Router(); -const Event = mongoose.model('Event'); -const EventGroup = mongoose.model('EventGroup'); -const addToLog = require('./helpers.js').addToLog; +const Event = mongoose.model("Event"); +const EventGroup = mongoose.model("EventGroup"); +const addToLog = require("./helpers.js").addToLog; -var moment = require('moment-timezone'); +var moment = require("moment-timezone"); -const marked = require('marked'); +const marked = require("marked"); -const generateRSAKeypair = require('generate-rsa-keypair'); -const crypto = require('crypto'); -const request = require('request'); -const niceware = require('niceware'); +const generateRSAKeypair = require("generate-rsa-keypair"); +const crypto = require("crypto"); +const request = require("request"); +const niceware = require("niceware"); -const domain = require('./config/domain.js').domain; -const contactEmail = require('./config/domain.js').email; -const mailService = require('./config/domain.js').mailService; -const siteName = require('./config/domain.js').sitename; -const siteLogo = require('./config/domain.js').logo_url; -let isFederated = require('./config/domain.js').isFederated; -let showKofi = require('./config/domain.js').showKofi; +const domain = require("./config/domain.js").domain; +const contactEmail = require("./config/domain.js").email; +const mailService = require("./config/domain.js").mailService; +const siteName = require("./config/domain.js").sitename; +const siteLogo = require("./config/domain.js").logo_url; +let isFederated = require("./config/domain.js").isFederated; +let showKofi = require("./config/domain.js").showKofi; // if the federation config isn't set, things are federated by default if (isFederated === undefined) { isFederated = true; } -const ap = require('./activitypub.js'); +const ap = require("./activitypub.js"); // Extra marked renderer (used to render plaintext event description for page metadata) // Adapted from https://dustinpfister.github.io/2017/11/19/nodejs-marked/ @@ -47,7 +50,7 @@ const ap = require('./activitypub.js'); function htmlEscapeToText(text) { return text.replace(/\&\#[0-9]*;|&/g, function (escapeCode) { if (escapeCode.match(/amp/)) { - return '&'; + return "&"; } return String.fromCharCode(escapeCode.match(/[0-9]+/)); }); @@ -61,45 +64,45 @@ function render_plain() { }; render.strong = function (text) { return text; - } + }; render.em = function (text) { return text; - } + }; // render just the text of a paragraph render.paragraph = function (text) { - return htmlEscapeToText(text) + '\r\n'; + return htmlEscapeToText(text) + "\r\n"; }; // render nothing for headings, images, and br render.heading = function (text, level) { - return ''; + return ""; }; render.image = function (href, title, text) { - return ''; + return ""; }; render.br = function () { - return ''; + return ""; }; return render; } -const ical = require('ical'); -const { exportIcal } = require('./helpers.js'); +const ical = require("ical"); +const { exportIcal } = require("./helpers.js"); -const sgMail = require('@sendgrid/mail'); +const sgMail = require("@sendgrid/mail"); const nodemailer = require("nodemailer"); -const apiCredentials = require('./config/api.js'); +const apiCredentials = require("./config/api.js"); let sendEmails = false; let nodemailerTransporter; if (mailService) { switch (mailService) { - case 'sendgrid': + case "sendgrid": sgMail.setApiKey(apiCredentials.sendgrid); console.log("Sendgrid is ready to send emails."); sendEmails = true; break; - case 'nodemailer': + case "nodemailer": nodemailerTransporter = nodemailer.createTransport({ host: apiCredentials.smtpServer, port: apiCredentials.smtpPort, @@ -119,60 +122,104 @@ if (mailService) { }); break; default: - console.error('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.') + console.error( + "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." + ); } } -const fileUpload = require('express-fileupload'); -var Jimp = require('jimp'); +const fileUpload = require("express-fileupload"); +var Jimp = require("jimp"); router.use(fileUpload()); // SCHEDULED DELETION -const schedule = require('node-schedule'); -schedule.scheduleJob('59 23 * * *', function (fireDate) { - const too_old = moment.tz('Etc/UTC').subtract(7, 'days').toDate(); - console.log("Old event deletion running! Deleting all events concluding before ", too_old); - - Event.find({ end: { $lte: too_old } }).then((oldEvents) => { - oldEvents.forEach(event => { - const deleteEventFromDB = (id) => { - Event.remove({ "_id": id }) - .then(response => { - addToLog("deleteOldEvents", "success", "Old event " + id + " deleted"); - }).catch((err) => { - addToLog("deleteOldEvents", "error", "Attempt to delete old event " + id + " failed with error: " + err); - }); - } +const schedule = require("node-schedule"); +schedule.scheduleJob("59 23 * * *", function (fireDate) { + const too_old = moment.tz("Etc/UTC").subtract(7, "days").toDate(); + console.log( + "Old event deletion running! Deleting all events concluding before ", + too_old + ); + + Event.find({ end: { $lte: too_old } }) + .then((oldEvents) => { + oldEvents.forEach((event) => { + const deleteEventFromDB = (id) => { + Event.remove({ _id: id }) + .then((response) => { + addToLog( + "deleteOldEvents", + "success", + "Old event " + id + " deleted" + ); + }) + .catch((err) => { + addToLog( + "deleteOldEvents", + "error", + "Attempt to delete old event " + + id + + " failed with error: " + + err + ); + }); + }; - if (event.image) { - fs.unlink(global.appRoot + '/public/events/' + event.image, (err) => { - if (err) { - addToLog("deleteOldEvents", "error", "Attempt to delete event image for old event " + event.id + " failed with error: " + err); - } - // Image removed - addToLog("deleteOldEvents", "error", "Image deleted for old event " + event.id); - }) - } - // Check if event has ActivityPub fields - if (event.activityPubActor && event.activityPubEvent) { - // Broadcast a Delete profile message to all followers so that at least Mastodon servers will delete their local profile information - const guidUpdateObject = crypto.randomBytes(16).toString('hex'); - const jsonUpdateObject = JSON.parse(event.activityPubActor); - const jsonEventObject = JSON.parse(event.activityPubEvent); - // first broadcast AP messages, THEN delete from DB - ap.broadcastDeleteMessage(jsonUpdateObject, event.followers, event.id, function (statuses) { - ap.broadcastDeleteMessage(jsonEventObject, event.followers, event.id, function (statuses) { - deleteEventFromDB(event._id); + if (event.image) { + fs.unlink(global.appRoot + "/public/events/" + event.image, (err) => { + if (err) { + addToLog( + "deleteOldEvents", + "error", + "Attempt to delete event image for old event " + + event.id + + " failed with error: " + + err + ); + } + // Image removed + addToLog( + "deleteOldEvents", + "error", + "Image deleted for old event " + event.id + ); }); - }); - } else { - // No ActivityPub data - simply delete the event - deleteEventFromDB(event._id); - } + } + // Check if event has ActivityPub fields + if (event.activityPubActor && event.activityPubEvent) { + // Broadcast a Delete profile message to all followers so that at least Mastodon servers will delete their local profile information + const guidUpdateObject = crypto.randomBytes(16).toString("hex"); + const jsonUpdateObject = JSON.parse(event.activityPubActor); + const jsonEventObject = JSON.parse(event.activityPubEvent); + // first broadcast AP messages, THEN delete from DB + ap.broadcastDeleteMessage( + jsonUpdateObject, + event.followers, + event.id, + function (statuses) { + ap.broadcastDeleteMessage( + jsonEventObject, + event.followers, + event.id, + function (statuses) { + deleteEventFromDB(event._id); + } + ); + } + ); + } else { + // No ActivityPub data - simply delete the event + deleteEventFromDB(event._id); + } + }); }) - }).catch((err) => { - addToLog("deleteOldEvents", "error", "Attempt to delete old event " + event.id + " failed with error: " + err); - }); + .catch((err) => { + addToLog( + "deleteOldEvents", + "error", + "Attempt to delete old event " + event.id + " failed with error: " + err + ); + }); // TODO: While we're here, also remove all provisioned event attendees over a day // old (they're not going to become active) @@ -180,8 +227,8 @@ schedule.scheduleJob('59 23 * * *', function (fireDate) { // FRONTEND ROUTES -router.get('/', (req, res) => { - res.render('home', { +router.get("/", (req, res) => { + res.render("home", { domain, email: contactEmail, siteName, @@ -189,192 +236,236 @@ router.get('/', (req, res) => { }); }); -router.get('/new', (req, res) => { - res.render('home'); +router.get("/new", (req, res) => { + res.render("home"); }); -router.get('/new/event', (req, res) => { - res.render('newevent', { +router.get("/new/event", (req, res) => { + res.render("newevent", { domain: domain, email: contactEmail, siteName: siteName, }); }); -router.get('/new/event/public', (req, res) => { +router.get("/new/event/public", (req, res) => { let isPrivate = false; let isPublic = true; let isOrganisation = false; let isUnknownType = false; - res.render('newevent', { - title: 'New event', + res.render("newevent", { + title: "New event", isPrivate: isPrivate, isPublic: isPublic, isOrganisation: isOrganisation, isUnknownType: isUnknownType, - eventType: 'public', + eventType: "public", domain: domain, email: contactEmail, siteName: siteName, }); -}) +}); // return the JSON for the featured/pinned post for this event -router.get('/:eventID/featured', (req, res) => { +router.get("/:eventID/featured", (req, res) => { if (!isFederated) return res.sendStatus(404); const { eventID } = req.params; - const guidObject = crypto.randomBytes(16).toString('hex'); + const guidObject = crypto.randomBytes(16).toString("hex"); const featured = { "@context": "https://www.w3.org/ns/activitystreams", - "id": `https://${domain}/${eventID}/featured`, - "type": "OrderedCollection", - "orderedItems": [ - ap.createFeaturedPost(eventID) - ] - } + id: `https://${domain}/${eventID}/featured`, + type: "OrderedCollection", + orderedItems: [ap.createFeaturedPost(eventID)], + }; res.json(featured); }); // return the JSON for a given activitypub message -router.get('/:eventID/m/:hash', (req, res) => { +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 + 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); + res.render("404", { url: req.url }); + } else { + const message = event.activityPubMessages.find((el) => el.id === id); if (message) { return res.json(JSON.parse(message.content)); - } - else { + } else { res.status(404); - return res.render('404', { url: req.url }); + return res.render("404", { url: req.url }); } } }) .catch((err) => { - addToLog("getActivityPubMessage", "error", "Attempt to get Activity Pub Message for " + id + " failed with error: " + 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 }); + res.render("404", { url: req.url }); return; }); }); // return the webfinger record required for the initial activitypub handshake -router.get('/.well-known/webfinger', (req, res) => { +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 { + 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:', ''); + let activityPubAccount = resource.replace("acct:", ""); // "foo" - let eventID = activityPubAccount.replace(/@.*/, ''); + let eventID = activityPubAccount.replace(/@.*/, ""); Event.findOne({ - id: eventID + id: eventID, }) .then((event) => { if (!event) { res.status(404); - res.render('404', { url: req.url }); - } - else { + res.render("404", { url: req.url }); + } else { res.json(ap.createWebfinger(eventID, domain)); } }) .catch((err) => { - addToLog("renderWebfinger", "error", "Attempt to render webfinger for " + req.params.eventID + " failed with error: " + 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 }); + res.render("404", { url: req.url }); return; }); } }); -router.get('/:eventID', (req, res) => { +router.get("/:eventID", (req, res) => { Event.findOne({ - id: req.params.eventID + id: req.params.eventID, }) .lean() // Required, see: https://stackoverflow.com/questions/59690923/handlebars-access-has-been-denied-to-resolve-the-property-from-because-it-is - .populate('eventGroup') + .populate("eventGroup") .then((event) => { if (event) { - const parsedLocation = event.location.replace(/\s+/g, '+'); + const parsedLocation = event.location.replace(/\s+/g, "+"); let displayDate; - if (moment.tz(event.end, event.timezone).isSame(event.start, 'day')) { + if (moment.tz(event.end, event.timezone).isSame(event.start, "day")) { // Happening during one day - displayDate = moment.tz(event.start, event.timezone).format('dddd D MMMM YYYY [from] h:mm a') + moment.tz(event.end, event.timezone).format(' [to] h:mm a [](z)[]'); - } - else { - displayDate = moment.tz(event.start, event.timezone).format('dddd D MMMM YYYY [at] h:mm a') + moment.tz(event.end, event.timezone).format(' [–] dddd D MMMM YYYY [at] h:mm a [](z)[]'); + displayDate = + moment + .tz(event.start, event.timezone) + .format( + 'dddd D MMMM YYYY [from] h:mm a' + ) + + moment + .tz(event.end, event.timezone) + .format( + ' [to] h:mm a [](z)[]' + ); + } else { + displayDate = + moment + .tz(event.start, event.timezone) + .format( + 'dddd D MMMM YYYY [at] h:mm a' + ) + + moment + .tz(event.end, event.timezone) + .format( + ' [–] dddd D MMMM YYYY [at] h:mm a [](z)[]' + ); } let eventStartISO = moment.tz(event.start, "Etc/UTC").toISOString(); let eventEndISO = moment.tz(event.end, "Etc/UTC").toISOString(); - let parsedStart = moment.tz(event.start, event.timezone).format('YYYYMMDD[T]HHmmss'); - let parsedEnd = moment.tz(event.end, event.timezone).format('YYYYMMDD[T]HHmmss'); + let parsedStart = moment + .tz(event.start, event.timezone) + .format("YYYYMMDD[T]HHmmss"); + let parsedEnd = moment + .tz(event.end, event.timezone) + .format("YYYYMMDD[T]HHmmss"); let eventHasConcluded = false; - if (moment.tz(event.end, event.timezone).isBefore(moment.tz(event.timezone))) { + if ( + moment + .tz(event.end, event.timezone) + .isBefore(moment.tz(event.timezone)) + ) { eventHasConcluded = true; } let eventHasBegun = false; - if (moment.tz(event.start, event.timezone).isBefore(moment.tz(event.timezone))) { + if ( + moment + .tz(event.start, event.timezone) + .isBefore(moment.tz(event.timezone)) + ) { eventHasBegun = true; } let fromNow = moment.tz(event.start, event.timezone).fromNow(); let parsedDescription = marked.parse(event.description); let eventEditToken = event.editToken; - let escapedName = event.name.replace(/\s+/g, '+'); + let escapedName = event.name.replace(/\s+/g, "+"); let eventHasCoverImage = false; if (event.image) { eventHasCoverImage = true; - } - else { + } else { eventHasCoverImage = false; } let eventHasHost = false; if (event.hostName) { eventHasHost = true; - } - else { + } else { eventHasHost = false; } let firstLoad = false; if (event.firstLoad === true) { firstLoad = true; - Event.findOneAndUpdate({ id: req.params.eventID }, { firstLoad: false }, function (err, raw) { - if (err) { - res.send(err); + Event.findOneAndUpdate( + { id: req.params.eventID }, + { firstLoad: false }, + function (err, raw) { + if (err) { + res.send(err); + } } - }); + ); } let editingEnabled = false; if (Object.keys(req.query).length !== 0) { if (!req.query.e) { editingEnabled = false; console.log("No edit token set"); - } - else { + } else { if (req.query.e === eventEditToken) { editingEnabled = true; - } - else { + } else { editingEnabled = false; } } } - let eventAttendees = event.attendees.sort((a, b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)) - .map(el => { + let eventAttendees = event.attendees + .sort((a, b) => (a.name > b.name ? 1 : b.name > a.name ? -1 : 0)) + .map((el) => { if (!el.id) { el.id = el._id; } @@ -384,12 +475,15 @@ router.get('/:eventID', (req, res) => { return el; }) .filter((obj, pos, arr) => { - return obj.status === 'attending' && arr.map(mapObj => mapObj.id).indexOf(obj.id) === pos; + return ( + obj.status === "attending" && + arr.map((mapObj) => mapObj.id).indexOf(obj.id) === pos + ); }); let spotsRemaining, noMoreSpots; let numberOfAttendees = eventAttendees.reduce((acc, attendee) => { - if (attendee.status === 'attending') { + if (attendee.status === "attending") { return acc + attendee.number || 1; } return acc; @@ -402,16 +496,27 @@ router.get('/:eventID', (req, res) => { } let metadata = { title: event.name, - description: marked.parse(event.description, { renderer: render_plain() }).split(" ").splice(0, 40).join(" ").trim(), - image: (eventHasCoverImage ? `https://${domain}/events/` + event.image : null), - url: `https://${domain}/` + req.params.eventID + description: marked + .parse(event.description, { renderer: render_plain() }) + .split(" ") + .splice(0, 40) + .join(" ") + .trim(), + image: eventHasCoverImage + ? `https://${domain}/events/` + event.image + : null, + url: `https://${domain}/` + req.params.eventID, }; - if (req.headers.accept && (req.headers.accept.includes('application/activity+json') || req.headers.accept.includes('application/json') || req.headers.accept.includes('application/json+ld'))) { + if ( + req.headers.accept && + (req.headers.accept.includes("application/activity+json") || + req.headers.accept.includes("application/json") || + req.headers.accept.includes("application/json+ld")) + ) { res.json(JSON.parse(event.activityPubActor)); - } - else { + } else { res.set("X-Robots-Tag", "noindex"); - res.render('event', { + res.render("event", { domain: domain, isFederated: isFederated, email: contactEmail, @@ -438,58 +543,61 @@ router.get('/:eventID', (req, res) => { eventHasConcluded: eventHasConcluded, eventHasBegun: eventHasBegun, metadata: metadata, - siteName: siteName - }) + siteName: siteName, + }); } - } - else { + } else { res.status(404); - res.render('404', { url: req.url }); + res.render("404", { url: req.url }); } - }) .catch((err) => { - addToLog("displayEvent", "error", "Attempt to display event " + req.params.eventID + " failed with error: " + err); - console.log(err) + addToLog( + "displayEvent", + "error", + "Attempt to display event " + + req.params.eventID + + " failed with error: " + + err + ); + console.log(err); res.status(404); - res.render('404', { url: req.url }); + res.render("404", { url: req.url }); return; }); -}) +}); -router.get('/:eventID/followers', (req, res) => { +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"] - }; - return res.json(followersCollection); - } - else { - return res.status(400).send('Bad request.'); - } - }) -}) + 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"], + }; + return res.json(followersCollection); + } else { + return res.status(400).send("Bad request."); + } + }); +}); -router.get('/group/:eventGroupID', (req, res) => { +router.get("/group/:eventGroupID", (req, res) => { EventGroup.findOne({ - id: req.params.eventGroupID + id: req.params.eventGroupID, }) .lean() // Required, see: https://stackoverflow.com/questions/59690923/handlebars-access-has-been-denied-to-resolve-the-property-from-because-it-is .then(async (eventGroup) => { @@ -497,78 +605,99 @@ router.get('/group/:eventGroupID', (req, res) => { let parsedDescription = marked.parse(eventGroup.description); let eventGroupEditToken = eventGroup.editToken; - let escapedName = eventGroup.name.replace(/\s+/g, '+'); + let escapedName = eventGroup.name.replace(/\s+/g, "+"); let eventGroupHasCoverImage = false; if (eventGroup.image) { eventGroupHasCoverImage = true; - } - else { + } else { eventGroupHasCoverImage = false; } let eventGroupHasHost = false; if (eventGroup.hostName) { eventGroupHasHost = true; - } - else { + } else { eventGroupHasHost = false; } - let events = await Event.find({ eventGroup: eventGroup._id }).lean().sort('start'); + let events = await Event.find({ eventGroup: eventGroup._id }) + .lean() + .sort("start"); - events.map(event => { - if (moment.tz(event.end, event.timezone).isSame(event.start, 'day')) { + events.map((event) => { + if (moment.tz(event.end, event.timezone).isSame(event.start, "day")) { // Happening during one day - event.displayDate = moment.tz(event.start, event.timezone).format('D MMM YYYY'); - } - else { - event.displayDate = moment.tz(event.start, event.timezone).format('D MMM YYYY') + moment.tz(event.end, event.timezone).format(' - D MMM YYYY'); + event.displayDate = moment + .tz(event.start, event.timezone) + .format("D MMM YYYY"); + } else { + event.displayDate = + moment.tz(event.start, event.timezone).format("D MMM YYYY") + + moment.tz(event.end, event.timezone).format(" - D MMM YYYY"); } - if (moment.tz(event.end, event.timezone).isBefore(moment.tz(event.timezone))) { + if ( + moment + .tz(event.end, event.timezone) + .isBefore(moment.tz(event.timezone)) + ) { event.eventHasConcluded = true; } else { event.eventHasConcluded = false; } - return (({ id, name, displayDate, eventHasConcluded }) => ({ id, name, displayDate, eventHasConcluded }))(event); + return (({ id, name, displayDate, eventHasConcluded }) => ({ + id, + name, + displayDate, + eventHasConcluded, + }))(event); }); let upcomingEventsExist = false; - if (events.some(e => e.eventHasConcluded === false)) { + if (events.some((e) => e.eventHasConcluded === false)) { upcomingEventsExist = true; } let firstLoad = false; if (eventGroup.firstLoad === true) { firstLoad = true; - EventGroup.findOneAndUpdate({ id: req.params.eventGroupID }, { firstLoad: false }, function (err, raw) { - if (err) { - res.send(err); + EventGroup.findOneAndUpdate( + { id: req.params.eventGroupID }, + { firstLoad: false }, + function (err, raw) { + if (err) { + res.send(err); + } } - }); + ); } let editingEnabled = false; if (Object.keys(req.query).length !== 0) { if (!req.query.e) { editingEnabled = false; console.log("No edit token set"); - } - else { + } else { if (req.query.e === eventGroupEditToken) { editingEnabled = true; - } - else { + } else { editingEnabled = false; } } } let metadata = { title: eventGroup.name, - description: marked.parse(eventGroup.description, { renderer: render_plain() }).split(" ").splice(0, 40).join(" ").trim(), - image: (eventGroupHasCoverImage ? `https://${domain}/events/` + eventGroup.image : null), - url: `https://${domain}/` + req.params.eventID + description: marked + .parse(eventGroup.description, { renderer: render_plain() }) + .split(" ") + .splice(0, 40) + .join(" ") + .trim(), + image: eventGroupHasCoverImage + ? `https://${domain}/events/` + eventGroup.image + : null, + url: `https://${domain}/` + req.params.eventID, }; res.set("X-Robots-Tag", "noindex"); - res.render('eventgroup', { + res.render("eventgroup", { domain: domain, title: eventGroup.name, eventGroupData: eventGroup, @@ -580,51 +709,65 @@ router.get('/group/:eventGroupID', (req, res) => { eventGroupHasCoverImage: eventGroupHasCoverImage, eventGroupHasHost: eventGroupHasHost, firstLoad: firstLoad, - metadata: metadata - }) - } - else { + metadata: metadata, + }); + } else { res.status(404); - res.render('404', { url: req.url }); + res.render("404", { url: req.url }); } - }) .catch((err) => { - addToLog("displayEventGroup", "error", "Attempt to display event group " + req.params.eventGroupID + " failed with error: " + err); - console.log(err) + addToLog( + "displayEventGroup", + "error", + "Attempt to display event group " + + req.params.eventGroupID + + " failed with error: " + + err + ); + console.log(err); res.status(404); - res.render('404', { url: req.url }); + res.render("404", { url: req.url }); return; }); -}) +}); -router.get('/group/:eventGroupID/feed.ics', (req, res) => { +router.get("/group/:eventGroupID/feed.ics", (req, res) => { EventGroup.findOne({ - id: req.params.eventGroupID + id: req.params.eventGroupID, }) .lean() // Required, see: https://stackoverflow.com/questions/59690923/handlebars-access-has-been-denied-to-resolve-the-property-from-because-it-is .then(async (eventGroup) => { if (eventGroup) { - let events = await Event.find({ eventGroup: eventGroup._id }).lean().sort('start'); + let events = await Event.find({ eventGroup: eventGroup._id }) + .lean() + .sort("start"); const string = exportIcal(events, eventGroup.name); - res.set('Content-Type', 'text/calendar'); + res.set("Content-Type", "text/calendar"); return res.send(string); } }) .catch((err) => { - addToLog("eventGroupFeed", "error", "Attempt to display event group feed for " + req.params.eventGroupID + " failed with error: " + err); - console.log(err) + addToLog( + "eventGroupFeed", + "error", + "Attempt to display event group feed for " + + req.params.eventGroupID + + " failed with error: " + + err + ); + console.log(err); res.status(404); - res.render('404', { url: req.url }); + res.render("404", { url: req.url }); return; }); }); -router.get('/exportevent/:eventID', (req, res) => { +router.get("/exportevent/:eventID", (req, res) => { Event.findOne({ - id: req.params.eventID + id: req.params.eventID, }) - .populate('eventGroup') + .populate("eventGroup") .then((event) => { if (event) { const string = exportIcal([event]); @@ -632,38 +775,54 @@ router.get('/exportevent/:eventID', (req, res) => { } }) .catch((err) => { - addToLog("exportEvent", "error", "Attempt to export event " + req.params.eventID + " failed with error: " + err); - console.log(err) + addToLog( + "exportEvent", + "error", + "Attempt to export event " + + req.params.eventID + + " failed with error: " + + err + ); + console.log(err); res.status(404); - res.render('404', { url: req.url }); + res.render("404", { url: req.url }); return; }); }); -router.get('/exportgroup/:eventGroupID', (req, res) => { +router.get("/exportgroup/:eventGroupID", (req, res) => { EventGroup.findOne({ - id: req.params.eventGroupID + id: req.params.eventGroupID, }) .lean() // Required, see: https://stackoverflow.com/questions/59690923/handlebars-access-has-been-denied-to-resolve-the-property-from-because-it-is .then(async (eventGroup) => { if (eventGroup) { - let events = await Event.find({ eventGroup: eventGroup._id }).lean().sort('start'); + let events = await Event.find({ eventGroup: eventGroup._id }) + .lean() + .sort("start"); const string = exportIcal(events); res.send(string); } }) .catch((err) => { - addToLog("exportEvent", "error", "Attempt to export event group " + req.params.eventGroupID + " failed with error: " + err); - console.log(err) + addToLog( + "exportEvent", + "error", + "Attempt to export event group " + + req.params.eventGroupID + + " failed with error: " + + err + ); + console.log(err); res.status(404); - res.render('404', { url: req.url }); + res.render("404", { url: req.url }); return; }); }); // BACKEND ROUTES -router.post('/newevent', async (req, res) => { +router.post("/newevent", async (req, res) => { let eventID = nanoid(); let editToken = randomstring.generate(); let eventImageFilename = ""; @@ -671,26 +830,38 @@ router.post('/newevent', async (req, res) => { if (req.files && Object.keys(req.files).length !== 0) { let eventImageBuffer = req.files.imageUpload.data; eventImageFilename = await Jimp.read(eventImageBuffer) - .then(img => { + .then((img) => { img .resize(920, Jimp.AUTO) // resize .quality(80) // set JPEG quality - .write('./public/events/' + eventID + '.jpg'); // save - const filename = eventID + '.jpg'; + .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); + }) + .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 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 - }) + editToken: req.body.eventGroupEditToken, + }); if (eventGroup) { isPartOfEventGroup = true; } @@ -721,97 +892,171 @@ router.post('/newevent', async (req, res) => { usersCanComment: req.body.interactionCheckbox ? true : false, maxAttendees: req.body.maxAttendees, firstLoad: true, - activityPubActor: ap.createActivityPubActor(eventID, domain, pair.public, marked.parse(req.body.eventDescription), req.body.eventName, req.body.eventLocation, eventImageFilename, startUTC, endUTC, req.body.timezone), - activityPubEvent: ap.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(ap.createFeaturedPost(eventID, req.body.eventName, startUTC, endUTC, req.body.timezone, req.body.eventDescription, req.body.eventLocation)) }], + activityPubActor: ap.createActivityPubActor( + eventID, + domain, + pair.public, + marked.parse(req.body.eventDescription), + req.body.eventName, + req.body.eventLocation, + eventImageFilename, + startUTC, + endUTC, + req.body.timezone + ), + activityPubEvent: ap.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( + ap.createFeaturedPost( + eventID, + req.body.eventName, + startUTC, + endUTC, + req.body.timezone, + req.body.eventDescription, + req.body.eventLocation + ) + ), + }, + ], publicKey: pair.public, - privateKey: pair.private + privateKey: pair.private, }); - event.save() + 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 + req.app + .get("hbsInstance") + .renderView( + "./views/emails/createevent.handlebars", + { + eventID, + editToken, + siteName, + siteLogo, + domain, + cache: true, + layout: "email.handlebars", }, - 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; - } - }); + 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; + 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 + Location: "/" + eventID + "?e=" + editToken, }); res.end(); }) - .catch((err) => { res.status(500).send('Database error, please try again :( - ' + err); addToLog("createEvent", "error", "Attempt to create event failed with error: " + err); }); + .catch((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) => { +router.post("/importevent", (req, res) => { let eventID = nanoid(); let editToken = randomstring.generate(); if (req.files && Object.keys(req.files).length !== 0) { - let iCalObject = ical.parseICS(req.files.icsImportControl.data.toString('utf8')); + let iCalObject = ical.parseICS( + req.files.icsImportControl.data.toString("utf8") + ); let importedEventData = iCalObject[Object.keys(iCalObject)]; let creatorEmail; @@ -823,84 +1068,115 @@ router.post('/importevent', (req, res) => { const event = new Event({ id: eventID, - type: 'public', + type: "public", name: importedEventData.summary, location: importedEventData.location, start: importedEventData.start, end: importedEventData.end, - timezone: typeof importedEventData.start.tz !== 'undefined' ? importedEventData.start.tz : "Etc/UTC", + timezone: + typeof importedEventData.start.tz !== "undefined" + ? importedEventData.start.tz + : "Etc/UTC", description: importedEventData.description, - image: '', + image: "", creatorEmail: creatorEmail, - url: '', - hostName: importedEventData.organizer ? importedEventData.organizer.params.CN.replace(/["]+/g, '') : "", - viewPassword: '', - editPassword: '', + url: "", + hostName: importedEventData.organizer + ? importedEventData.organizer.params.CN.replace(/["]+/g, "") + : "", + viewPassword: "", + editPassword: "", editToken: editToken, usersCanAttend: false, showUsersList: false, usersCanComment: false, - firstLoad: true + firstLoad: true, }); - event.save() + event + .save() .then(() => { addToLog("createEvent", "success", "Event " + eventID + " created"); // Send email with edit link if (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 + req.app + .get("hbsInstance") + .renderView( + "./views/emails/createevent.handlebars", + { + eventID, + editToken, + siteName, + siteLogo, + domain, + cache: true, + layout: "email.handlebars", }, - subject: `${siteName}: ${importedEventData.summary}`, - 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; - } - }); + function (err, html) { + const msg = { + to: req.body.creatorEmail, + from: { + name: siteName, + email: contactEmail, + address: contactEmail, + }, + subject: `${siteName}: ${importedEventData.summary}`, + 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 + Location: "/" + eventID + "?e=" + editToken, }); res.end(); }) - .catch((err) => { res.send('Database error, please try again :('); addToLog("createEvent", "error", "Attempt to create event failed with error: " + err); }); - } - else { - console.log("Files array is empty!") + .catch((err) => { + res.send("Database error, please try again :("); + addToLog( + "createEvent", + "error", + "Attempt to create event failed with error: " + err + ); + }); + } else { + console.log("Files array is empty!"); res.status(500).end(); } }); -router.post('/neweventgroup', (req, res) => { +router.post("/neweventgroup", (req, res) => { let eventGroupID = nanoid(); let editToken = randomstring.generate(); let eventGroupImageFilename = ""; if (req.files && Object.keys(req.files).length !== 0) { let eventImageBuffer = req.files.imageUpload.data; Jimp.read(eventImageBuffer, (err, img) => { - if (err) addToLog("Jimp", "error", "Attempt to edit image failed with error: " + err); + if (err) + addToLog( + "Jimp", + "error", + "Attempt to edit image failed with error: " + err + ); img .resize(920, Jimp.AUTO) // resize .quality(80) // set JPEG quality - .write('./public/events/' + eventGroupID + '.jpg'); // save + .write("./public/events/" + eventGroupID + ".jpg"); // save }); - eventGroupImageFilename = eventGroupID + '.jpg'; + eventGroupImageFilename = eventGroupID + ".jpg"; } const eventGroup = new EventGroup({ id: eventGroupID, @@ -911,76 +1187,99 @@ router.post('/neweventgroup', (req, res) => { url: req.body.eventGroupURL, hostName: req.body.hostName, editToken: editToken, - firstLoad: true + firstLoad: true, }); - eventGroup.save() + eventGroup + .save() .then(() => { - addToLog("createEventGroup", "success", "Event group " + eventGroupID + " created"); + addToLog( + "createEventGroup", + "success", + "Event group " + eventGroupID + " created" + ); // Send email with edit link if (req.body.creatorEmail && sendEmails) { - req.app.get('hbsInstance').renderView('./views/emails/createeventgroup.handlebars', { eventGroupID, 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 + req.app + .get("hbsInstance") + .renderView( + "./views/emails/createeventgroup.handlebars", + { + eventGroupID, + editToken, + siteName, + siteLogo, + domain, + cache: true, + layout: "email.handlebars", }, - subject: `${siteName}: ${req.body.eventGroupName}`, - 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; - } - }); + function (err, html) { + const msg = { + to: req.body.creatorEmail, + from: { + name: siteName, + email: contactEmail, + address: contactEmail, + }, + subject: `${siteName}: ${req.body.eventGroupName}`, + 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': '/group/' + eventGroupID + '?e=' + editToken + Location: "/group/" + eventGroupID + "?e=" + editToken, }); res.end(); }) - .catch((err) => { res.send('Database error, please try again :( - ' + err); addToLog("createEvent", "error", "Attempt to create event failed with error: " + err); }); + .catch((err) => { + res.send("Database error, please try again :( - " + err); + addToLog( + "createEvent", + "error", + "Attempt to create event failed with error: " + err + ); + }); }); -router.post('/verifytoken/event/:eventID', (req, res) => { +router.post("/verifytoken/event/:eventID", (req, res) => { Event.findOne({ id: req.params.eventID, editToken: req.body.editToken, - }) - .then(event => { - if (event) return res.sendStatus(200); - return res.sendStatus(404); - }) + }).then((event) => { + if (event) return res.sendStatus(200); + return res.sendStatus(404); + }); }); -router.post('/verifytoken/group/:eventGroupID', (req, res) => { +router.post("/verifytoken/group/:eventGroupID", (req, res) => { EventGroup.findOne({ id: req.params.eventGroupID, editToken: req.body.editToken, - }) - .then(group => { - if (group) return res.sendStatus(200); - return res.sendStatus(404); - }) + }).then((group) => { + if (group) return res.sendStatus(200); + return res.sendStatus(404); + }); }); - -router.post('/editevent/:eventID/:editToken', (req, res) => { +router.post("/editevent/:eventID/:editToken", (req, res) => { let submittedEditToken = req.params.editToken; - Event.findOne(({ + Event.findOne({ id: req.params.eventID, - })) + }) .then(async (event) => { if (event.editToken === submittedEditToken) { // Token matches @@ -995,20 +1294,28 @@ router.post('/editevent/:eventID/:editToken', (req, res) => { img .resize(920, Jimp.AUTO) // resize .quality(80) // set JPEG - .write('./public/events/' + eventID + '.jpg'); // save + .write("./public/events/" + eventID + ".jpg"); // save }); - eventImageFilename = eventID + '.jpg'; + 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 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 - }) + editToken: req.body.eventGroupEditToken, + }); if (eventGroup) { isPartOfEventGroup = true; } @@ -1026,12 +1333,34 @@ router.post('/editevent/:eventID/:editToken', (req, res) => { 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, + maxAttendees: req.body.maxAttendeesCheckbox + ? req.body.maxAttendees + : null, eventGroup: isPartOfEventGroup ? eventGroup._id : null, - activityPubActor: event.activityPubActor ? ap.updateActivityPubActor(JSON.parse(event.activityPubActor), req.body.eventDescription, req.body.eventName, req.body.eventLocation, eventImageFilename, startUTC, endUTC, req.body.timezone) : null, - activityPubEvent: event.activityPubEvent ? ap.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.