session-ios/SignalServiceKit/src/Messages/OWSOutgoingReceiptManager.m

302 lines
10 KiB
Mathematica
Raw Normal View History

2018-10-11 18:51:58 +02:00
//
// Copyright (c) 2018 Open Whisper Systems. All rights reserved.
//
2018-10-11 21:29:01 +02:00
#import "OWSOutgoingReceiptManager.h"
2018-10-11 18:51:58 +02:00
#import "AppReadiness.h"
#import "OWSMessageSender.h"
#import "OWSPrimaryStorage.h"
#import "OWSReceiptsForSenderMessage.h"
#import "SSKEnvironment.h"
#import "TSContactThread.h"
#import "TSYapDatabaseObject.h"
2018-10-11 19:18:07 +02:00
#import <Reachability/Reachability.h>
2018-10-11 18:51:58 +02:00
#import <SignalServiceKit/SignalServiceKit-Swift.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSUInteger, OWSReceiptType) {
OWSReceiptType_Delivery,
OWSReceiptType_Read,
};
NSString *const kOutgoingDeliveryReceiptManagerCollection = @"kOutgoingDeliveryReceiptManagerCollection";
NSString *const kOutgoingReadReceiptManagerCollection = @"kOutgoingReadReceiptManagerCollection";
2018-10-11 18:51:58 +02:00
2018-10-11 21:29:01 +02:00
@interface OWSOutgoingReceiptManager ()
2018-10-11 18:51:58 +02:00
@property (nonatomic, readonly) YapDatabaseConnection *dbConnection;
2018-10-11 19:18:07 +02:00
@property (nonatomic) Reachability *reachability;
// This property should only be accessed on the serialQueue.
2018-10-11 18:51:58 +02:00
@property (nonatomic) BOOL isProcessing;
@end
#pragma mark -
2018-10-11 21:29:01 +02:00
@implementation OWSOutgoingReceiptManager
2018-10-11 18:51:58 +02:00
2018-10-12 17:49:50 +02:00
+ (instancetype)sharedManager
{
2018-10-11 21:29:01 +02:00
OWSAssert(SSKEnvironment.shared.outgoingReceiptManager);
2018-10-11 18:51:58 +02:00
2018-10-11 21:29:01 +02:00
return SSKEnvironment.shared.outgoingReceiptManager;
2018-10-11 18:51:58 +02:00
}
2018-10-12 17:49:50 +02:00
- (instancetype)initWithPrimaryStorage:(OWSPrimaryStorage *)primaryStorage
{
2018-10-11 18:51:58 +02:00
self = [super init];
if (!self) {
return self;
}
2018-10-11 19:18:07 +02:00
self.reachability = [Reachability reachabilityForInternetConnection];
2018-10-11 18:51:58 +02:00
_dbConnection = primaryStorage.newDatabaseConnection;
OWSSingletonAssert();
2018-10-11 19:18:07 +02:00
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged)
name:kReachabilityChangedNotification
object:nil];
2018-10-11 18:51:58 +02:00
// Start processing.
[AppReadiness runNowOrWhenAppIsReady:^{
2018-10-12 20:08:42 +02:00
[self process];
2018-10-11 18:51:58 +02:00
}];
return self;
}
2018-10-12 17:49:50 +02:00
- (void)dealloc
{
2018-10-11 18:51:58 +02:00
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Dependencies
2018-10-12 17:49:50 +02:00
- (OWSMessageSender *)messageSender
{
2018-10-11 18:51:58 +02:00
OWSAssertDebug(SSKEnvironment.shared.messageSender);
return SSKEnvironment.shared.messageSender;
}
#pragma mark -
2018-10-12 17:49:50 +02:00
- (dispatch_queue_t)serialQueue
{
2018-10-11 18:51:58 +02:00
static dispatch_queue_t _serialQueue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_serialQueue = dispatch_queue_create("org.whispersystems.outgoingReceipts", DISPATCH_QUEUE_SERIAL);
2018-10-11 18:51:58 +02:00
});
return _serialQueue;
}
// Schedules a processing pass, unless one is already scheduled.
2018-10-12 20:08:42 +02:00
- (void)process {
2018-10-11 18:51:58 +02:00
OWSAssertDebug(AppReadiness.isAppReady);
dispatch_async(self.serialQueue, ^{
if (self.isProcessing) {
return;
}
2018-10-12 20:08:42 +02:00
OWSLogVerbose(@"Processing outbound receipts.");
2018-10-11 18:51:58 +02:00
2018-10-12 20:08:42 +02:00
self.isProcessing = YES;
2018-10-11 18:51:58 +02:00
2018-10-12 20:08:42 +02:00
if (!self.reachability.isReachable) {
// No network availability; abort.
self.isProcessing = NO;
return;
}
2018-10-11 18:51:58 +02:00
2018-10-12 20:08:42 +02:00
NSMutableArray<AnyPromise *> *sendPromises = [NSMutableArray array];
[sendPromises addObjectsFromArray:[self sendReceiptsForReceiptType:OWSReceiptType_Delivery]];
[sendPromises addObjectsFromArray:[self sendReceiptsForReceiptType:OWSReceiptType_Read]];
2018-10-11 19:18:07 +02:00
2018-10-12 20:08:42 +02:00
if (sendPromises.count < 1) {
// No work to do; abort.
self.isProcessing = NO;
return;
}
2018-10-12 20:08:42 +02:00
AnyPromise *completionPromise = PMKJoin(sendPromises);
2018-10-13 21:21:46 +02:00
completionPromise.ensure(^() {
2018-10-12 20:08:42 +02:00
// Wait N seconds before conducting another pass.
// This allows time for a batch to accumulate.
//
// We want a value high enough to allow us to effectively de-duplicate
// receipts without being so high that we incur so much latency that
// the user notices.
const CGFloat kProcessingFrequencySeconds = 3.f;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kProcessingFrequencySeconds * NSEC_PER_SEC)),
self.serialQueue,
^{
self.isProcessing = NO;
[self process];
});
});
[completionPromise retainUntilComplete];
});
}
2018-10-12 20:08:42 +02:00
- (NSArray<AnyPromise *> *)sendReceiptsForReceiptType:(OWSReceiptType)receiptType {
NSString *collection = [self collectionForReceiptType:receiptType];
NSMutableDictionary<NSString *, NSSet<NSNumber *> *> *queuedReceiptMap = [NSMutableDictionary new];
2018-10-11 18:51:58 +02:00
[self.dbConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
[transaction enumerateKeysAndObjectsInCollection:collection
2018-10-11 18:51:58 +02:00
usingBlock:^(NSString *key, id object, BOOL *stop) {
NSString *recipientId = key;
NSSet<NSNumber *> *timestamps = object;
queuedReceiptMap[recipientId] = [timestamps copy];
2018-10-11 18:51:58 +02:00
}];
}];
2018-10-11 18:59:40 +02:00
NSMutableArray<AnyPromise *> *sendPromises = [NSMutableArray array];
2018-10-11 18:51:58 +02:00
for (NSString *recipientId in queuedReceiptMap) {
NSSet<NSNumber *> *timestamps = queuedReceiptMap[recipientId];
2018-10-11 18:51:58 +02:00
if (timestamps.count < 1) {
OWSFailDebug(@"Missing timestamps.");
continue;
}
TSThread *thread = [TSContactThread getOrCreateThreadWithContactId:recipientId];
OWSReceiptsForSenderMessage *message;
NSString *receiptName;
switch (receiptType) {
case OWSReceiptType_Delivery:
message =
[OWSReceiptsForSenderMessage deliveryReceiptsForSenderMessageWithThread:thread
messageTimestamps:timestamps.allObjects];
receiptName = @"Delivery";
break;
case OWSReceiptType_Read:
message = [OWSReceiptsForSenderMessage readReceiptsForSenderMessageWithThread:thread
messageTimestamps:timestamps.allObjects];
receiptName = @"Read";
break;
}
2018-10-11 18:51:58 +02:00
2018-10-11 18:59:40 +02:00
AnyPromise *sendPromise = [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) {
[self.messageSender sendMessage:message
2018-10-11 18:59:40 +02:00
success:^{
OWSLogInfo(
@"Successfully sent %lu %@ receipts to sender.", (unsigned long)timestamps.count, receiptName);
2018-10-11 18:51:58 +02:00
// DURABLE CLEANUP - we could replace the custom durability logic in this class
// with a durable JobQueue.
2018-10-12 20:08:42 +02:00
[self dequeueReceiptsWithRecipientId:recipientId timestamps:timestamps receiptType:receiptType];
2018-10-11 18:51:58 +02:00
2018-10-11 18:59:40 +02:00
// The value doesn't matter, we just need any non-NSError value.
resolve(@(1));
}
failure:^(NSError *error) {
OWSLogError(@"Failed to send %@ receipts to sender with error: %@", receiptName, error);
2018-10-11 18:51:58 +02:00
2018-10-11 18:59:40 +02:00
resolve(error);
}];
}];
[sendPromises addObject:sendPromise];
}
return [sendPromises copy];
2018-10-11 18:51:58 +02:00
}
2018-10-12 17:49:50 +02:00
- (void)enqueueDeliveryReceiptForEnvelope:(SSKProtoEnvelope *)envelope
{
[self enqueueReceiptWithRecipientId:envelope.source
timestamp:envelope.timestamp
2018-10-12 20:08:42 +02:00
receiptType:OWSReceiptType_Delivery];
}
2018-10-11 18:51:58 +02:00
2018-10-12 20:08:42 +02:00
- (void)enqueueReadReceiptForEnvelope:(NSString *)messageAuthorId timestamp:(uint64_t)timestamp {
[self enqueueReceiptWithRecipientId:messageAuthorId timestamp:timestamp receiptType:OWSReceiptType_Read];
2018-10-11 18:51:58 +02:00
}
- (void)enqueueReceiptWithRecipientId:(NSString *)recipientId
timestamp:(uint64_t)timestamp
2018-10-12 20:08:42 +02:00
receiptType:(OWSReceiptType)receiptType {
NSString *collection = [self collectionForReceiptType:receiptType];
2018-10-11 18:51:58 +02:00
if (recipientId.length < 1) {
OWSFailDebug(@"Invalid recipient id.");
return;
}
if (timestamp < 1) {
OWSFailDebug(@"Invalid timestamp.");
return;
}
dispatch_async(self.serialQueue, ^{
[self.dbConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
NSSet<NSNumber *> *_Nullable oldTimestamps = [transaction objectForKey:recipientId inCollection:collection];
2018-10-11 18:51:58 +02:00
NSMutableSet<NSNumber *> *newTimestamps
= (oldTimestamps ? [oldTimestamps mutableCopy] : [NSMutableSet new]);
[newTimestamps addObject:@(timestamp)];
[transaction setObject:newTimestamps forKey:recipientId inCollection:collection];
2018-10-11 18:51:58 +02:00
}];
2018-10-12 20:08:42 +02:00
[self process];
2018-10-11 18:51:58 +02:00
});
}
- (void)dequeueReceiptsWithRecipientId:(NSString *)recipientId
timestamps:(NSSet<NSNumber *> *)timestamps
2018-10-12 20:08:42 +02:00
receiptType:(OWSReceiptType)receiptType {
NSString *collection = [self collectionForReceiptType:receiptType];
2018-10-11 18:51:58 +02:00
if (recipientId.length < 1) {
OWSFailDebug(@"Invalid recipient id.");
return;
}
if (timestamps.count < 1) {
OWSFailDebug(@"Invalid timestamps.");
return;
}
dispatch_async(self.serialQueue, ^{
[self.dbConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
NSSet<NSNumber *> *_Nullable oldTimestamps = [transaction objectForKey:recipientId inCollection:collection];
2018-10-11 18:51:58 +02:00
NSMutableSet<NSNumber *> *newTimestamps
= (oldTimestamps ? [oldTimestamps mutableCopy] : [NSMutableSet new]);
[newTimestamps minusSet:timestamps];
if (newTimestamps.count > 0) {
[transaction setObject:newTimestamps forKey:recipientId inCollection:collection];
2018-10-11 18:51:58 +02:00
} else {
[transaction removeObjectForKey:recipientId inCollection:collection];
2018-10-11 18:51:58 +02:00
}
}];
});
}
2018-10-12 17:49:50 +02:00
- (void)reachabilityChanged
{
2018-10-11 19:18:07 +02:00
OWSAssertIsOnMainThread();
2018-10-12 20:08:42 +02:00
[self process];
}
- (NSString *)collectionForReceiptType:(OWSReceiptType)receiptType {
switch (receiptType) {
case OWSReceiptType_Delivery:
return kOutgoingDeliveryReceiptManagerCollection;
case OWSReceiptType_Read:
return kOutgoingReadReceiptManagerCollection;
}
2018-10-11 19:18:07 +02:00
}
2018-10-11 18:51:58 +02:00
@end
NS_ASSUME_NONNULL_END