From 22e59b178970b4817814c2be99e1894a5065adc0 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Mon, 2 Dec 2024 17:27:44 +1100 Subject: [PATCH] Fixed a crash which could occur when receiving a UserGroups config change --- Session.xcodeproj/project.pbxproj | 14 +- .../ConversationVC+Interaction.swift | 6 +- .../Settings/ThreadSettingsViewModel.swift | 2 +- .../GlobalSearchViewController.swift | 2 +- Session/Meta/SessionApp.swift | 2 +- .../PushRegistrationManager.swift | 2 +- Session/Onboarding/Onboarding.swift | 2 +- Session/Open Groups/JoinOpenGroupVC.swift | 2 +- Session/Utilities/MockDataGenerator.swift | 8 +- .../Migrations/_013_SessionUtilChanges.swift | 2 +- .../Database/Models/SessionThread.swift | 9 +- .../Config Handling/LibSession+Contacts.swift | 4 +- .../Config Handling/LibSession+Shared.swift | 246 ++++++++++-------- .../LibSession+UserGroups.swift | 19 +- .../LibSession+UserProfile.swift | 4 +- .../LibSession/Types/Config.swift | 28 ++ .../Open Groups/OpenGroupManager.swift | 10 +- .../MessageReceiver+Calls.swift | 4 +- .../MessageReceiver+ClosedGroups.swift | 10 +- .../MessageReceiver+MessageRequests.swift | 2 +- .../MessageReceiver+VisibleMessages.swift | 2 +- .../MessageSender+ClosedGroups.swift | 6 +- .../Jobs/Types/MessageSendJobSpec.swift | 2 +- .../Open Groups/OpenGroupManagerSpec.swift | 24 +- .../NotificationServiceExtension.swift | 2 +- 25 files changed, 247 insertions(+), 167 deletions(-) create mode 100644 SessionMessagingKit/LibSession/Types/Config.swift diff --git a/Session.xcodeproj/project.pbxproj b/Session.xcodeproj/project.pbxproj index 783bb078d..827d37d51 100644 --- a/Session.xcodeproj/project.pbxproj +++ b/Session.xcodeproj/project.pbxproj @@ -842,6 +842,7 @@ FDC13D562A171FE4007267C7 /* UnsubscribeRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDC13D552A171FE4007267C7 /* UnsubscribeRequest.swift */; }; FDC13D582A17207D007267C7 /* UnsubscribeResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDC13D572A17207D007267C7 /* UnsubscribeResponse.swift */; }; FDC13D5A2A1721C5007267C7 /* LegacyNotifyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDC13D592A1721C5007267C7 /* LegacyNotifyRequest.swift */; }; + FDC1BD662CFD6C4F002CDC71 /* Config.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDC1BD652CFD6C4E002CDC71 /* Config.swift */; }; FDC289422C86AB5800020BC2 /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = FDC289412C86AB5800020BC2 /* GRDB */; }; FDC289472C881A3800020BC2 /* MutableIdentifiable.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDC289462C881A3800020BC2 /* MutableIdentifiable.swift */; }; FDC2908727D7047F005DAE71 /* RoomSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDC2908627D7047F005DAE71 /* RoomSpec.swift */; }; @@ -1966,6 +1967,7 @@ FDC13D552A171FE4007267C7 /* UnsubscribeRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnsubscribeRequest.swift; sourceTree = ""; }; FDC13D572A17207D007267C7 /* UnsubscribeResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnsubscribeResponse.swift; sourceTree = ""; }; FDC13D592A1721C5007267C7 /* LegacyNotifyRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LegacyNotifyRequest.swift; sourceTree = ""; }; + FDC1BD652CFD6C4E002CDC71 /* Config.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Config.swift; sourceTree = ""; }; FDC289462C881A3800020BC2 /* MutableIdentifiable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableIdentifiable.swift; sourceTree = ""; }; FDC2908627D7047F005DAE71 /* RoomSpec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomSpec.swift; sourceTree = ""; }; FDC2908827D70656005DAE71 /* RoomPollInfoSpec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomPollInfoSpec.swift; sourceTree = ""; }; @@ -4168,8 +4170,9 @@ FD8ECF7529340F4800C0D1BB /* LibSession */ = { isa = PBXGroup; children = ( - FD2B4B022949886900AB4848 /* Database */, FD8ECF8E29381FB200C0D1BB /* Config Handling */, + FD2B4B022949886900AB4848 /* Database */, + FDC1BD642CFD6C44002CDC71 /* Types */, FD8ECF7A29340FFD00C0D1BB /* LibSession+SessionMessagingKit.swift */, ); path = LibSession; @@ -4254,6 +4257,14 @@ path = Types; sourceTree = ""; }; + FDC1BD642CFD6C44002CDC71 /* Types */ = { + isa = PBXGroup; + children = ( + FDC1BD652CFD6C4E002CDC71 /* Config.swift */, + ); + path = Types; + sourceTree = ""; + }; FDC289482C881C5500020BC2 /* LibSession */ = { isa = PBXGroup; children = ( @@ -5997,6 +6008,7 @@ FD5C72FD284F0EC90029977D /* MessageReceiver+ExpirationTimers.swift in Sources */, C32C5A88256DBCF9003C73A2 /* MessageReceiver+ClosedGroups.swift in Sources */, B8D0A25925E367AC00C1835E /* Notification+MessageReceiver.swift in Sources */, + FDC1BD662CFD6C4F002CDC71 /* Config.swift in Sources */, FD245C53285065DB00B966DD /* ProximityMonitoringManager.swift in Sources */, FD245C55285065E500B966DD /* OpenGroupManager.swift in Sources */, C32C599E256DB02B003C73A2 /* TypingIndicators.swift in Sources */, diff --git a/Session/Conversations/ConversationVC+Interaction.swift b/Session/Conversations/ConversationVC+Interaction.swift index 2f1511f56..fc97e35d8 100644 --- a/Session/Conversations/ConversationVC+Interaction.swift +++ b/Session/Conversations/ConversationVC+Interaction.swift @@ -1273,7 +1273,7 @@ extension ConversationVC: id: sessionId, variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) } @@ -1309,7 +1309,7 @@ extension ConversationVC: id: (lookup.sessionId ?? lookup.blindedId), variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ).id } @@ -1766,7 +1766,7 @@ extension ConversationVC: roomToken: room, server: server, publicKey: publicKey, - calledFromConfigHandling: false + calledFromConfig: nil ) } .flatMap { successfullyAddedGroup in diff --git a/Session/Conversations/Settings/ThreadSettingsViewModel.swift b/Session/Conversations/Settings/ThreadSettingsViewModel.swift index c95caee7d..49ce12702 100644 --- a/Session/Conversations/Settings/ThreadSettingsViewModel.swift +++ b/Session/Conversations/Settings/ThreadSettingsViewModel.swift @@ -781,7 +781,7 @@ class ThreadSettingsViewModel: SessionTableViewModel, NavigationItemSource, Navi id: userId, variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) diff --git a/Session/Home/GlobalSearch/GlobalSearchViewController.swift b/Session/Home/GlobalSearch/GlobalSearchViewController.swift index cac8d947d..767917c6a 100644 --- a/Session/Home/GlobalSearch/GlobalSearchViewController.swift +++ b/Session/Home/GlobalSearch/GlobalSearchViewController.swift @@ -399,7 +399,7 @@ extension GlobalSearchViewController { id: threadId, variant: threadVariant, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) } diff --git a/Session/Meta/SessionApp.swift b/Session/Meta/SessionApp.swift index 0e9b6b38f..d84ce7363 100644 --- a/Session/Meta/SessionApp.swift +++ b/Session/Meta/SessionApp.swift @@ -90,7 +90,7 @@ public struct SessionApp { id: threadId, variant: variant, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) } diff --git a/Session/Notifications/PushRegistrationManager.swift b/Session/Notifications/PushRegistrationManager.swift index 971f99607..90466834b 100644 --- a/Session/Notifications/PushRegistrationManager.swift +++ b/Session/Notifications/PushRegistrationManager.swift @@ -318,7 +318,7 @@ public class PushRegistrationManager: NSObject, PKPushRegistryDelegate, PushRegi id: caller, variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) diff --git a/Session/Onboarding/Onboarding.swift b/Session/Onboarding/Onboarding.swift index 551a13d4b..89e8a80ca 100644 --- a/Session/Onboarding/Onboarding.swift +++ b/Session/Onboarding/Onboarding.swift @@ -175,7 +175,7 @@ enum Onboarding { id: x25519PublicKey, variant: .contact, values: SessionThread.TargetValues(shouldBeVisible: .setTo(false)), - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) diff --git a/Session/Open Groups/JoinOpenGroupVC.swift b/Session/Open Groups/JoinOpenGroupVC.swift index 808e294a8..5cf0f9d23 100644 --- a/Session/Open Groups/JoinOpenGroupVC.swift +++ b/Session/Open Groups/JoinOpenGroupVC.swift @@ -206,7 +206,7 @@ final class JoinOpenGroupVC: BaseVC, UIPageViewControllerDataSource, UIPageViewC roomToken: roomToken, server: server, publicKey: publicKey, - calledFromConfigHandling: false + calledFromConfig: nil ) } .flatMap { successfullyAddedGroup in diff --git a/Session/Utilities/MockDataGenerator.swift b/Session/Utilities/MockDataGenerator.swift index 7f802e4f7..db822af0a 100644 --- a/Session/Utilities/MockDataGenerator.swift +++ b/Session/Utilities/MockDataGenerator.swift @@ -54,7 +54,7 @@ enum MockDataGenerator { id: "MockDatabaseThread", variant: .contact, values: SessionThread.TargetValues(shouldBeVisible: .setTo(false)), - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) @@ -85,7 +85,7 @@ enum MockDataGenerator { id: randomSessionId, variant: .contact, values: SessionThread.TargetValues(shouldBeVisible: .setTo(true)), - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) @@ -198,7 +198,7 @@ enum MockDataGenerator { id: randomGroupPublicKey, variant: .legacyGroup, values: SessionThread.TargetValues(shouldBeVisible: .setTo(true)), - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) _ = try! ClosedGroup( @@ -329,7 +329,7 @@ enum MockDataGenerator { id: randomGroupPublicKey, variant: .community, values: SessionThread.TargetValues(shouldBeVisible: .setTo(true)), - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) _ = try! OpenGroup( diff --git a/SessionMessagingKit/Database/Migrations/_013_SessionUtilChanges.swift b/SessionMessagingKit/Database/Migrations/_013_SessionUtilChanges.swift index 2b2f33cf6..336768cac 100644 --- a/SessionMessagingKit/Database/Migrations/_013_SessionUtilChanges.swift +++ b/SessionMessagingKit/Database/Migrations/_013_SessionUtilChanges.swift @@ -248,7 +248,7 @@ enum _013_SessionUtilChanges: Migration { id: userPublicKey, variant: .contact, values: SessionThread.TargetValues(shouldBeVisible: .setTo(false)), - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) } diff --git a/SessionMessagingKit/Database/Models/SessionThread.swift b/SessionMessagingKit/Database/Models/SessionThread.swift index 1208b8c75..15f6d7224 100644 --- a/SessionMessagingKit/Database/Models/SessionThread.swift +++ b/SessionMessagingKit/Database/Models/SessionThread.swift @@ -202,7 +202,7 @@ public extension SessionThread { id: ID, variant: Variant, values: TargetValues, - calledFromConfig: Bool, + calledFromConfig configTriggeringChange: LibSession.Config.Variant?, using dependencies: Dependencies ) throws -> SessionThread { var result: SessionThread @@ -215,6 +215,7 @@ public extension SessionThread { db, threadId: id, threadVariant: variant, + conf: configTriggeringChange?.conf, using: dependencies ) @@ -239,13 +240,14 @@ public extension SessionThread { ) case (_, .useLibSession): // Create and save the config from libSession - guard !calledFromConfig else { throw LibSessionError.invalidConfigAccess } + guard configTriggeringChange == nil else { throw LibSessionError.invalidConfigAccess } try LibSession .disappearingMessagesConfig( db, threadId: id, threadVariant: variant, + conf: configTriggeringChange?.conf, using: dependencies )? .upserted(db) @@ -268,6 +270,7 @@ public extension SessionThread { db, threadId: id, threadVariant: variant, + conf: configTriggeringChange?.conf, using: dependencies ) let libSessionShouldBeVisible: Bool = LibSession.shouldBeVisible(priority: targetPriority) @@ -305,7 +308,7 @@ public extension SessionThread { .updateAllAndConfig( db, requiredChanges, - calledFromConfig: calledFromConfig, + calledFromConfig: (configTriggeringChange != nil), using: dependencies ) diff --git a/SessionMessagingKit/LibSession/Config Handling/LibSession+Contacts.swift b/SessionMessagingKit/LibSession/Config Handling/LibSession+Contacts.swift index 9175c04a0..b0c2614a9 100644 --- a/SessionMessagingKit/LibSession/Config Handling/LibSession+Contacts.swift +++ b/SessionMessagingKit/LibSession/Config Handling/LibSession+Contacts.swift @@ -39,7 +39,7 @@ internal extension LibSession { using dependencies: Dependencies ) throws { guard mergeNeedsDump else { return } - guard conf != nil else { throw LibSessionError.nilConfigObject } + guard let conf: UnsafeMutablePointer = conf else { throw LibSessionError.nilConfigObject } // The current users contact data is handled separately so exclude it if it's present (as that's // actually a bug) @@ -178,7 +178,7 @@ internal extension LibSession { .useExisting ) ), - calledFromConfig: true, + calledFromConfig: .contacts(conf), using: dependencies ) diff --git a/SessionMessagingKit/LibSession/Config Handling/LibSession+Shared.swift b/SessionMessagingKit/LibSession/Config Handling/LibSession+Shared.swift index 940914880..fb84e412e 100644 --- a/SessionMessagingKit/LibSession/Config Handling/LibSession+Shared.swift +++ b/SessionMessagingKit/LibSession/Config Handling/LibSession+Shared.swift @@ -410,6 +410,7 @@ public extension LibSession { _ db: Database, threadId: String, threadVariant: SessionThread.Variant, + conf: UnsafeMutablePointer?, using dependencies: Dependencies ) -> Int32 { let userPublicKey: String = getUserHexEncodedPublicKey(db) @@ -420,70 +421,81 @@ public extension LibSession { } }() - return dependencies.caches[.libSession] - .config(for: configVariant, publicKey: userPublicKey) - .wrappedValue - .map { conf in - guard var cThreadId: [CChar] = threadId.cString(using: .utf8) else { + guard let conf: UnsafeMutablePointer = conf else { + return dependencies.caches[.libSession] + .config(for: configVariant, publicKey: userPublicKey) + .wrappedValue + .map { conf in + LibSession.pinnedPriority( + db, + threadId: threadId, + threadVariant: threadVariant, + conf: conf, + using: dependencies + ) + } + .defaulting(to: LibSession.defaultNewThreadPriority) + } + + guard var cThreadId: [CChar] = threadId.cString(using: .utf8) else { + return LibSession.defaultNewThreadPriority + } + + switch threadVariant { + case .contact where threadId == userPublicKey: + return user_profile_get_nts_priority(conf) + + case .contact: + var contact: contacts_contact = contacts_contact() + + guard contacts_get(conf, &contact, &cThreadId) else { + LibSessionError.clear(conf) return LibSession.defaultNewThreadPriority } - switch threadVariant { - case .contact where threadId == userPublicKey: - return user_profile_get_nts_priority(conf) - - case .contact: - var contact: contacts_contact = contacts_contact() - - guard contacts_get(conf, &contact, &cThreadId) else { - LibSessionError.clear(conf) - return LibSession.defaultNewThreadPriority - } - - return contact.priority - - case .community: - let maybeUrlInfo: OpenGroupUrlInfo? = Storage.shared - .read { db in try OpenGroupUrlInfo.fetchAll(db, ids: [threadId]) }? - .first - - guard - let urlInfo: OpenGroupUrlInfo = maybeUrlInfo, - var cBaseUrl: [CChar] = urlInfo.server.cString(using: .utf8), - var cRoom: [CChar] = urlInfo.roomToken.cString(using: .utf8) - else { return LibSession.defaultNewThreadPriority } - - var community: ugroups_community_info = ugroups_community_info() - let result: Bool = user_groups_get_community(conf, &community, &cBaseUrl, &cRoom) - LibSessionError.clear(conf) - - return community.priority - - case .legacyGroup: - let groupInfo: UnsafeMutablePointer? = user_groups_get_legacy_group(conf, &cThreadId) - LibSessionError.clear(conf) - - defer { - if groupInfo != nil { - ugroups_legacy_group_free(groupInfo) - } - } - - return (groupInfo?.pointee.priority ?? LibSession.defaultNewThreadPriority) - - case .group: - return LibSession.defaultNewThreadPriority // FIXME: Add in groups rebuild + return contact.priority + + case .community: + let maybeUrlInfo: OpenGroupUrlInfo? = Storage.shared + .read { db in try OpenGroupUrlInfo.fetchAll(db, ids: [threadId]) }? + .first + + guard + let urlInfo: OpenGroupUrlInfo = maybeUrlInfo, + var cBaseUrl: [CChar] = urlInfo.server.cString(using: .utf8), + var cRoom: [CChar] = urlInfo.roomToken.cString(using: .utf8) + else { return LibSession.defaultNewThreadPriority } + + var community: ugroups_community_info = ugroups_community_info() + let result: Bool = user_groups_get_community(conf, &community, &cBaseUrl, &cRoom) + LibSessionError.clear(conf) + + return community.priority + + case .legacyGroup: + let groupInfo: UnsafeMutablePointer? = user_groups_get_legacy_group(conf, &cThreadId) + LibSessionError.clear(conf) + + defer { + if groupInfo != nil { + ugroups_legacy_group_free(groupInfo) + } } - } - .defaulting(to: LibSession.defaultNewThreadPriority) + + return (groupInfo?.pointee.priority ?? LibSession.defaultNewThreadPriority) + + case .group: + return LibSession.defaultNewThreadPriority // FIXME: Add in groups rebuild + } } static func disappearingMessagesConfig( _ db: Database, threadId: String, threadVariant: SessionThread.Variant, + conf: UnsafeMutablePointer?, using dependencies: Dependencies - ) throws -> DisappearingMessagesConfiguration? { + ) -> DisappearingMessagesConfiguration? { switch threadVariant { case .community: return nil default: break @@ -497,65 +509,75 @@ public extension LibSession { } }() - return dependencies.caches[.libSession] - .config(for: configVariant, publicKey: userPublicKey) - .wrappedValue - .map { conf -> DisappearingMessagesConfiguration? in - guard var cThreadId: [CChar] = threadId.cString(using: .utf8) else { return nil } + guard let conf: UnsafeMutablePointer = conf else { + return dependencies.caches[.libSession] + .config(for: configVariant, publicKey: userPublicKey) + .wrappedValue + .map { conf in + LibSession.disappearingMessagesConfig( + db, + threadId: threadId, + threadVariant: threadVariant, + conf: conf, + using: dependencies + ) + } + } + + guard var cThreadId: [CChar] = threadId.cString(using: .utf8) else { return nil } + + switch threadVariant { + case .community: return nil + case .contact where threadId == userPublicKey: + let targetExpiry: Int32 = user_profile_get_nts_expiry(conf) + let targetIsEnabled: Bool = (targetExpiry > 0) - switch threadVariant { - case .community: return nil - case .contact where threadId == userPublicKey: - let targetExpiry: Int32 = user_profile_get_nts_expiry(conf) - let targetIsEnabled: Bool = (targetExpiry > 0) - - return DisappearingMessagesConfiguration( - threadId: threadId, - isEnabled: targetIsEnabled, - durationSeconds: TimeInterval(targetExpiry), - type: targetIsEnabled ? .disappearAfterSend : .unknown - ) - - case .contact: - var contact: contacts_contact = contacts_contact() - - guard contacts_get(conf, &contact, &cThreadId) else { - LibSessionError.clear(conf) - return nil - } - - return DisappearingMessagesConfiguration( - threadId: threadId, - isEnabled: contact.exp_seconds > 0, - durationSeconds: TimeInterval(contact.exp_seconds), - type: DisappearingMessagesConfiguration.DisappearingMessageType( - libSessionType: contact.exp_mode - ) - ) - - case .legacyGroup: - let groupInfo: UnsafeMutablePointer? = user_groups_get_legacy_group(conf, &cThreadId) - LibSessionError.clear(conf) - - defer { - if groupInfo != nil { - ugroups_legacy_group_free(groupInfo) - } - } - - return groupInfo.map { info in - DisappearingMessagesConfiguration( - threadId: userPublicKey, - isEnabled: (info.pointee.disappearing_timer > 0), - durationSeconds: TimeInterval(info.pointee.disappearing_timer), - type: .disappearAfterSend - ) - } - - case .group: - return nil // FIXME: Add in groups rebuild + return DisappearingMessagesConfiguration( + threadId: threadId, + isEnabled: targetIsEnabled, + durationSeconds: TimeInterval(targetExpiry), + type: targetIsEnabled ? .disappearAfterSend : .unknown + ) + + case .contact: + var contact: contacts_contact = contacts_contact() + + guard contacts_get(conf, &contact, &cThreadId) else { + LibSessionError.clear(conf) + return nil } - } + + return DisappearingMessagesConfiguration( + threadId: threadId, + isEnabled: contact.exp_seconds > 0, + durationSeconds: TimeInterval(contact.exp_seconds), + type: DisappearingMessagesConfiguration.DisappearingMessageType( + libSessionType: contact.exp_mode + ) + ) + + case .legacyGroup: + let groupInfo: UnsafeMutablePointer? = user_groups_get_legacy_group(conf, &cThreadId) + LibSessionError.clear(conf) + + defer { + if groupInfo != nil { + ugroups_legacy_group_free(groupInfo) + } + } + + return groupInfo.map { info in + DisappearingMessagesConfiguration( + threadId: userPublicKey, + isEnabled: (info.pointee.disappearing_timer > 0), + durationSeconds: TimeInterval(info.pointee.disappearing_timer), + type: .disappearAfterSend + ) + } + + case .group: + return nil // FIXME: Add in groups rebuild + } } static func conversationInConfig( @@ -565,8 +587,8 @@ public extension LibSession { visibleOnly: Bool, using dependencies: Dependencies ) -> Bool { - // Currently blinded conversations cannot be contained in the config, so there is no point checking (it'll always be - // false) + // Currently blinded conversations cannot be contained in the config, so there is no + // point checking (it'll always be false) guard threadVariant == .community || ( (try? SessionId(from: threadId))?.prefix != .blinded15 && diff --git a/SessionMessagingKit/LibSession/Config Handling/LibSession+UserGroups.swift b/SessionMessagingKit/LibSession/Config Handling/LibSession+UserGroups.swift index 08797ea09..af38e10fa 100644 --- a/SessionMessagingKit/LibSession/Config Handling/LibSession+UserGroups.swift +++ b/SessionMessagingKit/LibSession/Config Handling/LibSession+UserGroups.swift @@ -32,7 +32,7 @@ internal extension LibSession { using dependencies: Dependencies = Dependencies() ) throws { guard mergeNeedsDump else { return } - guard conf != nil else { throw LibSessionError.nilConfigObject } + guard let conf: UnsafeMutablePointer = conf else { throw LibSessionError.nilConfigObject } var infiniteLoopGuard: Int = 0 var communities: [PrioritisedData] = [] @@ -133,14 +133,13 @@ internal extension LibSession { // Add any new communities (via the OpenGroupManager) communities.forEach { community in - let successfullyAddedGroup: Bool = OpenGroupManager.shared - .add( - db, - roomToken: community.data.roomToken, - server: community.data.server, - publicKey: community.data.publicKey, - calledFromConfigHandling: true - ) + let successfullyAddedGroup: Bool = OpenGroupManager.shared.add( + db, + roomToken: community.data.roomToken, + server: community.data.server, + publicKey: community.data.publicKey, + calledFromConfig: .userGroups(conf) + ) if successfullyAddedGroup { db.afterNextTransactionNested { _ in @@ -241,7 +240,7 @@ internal extension LibSession { admins: updatedAdmins.map { $0.profileId }, expirationTimer: UInt32(group.disappearingConfig?.durationSeconds ?? 0), formationTimestampMs: UInt64(joinedAt * 1000), - calledFromConfigHandling: true, + calledFromConfig: .userGroups(conf), using: dependencies ) } diff --git a/SessionMessagingKit/LibSession/Config Handling/LibSession+UserProfile.swift b/SessionMessagingKit/LibSession/Config Handling/LibSession+UserProfile.swift index 3b152d071..ac3b04ac5 100644 --- a/SessionMessagingKit/LibSession/Config Handling/LibSession+UserProfile.swift +++ b/SessionMessagingKit/LibSession/Config Handling/LibSession+UserProfile.swift @@ -28,7 +28,7 @@ internal extension LibSession { typealias ProfileData = (profileName: String, profilePictureUrl: String?, profilePictureKey: Data?) guard mergeNeedsDump else { return } - guard conf != nil else { throw LibSessionError.nilConfigObject } + guard let conf: UnsafeMutablePointer = conf else { throw LibSessionError.nilConfigObject } // A profile must have a name so if this is null then it's invalid and can be ignored guard let profileNamePtr: UnsafePointer = user_profile_get_name(conf) else { return } @@ -106,7 +106,7 @@ internal extension LibSession { shouldBeVisible: .setTo(LibSession.shouldBeVisible(priority: targetPriority)), pinnedPriority: .setTo(targetPriority) ), - calledFromConfig: true, + calledFromConfig: .userProfile(conf), using: dependencies ) } diff --git a/SessionMessagingKit/LibSession/Types/Config.swift b/SessionMessagingKit/LibSession/Types/Config.swift new file mode 100644 index 000000000..bf0c57ec3 --- /dev/null +++ b/SessionMessagingKit/LibSession/Types/Config.swift @@ -0,0 +1,28 @@ +// Copyright © 2023 Rangeproof Pty Ltd. All rights reserved. +// +// stringlint:disable + +import Foundation +import SessionUtil +import SessionUtilitiesKit + +public extension LibSession { + // MARK: - Config + + enum Config { + public enum Variant { + case userProfile(UnsafeMutablePointer) + case contacts(UnsafeMutablePointer) + case convoInfoVolatile(UnsafeMutablePointer) + case userGroups(UnsafeMutablePointer) + + var conf: UnsafeMutablePointer { + switch self { + case .userProfile(let value), .contacts(let value), + .convoInfoVolatile(let value), .userGroups(let value): + return value + } + } + } + } +} diff --git a/SessionMessagingKit/Open Groups/OpenGroupManager.swift b/SessionMessagingKit/Open Groups/OpenGroupManager.swift index d10cdd34e..b4969484b 100644 --- a/SessionMessagingKit/Open Groups/OpenGroupManager.swift +++ b/SessionMessagingKit/Open Groups/OpenGroupManager.swift @@ -180,12 +180,12 @@ public final class OpenGroupManager { roomToken: String, server: String, publicKey: String, - calledFromConfigHandling: Bool, + calledFromConfig configTriggeringChange: LibSession.Config.Variant?, using dependencies: Dependencies = Dependencies() ) -> Bool { // If we are currently polling for this server and already have a TSGroupThread for this room the do nothing if hasExistingOpenGroup(db, roomToken: roomToken, server: server, publicKey: publicKey, using: dependencies) { - SNLog("Ignoring join open group attempt (already joined), user initiated: \(!calledFromConfigHandling)") + SNLog("Ignoring join open group attempt (already joined), user initiated: \(configTriggeringChange != nil)") return false } @@ -211,9 +211,9 @@ public final class OpenGroupManager { /// /// **Note:** We **MUST** provide a `nil` value if this method was called from the config handling as updating /// the `shouldVeVisible` state can trigger a config update which could result in an infinite loop in the future - shouldBeVisible: (calledFromConfigHandling ? .useExisting : .setTo(true)) + shouldBeVisible: (configTriggeringChange != nil ? .useExisting : .setTo(true)) ), - calledFromConfig: calledFromConfigHandling, + calledFromConfig: configTriggeringChange, using: dependencies ) @@ -225,7 +225,7 @@ public final class OpenGroupManager { // Set the group to active and reset the sequenceNumber (handle groups which have // been deactivated) - if calledFromConfigHandling { + if configTriggeringChange != nil { _ = try? OpenGroup .filter(id: OpenGroup.idFor(roomToken: roomToken, server: targetServer)) .updateAll( // Handling a config update so don't use `updateAllAndConfig` diff --git a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+Calls.swift b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+Calls.swift index 55d868631..54dcdc0e4 100644 --- a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+Calls.swift +++ b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+Calls.swift @@ -65,7 +65,7 @@ extension MessageReceiver { id: sender, variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) @@ -92,7 +92,7 @@ extension MessageReceiver { id: sender, variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) diff --git a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+ClosedGroups.swift b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+ClosedGroups.swift index 075a0bbcd..79750f55c 100644 --- a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+ClosedGroups.swift +++ b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+ClosedGroups.swift @@ -121,7 +121,7 @@ extension MessageReceiver { admins: adminsAsData.map { $0.toHexString() }, expirationTimer: expirationTimer, formationTimestampMs: sentTimestamp, - calledFromConfigHandling: false, + calledFromConfig: nil, using: dependencies ) } @@ -135,7 +135,7 @@ extension MessageReceiver { admins: [String], expirationTimer: UInt32, formationTimestampMs: UInt64, - calledFromConfigHandling: Bool, + calledFromConfig configTriggeringChange: LibSession.Config.Variant?, using dependencies: Dependencies ) throws { // With new closed groups we only want to create them if the admin creating the closed group is an @@ -153,7 +153,7 @@ extension MessageReceiver { // If the group came from the updated config handling then it doesn't matter if we // have an approved admin - we should add it regardless (as it's been synced from // antoher device) - guard hasApprovedAdmin || calledFromConfigHandling else { return } + guard hasApprovedAdmin || configTriggeringChange != nil else { return } // Create the group let thread: SessionThread = try SessionThread.upsert( @@ -164,7 +164,7 @@ extension MessageReceiver { creationDateTimestamp: (TimeInterval(formationTimestampMs) / 1000), shouldBeVisible: .setTo(true) ), - calledFromConfig: calledFromConfigHandling, + calledFromConfig: configTriggeringChange, using: dependencies ) let closedGroup: ClosedGroup = try ClosedGroup( @@ -226,7 +226,7 @@ extension MessageReceiver { try newKeyPair.insert(db) } - if !calledFromConfigHandling { + if configTriggeringChange == nil { // Update libSession try? LibSession.add( db, diff --git a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+MessageRequests.swift b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+MessageRequests.swift index e83796f4a..e4a12fd4d 100644 --- a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+MessageRequests.swift +++ b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+MessageRequests.swift @@ -55,7 +55,7 @@ extension MessageReceiver { id: senderId, variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) diff --git a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+VisibleMessages.swift b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+VisibleMessages.swift index ef9a21b7a..0dd8f4c6f 100644 --- a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+VisibleMessages.swift +++ b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+VisibleMessages.swift @@ -72,7 +72,7 @@ extension MessageReceiver { id: threadId, variant: threadVariant, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) let maybeOpenGroup: OpenGroup? = { diff --git a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageSender+ClosedGroups.swift b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageSender+ClosedGroups.swift index 05d7b56a1..2d08ddc96 100644 --- a/SessionMessagingKit/Sending & Receiving/Message Handling/MessageSender+ClosedGroups.swift +++ b/SessionMessagingKit/Sending & Receiving/Message Handling/MessageSender+ClosedGroups.swift @@ -45,7 +45,7 @@ extension MessageSender { id: groupPublicKey, variant: .legacyGroup, values: SessionThread.TargetValues(shouldBeVisible: .setTo(true)), - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) try ClosedGroup( @@ -483,7 +483,7 @@ extension MessageSender { id: member, variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) @@ -697,7 +697,7 @@ extension MessageSender { id: publicKey, variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) let ciphertext = try dependencies.crypto.tryGenerate( diff --git a/SessionMessagingKitTests/Jobs/Types/MessageSendJobSpec.swift b/SessionMessagingKitTests/Jobs/Types/MessageSendJobSpec.swift index ba74eb5f4..d3e231d3f 100644 --- a/SessionMessagingKitTests/Jobs/Types/MessageSendJobSpec.swift +++ b/SessionMessagingKitTests/Jobs/Types/MessageSendJobSpec.swift @@ -71,7 +71,7 @@ class MessageSendJobSpec: QuickSpec { // False is the default and will mean we don't need libSession loaded shouldBeVisible: .setTo(false) ), - calledFromConfig: false, + calledFromConfig: nil, using: dependencies ) }, diff --git a/SessionMessagingKitTests/Open Groups/OpenGroupManagerSpec.swift b/SessionMessagingKitTests/Open Groups/OpenGroupManagerSpec.swift index a12b9c06f..39c5a57bf 100644 --- a/SessionMessagingKitTests/Open Groups/OpenGroupManagerSpec.swift +++ b/SessionMessagingKitTests/Open Groups/OpenGroupManagerSpec.swift @@ -764,7 +764,11 @@ class OpenGroupManagerSpec: QuickSpec { roomToken: "testRoom", server: "http://127.0.0.1", publicKey: TestConstants.serverPublicKey, - calledFromConfigHandling: true, // Don't trigger LibSession logic + calledFromConfig: .userGroups( // Don't trigger LibSession logic + dependencies.caches[.libSession] + .config(for: .userGroups, publicKey: "05\(TestConstants.publicKey)") + .wrappedValue! + ), using: dependencies ) } @@ -802,7 +806,11 @@ class OpenGroupManagerSpec: QuickSpec { roomToken: "testRoom", server: "http://127.0.0.1", publicKey: TestConstants.serverPublicKey, - calledFromConfigHandling: true, // Don't trigger LibSession logic + calledFromConfig: .userGroups( // Don't trigger LibSession logic + dependencies.caches[.libSession] + .config(for: .userGroups, publicKey: "05\(TestConstants.publicKey)") + .wrappedValue! + ), using: dependencies ) } @@ -849,7 +857,11 @@ class OpenGroupManagerSpec: QuickSpec { publicKey: TestConstants.serverPublicKey .replacingOccurrences(of: "c3", with: "00") .replacingOccurrences(of: "b3", with: "00"), - calledFromConfigHandling: true, // Don't trigger LibSession logic + calledFromConfig: .userGroups( // Don't trigger LibSession logic + dependencies.caches[.libSession] + .config(for: .userGroups, publicKey: "05\(TestConstants.publicKey)") + .wrappedValue! + ), using: dependencies ) } @@ -914,7 +926,11 @@ class OpenGroupManagerSpec: QuickSpec { roomToken: "testRoom", server: "http://127.0.0.1", publicKey: TestConstants.serverPublicKey, - calledFromConfigHandling: true, // Don't trigger LibSession logic + calledFromConfig: .userGroups( // Don't trigger LibSession logic + dependencies.caches[.libSession] + .config(for: .userGroups, publicKey: "05\(TestConstants.publicKey)") + .wrappedValue! + ), using: dependencies ) } diff --git a/SessionNotificationServiceExtension/NotificationServiceExtension.swift b/SessionNotificationServiceExtension/NotificationServiceExtension.swift index 3ab4d3c1e..39d31ebd0 100644 --- a/SessionNotificationServiceExtension/NotificationServiceExtension.swift +++ b/SessionNotificationServiceExtension/NotificationServiceExtension.swift @@ -169,7 +169,7 @@ public final class NotificationServiceExtension: UNNotificationServiceExtension id: sender, variant: .contact, values: .existingOrDefault, - calledFromConfig: false, + calledFromConfig: nil, using: dependencies )