forked from lowercasename/gathio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
activitypub.js
923 lines (885 loc) · 36 KB
/
activitypub.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
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 shortid = require('shortid');
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'
],
'id': `https://${domain}/${eventID}`,
'type': 'Person',
'preferredUsername': `${eventID}`,
'inbox': `https://${domain}/activitypub/inbox`,
'outbox': `https://${domain}/${eventID}/outbox`,
'followers': `https://${domain}/${eventID}/followers`,
'summary': `<p>${description}</p>`,
'name': name,
'featured': `https://${domain}/${eventID}/featured`,
'publicKey': {
'id': `https://${domain}/${eventID}#main-key`,
'owner': `https://${domain}/${eventID}`,
'publicKeyPem': pubkey
}
};
if (location) {
actor.summary += `<p>Location: ${location}.</p>`
}
let displayDate;
if (startUTC && timezone) {
displayDate = moment.tz(startUTC, timezone).format('D MMMM YYYY h:mm a');
actor.summary += `<p>Starting ${displayDate} ${timezone}.</p>`;
}
if (imageFilename) {
actor.icon = {
'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');
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
}
return JSON.stringify(eventObject);
}
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": `<p>This is an event that was posted on <a href="https://${domain}">${siteName}</a>. 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.</p><p>For more information on how to interact with this, <a href="https://github.com/lowercasename/gathio/wiki/Fediverse-Instructions">check out this link</a>.</p>`,
'attributedTo': `https://${domain}/${eventID}`,
}
return featured;
}
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
}
return JSON.stringify(eventObject);
}
function updateActivityPubActor(actor, description, name, location, imageFilename, startUTC, endUTC, timezone) {
if (!actor) return;
actor.summary = `<p>${description}</p>`;
actor.name = name;
if (location) {
actor.summary += `<p>Location: ${location}.</p>`
}
let displayDate;
if (startUTC && timezone) {
displayDate = moment.tz(startUTC, timezone).format('D MMMM YYYY h:mm a');
actor.summary += `<p>Starting ${displayDate} ${timezone}.</p>`;
}
if (imageFilename) {
actor.icon = {
'type': 'Image',
'mediaType': 'image/jpg',
'url': `https://${domain}/events/${imageFilename}`,
};
}
return JSON.stringify(actor);
}
function signAndSend(message, eventID, targetDomain, inbox, callback) {
if (!isFederated) return;
let inboxFragment = inbox.replace('https://'+targetDomain,'');
// get the private key
Event.findOne({
id: eventID
})
.then((event) => {
if (event) {
const privateKey = event.privateKey;
const signer = crypto.createSign('sha256');
let d = new Date();
let stringToSign = `(request-target): post ${inboxFragment}\nhost: ${targetDomain}\ndate: ${d.toUTCString()}`;
signer.update(stringToSign);
signer.end();
const signature = signer.sign(privateKey);
const signature_b64 = signature.toString('base64');
const header = `keyId="https://${domain}/${eventID}",headers="(request-target) host date",signature="${signature_b64}"`;
request({
url: inbox,
headers: {
'Host': targetDomain,
'Date': d.toUTCString(),
'Signature': header
},
method: 'POST',
json: true,
body: message
}, function (error, response){
if (error) {
callback(error, null, 500);
}
else {
// Add the message to the database
const messageID = message.id;
const newMessage = {
id: message.id,
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.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);
}
});
}
// this function sends something to the timeline of every follower in the followers array
// it's also an unlisted public message, meaning non-followers can see the message if they look at
// 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',
'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',
'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');
// 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}`);
}
});
}
function broadcastDeleteMessage(apObject, followers, eventID, callback) {
if (!isFederated) return;
callback = callback || function() {};
// we need to build an array of promises for each message we're sending, run Promise.all(), and then that will resolve when every message has been sent (or failed)
// 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');
// 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);
}
});
}
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);
}
}); // end event
}));
} // end followers
Promise.all(promises.map(p => p.catch(e => e))).then(statuses => {
callback(statuses);
});
}
// 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');
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)
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
};
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);
}
}
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');
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,
};
// 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);
}
}
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}/`,'');
// 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": `<span class=\"h-card\"><a href="${req.body.actor}" class="u-url mention">@<span>${name}</span></a></span> 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
}
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
};
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": `<span class=\"h-card\"><a href="${newAttendee.id}" class="u-url mention">@<span>${newAttendee.name}</span></a></span> Thanks for RSVPing! You can remove yourself from the RSVP list by clicking here: <a href="https://${domain}/oneclickunattendevent/${event.id}/${fullAttendee._id}">https://${domain}/oneclickunattendevent/${event.id}/${fullAttendee._id}</a>`,
"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 _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
};
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": `<span class=\"h-card\"><a href="${newAttendee.id}" class="u-url mention">@<span>${newAttendee.name}</span></a></span> Thanks for RSVPing! You can remove yourself from the RSVP list by clicking here: <a href="https://${domain}/oneclickunattendevent/${event.id}/${fullAttendee._id}">https://${domain}/oneclickunattendevent/${event.id}/${fullAttendee._id}</a>`,
"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);
}
// 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);
}
// 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') {
cc = [cc];
}
// normalize to into an array
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'))) {
// 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)
if (ourEvents.length === 1) {
let eventID = ourEvents[0];
// add comment
let commentID = shortid.generate();
// 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);
});
});
}
});
} // end ourevent
} // end public message
}
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') {
_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') {
_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') {
_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') {
_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) {
_handleCreateNote(req, res);
}
// if a Delete activity hits the inbox, it might a deletion of a comment
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) {
_handleCreateNoteComment(req, res);
} // CC'ed
}
catch(e) {
console.log('Error in processing inbox:', e)
}
}
function createWebfinger(eventID, domain) {
return {
'subject': `acct:${eventID}@${domain}`,
'links': [
{
'rel': 'self',
'type': 'application/activity+json',
'href': `https://${domain}/${eventID}`
}
]
};
}
module.exports = {
processInbox,
sendAcceptMessage,
sendDirectMessage,
broadcastAnnounceMessage,
broadcastUpdateMessage,
broadcastDeleteMessage,
broadcastCreateMessage,
signAndSend,
createActivityPubActor,
updateActivityPubActor,
createActivityPubEvent,
updateActivityPubEvent,
createFeaturedPost,
createWebfinger,
}