From fdf7d99ff341c283cf7a740a2c572fec4377c170 Mon Sep 17 00:00:00 2001 From: Mikunj Date: Mon, 20 May 2019 15:59:49 +1000 Subject: [PATCH] Fix removing interaction while enumerating. Fix most recent message not being kept. --- SignalServiceKit/src/Contacts/TSThread.m | 25 ++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/SignalServiceKit/src/Contacts/TSThread.m b/SignalServiceKit/src/Contacts/TSThread.m index 4e59c579f..1bc07c309 100644 --- a/SignalServiceKit/src/Contacts/TSThread.m +++ b/SignalServiceKit/src/Contacts/TSThread.m @@ -715,6 +715,8 @@ ConversationColorName const kConversationColorName_Default = ConversationColorNa return; } + NSMutableArray *idsToRemove = [NSMutableArray new]; + __block TSMessage *_Nullable messageToKeep = nil; // We want to keep this interaction and not remove it OWSInteractionType interactionType = incoming ? OWSInteractionType_IncomingMessage : OWSInteractionType_OutgoingMessage; [self enumerateInteractionsWithTransaction:transaction usingBlock:^(TSInteraction * _Nonnull interaction, YapDatabaseReadTransaction * _Nonnull transaction) { @@ -725,6 +727,11 @@ ConversationColorName const kConversationColorName_Default = ConversationColorNa BOOL removeMessage = false; TSMessage *message = (TSMessage *)interaction; + // We want to keep the most recent message + if (!messageToKeep || messageToKeep.timestamp < message.timestamp) { + messageToKeep = message; + } + // We want to remove any old incoming friend request messages if (interactionType == OWSInteractionType_IncomingMessage) { removeMessage = message.isFriendRequest; @@ -735,10 +742,24 @@ ConversationColorName const kConversationColorName_Default = ConversationColorNa } if (removeMessage) { - [interaction removeWithTransaction:transaction]; + [idsToRemove addObject:interaction.uniqueId]; } - }]; + + for (NSString *interactionId in idsToRemove) { + // Don't delete the recent message + if (messageToKeep && interactionId == messageToKeep.uniqueId) { + continue; + } + + // We need to fetch each interaction, since [TSInteraction removeWithTransaction:] does important work. + TSInteraction *_Nullable interaction = [TSInteraction fetchObjectWithUniqueID:interactionId transaction:transaction]; + if (!interaction) { + OWSFailDebug(@"couldn't load thread's interaction for deletion."); + continue; + } + [interaction removeWithTransaction:transaction]; + } } - (void)saveFriendRequestStatus:(TSThreadFriendRequestStatus)friendRequestStatus withTransaction:(YapDatabaseReadWriteTransaction *_Nullable)transaction