Repository navigation
Expand file tree
/
Copy pathActivityPubInboxService.cs
More file actions
1671 lines (1465 loc) · 68.5 KB
/
Copy pathActivityPubInboxService.cs
File metadata and controls
1671 lines (1465 loc) · 68.5 KB
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Text.Json;
using System.Security.Cryptography;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using static EndpointLoggingHelpers;
public static class ActivityPubInboxService
{
public static async Task<bool> SendActivityPubFollowAckAsync(
string inboxUrl,
string localActorUrl,
string sourceActivityId,
string sourceActivityType,
string sourceActorIri,
string? sourceObjectIri,
bool accepted,
string statusMessage,
Func<string, string, object, string, Task<bool>> sendSignedActivityPubMessageAsync)
{
var ackActivity = new Dictionary<string, object?>
{
["@context"] = "https://www.w3.org/ns/activitystreams",
["id"] = $"{GlobalConfig.Hostname}/apv1/activities/{Guid.NewGuid()}",
["type"] = accepted ? "Accept" : "Reject",
["actor"] = localActorUrl,
["object"] = new Dictionary<string, object?>
{
["id"] = sourceActivityId,
["type"] = sourceActivityType,
["actor"] = sourceActorIri,
["object"] = sourceObjectIri
},
["summary"] = statusMessage,
["published"] = DateTimeOffset.UtcNow.ToString("o")
};
return await sendSignedActivityPubMessageAsync(
inboxUrl,
localActorUrl,
ackActivity,
$"AP {(accepted ? "Accept" : "Reject")} sent to {inboxUrl} for activity {sourceActivityId}");
}
public static async Task<IResult> HandleListInboxAsync(
int listId,
JsonElement activityJson,
GeFeSLEDb db,
Func<JsonElement, string?> readIriFromActivityPubNode,
Func<string, GeListFollower?, Task<string?>> resolveActorInboxAsync,
Func<string, string, string, string, string, string?, bool, string, Task<bool>> sendActivityPubFollowAckAsync,
Func<GeList, GeFeSLEDb, GeListItem, string, GeListFollower?, Task> broadcastActivityPubItemToFollowersAsync,
Func<GeList, GeFeSLEDb, string, string, GeListFollower?, Task> broadcastActivityPubCommentAnnounceToFollowersAsync)
{
string fn = $"/apv1/lists/{listId}/inbox (POST)";
DBg.d(LogLevel.Trace, fn);
LogDtoIn(fn, nameof(JsonElement), activityJson);
GeList? list = await db.Lists.FirstOrDefaultAsync(l => l.Id == listId);
string expectedActorUrl = $"{GlobalConfig.Hostname}/apv1/lists/{listId}";
if (list == null)
{
string msg = $"List with id {listId} not found";
return NotFoundWithTrace(fn, msg);
}
//DBg.d(LogLevel.Trace, $"{fn} <-- {activityJson.GetRawText()}");
string incomingType = activityJson.TryGetProperty("type", out var typeProp) && typeProp.ValueKind == JsonValueKind.String
? typeProp.GetString() ?? string.Empty
: string.Empty;
string incomingId = activityJson.TryGetProperty("id", out var idProp) && idProp.ValueKind == JsonValueKind.String
? idProp.GetString() ?? $"{GlobalConfig.Hostname}/apv1/activities/unknown-{Guid.NewGuid()}"
: $"{GlobalConfig.Hostname}/apv1/activities/unknown-{Guid.NewGuid()}";
var persistedActivity = await TryWriteIncomingActivityAsync(incomingId, activityJson);
string persistedActivityPath = persistedActivity.FilePath ?? "(not written)";
if (persistedActivity.Wrote)
{
DBg.d(LogLevel.Debug, $"{fn} -- incoming ActivityPub activity saved to {persistedActivityPath}");
}
else if (string.IsNullOrWhiteSpace(persistedActivity.Error))
{
DBg.d(LogLevel.Trace, $"{fn} -- incoming ActivityPub activity persistence skipped (full logging disabled)");
}
else
{
DBg.d(LogLevel.Warning, $"{fn} -- incoming ActivityPub activity not saved: {persistedActivity.Error ?? "unknown error"}");
}
string? actorIri = activityJson.TryGetProperty("actor", out var actorProp)
? readIriFromActivityPubNode(actorProp)
: null;
string? targetObject = null;
string? topLevelObjectIri = null;
string? nestedObjectType = null;
bool hasObject = activityJson.TryGetProperty("object", out var objectProp);
if (hasObject)
{
topLevelObjectIri = readIriFromActivityPubNode(objectProp);
targetObject = topLevelObjectIri;
if (objectProp.ValueKind == JsonValueKind.Object)
{
if (objectProp.TryGetProperty("type", out var nestedTypeProp)
&& nestedTypeProp.ValueKind == JsonValueKind.String)
{
nestedObjectType = nestedTypeProp.GetString();
}
if (objectProp.TryGetProperty("object", out var followTargetProp))
{
targetObject = readIriFromActivityPubNode(followTargetProp) ?? targetObject;
}
if (string.IsNullOrWhiteSpace(actorIri)
&& objectProp.TryGetProperty("actor", out var nestedActorProp))
{
actorIri = readIriFromActivityPubNode(nestedActorProp);
}
}
}
expectedActorUrl = $"{GlobalConfig.Hostname}/apv1/lists/{list.Id}";
bool isDirectFollow = string.Equals(incomingType, "Follow", StringComparison.OrdinalIgnoreCase);
bool isDirectUnfollow = string.Equals(incomingType, "Unfollow", StringComparison.OrdinalIgnoreCase);
bool isCreateFollow = string.Equals(incomingType, "Create", StringComparison.OrdinalIgnoreCase)
&& string.Equals(nestedObjectType, "Follow", StringComparison.OrdinalIgnoreCase);
bool isUndoFollow = string.Equals(incomingType, "Undo", StringComparison.OrdinalIgnoreCase)
&& string.Equals(nestedObjectType, "Follow", StringComparison.OrdinalIgnoreCase);
bool isDeleteFollow = string.Equals(incomingType, "Delete", StringComparison.OrdinalIgnoreCase)
&& string.Equals(nestedObjectType, "Follow", StringComparison.OrdinalIgnoreCase);
bool isFollow = isDirectFollow || isCreateFollow;
bool isUnfollow = isDirectUnfollow || isUndoFollow || isDeleteFollow;
bool isCreateNote = string.Equals(incomingType, "Create", StringComparison.OrdinalIgnoreCase)
&& hasObject
&& string.Equals(nestedObjectType, "Note", StringComparison.OrdinalIgnoreCase);
bool isUpdateNote = string.Equals(incomingType, "Update", StringComparison.OrdinalIgnoreCase)
&& hasObject
&& string.Equals(nestedObjectType, "Note", StringComparison.OrdinalIgnoreCase);
bool isLike = string.Equals(incomingType, "Like", StringComparison.OrdinalIgnoreCase);
bool isUndo = string.Equals(incomingType, "Undo", StringComparison.OrdinalIgnoreCase);
bool isDeleteActor = string.Equals(incomingType, "Delete", StringComparison.OrdinalIgnoreCase)
&& !string.IsNullOrWhiteSpace(actorIri)
&& !string.IsNullOrWhiteSpace(topLevelObjectIri)
&& string.Equals(topLevelObjectIri, actorIri, StringComparison.OrdinalIgnoreCase);
if (string.Equals(incomingType, "Delete", StringComparison.OrdinalIgnoreCase))
{
DBg.d(LogLevel.Debug,
$"{fn} -- Delete diagnostics from activity file: {persistedActivityPath}");
}
if (string.IsNullOrWhiteSpace(actorIri))
{
string msg = "activity.actor is null or empty";
return BadRequestWithTrace(fn, msg);
}
if (isDeleteActor)
{
GeListFollower? deletedFollower = await db.ListFollowers.FirstOrDefaultAsync(f => f.Id == actorIri);
if (deletedFollower is not null)
{
bool removed = deletedFollower.FollowingLists.RemoveAll(id => id == list.Id) > 0;
if (deletedFollower.FollowingLists.Count == 0)
{
db.ListFollowers.Remove(deletedFollower);
}
await db.SaveChangesAsync();
if (removed)
{
// this was easy - we can improve by restricting to just the lists they actuall used to follow.
await list.RegenerateAllFiles(db);
}
DBg.d(LogLevel.Information, $"{fn} -- processed Delete actor cleanup for follower {actorIri} on list {list.Id}");
}
else
{
DBg.d(LogLevel.Information, $"{fn} -- Delete actor received for unknown follower {actorIri}; ignoring");
}
string msg = $"Delete actor processed for {actorIri}";
return OkWithTrace(fn, msg);
}
if (isLike)
{
DBg.d(LogLevel.Information, $"{fn} -- received ActivityPub Like from {actorIri} (activityId={incomingId ?? "<none>"})");
string? likeTargetIri = topLevelObjectIri;
if (hasObject && objectProp.ValueKind == JsonValueKind.Object)
{
likeTargetIri ??= ReadIriProperty(objectProp, "id", readIriFromActivityPubNode);
if (string.IsNullOrWhiteSpace(likeTargetIri)
&& objectProp.TryGetProperty("object", out var nestedLikeObjectProp))
{
likeTargetIri = readIriFromActivityPubNode(nestedLikeObjectProp);
}
}
var resolvedLikeTarget = await ResolveIncomingLikeTargetAsync(list.Id, likeTargetIri, db);
if (resolvedLikeTarget is null)
{
string ignoredMsg = $"Ignored ActivityPub Like for unknown/non-local object {(likeTargetIri ?? "(null)")}";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
DBg.d(LogLevel.Trace,
$"{fn} -- ActivityPub Like target resolved to object={resolvedLikeTarget.ObjectIri}, itemId={resolvedLikeTarget.ItemId?.ToString() ?? "<null>"}, commentId={resolvedLikeTarget.CommentId?.ToString() ?? "<null>"}");
ActivityPubObjectLike? existingLike = null;
if (!string.IsNullOrWhiteSpace(incomingId))
{
existingLike = await db.ActivityPubObjectLikes.FirstOrDefaultAsync(l =>
l.ListId == list.Id
&& l.LikeActivityIri == incomingId);
}
existingLike ??= await db.ActivityPubObjectLikes.FirstOrDefaultAsync(l =>
l.ListId == list.Id
&& l.ObjectIri == resolvedLikeTarget.ObjectIri
&& l.ActorIri == actorIri);
bool created = false;
if (existingLike is null)
{
existingLike = new ActivityPubObjectLike
{
ListId = list.Id,
ItemId = resolvedLikeTarget.ItemId,
CommentId = resolvedLikeTarget.CommentId,
ObjectIri = resolvedLikeTarget.ObjectIri,
ActorIri = actorIri,
LikeActivityIri = incomingId,
IsActive = true,
CreatedDate = DateTime.UtcNow,
ModifiedDate = DateTime.UtcNow
};
db.ActivityPubObjectLikes.Add(existingLike);
created = true;
}
else
{
existingLike.ItemId = resolvedLikeTarget.ItemId;
existingLike.CommentId = resolvedLikeTarget.CommentId;
existingLike.IsActive = true;
existingLike.ModifiedDate = DateTime.UtcNow;
existingLike.LikeActivityIri = incomingId;
}
await db.SaveChangesAsync();
string msg = $"ActivityPub Like applied for {resolvedLikeTarget.ObjectIri} by {actorIri}";
DBg.d(LogLevel.Information, $"{fn} -- {msg}");
return OkPayloadWithTrace(fn, new
{
objectIri = resolvedLikeTarget.ObjectIri,
itemId = resolvedLikeTarget.ItemId,
commentId = resolvedLikeTarget.CommentId,
actor = actorIri,
likeActivity = incomingId,
created,
active = true,
persistedActivityPath
}, msg);
}
if (isUndo && !isUndoFollow)
{
DBg.d(LogLevel.Information, $"{fn} -- received ActivityPub Undo from {actorIri}");
string? undoLikeActivityIri = null;
string? undoLikeTargetIri = null;
if (hasObject)
{
undoLikeActivityIri = topLevelObjectIri;
if (objectProp.ValueKind == JsonValueKind.Object)
{
string? undoNestedType = ReadStringProperty(objectProp, "type");
if (string.Equals(undoNestedType, "Like", StringComparison.OrdinalIgnoreCase))
{
undoLikeActivityIri = readIriFromActivityPubNode(objectProp) ?? undoLikeActivityIri;
if (objectProp.TryGetProperty("object", out var undoNestedTargetProp))
{
undoLikeTargetIri = readIriFromActivityPubNode(undoNestedTargetProp);
}
}
else if (objectProp.TryGetProperty("object", out var undoObjectProp))
{
undoLikeTargetIri = readIriFromActivityPubNode(undoObjectProp);
}
}
}
ActivityPubObjectLike? existingLike = null;
if (!string.IsNullOrWhiteSpace(undoLikeActivityIri))
{
existingLike = await db.ActivityPubObjectLikes.FirstOrDefaultAsync(l =>
l.ListId == list.Id
&& l.IsActive
&& l.LikeActivityIri == undoLikeActivityIri);
}
if (existingLike is null)
{
string? candidateTarget = undoLikeTargetIri;
if (string.IsNullOrWhiteSpace(candidateTarget)
&& !string.IsNullOrWhiteSpace(undoLikeActivityIri)
&& Uri.TryCreate(undoLikeActivityIri, UriKind.Absolute, out _))
{
candidateTarget = undoLikeActivityIri;
}
var resolvedUndoTarget = await ResolveIncomingLikeTargetAsync(list.Id, candidateTarget, db);
if (resolvedUndoTarget is not null)
{
existingLike = await db.ActivityPubObjectLikes.FirstOrDefaultAsync(l =>
l.ListId == list.Id
&& l.ObjectIri == resolvedUndoTarget.ObjectIri
&& l.ActorIri == actorIri
&& l.IsActive);
}
}
if (existingLike is null)
{
string ignoredMsg = $"Ignored ActivityPub Undo with no matching active Like for actor {actorIri}";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
existingLike.IsActive = false;
existingLike.ModifiedDate = DateTime.UtcNow;
await db.SaveChangesAsync();
string msg = $"ActivityPub Undo(Like) applied for {existingLike.ObjectIri} by {actorIri}";
DBg.d(LogLevel.Information, $"{fn} -- {msg}");
return OkPayloadWithTrace(fn, new
{
objectIri = existingLike.ObjectIri,
itemId = existingLike.ItemId,
commentId = existingLike.CommentId,
actor = actorIri,
likeActivity = existingLike.LikeActivityIri,
active = false,
persistedActivityPath
}, msg);
}
if (string.Equals(incomingType, "Delete", StringComparison.OrdinalIgnoreCase) && !isDeleteFollow)
{
string? deleteObjectIri = topLevelObjectIri;
if (string.IsNullOrWhiteSpace(deleteObjectIri) && hasObject && objectProp.ValueKind == JsonValueKind.Object)
{
deleteObjectIri = ReadIriProperty(objectProp, "atomUri", readIriFromActivityPubNode)
?? ReadStringProperty(objectProp, "atomUri");
}
if (string.IsNullOrWhiteSpace(deleteObjectIri))
{
string ignoredMsg = "Ignored ActivityPub Delete without a resolvable object IRI";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
GeListItemComment? deletedComment = await db.ItemComments.FirstOrDefaultAsync(c =>
c.ListId == list.Id
&& c.RemoteObjectIri == deleteObjectIri);
if (deletedComment is null)
{
string ignoredMsg = $"Ignored ActivityPub Delete for unknown comment object {deleteObjectIri}";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
if (!IsCommentDeleteAuthorized(actorIri, deletedComment))
{
string ignoredMsg = $"Ignored ActivityPub Delete for comment {deletedComment.Id} due to actor mismatch. Actor: {actorIri}";
DBg.d(LogLevel.Warning, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
// Keep the comment row as a tombstone so existing child threading stays intact.
deletedComment.ActorIri = null;
deletedComment.AttributedToIri = null;
deletedComment.Name = null;
deletedComment.ContentHtml = null;
deletedComment.Summary = "<comment deleted>";
deletedComment.RawNoteJson = null;
deletedComment.UpdatedAt = DateTimeOffset.UtcNow;
deletedComment.ModifiedDate = DateTime.UtcNow;
deletedComment.LastReceivedAt = DateTime.UtcNow;
await db.SaveChangesAsync();
await list.GenerateHTMLListPage(db);
await broadcastActivityPubCommentAnnounceToFollowersAsync(
list,
db,
deleteObjectIri,
$"Deleted remote comment for list item {deletedComment.ItemId}",
null);
string deletedMsg = $"ActivityPub comment delete applied for item {deletedComment.ItemId}: comment {deletedComment.Id}";
return OkPayloadWithTrace(fn, new
{
itemId = deletedComment.ItemId,
commentId = deletedComment.Id,
remoteObject = deleteObjectIri,
tombstoned = true,
persistedActivityPath
}, deletedMsg);
}
if (isCreateNote && hasObject)
{
string followersUrl = $"{GlobalConfig.Hostname}/apv1/lists/{list.Id}/followers";
bool addressedToList = IsActivityAddressedToListActor(activityJson, expectedActorUrl, followersUrl)
|| IsNoteMentioningListActor(objectProp, expectedActorUrl, list.ActivityPubId, GlobalConfig.APDomain);
if (!addressedToList)
{
string ignoredMsg = "Ignored ActivityPub Create/Note not addressed to this list actor";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
string? noteObjectIri = readIriFromActivityPubNode(objectProp) ?? topLevelObjectIri;
string? noteInReplyToIri = ReadIriProperty(objectProp, "inReplyTo", readIriFromActivityPubNode)
?? ReadIriProperty(objectProp, "inreplyto", readIriFromActivityPubNode);
if (!string.IsNullOrWhiteSpace(noteInReplyToIri) && !string.IsNullOrWhiteSpace(noteObjectIri))
{
var threadTarget = await ResolveCommentThreadTargetAsync(list.Id, noteInReplyToIri, db);
if (threadTarget is not null)
{
GeListItemComment? existingComment = await db.ItemComments.FirstOrDefaultAsync(c =>
c.ListId == list.Id
&& c.RemoteObjectIri == noteObjectIri);
if (existingComment is null)
{
existingComment = new GeListItemComment
{
ListId = list.Id,
ItemId = threadTarget.ItemId,
ParentCommentId = threadTarget.ParentCommentId,
RemoteObjectIri = noteObjectIri,
InReplyToIri = noteInReplyToIri,
CreatedDate = DateTime.UtcNow,
ModifiedDate = DateTime.UtcNow,
LastReceivedAt = DateTime.UtcNow
};
db.ItemComments.Add(existingComment);
}
else if (IsCommentTombstoned(existingComment))
{
string ignoredMsg = $"Ignored ActivityPub Create/Note for tombstoned comment object {noteObjectIri}";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
ApplyIncomingCommentNote(existingComment, objectProp, actorIri, readIriFromActivityPubNode);
existingComment.ItemId = threadTarget.ItemId;
existingComment.ParentCommentId = threadTarget.ParentCommentId;
existingComment.InReplyToIri = noteInReplyToIri;
existingComment.ModifiedDate = DateTime.UtcNow;
existingComment.LastReceivedAt = DateTime.UtcNow;
await db.SaveChangesAsync();
await list.RefreshRemoteCommentLikesForItemAsync(existingComment.ItemId, db);
await list.GenerateHTMLListPage(db);
await broadcastActivityPubCommentAnnounceToFollowersAsync(
list,
db,
existingComment.RemoteObjectIri,
$"New remote comment for list item {existingComment.ItemId}",
null);
string commentCreateMsg = $"ActivityPub threaded comment accepted for item {existingComment.ItemId}: comment {existingComment.Id}";
return OkPayloadWithTrace(fn, new
{
itemId = existingComment.ItemId,
commentId = existingComment.Id,
remoteObject = existingComment.RemoteObjectIri,
inReplyTo = existingComment.InReplyToIri,
parentCommentId = existingComment.ParentCommentId,
persistedActivityPath
}, commentCreateMsg);
}
string ignoredThreadMsg = $"Ignored ActivityPub Create/Note reply with unknown inReplyTo target {noteInReplyToIri}";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredThreadMsg}");
return OkWithTrace(fn, ignoredThreadMsg);
}
string submitterLabel = BuildActorMentionLabel(activityJson, actorIri);
var suggestedItem = BuildSuggestedItemFromNote(
list.Id,
objectProp,
actorIri,
readIriFromActivityPubNode,
fallbackName: $"Suggestion from {submitterLabel}",
visible: false);
noteObjectIri = suggestedItem.SourceObjectIri ?? noteObjectIri;
string? attributedToIri = suggestedItem.SourceAttributedToIri;
GeList? modlist = await db.Lists.FirstOrDefaultAsync(l => l.Name == GlobalConfig.modListName);
if (modlist is null)
{
modlist = new GeList
{
Name = GlobalConfig.modListName,
Visibility = GeListVisibility.ListOwners,
CreatorId = list.CreatorId
};
db.Lists.Add(modlist);
}
db.Items.Add(suggestedItem);
await db.SaveChangesAsync();
var modItem = new GeListItem
{
Name = $"{list.Name}#{suggestedItem.Id} <= by {actorIri}",
ListId = modlist.Id,
Visible = true,
ModeratedItemId = suggestedItem.Id,
Tags = new List<string> { "SUGGESTED", "ACTIVITYPUB", list.Name ?? $"list-{list.Id}" }
};
var modComment = new StringBuilder();
modComment.AppendLine($"SUGGESTED via ActivityPub by {actorIri} ");
if (!string.IsNullOrWhiteSpace(noteObjectIri))
{
modComment.AppendLine($"Source object: <a href=\"{WebUtility.HtmlEncode(noteObjectIri)}\">{WebUtility.HtmlEncode(noteObjectIri)}</a> ");
}
if (!string.IsNullOrWhiteSpace(attributedToIri))
{
modComment.AppendLine($"Attributed to: <a href=\"{WebUtility.HtmlEncode(attributedToIri)}\">{WebUtility.HtmlEncode(attributedToIri)}</a> ");
}
modComment.AppendLine("Item has been preemptively marked as invisible pending approval ");
modComment.AppendLine("--------- ");
modComment.AppendLine($"<a href=\"_edit.item.html?listid={list.Id}&itemid={suggestedItem.Id}\">LINK TO APPROVE</a>");
modItem.Comment = modComment.ToString();
db.Items.Add(modItem);
await db.SaveChangesAsync();
suggestedItem.ModerationItemId = modItem.Id;
await db.SaveChangesAsync();
await list.RegenerateAllFiles(db);
await modlist.RegenerateAllFiles(db);
string msg = $"ActivityPub suggestion accepted for moderation: item {suggestedItem.Id}, moderation ticket {modItem.Id}";
return OkPayloadWithTrace(fn, new
{
suggestedItemId = suggestedItem.Id,
moderationItemId = modItem.Id,
sourceActor = actorIri,
sourceObject = noteObjectIri,
sourceAttributedTo = attributedToIri,
persistedActivityPath
}, msg);
}
if (isUpdateNote && hasObject)
{
string followersUrl = $"{GlobalConfig.Hostname}/apv1/lists/{list.Id}/followers";
bool addressedToList = IsActivityAddressedToListActor(activityJson, expectedActorUrl, followersUrl)
|| IsNoteMentioningListActor(objectProp, expectedActorUrl, list.ActivityPubId, GlobalConfig.APDomain);
if (!addressedToList)
{
string ignoredMsg = "Ignored ActivityPub Update/Note not addressed to this list actor";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
string? noteObjectIri = readIriFromActivityPubNode(objectProp) ?? topLevelObjectIri;
if (string.IsNullOrWhiteSpace(noteObjectIri))
{
string ignoredMsg = "Ignored ActivityPub Update/Note without a resolvable object IRI";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
GeListItemComment? existingComment = await db.ItemComments.FirstOrDefaultAsync(c =>
c.ListId == list.Id
&& c.RemoteObjectIri == noteObjectIri);
if (existingComment is not null)
{
if (IsCommentTombstoned(existingComment))
{
string ignoredMsg = $"Ignored ActivityPub Update/Note for tombstoned comment object {noteObjectIri}";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
string? noteInReplyToIri = ReadIriProperty(objectProp, "inReplyTo", readIriFromActivityPubNode)
?? ReadIriProperty(objectProp, "inreplyto", readIriFromActivityPubNode);
if (!string.IsNullOrWhiteSpace(noteInReplyToIri))
{
var threadTarget = await ResolveCommentThreadTargetAsync(list.Id, noteInReplyToIri, db);
if (threadTarget is not null)
{
existingComment.ItemId = threadTarget.ItemId;
existingComment.ParentCommentId = threadTarget.ParentCommentId;
existingComment.InReplyToIri = noteInReplyToIri;
}
}
ApplyIncomingCommentNote(existingComment, objectProp, actorIri, readIriFromActivityPubNode);
existingComment.ModifiedDate = DateTime.UtcNow;
existingComment.LastReceivedAt = DateTime.UtcNow;
await db.SaveChangesAsync();
await list.RefreshRemoteCommentLikesForItemAsync(existingComment.ItemId, db);
await list.GenerateHTMLListPage(db);
await broadcastActivityPubCommentAnnounceToFollowersAsync(
list,
db,
existingComment.RemoteObjectIri,
$"Updated remote comment for list item {existingComment.ItemId}",
null);
string updateMsg = $"ActivityPub comment update applied for item {existingComment.ItemId}: comment {existingComment.Id}";
return OkPayloadWithTrace(fn, new
{
itemId = existingComment.ItemId,
commentId = existingComment.Id,
remoteObject = existingComment.RemoteObjectIri,
inReplyTo = existingComment.InReplyToIri,
parentCommentId = existingComment.ParentCommentId,
persistedActivityPath
}, updateMsg);
}
// This next bit handles the case where we were not originally addressed in a post, but then
// an update to a comment/item that we know about subsequently gets addressed properly to us. The thing we care about is in the inReplyTo block.
string? updateInReplyToIri = ReadIriProperty(objectProp, "inReplyTo", readIriFromActivityPubNode)
?? ReadIriProperty(objectProp, "inreplyto", readIriFromActivityPubNode);
if (!string.IsNullOrWhiteSpace(updateInReplyToIri))
{
if (!IsIncomingNoteActorConsistent(actorIri, objectProp, readIriFromActivityPubNode))
{
string ignoredMsg = $"Ignored ActivityPub Update/Note for unknown comment object {noteObjectIri} due to actor/attributedTo mismatch";
DBg.d(LogLevel.Warning, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
var threadTarget = await ResolveCommentThreadTargetAsync(list.Id, updateInReplyToIri, db);
if (threadTarget is not null)
{
var createdFromUpdate = new GeListItemComment
{
ListId = list.Id,
ItemId = threadTarget.ItemId,
ParentCommentId = threadTarget.ParentCommentId,
RemoteObjectIri = noteObjectIri,
InReplyToIri = updateInReplyToIri,
CreatedDate = DateTime.UtcNow,
ModifiedDate = DateTime.UtcNow,
LastReceivedAt = DateTime.UtcNow
};
ApplyIncomingCommentNote(createdFromUpdate, objectProp, actorIri, readIriFromActivityPubNode);
db.ItemComments.Add(createdFromUpdate);
await db.SaveChangesAsync();
await list.RefreshRemoteCommentLikesForItemAsync(createdFromUpdate.ItemId, db);
await list.GenerateHTMLListPage(db);
await broadcastActivityPubCommentAnnounceToFollowersAsync(
list,
db,
createdFromUpdate.RemoteObjectIri,
$"Accepted first-seen remote comment via Update for list item {createdFromUpdate.ItemId}",
null);
string createdFromUpdateMsg = $"ActivityPub threaded comment accepted via Update for item {createdFromUpdate.ItemId}: comment {createdFromUpdate.Id}";
return OkPayloadWithTrace(fn, new
{
itemId = createdFromUpdate.ItemId,
commentId = createdFromUpdate.Id,
remoteObject = createdFromUpdate.RemoteObjectIri,
inReplyTo = createdFromUpdate.InReplyToIri,
parentCommentId = createdFromUpdate.ParentCommentId,
acceptedViaUpdate = true,
persistedActivityPath
}, createdFromUpdateMsg);
}
}
GeListItem? existingItem = await db.Items.FirstOrDefaultAsync(item =>
item.ListId == list.Id
&& !string.IsNullOrWhiteSpace(item.SourceObjectIri)
&& item.SourceObjectIri == noteObjectIri);
if (existingItem is null)
{
string ignoredMsg = $"Ignored ActivityPub Update/Note for unknown source object {noteObjectIri}";
DBg.d(LogLevel.Information, $"{fn} -- {ignoredMsg}");
return OkWithTrace(fn, ignoredMsg);
}
string? oldName = existingItem.Name;
string? oldComment = existingItem.Comment;
List<string> oldTags = existingItem.Tags?.ToList() ?? new List<string>();
string? oldSourceAttributedTo = existingItem.SourceAttributedToIri;
string? oldOriginatorActor = existingItem.OriginatorActorIri;
string? noteContent = ReadStringProperty(objectProp, "content")
?? ReadStringProperty(objectProp, "summary");
string attachmentsHtml = BuildIncomingAttachmentMarkup(objectProp, readIriFromActivityPubNode);
string combinedComment = BuildSuggestedItemComment(noteContent, attachmentsHtml);
string? noteName = ReadStringProperty(objectProp, "name");
if (!string.IsNullOrWhiteSpace(noteName))
{
existingItem.Name = noteName;
}
if (!string.IsNullOrWhiteSpace(combinedComment))
{
existingItem.Comment = combinedComment;
}
existingItem.IsComplete = false;
existingItem.OriginatorActorIri = actorIri;
existingItem.SourceObjectIri = noteObjectIri;
string? attributedToIri = ReadIriProperty(objectProp, "attributedTo", readIriFromActivityPubNode)
?? ReadIriProperty(objectProp, "attributedto", readIriFromActivityPubNode);
if (!string.IsNullOrWhiteSpace(attributedToIri))
{
existingItem.SourceAttributedToIri = attributedToIri;
}
existingItem.Tags = ExtractHashtagsFromNoteTag(objectProp).ToList();
existingItem.ModifiedDate = DateTime.Now;
GeList? modlist = await db.Lists.FirstOrDefaultAsync(l => l.Name == GlobalConfig.modListName);
if (modlist is null)
{
modlist = new GeList
{
Name = GlobalConfig.modListName,
Visibility = GeListVisibility.ListOwners,
CreatorId = list.CreatorId
};
db.Lists.Add(modlist);
await db.SaveChangesAsync();
}
await db.SaveChangesAsync();
var modItem = new GeListItem
{
Name = $"{list.Name}#{existingItem.Id} <= UPDATE by {actorIri}",
ListId = modlist.Id,
Visible = true,
Tags = new List<string> { "SUGGESTED", "ACTIVITYPUB", "UPDATED", list.Name ?? $"list-{list.Id}" }
};
string oldTagsJoined = string.Join(", ", oldTags);
string newTagsJoined = string.Join(", ", existingItem.Tags ?? new List<string>());
var modComment = new StringBuilder();
modComment.AppendLine($"UPDATE received via ActivityPub for existing suggestion by {actorIri} ");
modComment.AppendLine($"Target item: <a href=\"_edit.item.html?listid={list.Id}&itemid={existingItem.Id}\">{list.Name}#{existingItem.Id}</a> ");
modComment.AppendLine($"Source object: <a href=\"{WebUtility.HtmlEncode(noteObjectIri)}\">{WebUtility.HtmlEncode(noteObjectIri)}</a> ");
modComment.AppendLine("--------- ");
modComment.AppendLine("**Diff (old -> new):** ");
bool anyChanged = false;
string? diffName = BuildDiffBlockIfChanged("Name", oldName, existingItem.Name);
if (!string.IsNullOrWhiteSpace(diffName))
{
anyChanged = true;
modComment.AppendLine(diffName);
}
string? diffComment = BuildDiffBlockIfChanged("Comment", oldComment, existingItem.Comment);
if (!string.IsNullOrWhiteSpace(diffComment))
{
anyChanged = true;
modComment.AppendLine(diffComment);
}
string? diffTags = BuildDiffBlockIfChanged("Tags", oldTagsJoined, newTagsJoined);
if (!string.IsNullOrWhiteSpace(diffTags))
{
anyChanged = true;
modComment.AppendLine(diffTags);
}
string? diffAttributedTo = BuildDiffBlockIfChanged("Source AttributedTo", oldSourceAttributedTo, existingItem.SourceAttributedToIri);
if (!string.IsNullOrWhiteSpace(diffAttributedTo))
{
anyChanged = true;
modComment.AppendLine(diffAttributedTo);
}
string? diffSourceActor = BuildDiffBlockIfChanged("Source Actor", oldOriginatorActor, existingItem.OriginatorActorIri);
if (!string.IsNullOrWhiteSpace(diffSourceActor))
{
anyChanged = true;
modComment.AppendLine(diffSourceActor);
}
if (!anyChanged)
{
modComment.AppendLine("No material field changes detected after normalization. ");
}
modComment.AppendLine("--------- ");
modComment.AppendLine("**Previous snapshot:** ");
modComment.AppendLine($"- Name: {FormatValueInline(oldName)} ");
modComment.AppendLine($"- Tags: {FormatValueInline(oldTagsJoined)} ");
modComment.AppendLine("- Comment: ");
modComment.AppendLine("```text");
modComment.AppendLine(SanitizeForCodeFence(oldComment));
modComment.AppendLine("``` ");
modComment.AppendLine("--------- ");
modComment.AppendLine($"<a href=\"_edit.item.html?listid={list.Id}&itemid={existingItem.Id}\">LINK TO REVIEW UPDATED ITEM</a>");
modItem.Comment = modComment.ToString();
modItem.ModeratedItemId = existingItem.Id;
db.Items.Add(modItem);
await db.SaveChangesAsync();
existingItem.ModerationItemId = modItem.Id;
await db.SaveChangesAsync();
await list.RegenerateAllFiles(db);
await modlist.RegenerateAllFiles(db);
string msg = $"ActivityPub update applied to item {existingItem.Id}; moderation ticket {modItem.Id} created";
return OkPayloadWithTrace(fn, new
{
itemId = existingItem.Id,
moderationItemId = modItem.Id,
sourceObject = noteObjectIri,
sourceActor = actorIri,
sourceAttributedTo = existingItem.SourceAttributedToIri,
persistedActivityPath
}, msg);
}
if (!isFollow && !isUnfollow)
{
string msg = $"Ignored unsupported ActivityPub activity type: {incomingType}";
return OkWithTrace(fn, msg);
}
if (string.IsNullOrWhiteSpace(targetObject) || !string.Equals(targetObject, expectedActorUrl, StringComparison.OrdinalIgnoreCase))
{
string msg = $"activity.object is null or does not match expected actor URL. Expected: {expectedActorUrl}, Actual: {targetObject ?? "(null)"}";
string? rejectInbox = await resolveActorInboxAsync(actorIri, null);
if (!string.IsNullOrWhiteSpace(rejectInbox))
{
await sendActivityPubFollowAckAsync(rejectInbox, expectedActorUrl, incomingId, incomingType, actorIri, targetObject, false,
$"Rejected: {msg}");
}
return BadRequestWithTrace(fn, msg);
}
GeListFollower? follower = await db.ListFollowers.FirstOrDefaultAsync(f => f.Id == actorIri);
if (isUnfollow)
{
if (follower == null)
{
string rejectMsg = $"Unfollow rejected: follower {actorIri} is unknown for this list";
string? rejectInbox = await resolveActorInboxAsync(actorIri, null);
if (!string.IsNullOrWhiteSpace(rejectInbox))
{
await sendActivityPubFollowAckAsync(rejectInbox, expectedActorUrl, incomingId, incomingType, actorIri, targetObject, false,
rejectMsg);
}
return BadRequestWithTrace(fn, rejectMsg);
}
bool removedFromList = follower.FollowingLists.RemoveAll(id => id == list.Id) > 0;
if (follower.FollowingLists.Count == 0)
{
db.ListFollowers.Remove(follower);
}
await db.SaveChangesAsync();
string? acceptInbox = await resolveActorInboxAsync(actorIri, follower);
if (string.IsNullOrWhiteSpace(acceptInbox)
|| !await sendActivityPubFollowAckAsync(acceptInbox, expectedActorUrl, incomingId, incomingType, actorIri, targetObject, true,
$"Unfollow accepted for list {list.Name} (id: {list.Id})"))
{
string acceptFailureMsg = $"Unfollow processed locally but failed to send ActivityPub Accept to {actorIri}";
return ProblemWithTrace(fn, acceptFailureMsg, 502);
}
if (removedFromList)
{
await list.RegenerateAllFiles(db);
}
string unfollowSuccessMsg = $"Unfollow processed for list {list.Name} (id: {list.Id})";
return OkWithTrace(fn, unfollowSuccessMsg);
}
if (follower == null)
{
follower = new GeListFollower
{
Id = actorIri,
Type = "Person"
};
db.ListFollowers.Add(follower);
DBg.d(LogLevel.Information, $"{fn} -- added new follower to DB {follower.Id}");
}
else
{
DBg.d(LogLevel.Information, $"{fn} -- found existing follower in DB {follower.Id}");
}
await follower.FetchActorInfoFromIriAsync();
bool addedToList = false;
if (!follower.FollowingLists.Contains(list.Id))
{
follower.FollowingLists.Add(list.Id);
addedToList = true;
DBg.d(LogLevel.Information, $"{fn} -- added follower {follower.Id} to list {list.Name} (id: {list.Id})");
}
await db.SaveChangesAsync();
string? acceptInboxForFollow = await resolveActorInboxAsync(actorIri, follower);
if (string.IsNullOrWhiteSpace(acceptInboxForFollow)
|| !await sendActivityPubFollowAckAsync(acceptInboxForFollow, expectedActorUrl, incomingId, incomingType, actorIri, targetObject, true,
$"Follow accepted for list {list.Name} (id: {list.Id})"))
{
string msg = $"Follow processed locally but failed to send ActivityPub Accept to {actorIri}";
return ProblemWithTrace(fn, msg, 502);
}
var currentItems = await list.GetItems(db);
foreach (var currentItem in currentItems.Where(i => i.Visible && !i.IsDeleted))
{
await broadcastActivityPubItemToFollowersAsync(list, db, currentItem, "Create", follower);
}
if (addedToList)
{
await list.RegenerateAllFiles(db);
}
string successMsg = $"Activity received and processed for list {list.Name} (id: {list.Id})";
return OkWithTrace(fn, successMsg);
}
private static async Task<(bool Wrote, string? FilePath, string? Error)> TryWriteIncomingActivityAsync(string activityId, JsonElement activityJson)
{
if (!ActivityPubActivityLogStore.IsFullLoggingEnabled())
{
return (false, null, null);
}
if (string.IsNullOrWhiteSpace(GlobalConfig.ActivityPubActivitiesFolder))
{
return (false, null, "ActivityPub activities folder is not configured.");
}
try
{
Directory.CreateDirectory(GlobalConfig.ActivityPubActivitiesFolder);
string filePath = BuildIncomingActivityFilePath(activityId);
await File.WriteAllTextAsync(filePath, activityJson.GetRawText());
return (true, filePath, null);
}
catch (Exception ex)
{
return (false, null, ex.Message);
}
}
private static string BuildIncomingActivityFilePath(string activityId)
{
string encodedId = Uri.EscapeDataString(activityId);
if (string.IsNullOrWhiteSpace(encodedId))
{
encodedId = $"unknown-{Guid.NewGuid()}";
}
const int maxFileNameLength = 180;
if (encodedId.Length > maxFileNameLength)
{
string hash = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(activityId))).ToLowerInvariant()[..16];
encodedId = $"{encodedId[..(maxFileNameLength - 17)]}_{hash}";
}
return Path.Combine(GlobalConfig.ActivityPubActivitiesFolder!, $"{encodedId}.json");
}