mirror of https://github.com/oxen-io/session-ios
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
418 lines
15 KiB
Matlab
418 lines
15 KiB
Matlab
8 years ago
|
//
|
||
|
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
|
||
|
//
|
||
9 years ago
|
|
||
|
#import "OWSDisappearingMessagesJob.h"
|
||
9 years ago
|
#import "ContactsManagerProtocol.h"
|
||
9 years ago
|
#import "NSDate+millisecondTimeStamp.h"
|
||
8 years ago
|
#import "NSTimer+OWS.h"
|
||
9 years ago
|
#import "OWSDisappearingConfigurationUpdateInfoMessage.h"
|
||
9 years ago
|
#import "OWSDisappearingMessagesConfiguration.h"
|
||
|
#import "OWSDisappearingMessagesFinder.h"
|
||
9 years ago
|
#import "TSIncomingMessage.h"
|
||
9 years ago
|
#import "TSMessage.h"
|
||
8 years ago
|
#import "TSStorageManager.h"
|
||
9 years ago
|
|
||
|
NS_ASSUME_NONNULL_BEGIN
|
||
|
|
||
|
@interface OWSDisappearingMessagesJob ()
|
||
|
|
||
8 years ago
|
@property (nonatomic, readonly) TSStorageManager *storageManager;
|
||
|
|
||
8 years ago
|
@property (nonatomic, readonly) YapDatabaseConnection *databaseConnection;
|
||
|
|
||
9 years ago
|
@property (nonatomic, readonly) OWSDisappearingMessagesFinder *disappearingMessagesFinder;
|
||
8 years ago
|
|
||
|
// These three properties should only be accessed on the main thread.
|
||
|
@property (nonatomic) BOOL hasStarted;
|
||
|
@property (nonatomic, nullable) NSTimer *timer;
|
||
|
@property (nonatomic, nullable) NSDate *timerScheduleDate;
|
||
9 years ago
|
|
||
|
@end
|
||
|
|
||
8 years ago
|
#pragma mark -
|
||
|
|
||
9 years ago
|
@implementation OWSDisappearingMessagesJob
|
||
|
|
||
8 years ago
|
+ (instancetype)sharedJob
|
||
|
{
|
||
|
static OWSDisappearingMessagesJob *sharedJob = nil;
|
||
|
static dispatch_once_t onceToken;
|
||
|
dispatch_once(&onceToken, ^{
|
||
|
sharedJob = [[self alloc] initWithStorageManager:[TSStorageManager sharedManager]];
|
||
|
});
|
||
|
return sharedJob;
|
||
|
}
|
||
|
|
||
9 years ago
|
- (instancetype)initWithStorageManager:(TSStorageManager *)storageManager
|
||
|
{
|
||
|
self = [super init];
|
||
|
if (!self) {
|
||
|
return self;
|
||
|
}
|
||
|
|
||
8 years ago
|
_storageManager = storageManager;
|
||
8 years ago
|
_databaseConnection = storageManager.newDatabaseConnection;
|
||
8 years ago
|
_disappearingMessagesFinder = [OWSDisappearingMessagesFinder new];
|
||
9 years ago
|
|
||
8 years ago
|
OWSSingletonAssert();
|
||
|
|
||
8 years ago
|
[[NSNotificationCenter defaultCenter] addObserver:self
|
||
|
selector:@selector(applicationDidBecomeActive:)
|
||
|
name:UIApplicationDidBecomeActiveNotification
|
||
|
object:nil];
|
||
|
[[NSNotificationCenter defaultCenter] addObserver:self
|
||
|
selector:@selector(applicationWillResignActive:)
|
||
|
name:UIApplicationWillResignActiveNotification
|
||
|
object:nil];
|
||
|
|
||
9 years ago
|
return self;
|
||
|
}
|
||
|
|
||
8 years ago
|
- (void)dealloc
|
||
|
{
|
||
|
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||
|
}
|
||
|
|
||
8 years ago
|
+ (dispatch_queue_t)serialQueue
|
||
|
{
|
||
|
static dispatch_queue_t queue = nil;
|
||
|
static dispatch_once_t onceToken;
|
||
|
dispatch_once(&onceToken, ^{
|
||
|
queue = dispatch_queue_create("org.whispersystems.disappearing.messages", DISPATCH_QUEUE_SERIAL);
|
||
|
});
|
||
|
return queue;
|
||
|
}
|
||
|
|
||
8 years ago
|
// This method should only be called on the serialQueue.
|
||
9 years ago
|
- (void)run
|
||
|
{
|
||
|
uint64_t now = [NSDate ows_millisecondTimeStamp];
|
||
|
|
||
|
__block uint expirationCount = 0;
|
||
8 years ago
|
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *_Nonnull transaction) {
|
||
8 years ago
|
[self.disappearingMessagesFinder enumerateExpiredMessagesWithBlock:^(TSMessage *message) {
|
||
|
// sanity check
|
||
|
if (message.expiresAt > now) {
|
||
|
DDLogError(
|
||
|
@"%@ Refusing to remove message which doesn't expire until: %lld", self.tag, message.expiresAt);
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
DDLogDebug(@"%@ Removing message which expired at: %lld", self.tag, message.expiresAt);
|
||
|
[message removeWithTransaction:transaction];
|
||
|
expirationCount++;
|
||
9 years ago
|
}
|
||
8 years ago
|
transaction:transaction];
|
||
9 years ago
|
}];
|
||
|
|
||
8 years ago
|
DDLogDebug(@"%@ Removed %u expired messages", self.tag, expirationCount);
|
||
9 years ago
|
}
|
||
|
|
||
8 years ago
|
// This method should only be called on the serialQueue.
|
||
9 years ago
|
- (void)runLoop
|
||
|
{
|
||
8 years ago
|
DDLogVerbose(@"%@ Run", self.tag);
|
||
9 years ago
|
|
||
|
[self run];
|
||
|
|
||
|
uint64_t now = [NSDate ows_millisecondTimeStamp];
|
||
8 years ago
|
__block NSNumber *nextExpirationTimestampNumber;
|
||
8 years ago
|
[self.databaseConnection readWithBlock:^(YapDatabaseReadTransaction *_Nonnull transaction) {
|
||
8 years ago
|
nextExpirationTimestampNumber =
|
||
|
[self.disappearingMessagesFinder nextExpirationTimestampWithTransaction:transaction];
|
||
|
}];
|
||
9 years ago
|
if (!nextExpirationTimestampNumber) {
|
||
|
// In theory we could kill the loop here. It should resume when the next expiring message is saved,
|
||
|
// But this is a safeguard for any race conditions that exist while running the job as a new message is saved.
|
||
8 years ago
|
DDLogDebug(@"%@ No more expiring messages.", self.tag);
|
||
|
[self runLater];
|
||
9 years ago
|
return;
|
||
|
}
|
||
|
|
||
|
uint64_t nextExpirationAt = [nextExpirationTimestampNumber unsignedLongLongValue];
|
||
8 years ago
|
[self runByDate:[NSDate ows_dateWithMillisecondsSince1970:MAX(nextExpirationAt, now)]];
|
||
|
}
|
||
9 years ago
|
|
||
8 years ago
|
+ (void)setExpirationForMessage:(TSMessage *)message
|
||
|
{
|
||
|
dispatch_async(self.serialQueue, ^{
|
||
|
[[self sharedJob] setExpirationForMessage:message];
|
||
|
});
|
||
9 years ago
|
}
|
||
|
|
||
|
- (void)setExpirationForMessage:(TSMessage *)message
|
||
|
{
|
||
|
if (!message.isExpiringMessage) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
OWSDisappearingMessagesConfiguration *disappearingConfig =
|
||
|
[OWSDisappearingMessagesConfiguration fetchObjectWithUniqueID:message.uniqueThreadId];
|
||
|
|
||
|
if (!disappearingConfig.isEnabled) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
[self setExpirationForMessage:message expirationStartedAt:[NSDate ows_millisecondTimeStamp]];
|
||
|
}
|
||
|
|
||
8 years ago
|
+ (void)setExpirationForMessage:(TSMessage *)message expirationStartedAt:(uint64_t)expirationStartedAt
|
||
|
{
|
||
|
dispatch_async(self.serialQueue, ^{
|
||
|
[[self sharedJob] setExpirationForMessage:message expirationStartedAt:expirationStartedAt];
|
||
|
});
|
||
|
}
|
||
|
|
||
|
// This method should only be called on the serialQueue.
|
||
8 years ago
|
- (void)setExpirationForMessage:(TSMessage *)message expirationStartedAt:(uint64_t)expirationStartedAt
|
||
8 years ago
|
{
|
||
8 years ago
|
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *_Nonnull transaction) {
|
||
8 years ago
|
[self setExpirationForMessage:message expirationStartedAt:expirationStartedAt transaction:transaction];
|
||
|
}];
|
||
8 years ago
|
}
|
||
|
|
||
8 years ago
|
- (void)setExpirationForMessage:(TSMessage *)message
|
||
|
expirationStartedAt:(uint64_t)expirationStartedAt
|
||
|
transaction:(YapDatabaseReadWriteTransaction *_Nonnull)transaction
|
||
9 years ago
|
{
|
||
8 years ago
|
OWSAssert(transaction);
|
||
|
|
||
9 years ago
|
if (!message.isExpiringMessage) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
int startedSecondsAgo = [NSDate new].timeIntervalSince1970 - expirationStartedAt / 1000.0;
|
||
|
DDLogDebug(@"%@ Starting expiration for message read %d seconds ago", self.tag, startedSecondsAgo);
|
||
|
|
||
|
// Don't clobber if multiple actions simultaneously triggered expiration.
|
||
|
if (message.expireStartedAt == 0 || message.expireStartedAt > expirationStartedAt) {
|
||
|
message.expireStartedAt = expirationStartedAt;
|
||
8 years ago
|
[message saveWithTransaction:transaction];
|
||
9 years ago
|
}
|
||
|
|
||
|
// Necessary that the async expiration run happens *after* the message is saved with expiration configuration.
|
||
8 years ago
|
[self runByDate:[NSDate ows_dateWithMillisecondsSince1970:message.expiresAt]];
|
||
|
}
|
||
|
|
||
|
+ (void)setExpirationsForThread:(TSThread *)thread
|
||
|
{
|
||
|
dispatch_async(self.serialQueue, ^{
|
||
|
[[self sharedJob] setExpirationsForThread:thread];
|
||
|
});
|
||
9 years ago
|
}
|
||
|
|
||
8 years ago
|
// This method should only be called on the serialQueue.
|
||
9 years ago
|
- (void)setExpirationsForThread:(TSThread *)thread
|
||
|
{
|
||
|
uint64_t now = [NSDate ows_millisecondTimeStamp];
|
||
8 years ago
|
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *_Nonnull transaction) {
|
||
8 years ago
|
[self.disappearingMessagesFinder
|
||
|
enumerateUnstartedExpiringMessagesInThread:thread
|
||
|
block:^(TSMessage *_Nonnull message) {
|
||
|
DDLogWarn(
|
||
|
@"%@ Starting expiring message which should have already "
|
||
|
@"been started.",
|
||
|
self.tag);
|
||
|
// specify "now" in case D.M. have since been disabled, but we have
|
||
|
// existing unstarted expiring messages that still need to expire.
|
||
|
[self setExpirationForMessage:message
|
||
|
expirationStartedAt:now
|
||
|
transaction:transaction];
|
||
|
}
|
||
|
transaction:transaction];
|
||
|
}];
|
||
9 years ago
|
}
|
||
|
|
||
8 years ago
|
+ (void)becomeConsistentWithConfigurationForMessage:(TSMessage *)message
|
||
|
contactsManager:(id<ContactsManagerProtocol>)contactsManager
|
||
9 years ago
|
{
|
||
8 years ago
|
dispatch_async(self.serialQueue, ^{
|
||
|
[[self sharedJob] becomeConsistentWithConfigurationForMessage:message contactsManager:contactsManager];
|
||
|
});
|
||
9 years ago
|
}
|
||
|
|
||
9 years ago
|
- (void)becomeConsistentWithConfigurationForMessage:(TSMessage *)message
|
||
|
contactsManager:(id<ContactsManagerProtocol>)contactsManager
|
||
|
{
|
||
|
// Become eventually consistent in the case that the remote changed their settings at the same time.
|
||
|
// Also in case remote doesn't support expiring messages
|
||
|
OWSDisappearingMessagesConfiguration *disappearingMessagesConfiguration =
|
||
9 years ago
|
[OWSDisappearingMessagesConfiguration fetchOrCreateDefaultWithThreadId:message.uniqueThreadId];
|
||
9 years ago
|
|
||
|
BOOL changed = NO;
|
||
|
if (message.expiresInSeconds == 0) {
|
||
|
if (disappearingMessagesConfiguration.isEnabled) {
|
||
|
changed = YES;
|
||
|
DDLogWarn(@"%@ Received remote message which had no expiration set, disabling our expiration to become "
|
||
|
@"consistent.",
|
||
|
self.tag);
|
||
|
disappearingMessagesConfiguration.enabled = NO;
|
||
|
[disappearingMessagesConfiguration save];
|
||
|
}
|
||
|
} else if (message.expiresInSeconds != disappearingMessagesConfiguration.durationSeconds) {
|
||
|
changed = YES;
|
||
|
DDLogInfo(
|
||
|
@"%@ Received remote message with different expiration set, updating our expiration to become consistent.",
|
||
|
self.tag);
|
||
|
disappearingMessagesConfiguration.enabled = YES;
|
||
|
disappearingMessagesConfiguration.durationSeconds = message.expiresInSeconds;
|
||
|
[disappearingMessagesConfiguration save];
|
||
|
}
|
||
|
|
||
|
if (!changed) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
if ([message isKindOfClass:[TSIncomingMessage class]]) {
|
||
|
TSIncomingMessage *incomingMessage = (TSIncomingMessage *)message;
|
||
9 years ago
|
NSString *contactName = [contactsManager displayNameForPhoneIdentifier:incomingMessage.authorId];
|
||
9 years ago
|
|
||
|
[[[OWSDisappearingConfigurationUpdateInfoMessage alloc] initWithTimestamp:message.timestamp
|
||
|
thread:message.thread
|
||
|
configuration:disappearingMessagesConfiguration
|
||
|
createdByRemoteName:contactName] save];
|
||
|
} else {
|
||
|
[[[OWSDisappearingConfigurationUpdateInfoMessage alloc] initWithTimestamp:message.timestamp
|
||
|
thread:message.thread
|
||
|
configuration:disappearingMessagesConfiguration]
|
||
|
save];
|
||
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
- (void)startIfNecessary
|
||
|
{
|
||
|
dispatch_async(dispatch_get_main_queue(), ^{
|
||
|
if (self.hasStarted) {
|
||
|
return;
|
||
|
}
|
||
|
self.hasStarted = YES;
|
||
|
|
||
|
[self runNow];
|
||
|
});
|
||
|
}
|
||
|
|
||
|
- (void)runNow
|
||
|
{
|
||
|
[self runByDate:[NSDate new] ignoreMinDelay:YES];
|
||
|
}
|
||
|
|
||
8 years ago
|
- (NSTimeInterval)maxDelaySeconds
|
||
|
{
|
||
|
// Don't run less often than once per N minutes.
|
||
|
return 5 * 60.f;
|
||
|
}
|
||
|
|
||
|
// Waits the maximum amount of time to run again.
|
||
|
- (void)runLater
|
||
|
{
|
||
|
[self runByDate:[NSDate dateWithTimeIntervalSinceNow:self.maxDelaySeconds] ignoreMinDelay:YES];
|
||
|
}
|
||
|
|
||
8 years ago
|
- (void)runByDate:(NSDate *)date
|
||
|
{
|
||
|
[self runByDate:date ignoreMinDelay:NO];
|
||
|
}
|
||
|
|
||
|
- (void)runByDate:(NSDate *)date ignoreMinDelay:(BOOL)ignoreMinDelay
|
||
|
{
|
||
|
OWSAssert(date);
|
||
|
|
||
|
dispatch_async(dispatch_get_main_queue(), ^{
|
||
8 years ago
|
if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
|
||
|
// Don't schedule run when inactive.
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
NSDateFormatter *dateFormatter = [NSDateFormatter new];
|
||
|
dateFormatter.dateStyle = NSDateFormatterNoStyle;
|
||
|
dateFormatter.timeStyle = kCFDateFormatterMediumStyle;
|
||
|
|
||
8 years ago
|
// Don't run more often than once per second.
|
||
|
const NSTimeInterval kMinDelaySeconds = ignoreMinDelay ? 0.f : 1.f;
|
||
|
NSTimeInterval delaySeconds
|
||
8 years ago
|
= MAX(kMinDelaySeconds, MIN(self.maxDelaySeconds, [date timeIntervalSinceDate:[NSDate new]]));
|
||
8 years ago
|
NSDate *timerScheduleDate = [NSDate dateWithTimeIntervalSinceNow:delaySeconds];
|
||
|
if (self.timerScheduleDate && [timerScheduleDate timeIntervalSinceDate:self.timerScheduleDate] > 0) {
|
||
|
DDLogVerbose(@"%@ Request to run at %@ (%d sec.) ignored due to scheduled run at %@ (%d sec.)",
|
||
|
self.tag,
|
||
|
[dateFormatter stringFromDate:date],
|
||
|
(int)round(MAX(0, [date timeIntervalSinceDate:[NSDate new]])),
|
||
|
[dateFormatter stringFromDate:self.timerScheduleDate],
|
||
|
(int)round(MAX(0, [self.timerScheduleDate timeIntervalSinceDate:[NSDate new]])));
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// Update Schedule
|
||
|
DDLogVerbose(@"%@ Scheduled run at %@ (%d sec.)",
|
||
|
self.tag,
|
||
|
[dateFormatter stringFromDate:timerScheduleDate],
|
||
|
(int)round(MAX(0, [timerScheduleDate timeIntervalSinceDate:[NSDate new]])));
|
||
8 years ago
|
[self resetTimer];
|
||
8 years ago
|
self.timerScheduleDate = timerScheduleDate;
|
||
|
self.timer = [NSTimer weakScheduledTimerWithTimeInterval:delaySeconds
|
||
|
target:self
|
||
|
selector:@selector(timerDidFire)
|
||
|
userInfo:nil
|
||
|
repeats:NO];
|
||
|
});
|
||
|
}
|
||
|
|
||
|
- (void)timerDidFire
|
||
|
{
|
||
8 years ago
|
OWSAssert([NSThread isMainThread]);
|
||
|
|
||
|
if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
|
||
|
// Don't run when inactive.
|
||
|
OWSAssert(0);
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
[self resetTimer];
|
||
8 years ago
|
|
||
|
dispatch_async(OWSDisappearingMessagesJob.serialQueue, ^{
|
||
|
[self runLoop];
|
||
|
});
|
||
|
}
|
||
|
|
||
8 years ago
|
- (void)resetTimer
|
||
|
{
|
||
|
OWSAssert([NSThread isMainThread]);
|
||
|
|
||
|
[self.timer invalidate];
|
||
|
self.timer = nil;
|
||
|
self.timerScheduleDate = nil;
|
||
|
}
|
||
|
|
||
|
#pragma mark - Notifications
|
||
|
|
||
|
- (void)applicationDidBecomeActive:(NSNotification *)notification
|
||
|
{
|
||
|
OWSAssert([NSThread isMainThread]);
|
||
|
|
||
|
[self runNow];
|
||
|
}
|
||
|
|
||
|
- (void)applicationWillResignActive:(NSNotification *)notification
|
||
|
{
|
||
|
OWSAssert([NSThread isMainThread]);
|
||
|
|
||
|
[self resetTimer];
|
||
|
}
|
||
|
|
||
9 years ago
|
#pragma mark - Logging
|
||
|
|
||
|
+ (NSString *)tag
|
||
|
{
|
||
|
return [NSString stringWithFormat:@"[%@]", self.class];
|
||
|
}
|
||
|
|
||
|
- (NSString *)tag
|
||
|
{
|
||
|
return self.class.tag;
|
||
|
}
|
||
|
|
||
|
@end
|
||
|
|
||
|
NS_ASSUME_NONNULL_END
|