-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathParatextProjectDataProvider.cs
More file actions
1701 lines (1473 loc) · 69.5 KB
/
ParatextProjectDataProvider.cs
File metadata and controls
1701 lines (1473 loc) · 69.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.Runtime.CompilerServices;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Paranext.DataProvider.JsonUtils;
using Paranext.DataProvider.Services;
using Paratext.Data;
using Paratext.Data.ProjectComments;
using Paratext.Data.ProjectSettingsAccess;
using PtxUtils;
using SIL.Scripture;
namespace Paranext.DataProvider.Projects;
internal class ParatextProjectDataProvider : ProjectDataProvider
{
#region Constants / Member variables
// All data types related to Scripture editing. Changes to any portion of Scripture should send
// out updates to all these data types
public static readonly List<string> AllScriptureDataTypes =
[
ProjectDataType.BOOK_USFM,
ProjectDataType.CHAPTER_USFM,
ProjectDataType.VERSE_USFM,
ProjectDataType.BOOK_USX,
ProjectDataType.CHAPTER_USX,
ProjectDataType.VERSE_USX,
ProjectDataType.VERSE_PLAIN_TEXT,
];
// All data types related to Scripture editing plus project settings. This is useful when an edit
// changes Scripture and also causes a project setting to change (e.g., adding a new book updates
// the BooksPresent setting)
public static readonly List<string> AllScriptureDataTypesPlusSettings =
[
.. AllScriptureDataTypes,
ProjectDataType.SETTING,
];
public static readonly List<string> AllCommentDataTypes =
[
ProjectDataType.COMMENTS,
ProjectDataType.COMMENT_THREADS,
];
private readonly LocalParatextProjects _paratextProjects;
private readonly CommentManager _commentManager;
#endregion
#region Constructors
public ParatextProjectDataProvider(
string name,
PapiClient papiClient,
ProjectDetails projectDetails,
LocalParatextProjects paratextProjects
)
: base(name, papiClient, projectDetails)
{
_paratextProjects = paratextProjects;
_commentManager = CommentManager.Get(
LocalParatextProjects.GetParatextProject(projectDetails.Metadata.Id)
);
RegisterSettingsValidators();
}
#endregion
#region Data Provider methods
protected override List<(string functionName, Delegate function)> GetFunctions()
{
var retVal = base.GetFunctions();
retVal.Add(("getBookUSFM", GetBookUsfm));
retVal.Add(("setBookUSFM", SetBookUsfm));
retVal.Add(("getChapterUSFM", GetChapterUsfm));
retVal.Add(("setChapterUSFM", SetChapterUsfm));
retVal.Add(("getVerseUSFM", GetVerseUsfm));
retVal.Add(("getBookUSX", GetBookUsx));
retVal.Add(("setBookUSX", SetBookUsx));
retVal.Add(("getChapterUSX", GetChapterUsx));
retVal.Add(("setChapterUSX", SetChapterUsx));
retVal.Add(("getVerseUSX", GetVerseUsx));
retVal.Add(("getVersePlainText", GetVersePlainText));
retVal.Add(("getCommentThreads", GetCommentThreads));
retVal.Add(("createComment", CreateComment));
retVal.Add(("addCommentToThread", AddCommentToThread));
retVal.Add(("deleteComment", DeleteComment));
retVal.Add(("updateComment", UpdateComment));
retVal.Add(("setIsCommentThreadRead", SetIsCommentThreadRead));
retVal.Add(("findAssignableUsers", FindAssignableUsers));
retVal.Add(("canUserCreateComments", CanUserCreateComments));
retVal.Add(("canUserAddCommentToThread", CanUserAddCommentToThread));
retVal.Add(("canUserAssignThread", CanUserAssignThread));
retVal.Add(("canUserResolveThread", CanUserResolveThread));
retVal.Add(("canUserEditOrDeleteComment", CanUserEditOrDeleteComment));
retVal.Add(("getSetting", GetProjectSetting));
retVal.Add(("setSetting", SetProjectSetting));
retVal.Add(("resetSetting", ResetProjectSetting));
retVal.Add(("getMarkerNames", GetMarkerNames));
retVal.Add(("lookupFinalVerseNumber", LookupFinalVerseNumber));
retVal.Add(("lookupFinalChapter", LookupFinalChapter));
retVal.Add(("lookupFinalVerseNumbersInBook", LookupFinalVerseNumbersInBook));
return retVal;
}
protected override Task StartDataProviderAsync()
{
_paratextProjects.Initialize();
return Task.CompletedTask;
}
#endregion
#region Extension Data
public override object? GetExtensionData(ProjectDataScope scope)
{
if (string.IsNullOrEmpty(scope.ExtensionName))
throw new InvalidDataException("Must provide an extension name");
if (string.IsNullOrEmpty(scope.DataQualifier))
throw new InvalidDataException("Must provide a data qualifier");
scope.ProjectID = ProjectDetails.Metadata.Id;
Stream? dataStream =
GetExtensionStream(scope, true)
?? throw new InvalidDataException("Extension data not found");
using (dataStream)
{
return new StreamReader(dataStream, Encoding.UTF8).ReadToEnd();
}
}
public override bool SetExtensionData(ProjectDataScope scope, string data)
{
if (string.IsNullOrEmpty(scope.ExtensionName))
throw new InvalidDataException("Must provide an extension name");
if (string.IsNullOrEmpty(scope.DataQualifier))
throw new InvalidDataException("Must provide a data qualifier");
scope.ProjectID = ProjectDetails.Metadata.Id;
Stream? dataStream =
GetExtensionStream(scope, true)
?? throw new InvalidDataException("Unable to create extension data");
ScrText scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
RunWithinLock(
WriteScope.EntireProject(scrText),
writeLock =>
{
if (!writeLock.Active)
throw new InvalidOperationException("Write lock is not active");
dataStream.SetLength(0);
using TextWriter textWriter = new StreamWriter(dataStream, Encoding.UTF8);
textWriter.Write(data);
textWriter.Flush();
}
);
SendDataUpdateEvent(ProjectDataType.EXTENSION_DATA, "extension data update event");
return true;
}
private Stream? GetExtensionStream(ProjectDataScope scope, bool createIfNotExists)
{
ProjectDetails projectDetails = _paratextProjects.GetProjectDetails(scope.ProjectID!);
IProjectStreamManager extensionStreamManager = CreateStreamManager(projectDetails);
return extensionStreamManager.GetDataStream(
$"{LocalParatextProjects.EXTENSION_DATA_SUBDIRECTORY}/{scope.ExtensionName}/{scope.DataQualifier}",
createIfNotExists
);
}
protected virtual IProjectStreamManager CreateStreamManager(ProjectDetails projectDetails)
{
return new RawDirectoryProjectStreamManager(projectDetails);
}
#endregion
#region Comments
public List<PlatformCommentThreadWrapper> GetCommentThreads(CommentThreadSelector selector)
{
// Get all threads (activeOnly=false to include threads with deleted comments)
List<CommentThread> allThreads = _commentManager.FindThreads(activeOnly: false);
// If no selector provided, apply defaults (exclude BT/spelling, deduplicate)
selector ??= new CommentThreadSelector();
IEnumerable<CommentThread> filteredThreads = allThreads;
// Note-category filtering is applied BEFORE deduplication so that flags from excluded
// threads cannot bleed into the merged metadata of a surviving thread with the same ID.
filteredThreads = selector.NoteCategory switch
{
NoteCategory.BtNotes => filteredThreads.Where(t => t.IsBTNote),
NoteCategory.SpellingNotes => filteredThreads.Where(t => t.IsSpellingNote),
_ => filteredThreads.Where(t => !t.IsBTNote && !t.IsSpellingNote), // NoteCategory.General (default)
};
// Filter by thread ID (exact match)
if (!string.IsNullOrEmpty(selector.ThreadId))
filteredThreads = filteredThreads.Where(t => string.Equals(t.Id, selector.ThreadId));
// Filter by status
if (selector.Status != Enum<NoteStatus>.Null)
{
filteredThreads = filteredThreads.Where(t => t.Status == selector.Status);
}
// Filter by type
if (selector.Type != null)
{
filteredThreads = filteredThreads.Where(t => t.Type == selector.Type);
}
// Filter by user (who created comments in the thread)
if (!string.IsNullOrEmpty(selector.Author))
filteredThreads = filteredThreads.Where(t =>
t.Comments.Any(c => c.User == selector.Author)
);
// Filter by assigned user
if (!string.IsNullOrEmpty(selector.AssignedTo))
filteredThreads = filteredThreads.Where(t => t.AssignedUser == selector.AssignedTo);
// Filter by date
if (selector.DateFilter != null)
filteredThreads = FilterByDate(filteredThreads, selector.DateFilter);
// Filter by scripture ranges
if (selector.ScriptureRanges != null && selector.ScriptureRanges.Count > 0)
filteredThreads = FilterByScriptureRanges(filteredThreads, selector.ScriptureRanges);
// Filter by read status
if (selector.IsRead is bool isRead)
filteredThreads = filteredThreads.Where(t => ThreadStatus.IsThreadRead(t) == isRead);
List<PlatformCommentThreadWrapper> results = filteredThreads
.Select(t => new PlatformCommentThreadWrapper(t))
.ToList();
// Deduplicate threads with the same ID: combine unique comments, use the thread
// with the latest ModifiedDate as the metadata base, and drop all-deleted threads.
// Done after wrapping to avoid mutating ParatextData's internal CommentThread objects.
if (selector.DeduplicateThreads)
results = DeduplicateCommentThreads(results);
return results;
}
public bool DeleteComment(string commentId)
{
// Find the comment by ID and its parent thread
var (commentToDelete, parentThread) = FindCommentByIdWithThread(commentId);
if (commentToDelete == null || parentThread == null)
return false;
VerifyUserCanEditOrDeleteComment(commentId);
// Remove the comment using CommentManager
_commentManager.RemoveComment(commentToDelete);
_commentManager.SaveUser(commentToDelete.User, false);
SendDataUpdateEvent(AllCommentDataTypes, "comment deleted event");
return true;
}
/// <summary>
/// Replace newlines in the text with spaces. We need to do this to the USFM text in comments
/// before saving them to file because they come from the PAPI with newlines but should be saved
/// to file with spaces.
/// </summary>
private static string ReplaceNewlinesWithSpaces(string text)
{
text = text.Replace("\r", "").Replace("\n", " ");
return text;
}
/// <summary>
/// Creates a new comment and a new thread. Any thread id, user, or date provided in the
/// comment parameter will be ignored - these are auto-generated by the Comment constructor.
/// </summary>
/// <param name="comment">Comment data. Thread, User, and Date will be ignored/auto-generated.</param>
/// <returns>The auto-generated comment ID (format: "threadId/userName/date")</returns>
/// <exception cref="InvalidOperationException">If the selected text is invalid or the comment's
/// assigned (<see cref="PlatformCommentWrapper.AssignedUser"/>) cannot be assigned to threads
/// in this project.
public string CreateComment(PlatformCommentWrapper comment)
{
VerifyUserCanCreateComments();
if (comment.SelectedText != null && comment.SelectedText.Contains('\\'))
{
throw new InvalidOperationException(
"Invalid selection. Selected text must be a simple word or phrase. "
+ "Selected text cannot contain USFM markers (backslash characters)."
);
}
var scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
if (comment.AssignedUser != null)
{
var assignableUsers = CommentThread
.GetAssignToUsers(scrText, includeCurrentUserInUnsharedProject: true)
.ToList();
if (!assignableUsers.Contains(comment.AssignedUser))
throw new InvalidOperationException(
$"User '{comment.AssignedUser}' cannot be assigned to threads in this project."
);
}
Comment newComment = new(scrText.User);
CopyCommentProperties(comment, newComment);
// Reformat USFM text in the comment by replacing newlines with spaces
if (comment.SelectedText != null)
newComment.SelectedText = ReplaceNewlinesWithSpaces(comment.SelectedText);
if (
string.IsNullOrEmpty(newComment.Verse)
&& string.IsNullOrEmpty(newComment.ContextBefore)
&& string.IsNullOrEmpty(newComment.ContextAfter)
)
{
// Check *incoming* values that do not necessarily get copied to newComment.
if (
string.IsNullOrEmpty(comment.VerseRefStr) // This condition will throw exception below.
|| comment.StartPosition < 0
|| comment.SelectedText == null
)
{
Console.Error.WriteLine(
"VerseRef, StartPosition, and SelectedText are required when Verse, ContextBefore, and ContextAfter are not provided"
);
}
else
{
// Get the values of Verse, ContextBefore, and ContextAfter from the scrText since that's
// the data that is supposed to be saved (already has spaces instead of newlines)
// From CommentManager.CreateThread
newComment.Verse = scrText.Parser.GetVerseUsfmText(newComment.VerseRef);
if (newComment.Verse == null)
{
Console.Error.WriteLine(
$"Unable to retrieve verse text for VerseRef {newComment.VerseRef}"
);
}
else
{
newComment.ContextBefore = newComment.Verse[..newComment.StartPosition];
newComment.ContextAfter = newComment.Verse[
(newComment.StartPosition + newComment.SelectedText.Length)..
];
}
}
}
// Create a ScriptureSelection to put the USFM snippets through the same processing as they
// go through in P9
ScriptureSelection selection;
try
{
selection = new ScriptureSelection(
newComment.VerseRef,
newComment.SelectedText,
newComment.StartPosition,
newComment.ContextBefore,
newComment.ContextAfter
);
}
catch (Exception ex)
{
throw new InvalidOperationException($"Invalid Scripture selection: {ex.Message}", ex);
}
// From CommentManager.CreateThread
CommentUtils.AdjustNoteSelection(scrText, selection);
newComment.StartPosition = selection.StartPosition;
newComment.SelectedText = selection.SelectedText;
newComment.ContextBefore = selection.ContextBefore;
newComment.ContextAfter = selection.ContextAfter;
if (string.IsNullOrEmpty(newComment.Language))
newComment.Language = scrText.Language.Id;
_commentManager.AddComment(newComment);
_commentManager.SaveUser(newComment.User, false);
ThreadStatus.MarkThreadRead(_commentManager.FindThread(newComment.Thread));
SendDataUpdateEvent(AllCommentDataTypes, "comment created event");
return newComment.Id;
}
/// <summary>
/// Adds a comment to an existing thread. The thread must already exist.
/// Can also be used to modify thread-level properties (status, assignedUser) without
/// adding comment content.
/// </summary>
/// <param name="comment">Comment data. Must have a valid Thread ID that exists.</param>
/// <returns>The auto-generated comment ID (format: "threadId/userName/date")</returns>
/// <exception cref="InvalidDataException">If the thread ID is missing or doesn't exist</exception>
public string AddCommentToThread(PlatformCommentWrapper comment)
{
if (string.IsNullOrEmpty(comment.Thread))
throw new InvalidDataException("Thread ID is required for AddCommentToThread");
bool hasContents =
comment.Contents != null && !string.IsNullOrEmpty(comment.Contents.InnerText);
bool hasStatus = comment.Status != NoteStatus.Unspecified;
bool hasAssignedUser = comment.AssignedUser != null;
if (!hasContents && !hasStatus && !hasAssignedUser)
throw new InvalidDataException(
"At least one of Contents, Status, or AssignedUser must be provided for AddCommentToThread"
);
CommentThread? existingThread = _commentManager.FindThread(comment.Thread);
if (existingThread == null)
throw new InvalidDataException($"Thread with id {comment.Thread} does not exist");
var scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
VerifyUserCanAddCommentToThread();
// Validate permissions for status changes (resolve/re-open)
if (
comment.Status != NoteStatus.Unspecified
&& (comment.Status == NoteStatus.Resolved || comment.Status == NoteStatus.Todo)
)
{
VerifyUserCanResolveThread(comment.Thread);
}
// Validate assigned user has permission to be assigned and is in the assignable users list
if (comment.AssignedUser != null)
{
VerifyUserCanAssignThread(comment.Thread);
var assignableUsers = CommentThread
.GetAssignToUsers(scrText, includeCurrentUserInUnsharedProject: true)
.ToList();
if (!assignableUsers.Contains(comment.AssignedUser))
throw new InvalidOperationException(
$"User '{comment.AssignedUser}' cannot be assigned to threads in this project."
);
}
Comment newComment = existingThread.AddNewComment();
CopyCommentProperties(comment, newComment);
if (
comment.Status == NoteStatus.Unspecified
&& existingThread.Status == NoteStatus.Resolved
&& hasContents
)
{
Console.WriteLine(
$"Reopening resolved thread {existingThread.Id} because a new comment is being added to it."
);
newComment.Status = NoteStatus.Todo;
}
_commentManager.AddComment(newComment);
_commentManager.SaveUser(newComment.User, false);
ThreadStatus.MarkThreadRead(existingThread);
SendDataUpdateEvent(AllCommentDataTypes, "comment added to thread event");
return newComment.Id;
}
/// <summary>
/// Copies properties from the source comment to the target comment, excluding
/// auto-generated fields (Thread, User, Date).
/// </summary>
private static void CopyCommentProperties(PlatformCommentWrapper source, Comment target)
{
if (!string.IsNullOrEmpty(source.ContextAfter))
target.ContextAfter = source.ContextAfter;
if (!string.IsNullOrEmpty(source.ContextBefore))
target.ContextBefore = source.ContextBefore;
if (!string.IsNullOrEmpty(source.SelectedText))
target.SelectedText = source.SelectedText;
if (source.StartPosition >= 0)
target.StartPosition = source.StartPosition;
// AssignedUser allows empty string (means "unassigned"), so only check for null
if (source.AssignedUser != null)
target.AssignedUser = source.AssignedUser;
if (!string.IsNullOrEmpty(source.BiblicalTermId))
target.BiblicalTermId = source.BiblicalTermId;
if (source.ConflictType != default)
target.ConflictType = source.ConflictType;
if (source.Deleted)
target.Deleted = source.Deleted;
if (source.HideInTextWindow)
target.HideInTextWindow = source.HideInTextWindow;
if (!string.IsNullOrEmpty(source.Language))
target.Language = source.Language;
if (!string.IsNullOrEmpty(source.ReplyToUser))
target.ReplyToUser = source.ReplyToUser;
if (!string.IsNullOrEmpty(source.Shared))
target.Shared = source.Shared;
if (source.Status != NoteStatus.Unspecified)
target.Status = source.Status;
if (source.Type != NoteType.Unspecified)
target.Type = source.Type;
if (!string.IsNullOrEmpty(source.Verse))
target.Verse = source.Verse;
if (!string.IsNullOrEmpty(source.VerseRefStr))
target.VerseRefStr = source.VerseRefStr;
if (source.Contents != null)
target.Contents = source.Contents;
if (source.TagsAdded != null && source.TagsAdded.Length > 0)
target.TagsAdded = source.TagsAdded;
if (source.TagsRemoved != null && source.TagsRemoved.Length > 0)
target.TagsRemoved = source.TagsRemoved;
if (!string.IsNullOrEmpty(source.ExtraHeadingInfoInternal))
target.ExtraHeadingInfoInternal = source.ExtraHeadingInfoInternal;
}
public bool UpdateComment(string commentId, string updatedContentHtml)
{
if (string.IsNullOrEmpty(commentId))
return false;
// Find the comment by ID and its parent thread
var (commentToUpdate, parentThread) = FindCommentByIdWithThread(commentId);
if (commentToUpdate == null || parentThread == null)
return false;
VerifyUserCanEditOrDeleteComment(commentId);
// Update the comment contents from HTML
var commentWrapper = new PlatformCommentWrapper(
commentToUpdate,
new PlatformCommentThreadWrapper(parentThread)
);
commentWrapper.ContentsHtml = updatedContentHtml;
// Reset the status field to Unspecified when a comment is edited
commentToUpdate.Status = NoteStatus.Unspecified;
_commentManager.SaveUser(commentToUpdate.User, false);
SendDataUpdateEvent(AllCommentDataTypes, "comment updated");
return true;
}
public void SetIsCommentThreadRead(string threadId, bool markRead)
{
CommentThread? thread = _commentManager.FindThread(threadId);
if (thread == null)
throw new ArgumentException($"Thread with ID '{threadId}' not found", nameof(threadId));
if (markRead)
ThreadStatus.MarkThreadRead(thread);
else
ThreadStatus.MarkThreadUnread(thread);
SendDataUpdateEvent(AllCommentDataTypes, "comment thread read status updated");
}
/// <summary>
/// Finds the list of users that can be assigned to comment threads in this project.
/// </summary>
/// <returns>List of usernames that can be assigned to threads. Includes special values:
/// "Team" for team assignment, and "" (empty string) for unassigned.</returns>
public List<string> FindAssignableUsers()
{
var scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
return
[
.. CommentThread.GetAssignToUsers(scrText, includeCurrentUserInUnsharedProject: true),
];
}
#region Permission Checks
/// <summary>
/// Verifies that the current user can create new comment threads in this project.
/// Throws an <see cref="InvalidOperationException"/> with a specific message if not allowed.
/// </summary>
/// <param name="allowInSba">Allow creating comments in Study Bible Additions projects (default: false)</param>
private void VerifyUserCanCreateComments(bool allowInSba = false)
{
var scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
// Cannot create comments in resource projects
if (scrText.IsResourceProject)
throw new InvalidOperationException("Cannot create comments in resource projects.");
// Must have a role other than Observer or None
if (!scrText.Permissions.HaveRoleNotObserver)
throw new InvalidOperationException(
"You do not have permission to create comments in this project."
);
// Cannot create comments in Study Bible Additions (unless explicitly allowed)
if (!allowInSba && scrText.Settings.IsStudyBibleAdditions)
throw new InvalidOperationException(
"Cannot create comments in Study Bible Additions projects."
);
// Cannot create comments in Transliteration with Encoder projects
if (scrText.Settings.TranslationInfo.Type == ProjectType.TransliterationWithEncoder)
throw new InvalidOperationException(
"Cannot create comments in Transliteration with Encoder projects."
);
}
/// <summary>
/// Determines if the current user can create new comment threads in this project.
/// </summary>
/// <param name="allowInSba">Allow creating comments in Study Bible Additions projects (default: false)</param>
/// <returns>True if the user can create comments, false otherwise</returns>
public bool CanUserCreateComments(bool allowInSba = false)
{
try
{
VerifyUserCanCreateComments(allowInSba);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Verifies that the current user can add comments to existing threads in this project.
/// Throws an <see cref="InvalidOperationException"/> with a specific message if not allowed.
/// </summary>
private void VerifyUserCanAddCommentToThread()
{
var scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
// Must have a role other than Observer or None
if (!scrText.Permissions.HaveRoleNotObserver)
throw new InvalidOperationException(
$"User '{scrText.User.Name}' does not have permission to add comments to threads in this project."
);
// Resource projects with global note types are read-only
if (scrText.IsResourceProject && scrText.Settings.TranslationInfo.Type.IsGlobalNoteType())
throw new InvalidOperationException(
"Resource projects with global note types are read-only."
);
}
/// <summary>
/// Determines if the current user can add comments to existing threads in this project.
/// This is slightly different from CanUserAddNotes - it allows adding to threads
/// in resource projects that aren't global note types.
/// </summary>
/// <returns>True if the user can add comments to threads, false otherwise</returns>
public bool CanUserAddCommentToThread()
{
try
{
VerifyUserCanAddCommentToThread();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Verifies that the current user can change the assigned user on a specific thread.
/// Throws an <see cref="InvalidOperationException"/> with a specific message if not allowed.
/// </summary>
/// <param name="threadId">The ID of the thread to check</param>
private void VerifyUserCanAssignThread(string threadId)
{
var scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
// Must have a role other than Observer or None
if (!scrText.Permissions.HaveRoleNotObserver)
throw new InvalidOperationException(
$"User '{scrText.User.Name}' does not have permission to assign this thread."
);
CommentThread? thread = _commentManager.FindThread(threadId);
if (thread == null)
throw new InvalidOperationException($"Thread with id {threadId} does not exist.");
// Biblical Term notes cannot have assignments
if (thread.IsBTNote)
throw new InvalidOperationException("Biblical Term notes cannot have assignments.");
// Spelling notes cannot have assignments
if (thread.IsSpellingNote)
throw new InvalidOperationException("Spelling notes cannot have assignments.");
}
/// <summary>
/// Determines if the current user can change the assigned user on a specific thread.
/// </summary>
/// <param name="threadId">The ID of the thread to check</param>
/// <returns>True if the user can assign the thread, false otherwise</returns>
public bool CanUserAssignThread(string threadId)
{
try
{
VerifyUserCanAssignThread(threadId);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Verifies that the current user can resolve or re-open a specific thread.
/// Throws an <see cref="InvalidOperationException"/> with a specific message if not allowed.
/// </summary>
/// <param name="threadId">The ID of the thread to check</param>
private void VerifyUserCanResolveThread(string threadId)
{
var scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
// Must have a role other than Observer or None
if (!scrText.Permissions.HaveRoleNotObserver)
throw new InvalidOperationException(
$"User '{scrText.User.Name}' does not have permission to resolve or re-open threads in this project."
);
// Resource projects with global note types are read-only
if (scrText.IsResourceProject && scrText.Settings.TranslationInfo.Type.IsGlobalNoteType())
throw new InvalidOperationException(
"Resource projects with global note types are read-only."
);
CommentThread? thread = _commentManager.FindThread(threadId);
if (thread == null)
throw new InvalidOperationException($"Thread with id {threadId} does not exist.");
CommentTags tags = CommentTags.Get(scrText);
// Check if user can resolve based on all tags on the thread
if (!thread.TagIds.All(tagId => thread.CanCurrentUserResolve(tags.Get(tagId))))
throw new InvalidOperationException(
$"User '{scrText.User.Name}' cannot resolve or re-open thread '{threadId}' - insufficient permissions."
);
}
/// <summary>
/// Determines if the current user can resolve or re-open a specific thread.
/// </summary>
/// <param name="threadId">The ID of the thread to check</param>
/// <returns>True if the user can resolve the thread, false otherwise</returns>
public bool CanUserResolveThread(string threadId)
{
try
{
VerifyUserCanResolveThread(threadId);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Verifies that the current user can edit or delete a specific comment.
/// Throws an <see cref="InvalidOperationException"/> with a specific message if not allowed.
/// Checks are ordered from most fundamental (role/project level) to most specific (comment level),
/// so the most actionable error is always reported first.
/// </summary>
/// <param name="commentId">The ID of the comment to check</param>
private void VerifyUserCanEditOrDeleteComment(string commentId)
{
var scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
// Must have general edit permission on the project (checked first - most fundamental)
if (!scrText.Permissions.HaveRoleNotObserver)
throw new InvalidOperationException(
$"User does not have permission to edit or delete comment {commentId}."
);
// Resource projects with global note types are read-only
if (scrText.IsResourceProject && scrText.Settings.TranslationInfo.Type.IsGlobalNoteType())
throw new InvalidOperationException(
$"User does not have permission to edit or delete comment {commentId}."
);
var (comment, thread) = FindCommentByIdWithThread(commentId);
if (comment == null || thread == null)
throw new InvalidOperationException($"Comment with ID {commentId} does not exist.");
// Must be the last comment in the thread
var lastComment = thread.LastComment;
if (lastComment == null || comment.Id != lastComment.Id)
throw new InvalidOperationException(
$"Cannot edit or delete comment {commentId} in thread {thread.Id} - only the last comment can be edited or deleted (last comment ID: {lastComment?.Id})"
);
// Must be the author of the comment
if (comment.User != scrText.User.Name)
throw new InvalidOperationException(
$"Cannot edit or delete comment {commentId} in thread {comment.Thread} - not created by current user {scrText.User.Name} (created by {comment.User})"
);
// Cannot edit/delete if it's a conflict resolution action
if (comment.ConflictResolutionAction != NoteConflictResolutions.None)
throw new InvalidOperationException(
$"Cannot edit or delete comment {commentId} in thread {thread.Id} - comment is a conflict resolution action."
);
// Cannot edit/delete the first comment of a conflict note
if (thread.Type == NoteType.Conflict && thread.Comments[0].Id == comment.Id)
throw new InvalidOperationException(
$"Cannot edit or delete comment {commentId} in thread {thread.Id} - cannot edit or delete the first comment of a conflict note."
);
}
/// <summary>
/// Determines if the current user can edit or delete a specific comment.
/// In Paratext 9, edit and delete have identical permission requirements.
/// </summary>
/// <param name="commentId">The ID of the comment to check</param>
/// <returns>True if the user can edit or delete the comment, false otherwise</returns>
public bool CanUserEditOrDeleteComment(string commentId)
{
try
{
VerifyUserCanEditOrDeleteComment(commentId);
return true;
}
catch
{
return false;
}
}
#endregion
private (Comment?, CommentThread?) FindCommentByIdWithThread(string commentId)
{
// Get all threads (activeOnly=false to include deleted comments)
List<CommentThread> allThreads = _commentManager.FindThreads(activeOnly: false);
// Search through all threads to find the comment with matching ID
foreach (var thread in allThreads)
{
var comment = thread.Comments.FirstOrDefault(c => c.Id == commentId);
if (comment != null)
return (comment, thread);
}
return (null, null);
}
/// <summary>
/// Merges threads with duplicate IDs: combines unique comments and uses the thread with the
/// latest <see cref="PlatformCommentThreadWrapper.ModifiedDate"/> as the metadata base.
/// Drops threads where all comments are deleted.
/// Works on wrappers to avoid mutating ParatextData's internal CommentThread objects.
/// </summary>
internal static List<PlatformCommentThreadWrapper> DeduplicateCommentThreads(
List<PlatformCommentThreadWrapper> wrappers
)
{
var threadMap = new Dictionary<string, PlatformCommentThreadWrapper>();
foreach (PlatformCommentThreadWrapper wrapper in wrappers)
{
if (!threadMap.TryGetValue(wrapper.Id, out PlatformCommentThreadWrapper? existing))
{
threadMap[wrapper.Id] = wrapper;
continue;
}
// Use the thread with the later ModifiedDate as the metadata base
if (wrapper.ModifiedDate > existing.ModifiedDate)
{
// New thread is newer — it becomes the base, merge existing's comments into it
wrapper.MergeCommentsFrom(existing);
threadMap[wrapper.Id] = wrapper;
}
else
{
// Existing thread is newer or same — merge the new thread's comments into it
existing.MergeCommentsFrom(wrapper);
}
}
// Drop threads where all comments are deleted
return threadMap.Values.Where(t => t.HasNonDeletedComments).ToList();
}
private static IEnumerable<CommentThread> FilterByDate(
IEnumerable<CommentThread> threads,
DateFilter dateFilter
)
{
if (!string.IsNullOrEmpty(dateFilter.Exact))
{
var targetDate = DateTimeOffset.Parse(dateFilter.Exact);
// For exact date matching, compare only the date portion (ignore time)
return threads.Where(t => t.ModifiedDate.Date == targetDate.Date);
}
if (!string.IsNullOrEmpty(dateFilter.Before))
{
var beforeDate = DateTimeOffset.Parse(dateFilter.Before);
return threads.Where(t => t.ModifiedDate <= beforeDate);
}
if (!string.IsNullOrEmpty(dateFilter.After))
{
var afterDate = DateTimeOffset.Parse(dateFilter.After);
return threads.Where(t => t.ModifiedDate >= afterDate);
}
if (!string.IsNullOrEmpty(dateFilter.Start) && !string.IsNullOrEmpty(dateFilter.End))
{
var startDate = DateTimeOffset.Parse(dateFilter.Start);
var endDate = DateTimeOffset.Parse(dateFilter.End);
return threads.Where(t => t.ModifiedDate >= startDate && t.ModifiedDate <= endDate);
}
return threads;
}
private IEnumerable<CommentThread> FilterByScriptureRanges(
IEnumerable<CommentThread> threads,
List<ScriptureRange> scriptureRanges
)
{
var scrText = LocalParatextProjects.GetParatextProject(ProjectDetails.Metadata.Id);
return threads.Where(thread =>
{
VerseRef threadVerseRef = thread.VerseRef;
return scriptureRanges.Any(range => MatchesScriptureRange(threadVerseRef, range));
});
}
private static bool MatchesScriptureRange(VerseRef verseRef, ScriptureRange range)
{
// Match based on granularity
string granularity = range.Granularity ?? "verse";
switch (granularity.ToLowerInvariant())
{
case "book":
// Match if the comment is in any book within the range
return verseRef.BookNum >= range.Start.BookNum
&& verseRef.BookNum <= range.End.BookNum;
case "chapter":
// Match if the comment is in the same book and within the chapter range
if (verseRef.BookNum != range.Start.BookNum)
return false;
return verseRef.ChapterNum >= range.Start.ChapterNum
&& verseRef.ChapterNum <= range.End.ChapterNum;
case "verse":
default:
// Match if the comment's verse is within the range
return verseRef.CompareTo(range.Start) >= 0 && verseRef.CompareTo(range.End) <= 0;
}
}
#endregion
#region Settings
public static string VisibilitySettingName => Setting.Visibility.ToString();
private void RegisterSettingsValidators()
{
ProjectSettingsService.RegisterValidator(
PapiClient,