-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathCommentService.m
1375 lines (1200 loc) · 55.8 KB
/
CommentService.m
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
#import "CommentService.h"
#import "AccountService.h"
#import "Blog.h"
@import WordPressData;
#import "ReaderPost.h"
#import "WPAccount.h"
#import "PostService.h"
#import "AbstractPost.h"
#import "WordPress-Swift.h"
@import WordPressShared;
NSUInteger const WPTopLevelHierarchicalCommentsPerPage = 20;
NSInteger const WPNumberOfCommentsToSync = 100;
static NSTimeInterval const CommentsRefreshTimeoutInSeconds = 60 * 5; // 5 minutes
@interface CommentService ()
@property (nonnull, strong, nonatomic) CommentServiceRemoteFactory *remoteFactory;
@end
@implementation CommentService
- (instancetype)initWithCoreDataStack:(id<CoreDataStack>)coreDataStack
{
return [self initWithCoreDataStack:coreDataStack commentServiceRemoteFactory:[CommentServiceRemoteFactory new]];
}
- (instancetype)initWithCoreDataStack:(id<CoreDataStack>)coreDataStack
commentServiceRemoteFactory:(CommentServiceRemoteFactory *)remoteFactory
{
self = [super initWithCoreDataStack:coreDataStack];
if (self) {
self.remoteFactory = remoteFactory;
}
return self;
}
+ (NSMutableSet *)syncingCommentsLocks
{
static NSMutableSet *syncingCommentsLocks;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
syncingCommentsLocks = [NSMutableSet set];
});
return syncingCommentsLocks;
}
+ (BOOL)isSyncingCommentsForBlog:(Blog *)blog {
return [self isSyncingCommentsForBlogID:blog.objectID];
}
+ (BOOL)isSyncingCommentsForBlogID:(NSManagedObjectID *)blogID
{
NSParameterAssert(blogID);
return [[self syncingCommentsLocks] containsObject:blogID];
}
+ (BOOL)startSyncingCommentsForBlog:(NSManagedObjectID *)blogID
{
NSParameterAssert(blogID);
@synchronized([self syncingCommentsLocks]) {
if ([self isSyncingCommentsForBlogID:blogID]){
return NO;
}
[[self syncingCommentsLocks] addObject:blogID];
return YES;
}
}
+ (void)stopSyncingCommentsForBlog:(NSManagedObjectID *)blogID
{
NSParameterAssert(blogID);
@synchronized([self syncingCommentsLocks]) {
[[self syncingCommentsLocks] removeObject:blogID];
}
}
+ (BOOL)shouldRefreshCacheFor:(Blog *)blog
{
NSDate *lastSynced = blog.lastCommentsSync;
BOOL isSyncing = [self isSyncingCommentsForBlog:blog];
return !isSyncing && (lastSynced == nil || ABS(lastSynced.timeIntervalSinceNow) > CommentsRefreshTimeoutInSeconds);
}
#pragma mark Public methods
#pragma mark Blog-centric methods
// Create comment
- (Comment *)createCommentForBlog:(Blog *)blog
{
NSParameterAssert(blog.managedObjectContext != nil);
Comment *comment = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Comment class])
inManagedObjectContext:blog.managedObjectContext];
comment.dateCreated = [NSDate new];
comment.blog = blog;
return comment;
}
// Create reply
- (void)createReplyForComment:(Comment *)comment content:(NSString *)content completion:(void (^)(Comment *reply))completion
{
NSManagedObjectID *parentCommentID = comment.objectID;
NSManagedObjectID * __block replyID = nil;
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *comment = [context existingObjectWithID:parentCommentID error:nil];
Comment *reply = [self createCommentForBlog:comment.blog];
reply.postID = comment.postID;
reply.post = comment.post;
reply.parentID = comment.commentID;
reply.status = [Comment descriptionFor:CommentStatusTypeApproved];
reply.content = content;
[context obtainPermanentIDsForObjects:@[reply] error:nil];
replyID = reply.objectID;
} completion:^{
if (completion) {
completion([self.coreDataStack.mainContext existingObjectWithID:replyID error:nil]);
}
} onQueue:dispatch_get_main_queue()];
}
// Sync comments
- (void)syncCommentsForBlog:(Blog *)blog
withStatus:(CommentStatusFilter)status
success:(void (^)(BOOL hasMore))success
failure:(void (^)(NSError *error))failure
{
[self syncCommentsForBlog:blog withStatus:status filterUnreplied:NO success:success failure:failure];
}
- (void)syncCommentsForBlog:(Blog *)blog
withStatus:(CommentStatusFilter)status
filterUnreplied:(BOOL)filterUnreplied
success:(void (^)(BOOL hasMore))success
failure:(void (^)(NSError *error))failure
{
NSManagedObjectID *blogID = blog.objectID;
if (![[self class] startSyncingCommentsForBlog:blogID]){
// We assume success because a sync is already running and it will change the comments
if (success) {
success(YES);
}
return;
}
// If the comment status is not specified, default to all.
CommentStatusFilter commentStatus = status ?: CommentStatusFilterAll;
NSDictionary *options = @{ @"status": [NSNumber numberWithInt:commentStatus] };
id<CommentServiceRemote> remote = [self remoteForBlog:blog];
[remote getCommentsWithMaximumCount:WPNumberOfCommentsToSync
options:options
success:^(NSArray *comments) {
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Blog *blog = [context existingObjectWithID:blogID error:nil];
if (!blog) {
return;
}
NSArray *fetchedComments = comments;
if (filterUnreplied) {
NSString *author = @"";
if (blog.account) {
// See if there is a linked Jetpack user that we should use.
BlogAuthor *blogAuthor = [blog getAuthorWithLinkedID:blog.account.userID];
author = (blogAuthor) ? blogAuthor.email : blog.account.email;
} else {
BlogAuthor *blogAuthor = [blog getAuthorWithId:blog.userID];
author = (blogAuthor) ? blogAuthor.email : author;
}
fetchedComments = [self filterUnrepliedComments:comments forAuthor:author];
}
[self mergeComments:fetchedComments forBlog:blog purgeExisting:YES];
blog.lastCommentsSync = [NSDate date];
} completion:^{
[[self class] stopSyncingCommentsForBlog:blogID];
if (success) {
// Note:
// We'll assume that if the requested page size couldn't be filled, there are no
// more comments left to retrieve. However, for unreplied comments, we only fetch the first page (for now).
BOOL hasMore = comments.count >= WPNumberOfCommentsToSync && !filterUnreplied;
success(hasMore);
}
} onQueue:dispatch_get_main_queue()];
} failure:^(NSError *error) {
[[self class] stopSyncingCommentsForBlog:blogID];
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
}
- (NSArray *)filterUnrepliedComments:(NSArray *)comments forAuthor:(NSString *)author {
NSMutableArray *marr = [comments mutableCopy];
NSMutableArray *foundIDs = [NSMutableArray array];
NSMutableArray *discardables = [NSMutableArray array];
// get ids of comments that user has replied to.
for (RemoteComment *comment in marr) {
if (![comment.authorEmail isEqualToString:author] || !comment.parentID) {
continue;
}
[foundIDs addObject:comment.parentID];
[discardables addObject:comment];
}
// Discard the replies, they aren't needed.
[marr removeObjectsInArray:discardables];
[discardables removeAllObjects];
// Get the parents, grandparents etc. and discard those too.
while ([foundIDs count] > 0) {
NSArray *needles = [foundIDs copy];
[foundIDs removeAllObjects];
for (RemoteComment *comment in marr) {
if ([needles containsObject:comment.commentID]) {
if (comment.parentID) {
[foundIDs addObject:comment.parentID];
}
[discardables addObject:comment];
}
}
// Discard the matches, and keep looking if items were found.
[marr removeObjectsInArray:discardables];
[discardables removeAllObjects];
}
// remove any remaining child comments.
// remove any remaining root comments made by the user.
for (RemoteComment *comment in marr) {
if (comment.parentID.intValue != 0) {
[discardables addObject:comment];
} else if ([comment.authorEmail isEqualToString:author]) {
[discardables addObject:comment];
}
}
[marr removeObjectsInArray:discardables];
// these are the most recent unreplied comments from other users.
return [NSArray arrayWithArray:marr];
}
- (Comment *)oldestCommentForBlog:(Blog *)blog {
NSParameterAssert(blog.managedObjectContext != nil);
NSString *entityName = NSStringFromClass([Comment class]);
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
request.predicate = [NSPredicate predicateWithFormat:@"dateCreated != NULL && blog=%@", blog];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"dateCreated" ascending:YES];
request.sortDescriptors = @[sortDescriptor];
Comment * __block oldestComment = nil;
[blog.managedObjectContext performBlockAndWait:^{
oldestComment = [[blog.managedObjectContext executeFetchRequest:request error:nil] firstObject];
}];
return oldestComment;
}
- (void)loadMoreCommentsForBlog:(Blog *)blog
withStatus:(CommentStatusFilter)status
success:(void (^)(BOOL hasMore))success
failure:(void (^)(NSError *))failure
{
NSManagedObjectID *blogID = blog.objectID;
if (![[self class] startSyncingCommentsForBlog:blogID]){
// We assume success because a sync is already running and it will change the comments
if (success) {
success(YES);
}
}
NSMutableDictionary *options = [NSMutableDictionary dictionary];
// If the comment status is not specified, default to all.
CommentStatusFilter commentStatus = status ?: CommentStatusFilterAll;
options[@"status"] = [NSNumber numberWithInt:commentStatus];
id<CommentServiceRemote> remote = [self remoteForBlog:blog];
if ([remote isKindOfClass:[CommentServiceRemoteREST class]]) {
Comment *oldestComment = [self oldestCommentForBlog:blog];
if (oldestComment.dateCreated) {
options[@"before"] = [oldestComment.dateCreated WordPressComJSONString];
options[@"order"] = @"desc";
}
} else if ([remote isKindOfClass:[CommentServiceRemoteXMLRPC class]]) {
NSUInteger commentCount = [blog.comments count];
options[@"offset"] = @(commentCount);
}
[remote getCommentsWithMaximumCount:WPNumberOfCommentsToSync
options:options
success:^(NSArray *comments) {
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Blog *blog = [context existingObjectWithID:blogID error:nil];
if (!blog) {
return;
}
[self mergeComments:comments forBlog:blog purgeExisting:NO];
} completion:^{
[[self class] stopSyncingCommentsForBlog:blogID];
if (success) {
success(comments.count > 1);
}
} onQueue:dispatch_get_main_queue()];
} failure:^(NSError *error) {
[[self class] stopSyncingCommentsForBlog:blogID];
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
}
- (void)loadCommentWithID:(NSNumber *)commentID
forBlog:(Blog *)blog
success:(void (^)(Comment *comment))success
failure:(void (^)(NSError *))failure {
NSManagedObjectID *blogID = blog.objectID;
id<CommentServiceRemote> remote = [self remoteForBlog:blog];
[remote getCommentWithID:commentID
success:^(RemoteComment *remoteComment) {
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Blog *blog = [context existingObjectWithID:blogID error:nil];
if (!blog) {
return;
}
Comment *comment = [blog commentWithID:remoteComment.commentID];
if (!comment) {
comment = [self createCommentForBlog:blog];
}
[self updateComment:comment withRemoteComment:remoteComment];
} completion:^{
if (success) {
[self.coreDataStack.mainContext performBlock:^{
Blog *blog = [self.coreDataStack.mainContext existingObjectWithID:blogID error:nil];
success([blog commentWithID:remoteComment.commentID]);
}];
}
} onQueue:dispatch_get_main_queue()];
} failure:^(NSError *error) {
DDLogError(@"Error loading comment for blog: %@", error);
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
}
- (void)loadCommentWithID:(NSNumber *)commentID
forPost:(ReaderPost *)post
success:(void (^)(Comment *comment))success
failure:(void (^)(NSError *))failure {
NSManagedObjectID *postID = post.objectID;
CommentServiceRemoteREST *service = [self restRemoteForSite:post.siteID];
[service getCommentWithID:commentID
success:^(RemoteComment *remoteComment) {
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
ReaderPost *post = [context existingObjectWithID:postID error:nil];
if (!post) {
return;
}
Comment *comment = [post commentWithID:remoteComment.commentID];
if (!comment) {
comment = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Comment class]) inManagedObjectContext:context];
comment.dateCreated = [NSDate new];
}
comment.post = post;
[self updateComment:comment withRemoteComment:remoteComment];
} completion:^{
if (success) {
[self.coreDataStack.mainContext performBlock:^{
ReaderPost *post = [self.coreDataStack.mainContext existingObjectWithID:postID error:nil];
success([post commentWithID:remoteComment.commentID]);
}];
}
} onQueue:dispatch_get_main_queue()];
} failure:^(NSError *error) {
DDLogError(@"Error loading comment for post: %@", error);
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
}
// Upload comment
- (void)uploadComment:(Comment *)comment
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
id<CommentServiceRemote> remote = [self remoteForComment:comment];
RemoteComment *remoteComment = [self remoteCommentWithComment:comment];
NSManagedObjectID *commentObjectID = comment.objectID;
void (^successBlock)(RemoteComment *comment) = ^(RemoteComment *comment) {
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *commentInContext = [context existingObjectWithID:commentObjectID error:nil];
if (commentInContext) {
[self updateComment:commentInContext withRemoteComment:comment];
}
} completion:success onQueue:dispatch_get_main_queue()];
};
if (comment.commentID != 0) {
[remote updateComment:remoteComment
success:successBlock
failure:failure];
} else {
[remote createComment:remoteComment
success:successBlock
failure:failure];
}
}
// Approve
- (void)approveComment:(Comment *)comment
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
[self moderateComment:comment
withStatus:CommentStatusTypeApproved
success:success
failure:failure];
}
// Unapprove
- (void)unapproveComment:(Comment *)comment
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
[self moderateComment:comment
withStatus:CommentStatusTypePending
success:success
failure:failure];
}
// Spam
- (void)spamComment:(Comment *)comment
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
// If the Comment is not permanently deleted, don't remove it from the local cache as it can still be displayed.
if (!comment.deleteWillBePermanent) {
[self moderateComment:comment
withStatus:CommentStatusTypeSpam
success:success
failure:failure];
return;
}
NSManagedObjectID *commentID = comment.objectID;
[self moderateComment:comment
withStatus:CommentStatusTypeSpam
success:^{
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *commentInContext = [context existingObjectWithID:commentID error:nil];
if (commentInContext != nil){
[context deleteObject:commentInContext];
}
} completion:success onQueue:dispatch_get_main_queue()];
} failure: failure];
}
// Trash comment
- (void)trashComment:(Comment *)comment
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
[self moderateComment:comment
withStatus:CommentStatusTypeUnapproved
success:success
failure:failure];
}
// Delete comment
- (void)deleteComment:(Comment *)comment
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
// If this comment is local only, just delete. No need to query the endpoint or do any other work.
if (comment.commentID == 0) {
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *commentInContext = [context existingObjectWithID:comment.objectID error:nil];
if (commentInContext != nil) {
[context deleteObject:commentInContext];
}
} completion:success onQueue:dispatch_get_main_queue()];
return;
}
RemoteComment *remoteComment = [self remoteCommentWithComment:comment];
id<CommentServiceRemote> remote = [self remoteForBlog:comment.blog];
// If the Comment is not permanently deleted, don't remove it from the local cache as it can still be displayed.
if (!comment.deleteWillBePermanent) {
[remote trashComment:remoteComment success:success failure:failure];
return;
}
// For the best user experience we want to optimistically delete the comment.
// However, if there is an error we need to restore it.
NSManagedObjectID *blogObjID = comment.blog.objectID;
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *commentInContext = [context existingObjectWithID:comment.objectID error:nil];
if (commentInContext != nil) {
[context deleteObject:commentInContext];
}
} completion:^{
[remote trashComment:remoteComment success:success failure:^(NSError *error) {
// Failure. Restore the comment.
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Blog *blog = [context objectWithID:blogObjID];
if (!blog) {
return;
}
Comment *comment = [self createCommentForBlog:blog];
[self updateComment:comment withRemoteComment:remoteComment];
} completion:^{
if (failure) {
failure(error);
}
} onQueue:dispatch_get_main_queue()];
}];
} onQueue:dispatch_get_main_queue()];
}
#pragma mark - Post-centric methods
- (void)syncHierarchicalCommentsForPost:(ReaderPost *)post
page:(NSUInteger)page
success:(void (^)(BOOL hasMore, NSNumber *totalComments))success
failure:(void (^)(NSError *error))failure
{
[self syncHierarchicalCommentsForPost:post
page:page
topLevelComments:WPTopLevelHierarchicalCommentsPerPage
success:success
failure:failure];
}
- (void)syncHierarchicalCommentsForPost:(ReaderPost *)post
topLevelComments:(NSUInteger)number
success:(void (^)(BOOL hasMore, NSNumber *totalComments))success
failure:(void (^)(NSError *error))failure
{
[self syncHierarchicalCommentsForPost:post
page:1
topLevelComments:number
success:success
failure:failure];
}
- (void)syncHierarchicalCommentsForPost:(ReaderPost *)post
page:(NSUInteger)page
topLevelComments:(NSUInteger)number
success:(void (^)(BOOL hasMore, NSNumber *totalComments))success
failure:(void (^)(NSError *error))failure
{
NSManagedObjectID *postObjectID = post.objectID;
NSNumber *siteID = post.siteID;
NSNumber *postID = post.postID;
NSUInteger commentsPerPage = number ?: WPTopLevelHierarchicalCommentsPerPage;
NSUInteger pageNumber = page ?: 1;
CommentServiceRemoteREST *service = [self restRemoteForSite:siteID];
[service syncHierarchicalCommentsForPost:postID
page:pageNumber
number:commentsPerPage
success:^(NSArray *comments, NSNumber *totalComments) {
BOOL __block includesNewComments = NO;
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
NSError *error;
ReaderPost *aPost = [context existingObjectWithID:postObjectID error:&error];
if (!aPost) {
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
return;
}
includesNewComments = [self mergeHierarchicalComments:comments forPage:page forPost:aPost];
} completion:^{
if (!success) {
return;
}
[self.coreDataStack.mainContext performBlock:^{
NSError *error;
ReaderPost *aPost = [self.coreDataStack.mainContext existingObjectWithID:postObjectID error:&error];
if (!aPost) {
if (failure) {
failure(error);
}
return;
}
// There are no more comments when:
// - There are fewer top level comments in the results than requested
// - Page > 1, the number of top level comments matches those requested, but there are no new comments
// We check this way because the API can return the last page of results instead
// of returning zero results when the requested page is the last + 1.
NSArray *parents = [self topLevelCommentsForPage:page forPost:aPost];
BOOL hasMore = YES;
if (([parents count] < WPTopLevelHierarchicalCommentsPerPage) || (page > 1 && !includesNewComments)) {
hasMore = NO;
}
success(hasMore, totalComments);
}];
} onQueue:dispatch_get_main_queue()];
} failure:^(NSError *error) {
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
}
- (NSInteger)numberOfHierarchicalPagesSyncedforPost:(ReaderPost *)post
{
NSSet *topComments = [post.comments filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"parentID = 0"]];
CGFloat page = [topComments count] / WPTopLevelHierarchicalCommentsPerPage;
return (NSInteger)page;
}
#pragma mark - REST Helpers
- (NSString *)sanitizeCommentContent:(NSString *)string isPrivateSite:(BOOL)isPrivateSite
{
NSString *content = string;
content = [RichContentFormatter removeTrailingBreakTags:content];
content = [RichContentFormatter formatContentString:content isPrivateSite:isPrivateSite];
return content;
}
// Edition
- (void)updateCommentWithID:(NSNumber *)commentID
siteID:(NSNumber *)siteID
content:(NSString *)content
success:(void (^)(RemoteComment *comment))success
failure:(void (^)(NSError *error))failure
{
CommentServiceRemoteREST *remote = [self restRemoteForSite:siteID];
[remote updateCommentWithID:commentID
content:content
success:success
failure:failure];
}
// Replies
- (void)replyToPost:(ReaderPost *)post
content:(NSString *)content
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
// Create and optimistically save a comment, based on the current wpcom acct
// post and content provided.
BOOL isPrivateSite = post.isBlogPrivate;
[self createHierarchicalCommentWithContent:content withParent:nil postObjectID:post.objectID siteID:post.siteID completion:^(NSManagedObjectID *commentID) {
if (!commentID) {
NSError *error = [NSError errorWithDomain:WKErrorDomain code:WKErrorUnknown userInfo:@{NSDebugDescriptionErrorKey: @"Failed to create a comment for a post"}];
if (failure) {
failure(error);
}
[WordPressAppDelegate logError:error];
return;
}
void (^successBlock)(RemoteComment *remoteComment) = ^void(RemoteComment *remoteComment) {
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *comment = [context existingObjectWithID:commentID error:nil];
if (!comment) {
return;
}
remoteComment.content = [self sanitizeCommentContent:remoteComment.content isPrivateSite:isPrivateSite];
[self updateHierarchicalComment:comment withRemoteComment:remoteComment];
} completion:success onQueue:dispatch_get_main_queue()];
};
void (^failureBlock)(NSError *error) = ^void(NSError *error) {
// Remove the optimistically saved comment.
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *commentInContext = [context existingObjectWithID:commentID error:nil];
if (commentInContext != nil) {
[context deleteObject:commentInContext];
}
} completion:^{
if (failure) {
failure(error);
}
} onQueue:dispatch_get_main_queue()];
};
CommentServiceRemoteREST *remote = [self restRemoteForSite:post.siteID];
[remote replyToPostWithID:post.postID
content:content
success:successBlock
failure:failureBlock];
}];
}
- (void)replyToHierarchicalCommentWithID:(NSNumber *)commentID
post:(ReaderPost *)post
content:(NSString *)content
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
// Create and optimistically save a comment, based on the current wpcom acct
// post and content provided.
BOOL isPrivateSite = post.isBlogPrivate;
[self createHierarchicalCommentWithContent:content withParent:nil postObjectID:post.objectID siteID:post.siteID completion:^(NSManagedObjectID *commentObjectID) {
if (!commentObjectID) {
NSError *error = [NSError errorWithDomain:WKErrorDomain code:WKErrorUnknown userInfo:@{NSDebugDescriptionErrorKey: @"Failed to create a comment for a post"}];
if (failure) {
failure(error);
}
[WordPressAppDelegate logError:error];
return;
}
void (^successBlock)(RemoteComment *remoteComment) = ^void(RemoteComment *remoteComment) {
// Update and save the comment
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *comment = [context existingObjectWithID:commentObjectID error:nil];
if (!comment) {
return;
}
remoteComment.content = [self sanitizeCommentContent:remoteComment.content isPrivateSite:isPrivateSite];
[self updateHierarchicalComment:comment withRemoteComment:remoteComment];
} completion:success onQueue:dispatch_get_main_queue()];
};
void (^failureBlock)(NSError *error) = ^void(NSError *error) {
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *commentInContext = [context existingObjectWithID:commentObjectID error:nil];
if (!commentInContext) {
return;
}
// Remove the optimistically saved comment.
[context deleteObject:commentInContext];
ReaderPost *post = (ReaderPost *)commentInContext.post;
post.commentCount = @([post.commentCount integerValue] - 1);
} completion:^{
if (failure) {
failure(error);
}
} onQueue:dispatch_get_main_queue()];
};
CommentServiceRemoteREST *remote = [self restRemoteForSite:post.siteID];
[remote replyToCommentWithID:commentID
content:content
success:successBlock
failure:failureBlock];
}];
}
- (void)replyToCommentWithID:(NSNumber *)commentID
siteID:(NSNumber *)siteID
content:(NSString *)content
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
CommentServiceRemoteREST *remote = [self restRemoteForSite:siteID];
[remote replyToCommentWithID:commentID
content:content
success:^(RemoteComment * __unused comment){
if (success){
success();
}
}
failure:failure];
}
// Likes
- (void)likeCommentWithID:(NSNumber *)commentID
siteID:(NSNumber *)siteID
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
CommentServiceRemoteREST *remote = [self restRemoteForSite:siteID];
[remote likeCommentWithID:commentID
success:success
failure:failure];
}
- (void)unlikeCommentWithID:(NSNumber *)commentID
siteID:(NSNumber *)siteID
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
CommentServiceRemoteREST *remote = [self restRemoteForSite:siteID];
[remote unlikeCommentWithID:commentID
success:success
failure:failure];
}
// Moderation
- (void)approveCommentWithID:(NSNumber *)commentID
siteID:(NSNumber *)siteID
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
CommentServiceRemoteREST *remote = [self restRemoteForSite:siteID];
[remote moderateCommentWithID:commentID
status:@"approved"
success:success
failure:failure];
}
- (void)unapproveCommentWithID:(NSNumber *)commentID
siteID:(NSNumber *)siteID
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
CommentServiceRemoteREST *remote = [self restRemoteForSite:siteID];
[remote moderateCommentWithID:commentID
status:@"unapproved"
success:success
failure:failure];
}
- (void)spamCommentWithID:(NSNumber *)commentID
siteID:(NSNumber *)siteID
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
CommentServiceRemoteREST *remote = [self restRemoteForSite:siteID];
[remote moderateCommentWithID:commentID
status:[Comment descriptionFor:CommentStatusTypeSpam]
success:success
failure:failure];
}
- (void)deleteCommentWithID:(NSNumber *)commentID
siteID:(NSNumber *)siteID
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
CommentServiceRemoteREST *remote = [self restRemoteForSite:siteID];
[remote trashCommentWithID:commentID
success:success
failure:failure];
}
- (void)toggleLikeStatusForComment:(Comment *)comment
siteID:(NSNumber *)siteID
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
NSManagedObjectID *commentObjectID = comment.objectID;
BOOL isLikedOriginally = comment.isLiked;
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
// toggle the like status and change the like count and save it
Comment *comment = [context existingObjectWithID:commentObjectID error:nil];
comment.isLiked = !isLikedOriginally;
comment.likeCount = comment.likeCount + (comment.isLiked ? 1 : -1);
} completion:^{
// This block will reverse the like/unlike action
void (^failureBlock)(NSError *) = ^(NSError *error) {
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *comment = [context existingObjectWithID:commentObjectID error:nil];
DDLogError(@"Error while %@ comment: %@", comment.isLiked ? @"liking" : @"unliking", error);
comment.isLiked = isLikedOriginally;
comment.likeCount = comment.likeCount + (comment.isLiked ? 1 : -1);
} completion:^{
if (failure) {
failure(error);
}
} onQueue:dispatch_get_main_queue()];
};
NSNumber *commentID = [NSNumber numberWithInt:comment.commentID];
if (!isLikedOriginally) {
[self likeCommentWithID:commentID siteID:siteID success:success failure:failureBlock];
}
else {
[self unlikeCommentWithID:commentID siteID:siteID success:success failure:failureBlock];
}
} onQueue:dispatch_get_main_queue()];
}
#pragma mark - Private methods
// Deletes orphaned comments. Does not save context.
- (void)deleteUnownedCommentsInContext:(NSManagedObjectContext *)context
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([Comment class])];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"post = NULL && blog = NULL"];
NSError *error;
NSArray *results = [context executeFetchRequest:fetchRequest error:&error];
if (error) {
DDLogError(@"Error fetching orphaned comments: %@", error);
}
for (Comment *comment in results) {
[context deleteObject:comment];
}
}
#pragma mark - Blog centric methods
// Generic moderation
- (void)moderateComment:(Comment *)comment
withStatus:(CommentStatusType)status
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
NSString *currentStatus = [Comment descriptionFor:status];
NSString *prevStatus = comment.status;
if ([prevStatus isEqualToString:currentStatus]) {
if (success) {
success();
}
return;
}
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *commentInContext = [context existingObjectWithID:comment.objectID error:nil];
commentInContext.status = currentStatus;
}];
comment.status = currentStatus;
id <CommentServiceRemote> remote = [self remoteForComment:comment];
RemoteComment *remoteComment = [self remoteCommentWithComment:comment];
[remote moderateComment:remoteComment
success:^(RemoteComment * __unused comment) {
if (success) {
success();
}
} failure:^(NSError *error) {
DDLogError(@"Error moderating comment: %@", error);
[self.coreDataStack performAndSaveUsingBlock:^(NSManagedObjectContext *context) {
Comment *commentInContext = [context existingObjectWithID:comment.objectID error:nil];
commentInContext.status = prevStatus;
} completion:^{
if (failure) {
failure(error);
}
} onQueue:dispatch_get_main_queue()];
}];
}
- (void)mergeComments:(NSArray *)comments
forBlog:(Blog *)blog
purgeExisting:(BOOL)purgeExisting
{
NSParameterAssert(blog.managedObjectContext != nil);
NSMutableArray *commentsToKeep = [NSMutableArray array];
for (RemoteComment *remoteComment in comments) {
Comment *comment = [blog commentWithID:remoteComment.commentID];
if (!comment) {
comment = [self createCommentForBlog:blog];
}
[self updateComment:comment withRemoteComment:remoteComment];
[commentsToKeep addObject:comment];
}
if (purgeExisting) {
NSSet *existingComments = blog.comments;