Merge pull request #173 from loki-project/refactoring

Minor Refactoring
pull/174/head
Niels Andriesse 5 years ago committed by GitHub
commit a9b9c807ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1 +1 @@
Subproject commit 37d85c1574ddf246b62931bae0843fe3cc07cd64 Subproject commit 9d99b8d67e152d5ddbf58f260f677908c724a3b2

@ -198,14 +198,14 @@ public final class LokiAPI : NSObject {
// Uses a read/write connection because getting the last message hash value also removes expired messages as needed // Uses a read/write connection because getting the last message hash value also removes expired messages as needed
// TODO: This shouldn't be the case; a getter shouldn't have an unexpected side effect // TODO: This shouldn't be the case; a getter shouldn't have an unexpected side effect
storage.dbReadWriteConnection.readWrite { transaction in storage.dbReadWriteConnection.readWrite { transaction in
result = storage.getLastMessageHash(forServiceNode: target.address, transaction: transaction) result = storage.getLastMessageHash(forSnode: target.address, transaction: transaction)
} }
return result return result
} }
private static func setLastMessageHashValue(for target: LokiAPITarget, hashValue: String, expirationDate: UInt64) { private static func setLastMessageHashValue(for target: LokiAPITarget, hashValue: String, expirationDate: UInt64) {
storage.dbReadWriteConnection.readWrite { transaction in storage.dbReadWriteConnection.readWrite { transaction in
storage.setLastMessageHash(forServiceNode: target.address, hash: hashValue, expiresAt: expirationDate, transaction: transaction) storage.setLastMessageHash(forSnode: target.address, hash: hashValue, expiresAt: expirationDate, transaction: transaction)
} }
} }

@ -1,21 +1,22 @@
#import "OWSPrimaryStorage.h" #import "OWSPrimaryStorage.h"
#import <AxolotlKit/PreKeyRecord.h>
#import <AxolotlKit/AxolotlExceptions.h>
#import <AxolotlKit/PreKeyBundle.h> #import <AxolotlKit/PreKeyBundle.h>
#import <YapDatabase/YapDatabase.h> #import <AxolotlKit/PreKeyRecord.h>
#import <Curve25519Kit/Ed25519.h> #import <Curve25519Kit/Ed25519.h>
#import <AxolotlKit/AxolotlExceptions.h> #import <YapDatabase/YapDatabase.h>
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
@interface OWSPrimaryStorage (Loki) @interface OWSPrimaryStorage (Loki)
# pragma mark - Pre Key for Contact # pragma mark - Pre Key Record Management
- (BOOL)hasPreKeyForContact:(NSString *)pubKey; - (BOOL)hasPreKeyRecordForContact:(NSString *)hexEncodedPublicKey;
- (PreKeyRecord *_Nullable)getPreKeyForContact:(NSString *)pubKey transaction:(YapDatabaseReadTransaction *)transaction; - (PreKeyRecord *_Nullable)getPreKeyRecordForContact:(NSString *)hexEncodedPublicKey transaction:(YapDatabaseReadTransaction *)transaction;
- (PreKeyRecord *)getOrCreatePreKeyForContact:(NSString *)pubKey; - (PreKeyRecord *)getOrCreatePreKeyRecordForContact:(NSString *)hexEncodedPublicKey;
# pragma mark - Pre Key Management # pragma mark - Pre Key Bundle Management
/** /**
* Generates a pre key bundle for the given contact. Doesn't store the pre key bundle (pre key bundles are supposed to be sent without ever being stored). * Generates a pre key bundle for the given contact. Doesn't store the pre key bundle (pre key bundles are supposed to be sent without ever being stored).
@ -30,16 +31,16 @@ NS_ASSUME_NONNULL_BEGIN
/** /**
* Gets the last message hash and removes it if its `expiresAt` has already passed. * Gets the last message hash and removes it if its `expiresAt` has already passed.
*/ */
- (NSString *_Nullable)getLastMessageHashForServiceNode:(NSString *)serviceNode transaction:(YapDatabaseReadWriteTransaction *)transaction; - (NSString *_Nullable)getLastMessageHashForSnode:(NSString *)snode transaction:(YapDatabaseReadWriteTransaction *)transaction;
- (void)setLastMessageHashForServiceNode:(NSString *)serviceNode hash:(NSString *)hash expiresAt:(u_int64_t)expiresAt transaction:(YapDatabaseReadWriteTransaction *)transaction NS_SWIFT_NAME(setLastMessageHash(forServiceNode:hash:expiresAt:transaction:)); - (void)setLastMessageHashForSnode:(NSString *)snode hash:(NSString *)hash expiresAt:(u_int64_t)expiresAt transaction:(YapDatabaseReadWriteTransaction *)transaction NS_SWIFT_NAME(setLastMessageHash(forSnode:hash:expiresAt:transaction:));
# pragma mark - Group Chat # pragma mark - Open Groups
- (void)setIDForMessageWithServerID:(NSUInteger)serverID to:(NSString *)messageID in:(YapDatabaseReadWriteTransaction *)transaction; - (void)setIDForMessageWithServerID:(NSUInteger)serverID to:(NSString *)messageID in:(YapDatabaseReadWriteTransaction *)transaction;
- (NSString *_Nullable)getIDForMessageWithServerID:(NSUInteger)serverID in:(YapDatabaseReadTransaction *)transaction; - (NSString *_Nullable)getIDForMessageWithServerID:(NSUInteger)serverID in:(YapDatabaseReadTransaction *)transaction;
- (void)updateMessageIDCollectionByPruningMessagesWithIDs:(NSSet<NSString *> *)targetMessageIDs in:(YapDatabaseReadWriteTransaction *)transaction NS_SWIFT_NAME(updateMessageIDCollectionByPruningMessagesWithIDs(_:in:)); - (void)updateMessageIDCollectionByPruningMessagesWithIDs:(NSSet<NSString *> *)targetMessageIDs in:(YapDatabaseReadWriteTransaction *)transaction NS_SWIFT_NAME(updateMessageIDCollectionByPruningMessagesWithIDs(_:in:));
# pragma mark - Restoration # pragma mark - Restoration from Seed
- (void)setRestorationTime:(NSTimeInterval)time; - (void)setRestorationTime:(NSTimeInterval)time;
- (NSTimeInterval)getRestorationTime; - (NSTimeInterval)getRestorationTime;

@ -17,9 +17,6 @@
# pragma mark - Convenience # pragma mark - Convenience
#define OWSPrimaryStoragePreKeyStoreCollection @"TSStorageManagerPreKeyStoreCollection"
#define LKPreKeyContactCollection @"LKPreKeyContactCollection"
- (OWSIdentityManager *)identityManager { - (OWSIdentityManager *)identityManager {
return OWSIdentityManager.sharedManager; return OWSIdentityManager.sharedManager;
} }
@ -28,57 +25,59 @@
return TSAccountManager.sharedInstance; return TSAccountManager.sharedInstance;
} }
# pragma mark - Pre Key for Contact # pragma mark - Pre Key Record Management
#define LKPreKeyContactCollection @"LKPreKeyContactCollection"
#define OWSPrimaryStoragePreKeyStoreCollection @"TSStorageManagerPreKeyStoreCollection"
- (BOOL)hasPreKeyForContact:(NSString *)pubKey { - (BOOL)hasPreKeyRecordForContact:(NSString *)hexEncodedPublicKey {
int preKeyId = [self.dbReadWriteConnection intForKey:pubKey inCollection:LKPreKeyContactCollection]; int preKeyId = [self.dbReadWriteConnection intForKey:hexEncodedPublicKey inCollection:LKPreKeyContactCollection];
return preKeyId > 0; return preKeyId > 0;
} }
- (PreKeyRecord *_Nullable)getPreKeyForContact:(NSString *)pubKey transaction:(YapDatabaseReadTransaction *)transaction { - (PreKeyRecord *_Nullable)getPreKeyRecordForContact:(NSString *)hexEncodedPublicKey transaction:(YapDatabaseReadTransaction *)transaction {
OWSAssertDebug(pubKey.length > 0); OWSAssertDebug(hexEncodedPublicKey.length > 0);
int preKeyId = [transaction intForKey:pubKey inCollection:LKPreKeyContactCollection]; int preKeyID = [transaction intForKey:hexEncodedPublicKey inCollection:LKPreKeyContactCollection];
// If we don't have an id then return nil if (preKeyID <= 0) { return nil; }
if (preKeyId <= 0) { return nil; }
/// throws_loadPreKey doesn't allow us to pass transaction ;( // throws_loadPreKey doesn't allow us to pass transaction
return [transaction preKeyRecordForKey:[self keyFromInt:preKeyId] inCollection:OWSPrimaryStoragePreKeyStoreCollection]; // FIXME: This seems like it could be a pretty big issue?
return [transaction preKeyRecordForKey:[self keyFromInt:preKeyID] inCollection:OWSPrimaryStoragePreKeyStoreCollection];
} }
- (PreKeyRecord *)getOrCreatePreKeyForContact:(NSString *)pubKey { - (PreKeyRecord *)getOrCreatePreKeyRecordForContact:(NSString *)hexEncodedPublicKey {
OWSAssertDebug(pubKey.length > 0); OWSAssertDebug(hexEncodedPublicKey.length > 0);
int preKeyId = [self.dbReadWriteConnection intForKey:pubKey inCollection:LKPreKeyContactCollection]; int preKeyID = [self.dbReadWriteConnection intForKey:hexEncodedPublicKey inCollection:LKPreKeyContactCollection];
// If we don't have an id then generate and store a new one // If we don't have an ID then generate and store a new one
if (preKeyId <= 0) { if (preKeyID <= 0) {
return [self generateAndStorePreKeyForContact:pubKey]; return [self generateAndStorePreKeyRecordForContact:hexEncodedPublicKey];
} }
// Load the prekey otherwise just generate a new one // Load existing pre key record if possible; generate a new one otherwise
@try { @try {
return [self throws_loadPreKey:preKeyId]; return [self throws_loadPreKey:preKeyID];
} @catch (NSException *exception) { } @catch (NSException *exception) {
return [self generateAndStorePreKeyForContact:pubKey]; return [self generateAndStorePreKeyRecordForContact:hexEncodedPublicKey];
} }
} }
/// Generate prekey for a contact and store it - (PreKeyRecord *)generateAndStorePreKeyRecordForContact:(NSString *)hexEncodedPublicKey {
- (PreKeyRecord *)generateAndStorePreKeyForContact:(NSString *)pubKey { [LKLogger print:[NSString stringWithFormat:@"[Loki] Generating new pre key record for: %@.", hexEncodedPublicKey]];
[LKLogger print:[NSString stringWithFormat:@"[Loki] Generating new pre key for: %@.", pubKey]]; OWSAssertDebug(hexEncodedPublicKey.length > 0);
OWSAssertDebug(pubKey.length > 0);
NSArray<PreKeyRecord *> *records = [self generatePreKeyRecords:1]; NSArray<PreKeyRecord *> *records = [self generatePreKeyRecords:1];
OWSAssertDebug(records.count > 0);
[self storePreKeyRecords:records]; [self storePreKeyRecords:records];
OWSAssertDebug(records.count > 0);
PreKeyRecord *record = records.firstObject; PreKeyRecord *record = records.firstObject;
[self.dbReadWriteConnection setInt:record.Id forKey:pubKey inCollection:LKPreKeyContactCollection]; [self.dbReadWriteConnection setInt:record.Id forKey:hexEncodedPublicKey inCollection:LKPreKeyContactCollection];
return record; return record;
} }
# pragma mark - Pre Key Management # pragma mark - Pre Key Bundle Management
#define LKPreKeyBundleCollection @"LKPreKeyBundleCollection" #define LKPreKeyBundleCollection @"LKPreKeyBundleCollection"
@ -103,7 +102,7 @@
OWSFailDebug(@"Signed pre key is nil."); OWSFailDebug(@"Signed pre key is nil.");
} }
PreKeyRecord *preKey = [self getOrCreatePreKeyForContact:hexEncodedPublicKey]; PreKeyRecord *preKey = [self getOrCreatePreKeyRecordForContact:hexEncodedPublicKey];
uint32_t registrationID = [self.accountManager getOrGenerateRegistrationId]; uint32_t registrationID = [self.accountManager getOrGenerateRegistrationId];
PreKeyBundle *bundle = [[PreKeyBundle alloc] initWithRegistrationId:registrationID PreKeyBundle *bundle = [[PreKeyBundle alloc] initWithRegistrationId:registrationID
@ -159,35 +158,34 @@
#define LKLastMessageHashCollection @"LKLastMessageHashCollection" #define LKLastMessageHashCollection @"LKLastMessageHashCollection"
- (NSString *_Nullable)getLastMessageHashForServiceNode:(NSString *)serviceNode transaction:(YapDatabaseReadWriteTransaction *)transaction { - (NSString *_Nullable)getLastMessageHashForSnode:(NSString *)snode transaction:(YapDatabaseReadWriteTransaction *)transaction {
NSDictionary *_Nullable dict = [transaction objectForKey:serviceNode inCollection:LKLastMessageHashCollection]; NSDictionary *_Nullable dict = [transaction objectForKey:snode inCollection:LKLastMessageHashCollection];
if (!dict) { return nil; } if (dict == nil) { return nil; }
NSString *_Nullable hash = dict[@"hash"]; NSString *_Nullable hash = dict[@"hash"];
if (!hash) { return nil; } if (hash == nil) { return nil; }
// Check if the hash isn't expired // Check if the hash has expired
uint64_t now = NSDate.ows_millisecondTimeStamp; uint64_t now = NSDate.ows_millisecondTimeStamp;
NSNumber *_Nullable expiresAt = dict[@"expiresAt"]; NSNumber *_Nullable expiresAt = dict[@"expiresAt"];
if (expiresAt && expiresAt.unsignedLongLongValue <= now) { if (expiresAt && expiresAt.unsignedLongLongValue <= now) {
// The last message has expired from the storage server [self removeLastMessageHashForSnode:snode transaction:transaction];
[self removeLastMessageHashForServiceNode:serviceNode transaction:transaction];
return nil; return nil;
} }
return hash; return hash;
} }
- (void)setLastMessageHashForServiceNode:(NSString *)serviceNode hash:(NSString *)hash expiresAt:(u_int64_t)expiresAt transaction:(YapDatabaseReadWriteTransaction *)transaction { - (void)setLastMessageHashForSnode:(NSString *)snode hash:(NSString *)hash expiresAt:(u_int64_t)expiresAt transaction:(YapDatabaseReadWriteTransaction *)transaction {
NSDictionary *dict = @{ @"hash" : hash, @"expiresAt": @(expiresAt) }; NSDictionary *dict = @{ @"hash" : hash, @"expiresAt": @(expiresAt) };
[transaction setObject:dict forKey:serviceNode inCollection:LKLastMessageHashCollection]; [transaction setObject:dict forKey:snode inCollection:LKLastMessageHashCollection];
} }
- (void)removeLastMessageHashForServiceNode:(NSString *)serviceNode transaction:(YapDatabaseReadWriteTransaction *)transaction { - (void)removeLastMessageHashForSnode:(NSString *)snode transaction:(YapDatabaseReadWriteTransaction *)transaction {
[transaction removeObjectForKey:serviceNode inCollection:LKLastMessageHashCollection]; [transaction removeObjectForKey:snode inCollection:LKLastMessageHashCollection];
} }
# pragma mark - Group Chat # pragma mark - Open Groups
#define LKMessageIDCollection @"LKMessageIDCollection" #define LKMessageIDCollection @"LKMessageIDCollection"
@ -212,7 +210,7 @@
[transaction removeObjectsForKeys:serverIDs inCollection:LKMessageIDCollection]; [transaction removeObjectsForKeys:serverIDs inCollection:LKMessageIDCollection];
} }
# pragma mark - Restoration # pragma mark - Restoration from Seed
#define LKGeneralCollection @"Loki" #define LKGeneralCollection @"Loki"

@ -6,7 +6,7 @@ public extension OWSPrimaryStorage {
} }
public func setDeviceLinks(_ deviceLinks: Set<DeviceLink>, in transaction: YapDatabaseReadWriteTransaction) { public func setDeviceLinks(_ deviceLinks: Set<DeviceLink>, in transaction: YapDatabaseReadWriteTransaction) {
// FIXME: Clear collections first? // TODO: Clear collections first?
deviceLinks.forEach { addDeviceLink($0, in: transaction) } // TODO: Check the performance impact of this deviceLinks.forEach { addDeviceLink($0, in: transaction) } // TODO: Check the performance impact of this
} }

@ -17,29 +17,30 @@ public final class ClosedGroupsProtocol : NSObject {
// MARK: - Receiving // MARK: - Receiving
@objc(shouldIgnoreClosedGroupMessage:inThread:wrappedIn:using:) @objc(shouldIgnoreClosedGroupMessage:inThread:wrappedIn:using:)
public static func shouldIgnoreClosedGroupMessage(_ dataMessage: SSKProtoDataMessage, in thread: TSThread, wrappedIn envelope: SSKProtoEnvelope, using transaction: YapDatabaseReadTransaction) -> Bool { public static func shouldIgnoreClosedGroupMessage(_ dataMessage: SSKProtoDataMessage, in thread: TSThread, wrappedIn envelope: SSKProtoEnvelope, using transaction: YapDatabaseReadTransaction) -> Bool {
// The envelope source is set during UD decryption
let hexEncodedPublicKey = envelope.source!
guard let thread = thread as? TSGroupThread, thread.groupModel.groupType == .closedGroup, guard let thread = thread as? TSGroupThread, thread.groupModel.groupType == .closedGroup,
dataMessage.group?.type == .deliver else { return false } dataMessage.group?.type == .deliver else { return false }
// The envelope source is set during UD decryption
let hexEncodedPublicKey = envelope.source!
return !thread.isUser(inGroup: hexEncodedPublicKey, transaction: transaction) return !thread.isUser(inGroup: hexEncodedPublicKey, transaction: transaction)
} }
@objc(shouldIgnoreClosedGroupUpdateMessage:in:using:) @objc(shouldIgnoreClosedGroupUpdateMessage:in:using:)
public static func shouldIgnoreClosedGroupUpdateMessage(_ envelope: SSKProtoEnvelope, in thread: TSGroupThread?, using transaction: YapDatabaseReadTransaction) -> Bool { public static func shouldIgnoreClosedGroupUpdateMessage(_ envelope: SSKProtoEnvelope, in thread: TSGroupThread?, using transaction: YapDatabaseReadTransaction) -> Bool {
guard let thread = thread else { return false }
// The envelope source is set during UD decryption // The envelope source is set during UD decryption
let hexEncodedPublicKey = envelope.source! let hexEncodedPublicKey = envelope.source!
guard let thread = thread else { return false }
return !thread.isUserAdmin(inGroup: hexEncodedPublicKey, transaction: transaction) // TODO: I wonder how this was happening in the first place? return !thread.isUserAdmin(inGroup: hexEncodedPublicKey, transaction: transaction) // TODO: I wonder how this was happening in the first place?
} }
@objc(establishSessionsIfNeededWithClosedGroupMembers:in:using:) @objc(establishSessionsIfNeededWithClosedGroupMembers:in:using:)
public static func establishSessionsIfNeeded(with closedGroupMembers: [String], in thread: TSGroupThread, using transaction: YapDatabaseReadWriteTransaction) { public static func establishSessionsIfNeeded(with closedGroupMembers: [String], in thread: TSGroupThread, using transaction: YapDatabaseReadWriteTransaction) {
for member in closedGroupMembers { closedGroupMembers.forEach { member in
guard member != getUserHexEncodedPublicKey() else { continue } guard member != getUserHexEncodedPublicKey() else { return }
let hasSession = storage.containsSession(member, deviceId: 1, protocolContext: transaction) // TODO: Instead of 1 we should use the primary device ID thingy let hasSession = storage.containsSession(member, deviceId: 1, protocolContext: transaction) // TODO: Instead of 1 we should use the primary device ID thingy
if hasSession { continue } if hasSession { return }
let thread = TSContactThread.getOrCreateThread(withContactId: member, transaction: transaction) let thread = TSContactThread.getOrCreateThread(withContactId: member, transaction: transaction)
let sessionRequestMessage = SessionRequestMessage(thread: thread) let sessionRequestMessage = SessionRequestMessage(thread: thread)
// TODO: I don't think this works correctly with multi device
let messageSenderJobQueue = SSKEnvironment.shared.messageSenderJobQueue let messageSenderJobQueue = SSKEnvironment.shared.messageSenderJobQueue
messageSenderJobQueue.add(message: sessionRequestMessage, transaction: transaction) messageSenderJobQueue.add(message: sessionRequestMessage, transaction: transaction)
} }

@ -20,7 +20,7 @@ public class LokiSessionResetImplementation : NSObject, SessionResetProtocol {
return return
} }
guard let preKeyMessage = whisperMessage as? PreKeyWhisperMessage else { return } guard let preKeyMessage = whisperMessage as? PreKeyWhisperMessage else { return }
guard let storedPreKey = storage.getPreKey(forContact: recipientID, transaction: transaction) else { guard let storedPreKey = storage.getPreKeyRecord(forContact: recipientID, transaction: transaction) else {
print("[Loki] Received a friend request from a public key for which no pre key bundle was created.") print("[Loki] Received a friend request from a public key for which no pre key bundle was created.")
throw Errors.invalidPreKey throw Errors.invalidPreKey
} }

@ -258,7 +258,6 @@ NS_ASSUME_NONNULL_BEGIN
OWSLogInfo(@"Handling decrypted envelope: %@.", [self descriptionForEnvelope:envelope]); OWSLogInfo(@"Handling decrypted envelope: %@.", [self descriptionForEnvelope:envelope]);
if (!wasReceivedByUD) { // TODO: I don't think this check is necessary. UD sets the source during decryption.
if (!envelope.hasSource || envelope.source.length < 1) { if (!envelope.hasSource || envelope.source.length < 1) {
OWSFailDebug(@"Incoming envelope with invalid source."); OWSFailDebug(@"Incoming envelope with invalid source.");
return; return;
@ -267,16 +266,9 @@ NS_ASSUME_NONNULL_BEGIN
OWSFailDebug(@"Incoming envelope with invalid source device."); OWSFailDebug(@"Incoming envelope with invalid source device.");
return; return;
} }
}
OWSAssertDebug(![self isEnvelopeSenderBlocked:envelope]); OWSAssertDebug(![self isEnvelopeSenderBlocked:envelope]);
// Loki: Ignore any friend requests from before restoration
if ([LKFriendRequestProtocol isFriendRequestFromBeforeRestoration:envelope]) {
[LKLogger print:@"[Loki] Ignoring friend request from before restoration."];
return;
}
[self checkForUnknownLinkedDevice:envelope transaction:transaction]; [self checkForUnknownLinkedDevice:envelope transaction:transaction];
switch (envelope.type) { switch (envelope.type) {
@ -423,6 +415,12 @@ NS_ASSUME_NONNULL_BEGIN
return; return;
} }
// Loki: Ignore any friend requests from before restoration
if ([LKFriendRequestProtocol isFriendRequestFromBeforeRestoration:envelope]) {
[LKLogger print:@"[Loki] Ignoring friend request from before restoration."];
return;
}
// Loki: Handle friend request acceptance if needed // Loki: Handle friend request acceptance if needed
[LKFriendRequestProtocol handleFriendRequestAcceptanceIfNeeded:envelope in:transaction]; [LKFriendRequestProtocol handleFriendRequestAcceptanceIfNeeded:envelope in:transaction];
@ -442,7 +440,9 @@ NS_ASSUME_NONNULL_BEGIN
[LKSessionManagementProtocol handlePreKeyBundleMessageIfNeeded:contentProto wrappedIn:envelope using:transaction]; [LKSessionManagementProtocol handlePreKeyBundleMessageIfNeeded:contentProto wrappedIn:envelope using:transaction];
// Loki: Handle address message if needed // Loki: Handle address message if needed
/*
[LKSessionProtocol handleP2PAddressMessageIfNeeded:contentProto wrappedIn:envelope]; [LKSessionProtocol handleP2PAddressMessageIfNeeded:contentProto wrappedIn:envelope];
*/
// Loki: Handle device linking message if needed // Loki: Handle device linking message if needed
if (contentProto.lokiDeviceLinkMessage != nil) { if (contentProto.lokiDeviceLinkMessage != nil) {
@ -455,6 +455,12 @@ NS_ASSUME_NONNULL_BEGIN
[[OWSDeviceManager sharedManager] setHasReceivedSyncMessage]; [[OWSDeviceManager sharedManager] setHasReceivedSyncMessage];
} else if (contentProto.dataMessage) { } else if (contentProto.dataMessage) {
// Loki: Don't process session request messages any further
if ([LKSessionManagementProtocol isSessionRequestMessage:contentProto.dataMessage]) { return; }
// Loki: Don't process session restore messages any further
if ([LKSessionManagementProtocol isSessionRestoreMessage:contentProto.dataMessage]) { return; }
[self handleIncomingEnvelope:envelope [self handleIncomingEnvelope:envelope
withDataMessage:contentProto.dataMessage withDataMessage:contentProto.dataMessage
wasReceivedByUD:wasReceivedByUD wasReceivedByUD:wasReceivedByUD
@ -508,11 +514,6 @@ NS_ASSUME_NONNULL_BEGIN
return; return;
} }
// Loki: Don't process session request messages any further
if ([LKSessionManagementProtocol isSessionRequestMessage:dataMessage]) { return; }
// Loki: Don't process session restore messages any further
if ([LKSessionManagementProtocol isSessionRestoreMessage:dataMessage]) { return; }
if ([self isDataMessageBlocked:dataMessage envelope:envelope]) { if ([self isDataMessageBlocked:dataMessage envelope:envelope]) {
NSString *logMessage = [NSString stringWithFormat:@"Ignoring blocked message from sender: %@.", envelope.source]; NSString *logMessage = [NSString stringWithFormat:@"Ignoring blocked message from sender: %@.", envelope.source];
if (dataMessage.group) { if (dataMessage.group) {
@ -534,9 +535,6 @@ NS_ASSUME_NONNULL_BEGIN
} }
} }
// Loki: Handle profile key update if needed
[LKSessionProtocol updateProfileKeyIfNeededForHexEncodedPublicKey:envelope.source using:dataMessage];
if (dataMessage.group) { if (dataMessage.group) {
TSGroupThread *_Nullable groupThread = TSGroupThread *_Nullable groupThread =
[TSGroupThread threadWithGroupId:dataMessage.group.id transaction:transaction]; [TSGroupThread threadWithGroupId:dataMessage.group.id transaction:transaction];
@ -905,7 +903,7 @@ NS_ASSUME_NONNULL_BEGIN
return; return;
} }
// Loki: Update if the sync message came from the master device // Loki: Update profile if needed (i.e. if the sync message came from the master device)
[LKSyncMessagesProtocol updateProfileFromSyncMessageIfNeeded:dataMessage wrappedIn:envelope using:transaction]; [LKSyncMessagesProtocol updateProfileFromSyncMessageIfNeeded:dataMessage wrappedIn:envelope using:transaction];
NSString *destination = syncMessage.sent.destination; NSString *destination = syncMessage.sent.destination;
@ -1276,9 +1274,9 @@ NS_ASSUME_NONNULL_BEGIN
} }
} }
NSString *hexEncodedPublicKey = ([LKDatabaseUtilities getMasterHexEncodedPublicKeyFor:envelope.source in:transaction] ?: envelope.source); NSString *senderMasterHexEncodedPublicKey = ([LKDatabaseUtilities getMasterHexEncodedPublicKeyFor:envelope.source in:transaction] ?: envelope.source);
NSString *localHexEncodedPublicKey = OWSIdentityManager.sharedManager.identityKeyPair.hexEncodedPublicKey; NSString *userHexEncodedPublicKey = OWSIdentityManager.sharedManager.identityKeyPair.hexEncodedPublicKey;
NSString *ourHexEncodedPublicKey = ([LKDatabaseUtilities getMasterHexEncodedPublicKeyFor:localHexEncodedPublicKey in:transaction] ?: localHexEncodedPublicKey); NSString *userMasterHexEncodedPublicKey = ([LKDatabaseUtilities getMasterHexEncodedPublicKeyFor:userHexEncodedPublicKey in:transaction] ?: userHexEncodedPublicKey);
// Group messages create the group if it doesn't already exist. // Group messages create the group if it doesn't already exist.
// //
@ -1297,8 +1295,11 @@ NS_ASSUME_NONNULL_BEGIN
// ======== // ========
} }
// Loki: Only set the display name here, the logic for updating profile pictures is handled when we're setting the profile key // Loki: Handle profile key update if needed
[LKSessionProtocol updateDisplayNameIfNeededForHexEncodedPublicKey:hexEncodedPublicKey using:dataMessage appendingShortID:NO in:transaction]; [LKSessionProtocol updateProfileKeyIfNeededForHexEncodedPublicKey:senderMasterHexEncodedPublicKey using:dataMessage];
// Loki: Handle display name update if needed
[LKSessionProtocol updateDisplayNameIfNeededForHexEncodedPublicKey:senderMasterHexEncodedPublicKey using:dataMessage appendingShortID:NO in:transaction];
switch (dataMessage.group.type) { switch (dataMessage.group.type) {
case SSKProtoGroupContextTypeUpdate: { case SSKProtoGroupContextTypeUpdate: {
@ -1322,7 +1323,7 @@ NS_ASSUME_NONNULL_BEGIN
[newGroupThread setGroupModel:newGroupModel withTransaction:transaction]; [newGroupThread setGroupModel:newGroupModel withTransaction:transaction];
BOOL wasCurrentUserRemovedFromGroup = [removedMemberIds containsObject:ourHexEncodedPublicKey]; BOOL wasCurrentUserRemovedFromGroup = [removedMemberIds containsObject:userMasterHexEncodedPublicKey];
if (!wasCurrentUserRemovedFromGroup) { if (!wasCurrentUserRemovedFromGroup) {
// Loki: Try to establish sessions with all members when a group is created or updated // Loki: Try to establish sessions with all members when a group is created or updated
[LKClosedGroupsProtocol establishSessionsIfNeededWithClosedGroupMembers:newMemberIds.allObjects in:newGroupThread using:transaction]; [LKClosedGroupsProtocol establishSessionsIfNeededWithClosedGroupMembers:newMemberIds.allObjects in:newGroupThread using:transaction];
@ -1354,12 +1355,12 @@ NS_ASSUME_NONNULL_BEGIN
return nil; return nil;
} }
newMemberIds = [NSMutableSet setWithArray:oldGroupThread.groupModel.groupMemberIds]; newMemberIds = [NSMutableSet setWithArray:oldGroupThread.groupModel.groupMemberIds];
[newMemberIds removeObject:hexEncodedPublicKey]; [newMemberIds removeObject:senderMasterHexEncodedPublicKey];
oldGroupThread.groupModel.groupMemberIds = [newMemberIds.allObjects mutableCopy]; oldGroupThread.groupModel.groupMemberIds = [newMemberIds.allObjects mutableCopy];
[oldGroupThread saveWithTransaction:transaction]; [oldGroupThread saveWithTransaction:transaction];
NSString *nameString = NSString *nameString =
[self.contactsManager displayNameForPhoneIdentifier:hexEncodedPublicKey transaction:transaction]; [self.contactsManager displayNameForPhoneIdentifier:senderMasterHexEncodedPublicKey transaction:transaction];
NSString *updateGroupInfo = NSString *updateGroupInfo =
[NSString stringWithFormat:NSLocalizedString(@"GROUP_MEMBER_LEFT", @""), nameString]; [NSString stringWithFormat:NSLocalizedString(@"GROUP_MEMBER_LEFT", @""), nameString];
// MJK TODO - should be safe to remove senderTimestamp // MJK TODO - should be safe to remove senderTimestamp
@ -1371,7 +1372,7 @@ NS_ASSUME_NONNULL_BEGIN
// If we were the one that quit then we need to leave the group (only relevant for slave // If we were the one that quit then we need to leave the group (only relevant for slave
// devices in a multi device context) // devices in a multi device context)
// TODO: This needs more documentation // TODO: This needs more documentation
if ([newMemberIds containsObject:ourHexEncodedPublicKey]) { if ([newMemberIds containsObject:userMasterHexEncodedPublicKey]) {
[oldGroupThread leaveGroupWithTransaction:transaction]; [oldGroupThread leaveGroupWithTransaction:transaction];
} }
@ -1385,7 +1386,7 @@ NS_ASSUME_NONNULL_BEGIN
[[OWSDisappearingMessagesJob sharedJob] becomeConsistentWithDisappearingDuration:dataMessage.expireTimer [[OWSDisappearingMessagesJob sharedJob] becomeConsistentWithDisappearingDuration:dataMessage.expireTimer
thread:oldGroupThread thread:oldGroupThread
createdByRemoteRecipientId:hexEncodedPublicKey createdByRemoteRecipientId:senderMasterHexEncodedPublicKey
createdInExistingGroup:NO createdInExistingGroup:NO
transaction:transaction]; transaction:transaction];
@ -1412,7 +1413,7 @@ NS_ASSUME_NONNULL_BEGIN
TSIncomingMessage *incomingMessage = TSIncomingMessage *incomingMessage =
[[TSIncomingMessage alloc] initIncomingMessageWithTimestamp:timestamp [[TSIncomingMessage alloc] initIncomingMessageWithTimestamp:timestamp
inThread:oldGroupThread inThread:oldGroupThread
authorId:hexEncodedPublicKey authorId:senderMasterHexEncodedPublicKey
sourceDeviceId:envelope.sourceDevice sourceDeviceId:envelope.sourceDevice
messageBody:body messageBody:body
attachmentIds:@[] attachmentIds:@[]
@ -1424,7 +1425,9 @@ NS_ASSUME_NONNULL_BEGIN
wasReceivedByUD:wasReceivedByUD]; wasReceivedByUD:wasReceivedByUD];
// Loki: Parse Loki specific properties if needed // Loki: Parse Loki specific properties if needed
/*
if (envelope.isPtpMessage) { incomingMessage.isP2P = YES; } if (envelope.isPtpMessage) { incomingMessage.isP2P = YES; }
*/
if (dataMessage.publicChatInfo != nil && dataMessage.publicChatInfo.hasServerID) { incomingMessage.openGroupServerMessageID = dataMessage.publicChatInfo.serverID; } if (dataMessage.publicChatInfo != nil && dataMessage.publicChatInfo.hasServerID) { incomingMessage.openGroupServerMessageID = dataMessage.publicChatInfo.serverID; }
NSArray<TSAttachmentPointer *> *attachmentPointers = NSArray<TSAttachmentPointer *> *attachmentPointers =
@ -1437,7 +1440,7 @@ NS_ASSUME_NONNULL_BEGIN
if (body.length == 0 && attachmentPointers.count < 1 && !contact) { if (body.length == 0 && attachmentPointers.count < 1 && !contact) {
OWSLogWarn(@"Ignoring empty incoming message from: %@ for group: %@ with timestamp: %lu.", OWSLogWarn(@"Ignoring empty incoming message from: %@ for group: %@ with timestamp: %lu.",
hexEncodedPublicKey, senderMasterHexEncodedPublicKey,
groupId, groupId,
(unsigned long)timestamp); (unsigned long)timestamp);
return nil; return nil;
@ -1521,7 +1524,9 @@ NS_ASSUME_NONNULL_BEGIN
[LKSessionProtocol updateProfileKeyIfNeededForHexEncodedPublicKey:thread.contactIdentifier using:dataMessage]; [LKSessionProtocol updateProfileKeyIfNeededForHexEncodedPublicKey:thread.contactIdentifier using:dataMessage];
// Loki: Parse Loki specific properties if needed // Loki: Parse Loki specific properties if needed
/*
if (envelope.isPtpMessage) { incomingMessage.isP2P = YES; } if (envelope.isPtpMessage) { incomingMessage.isP2P = YES; }
*/
NSArray<TSAttachmentPointer *> *attachmentPointers = NSArray<TSAttachmentPointer *> *attachmentPointers =
[TSAttachmentPointer attachmentPointersFromProtos:dataMessage.attachments albumMessage:incomingMessage]; [TSAttachmentPointer attachmentPointersFromProtos:dataMessage.attachments albumMessage:incomingMessage];
@ -1542,12 +1547,14 @@ NS_ASSUME_NONNULL_BEGIN
// Loki: If we received a message from a contact in the last 2 minutes that wasn't P2P, then we need to ping them. // Loki: If we received a message from a contact in the last 2 minutes that wasn't P2P, then we need to ping them.
// We assume this occurred because they don't have our P2P details. // We assume this occurred because they don't have our P2P details.
/*
if (!envelope.isPtpMessage && hexEncodedPublicKey != nil) { if (!envelope.isPtpMessage && hexEncodedPublicKey != nil) {
uint64_t timestamp = envelope.timestamp; uint64_t timestamp = envelope.timestamp;
uint64_t now = NSDate.ows_millisecondTimeStamp; uint64_t now = NSDate.ows_millisecondTimeStamp;
uint64_t ageInSeconds = (now - timestamp) / 1000; uint64_t ageInSeconds = (now - timestamp) / 1000;
if (ageInSeconds <= 120) { [LKP2PAPI pingContact:hexEncodedPublicKey]; } if (ageInSeconds <= 120) { [LKP2PAPI pingContact:hexEncodedPublicKey]; }
} }
*/
[self finalizeIncomingMessage:incomingMessage [self finalizeIncomingMessage:incomingMessage
thread:thread thread:thread

Loading…
Cancel
Save