diff --git a/TelegramCore/Account.swift b/TelegramCore/Account.swift index 3c53387454..502ac1b8fe 100644 --- a/TelegramCore/Account.swift +++ b/TelegramCore/Account.swift @@ -145,8 +145,8 @@ public class UnauthorizedAccount { postbox.removeKeychainEntryForKey(key) }) - return self.postbox.modify { modifier -> (LocalizationSettings?, ProxySettings?, NetworkSettings?) in - return (modifier.getPreferencesEntry(key: PreferencesKeys.localizationSettings) as? LocalizationSettings, modifier.getPreferencesEntry(key: PreferencesKeys.proxySettings) as? ProxySettings, modifier.getPreferencesEntry(key: PreferencesKeys.networkSettings) as? NetworkSettings) + return self.postbox.transaction { transaction -> (LocalizationSettings?, ProxySettings?, NetworkSettings?) in + return (transaction.getPreferencesEntry(key: PreferencesKeys.localizationSettings) as? LocalizationSettings, transaction.getPreferencesEntry(key: PreferencesKeys.proxySettings) as? ProxySettings, transaction.getPreferencesEntry(key: PreferencesKeys.networkSettings) as? NetworkSettings) } |> mapToSignal { (localizationSettings, proxySettings, networkSettings) -> Signal in return initializedNetwork(arguments: self.networkArguments, supplementary: false, datacenterId: Int(masterDatacenterId), keychain: keychain, basePath: self.basePath, testingEnvironment: self.testingEnvironment, languageCode: localizationSettings?.languageCode, proxySettings: proxySettings, networkSettings: networkSettings, phoneNumber: nil) |> map { network in @@ -299,8 +299,8 @@ public func accountWithId(networkArguments: NetworkInitializationArguments, id: return postbox.stateView() |> take(1) |> mapToSignal { view -> Signal in - return postbox.modify { modifier -> (LocalizationSettings?, ProxySettings?, NetworkSettings?) in - return (modifier.getPreferencesEntry(key: PreferencesKeys.localizationSettings) as? LocalizationSettings, modifier.getPreferencesEntry(key: PreferencesKeys.proxySettings) as? ProxySettings, modifier.getPreferencesEntry(key: PreferencesKeys.networkSettings) as? NetworkSettings) + return postbox.transaction { transaction -> (LocalizationSettings?, ProxySettings?, NetworkSettings?) in + return (transaction.getPreferencesEntry(key: PreferencesKeys.localizationSettings) as? LocalizationSettings, transaction.getPreferencesEntry(key: PreferencesKeys.proxySettings) as? ProxySettings, transaction.getPreferencesEntry(key: PreferencesKeys.networkSettings) as? NetworkSettings) } |> mapToSignal { (localizationSettings, proxySettings, networkSettings) -> Signal in let accountState = view.state @@ -320,8 +320,8 @@ public func accountWithId(networkArguments: NetworkInitializationArguments, id: return .unauthorized(UnauthorizedAccount(networkArguments: networkArguments, id: id, rootPath: rootPath, basePath: path, testingEnvironment: testingEnvironment, postbox: postbox, network: network, shouldKeepAutoConnection: shouldKeepAutoConnection)) } case let authorizedState as AuthorizedAccountState: - return postbox.modify { modifier -> String? in - return (modifier.getPeer(authorizedState.peerId) as? TelegramUser)?.phone + return postbox.transaction { transaction -> String? in + return (transaction.getPeer(authorizedState.peerId) as? TelegramUser)?.phone } |> mapToSignal { phoneNumber in return initializedNetwork(arguments: networkArguments, supplementary: supplementary, datacenterId: Int(authorizedState.masterDatacenterId), keychain: keychain, basePath: path, testingEnvironment: testingEnvironment, languageCode: localizationSettings?.languageCode, proxySettings: proxySettings, networkSettings: networkSettings, phoneNumber: phoneNumber) @@ -480,8 +480,8 @@ private func masterNotificationsKey(account: Account, ignoreDisabled: Bool) -> S //return .single(key) } - return account.postbox.modify(ignoreDisabled: ignoreDisabled, { modifier -> MasterNotificationKey in - if let value = modifier.keychainEntryForKey("master-notification-secret"), !value.isEmpty { + return account.postbox.transaction(ignoreDisabled: ignoreDisabled, { transaction -> MasterNotificationKey in + if let value = transaction.keychainEntryForKey("master-notification-secret"), !value.isEmpty { let authKeyHash = sha1Digest(value) let authKeyId = authKeyHash.subdata(in: authKeyHash.count - 8 ..< authKeyHash.count) let keyData = MasterNotificationKey(id: authKeyId, data: value) @@ -497,7 +497,7 @@ private func masterNotificationsKey(account: Account, ignoreDisabled: Bool) -> S assertionFailure() } - modifier.setKeychainEntry(secretData, forKey: "master-notification-secret") + transaction.setKeychainEntry(secretData, forKey: "master-notification-secret") let authKeyHash = sha1Digest(secretData) let authKeyId = authKeyHash.subdata(in: authKeyHash.count - 8 ..< authKeyHash.count) let keyData = MasterNotificationKey(id: authKeyId, data: secretData) @@ -814,14 +814,14 @@ public class Account { |> mapToSignal { _ -> Signal in return .complete() } let pushStatusRepeatedly = (pushStatusOnce |> then(delayRequest)) |> restart let peerId = strongSelf.peerId - let updatePresenceLocally = strongSelf.postbox.modify { modifier -> Void in + let updatePresenceLocally = strongSelf.postbox.transaction { transaction -> Void in let timestamp: Double if online { timestamp = CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970 + 60.0 * 60.0 * 24.0 * 356.0 } else { timestamp = CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970 - 1.0 } - modifier.updatePeerPresences([peerId: TelegramUserPresence(status: .present(until: Int32(timestamp)))]) + transaction.updatePeerPresences([peerId: TelegramUserPresence(status: .present(until: Int32(timestamp)))]) } return combineLatest(pushStatusRepeatedly, updatePresenceLocally) |> mapToSignal { _ -> Signal in return .complete() } diff --git a/TelegramCore/AccountManager.swift b/TelegramCore/AccountManager.swift index cec1a5f19e..097c7618be 100644 --- a/TelegramCore/AccountManager.swift +++ b/TelegramCore/AccountManager.swift @@ -98,10 +98,10 @@ public func currentAccount(networkArguments: NetworkInitializationArguments, sup } public func logoutFromAccount(id: AccountRecordId, accountManager: AccountManager) -> Signal { - return accountManager.modify { modifier -> Void in - let currentId = modifier.getCurrentId() + return accountManager.transaction { transaction -> Void in + let currentId = transaction.getCurrentId() if let currentId = currentId { - modifier.updateRecord(currentId, { current in + transaction.updateRecord(currentId, { current in if let current = current { var found = false for attribute in current.attributes { @@ -119,8 +119,8 @@ public func logoutFromAccount(id: AccountRecordId, accountManager: AccountManage return nil } }) - let id = modifier.createRecord([]) - modifier.setCurrentId(id) + let id = transaction.createRecord([]) + transaction.setCurrentId(id) } } } @@ -209,8 +209,8 @@ private func cleanupAccount(networkArguments: NetworkInitializationArguments, ac } |> mapToSignal { _ -> Signal in account.shouldBeServiceTaskMaster.set(.single(.never)) - return accountManager.modify { modifier -> Void in - modifier.updateRecord(id, { _ in + return accountManager.transaction { transaction -> Void in + transaction.updateRecord(id, { _ in return nil }) } diff --git a/TelegramCore/AccountStateManagementUtils.swift b/TelegramCore/AccountStateManagementUtils.swift index aa162d8df6..5f62212b76 100644 --- a/TelegramCore/AccountStateManagementUtils.swift +++ b/TelegramCore/AccountStateManagementUtils.swift @@ -256,32 +256,32 @@ private func locallyGeneratedMessageTimestampsFromDifference(_ difference: Api.u return messageTimestamps } -private func initialStateWithPeerIds(_ modifier: Modifier, peerIds: Set, associatedMessageIds: Set, peerIdsWithNewMessages: Set, locallyGeneratedMessageTimestamps: [PeerId: [(MessageId.Namespace, Int32)]]) -> AccountMutableState { +private func initialStateWithPeerIds(_ transaction: Transaction, peerIds: Set, associatedMessageIds: Set, peerIdsWithNewMessages: Set, locallyGeneratedMessageTimestamps: [PeerId: [(MessageId.Namespace, Int32)]]) -> AccountMutableState { var peers: [PeerId: Peer] = [:] var chatStates: [PeerId: PeerChatState] = [:] for peerId in peerIds { - if let peer = modifier.getPeer(peerId) { + if let peer = transaction.getPeer(peerId) { peers[peerId] = peer } if peerId.namespace == Namespaces.Peer.CloudChannel { - if let channelState = modifier.getPeerChatState(peerId) as? ChannelState { + if let channelState = transaction.getPeerChatState(peerId) as? ChannelState { chatStates[peerId] = channelState } } else if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup { - if let chatState = modifier.getPeerChatState(peerId) as? RegularChatState { + if let chatState = transaction.getPeerChatState(peerId) as? RegularChatState { chatStates[peerId] = chatState } } } - let storedMessages = modifier.filterStoredMessageIds(associatedMessageIds) + let storedMessages = transaction.filterStoredMessageIds(associatedMessageIds) var storedMessagesByPeerIdAndTimestamp: [PeerId: Set] = [:] if !locallyGeneratedMessageTimestamps.isEmpty { for (peerId, namespacesAndTimestamps) in locallyGeneratedMessageTimestamps { for (namespace, timestamp) in namespacesAndTimestamps { - if let messageId = modifier.storedMessageId(peerId: peerId, namespace: namespace, timestamp: timestamp) { + if let messageId = transaction.storedMessageId(peerId: peerId, namespace: namespace, timestamp: timestamp) { if storedMessagesByPeerIdAndTimestamp[peerId] == nil { storedMessagesByPeerIdAndTimestamp[peerId] = Set([MessageIndex(id: messageId, timestamp: timestamp)]) } else { @@ -297,10 +297,10 @@ private func initialStateWithPeerIds(_ modifier: Modifier, peerIds: Set, var cloudReadStates: [PeerId: PeerReadState] = [:] for peerId in peerIdsWithNewMessages { - if let notificationSettings = modifier.getPeerNotificationSettings(peerId) { + if let notificationSettings = transaction.getPeerNotificationSettings(peerId) { peerNotificationSettings[peerId] = notificationSettings } - if let readStates = modifier.getPeerReadStates(peerId) { + if let readStates = transaction.getPeerReadStates(peerId) { for (namespace, state) in readStates { if namespace == Namespaces.Message.Cloud { cloudReadStates[peerId] = state @@ -316,25 +316,25 @@ private func initialStateWithPeerIds(_ modifier: Modifier, peerIds: Set, } } - return AccountMutableState(initialState: AccountInitialState(state: (modifier.getState() as? AuthorizedAccountState)!.state!, peerIds: peerIds, messageIds: associatedMessageIds, peerIdsWithNewMessages: peerIdsWithNewMessages, chatStates: chatStates, peerNotificationSettings: peerNotificationSettings, locallyGeneratedMessageTimestamps: locallyGeneratedMessageTimestamps, cloudReadStates: cloudReadStates), initialPeers: peers, initialStoredMessages: storedMessages, initialReadInboxMaxIds: readInboxMaxIds, storedMessagesByPeerIdAndTimestamp: storedMessagesByPeerIdAndTimestamp) + return AccountMutableState(initialState: AccountInitialState(state: (transaction.getState() as? AuthorizedAccountState)!.state!, peerIds: peerIds, messageIds: associatedMessageIds, peerIdsWithNewMessages: peerIdsWithNewMessages, chatStates: chatStates, peerNotificationSettings: peerNotificationSettings, locallyGeneratedMessageTimestamps: locallyGeneratedMessageTimestamps, cloudReadStates: cloudReadStates), initialPeers: peers, initialStoredMessages: storedMessages, initialReadInboxMaxIds: readInboxMaxIds, storedMessagesByPeerIdAndTimestamp: storedMessagesByPeerIdAndTimestamp) } func initialStateWithUpdateGroups(_ account: Account, groups: [UpdateGroup]) -> Signal { - return account.postbox.modify { modifier -> AccountMutableState in + return account.postbox.transaction { transaction -> AccountMutableState in let peerIds = peerIdsFromUpdateGroups(groups) let associatedMessageIds = associatedMessageIdsFromUpdateGroups(groups) let peerIdsWithNewMessages = peersWithNewMessagesFromUpdateGroups(groups) - return initialStateWithPeerIds(modifier, peerIds: peerIds, associatedMessageIds: associatedMessageIds, peerIdsWithNewMessages: peerIdsWithNewMessages, locallyGeneratedMessageTimestamps: locallyGeneratedMessageTimestampsFromUpdateGroups(groups)) + return initialStateWithPeerIds(transaction, peerIds: peerIds, associatedMessageIds: associatedMessageIds, peerIdsWithNewMessages: peerIdsWithNewMessages, locallyGeneratedMessageTimestamps: locallyGeneratedMessageTimestampsFromUpdateGroups(groups)) } } func initialStateWithDifference(_ account: Account, difference: Api.updates.Difference) -> Signal { - return account.postbox.modify { modifier -> AccountMutableState in + return account.postbox.transaction { transaction -> AccountMutableState in let peerIds = peerIdsFromDifference(difference) let associatedMessageIds = associatedMessageIdsFromDifference(difference) let peerIdsWithNewMessages = peersWithNewMessagesFromDifference(difference) - return initialStateWithPeerIds(modifier, peerIds: peerIds, associatedMessageIds: associatedMessageIds, peerIdsWithNewMessages: peerIdsWithNewMessages, locallyGeneratedMessageTimestamps: locallyGeneratedMessageTimestampsFromDifference(difference)) + return initialStateWithPeerIds(transaction, peerIds: peerIds, associatedMessageIds: associatedMessageIds, peerIdsWithNewMessages: peerIdsWithNewMessages, locallyGeneratedMessageTimestamps: locallyGeneratedMessageTimestampsFromDifference(difference)) } } @@ -1306,15 +1306,15 @@ private func resolveMissingPeerCloudReadStates(account: Account, state: AccountM } func keepPollingChannel(account: Account, peerId: PeerId, stateManager: AccountStateManager) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let accountState = (modifier.getState() as? AuthorizedAccountState)?.state, let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Signal in + if let accountState = (transaction.getState() as? AuthorizedAccountState)?.state, let peer = transaction.getPeer(peerId) { var chatStates: [PeerId: PeerChatState] = [:] - if let channelState = modifier.getPeerChatState(peerId) as? ChannelState { + if let channelState = transaction.getPeerChatState(peerId) as? ChannelState { chatStates[peerId] = channelState } let initialPeers: [PeerId: Peer] = [peerId: peer] var peerNotificationSettings: [PeerId: TelegramPeerNotificationSettings] = [:] - if let notificationSettings = modifier.getPeerNotificationSettings(peerId) as? TelegramPeerNotificationSettings { + if let notificationSettings = transaction.getPeerNotificationSettings(peerId) as? TelegramPeerNotificationSettings { peerNotificationSettings[peerId] = notificationSettings } let initialState = AccountMutableState(initialState: AccountInitialState(state: accountState, peerIds: Set(), messageIds: Set(), peerIdsWithNewMessages: Set(), chatStates: chatStates, peerNotificationSettings: peerNotificationSettings, locallyGeneratedMessageTimestamps: [:], cloudReadStates: [:]), initialPeers: initialPeers, initialStoredMessages: Set(), initialReadInboxMaxIds: [:], storedMessagesByPeerIdAndTimestamp: [:]) @@ -1643,7 +1643,7 @@ private func pollChannel(_ account: Account, peer: Peer, state: AccountMutableSt } } -private func verifyTransaction(_ modifier: Modifier, finalState: AccountMutableState) -> Bool { +private func verifyTransaction(_ transaction: Transaction, finalState: AccountMutableState) -> Bool { var hadUpdateState = false var channelsWithUpdatedStates = Set() @@ -1674,7 +1674,7 @@ private func verifyTransaction(_ modifier: Modifier, finalState: AccountMutableS if hadUpdateState { var previousStateMatches = false - let currentState = (modifier.getState() as? AuthorizedAccountState)?.state + let currentState = (transaction.getState() as? AuthorizedAccountState)?.state let previousState = finalState.initialState.state if let currentState = currentState { previousStateMatches = previousState == currentState @@ -1689,7 +1689,7 @@ private func verifyTransaction(_ modifier: Modifier, finalState: AccountMutableS } for peerId in channelsWithUpdatedStates { - let currentState = modifier.getPeerChatState(peerId) + let currentState = transaction.getPeerChatState(peerId) var previousStateMatches = false let previousState = finalState.initialState.chatStates[peerId] as? ChannelState if let currentState = currentState, let previousState = previousState { @@ -1775,8 +1775,8 @@ private func optimizedOperations(_ operations: [AccountStateMutationOperation]) private var testAddInvalidation = false -func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modifier, auxiliaryMethods: AccountAuxiliaryMethods, finalState: AccountFinalState) -> AccountReplayedFinalState? { - let verified = verifyTransaction(modifier, finalState: finalState.state) +func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, transaction: Transaction, auxiliaryMethods: AccountAuxiliaryMethods, finalState: AccountFinalState) -> AccountReplayedFinalState? { + let verified = verifyTransaction(transaction, finalState: finalState.state) if !verified { Logger.shared.log("State", "failed to verify final state") return nil @@ -1800,17 +1800,17 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif for (peerId, namespaces) in finalState.state.namespacesWithHolesFromPreviousState { for namespace in namespaces { - modifier.addHole(MessageId(peerId: peerId, namespace: namespace, id: Int32.max)) + transaction.addHole(MessageId(peerId: peerId, namespace: namespace, id: Int32.max)) if namespace == Namespaces.Message.Cloud { - let peer: Peer? = finalState.state.peers[peerId] ?? modifier.getPeer(peerId) + let peer: Peer? = finalState.state.peers[peerId] ?? transaction.getPeer(peerId) if let peer = peer { var groupId: PeerGroupId? if let channel = peer as? TelegramChannel { groupId = channel.peerGroupId } if groupId == nil { - groupId = modifier.getPeerGroupId(peerId) + groupId = transaction.getPeerGroupId(peerId) } if let groupId = groupId { addHolesToGroupFeedIds.insert(groupId) @@ -1823,22 +1823,22 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif } for groupId in addHolesToGroupFeedIds { - modifier.addFeedHoleFromLatestEntries(groupId: groupId) - let groupState = (modifier.getPeerGroupState(groupId) as? TelegramPeerGroupState) ?? TelegramPeerGroupState() - modifier.setPeerGroupState(groupId, state: groupState.withInvalidatedStateIndex()) + transaction.addFeedHoleFromLatestEntries(groupId: groupId) + let groupState = (transaction.getPeerGroupState(groupId) as? TelegramPeerGroupState) ?? TelegramPeerGroupState() + transaction.setPeerGroupState(groupId, state: groupState.withInvalidatedStateIndex()) } if !testAddInvalidation { testAddInvalidation = true let groupId = PeerGroupId(rawValue: 1) - let groupState = (modifier.getPeerGroupState(groupId) as? TelegramPeerGroupState) ?? TelegramPeerGroupState() - modifier.setPeerGroupState(groupId, state: groupState.withInvalidatedStateIndex()) + let groupState = (transaction.getPeerGroupState(groupId) as? TelegramPeerGroupState) ?? TelegramPeerGroupState() + transaction.setPeerGroupState(groupId, state: groupState.withInvalidatedStateIndex()) } for operation in optimizedOperations(finalState.state.operations) { switch operation { case let .AddMessages(messages, location): - let _ = modifier.addMessages(messages, location: location) + let _ = transaction.addMessages(messages, location: location) if case .UpperHistoryBlock = location { for message in messages { let chatPeerId = message.id.peerId @@ -1887,13 +1887,13 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif } } case let .DeleteMessagesWithGlobalIds(ids): - modifier.deleteMessagesWithGlobalIds(ids) + transaction.deleteMessagesWithGlobalIds(ids) case let .DeleteMessages(ids): - modifier.deleteMessages(ids) + transaction.deleteMessages(ids) case let .UpdateMinAvailableMessage(id): - modifier.deleteMessagesInRange(peerId: id.peerId, namespace: id.namespace, minId: 1, maxId: id.id) + transaction.deleteMessagesInRange(peerId: id.peerId, namespace: id.namespace, minId: 1, maxId: id.id) case let .EditMessage(id, message): - modifier.updateMessage(id, update: { previousMessage in + transaction.updateMessage(id, update: { previousMessage in var updatedFlags = message.flags var updatedLocalTags = message.localTags if previousMessage.localTags.contains(.OutgoingLiveLocation) { @@ -1907,21 +1907,21 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif return .update(message.withUpdatedLocalTags(updatedLocalTags).withUpdatedFlags(updatedFlags)) }) case let .UpdateMedia(id, media): - modifier.updateMedia(id, update: media) + transaction.updateMedia(id, update: media) if let media = media as? TelegramMediaWebpage { updatedWebpages[id] = media } case let .ReadInbox(messageId): - modifier.applyIncomingReadMaxId(messageId) + transaction.applyIncomingReadMaxId(messageId) case let .ReadOutbox(messageId): - modifier.applyOutgoingReadMaxId(messageId) + transaction.applyOutgoingReadMaxId(messageId) case let .ReadGroupFeedInbox(groupId, index): - modifier.applyGroupFeedReadMaxIndex(groupId: groupId, index: index) + transaction.applyGroupFeedReadMaxIndex(groupId: groupId, index: index) case let .ResetReadState(peerId, namespace, maxIncomingReadId, maxOutgoingReadId, maxKnownId, count, markedUnread): var markedUnreadValue: Bool = false if let markedUnread = markedUnread { markedUnreadValue = markedUnread - } else if let states = modifier.getPeerReadStates(peerId) { + } else if let states = transaction.getPeerReadStates(peerId) { inner: for (stateNamespace, stateValue) in states { if stateNamespace == namespace { markedUnreadValue = stateValue.markedUnread @@ -1929,26 +1929,26 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif } } } - modifier.resetIncomingReadStates([peerId: [namespace: .idBased(maxIncomingReadId: maxIncomingReadId, maxOutgoingReadId: maxOutgoingReadId, maxKnownId: maxKnownId, count: count, markedUnread: markedUnreadValue)]]) + transaction.resetIncomingReadStates([peerId: [namespace: .idBased(maxIncomingReadId: maxIncomingReadId, maxOutgoingReadId: maxOutgoingReadId, maxKnownId: maxKnownId, count: count, markedUnread: markedUnreadValue)]]) case let .UpdatePeerChatUnreadMark(peerId, namespace, value): - modifier.applyMarkUnread(peerId: peerId, namespace: namespace, value: value, interactive: false) + transaction.applyMarkUnread(peerId: peerId, namespace: namespace, value: value, interactive: false) case let .ResetMessageTagSummary(peerId, namespace, count, range): - modifier.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: namespace, count: count, maxId: range.maxId) + transaction.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: namespace, count: count, maxId: range.maxId) case let .UpdateState(state): - let currentState = modifier.getState() as! AuthorizedAccountState - modifier.setState(currentState.changedState(state)) + let currentState = transaction.getState() as! AuthorizedAccountState + transaction.setState(currentState.changedState(state)) Logger.shared.log("State", "apply state \(state)") case let .UpdateChannelState(peerId, channelState): - modifier.setPeerChatState(peerId, state: channelState) + transaction.setPeerChatState(peerId, state: channelState) case let .UpdateNotificationSettings(subject, notificationSettings): switch subject { case let .peer(peerId): - modifier.updateCurrentPeerNotificationSettings([peerId: notificationSettings]) + transaction.updateCurrentPeerNotificationSettings([peerId: notificationSettings]) } case let .UpdateGlobalNotificationSettings(subject, notificationSettings): switch subject { case .privateChats: - modifier.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in + transaction.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in var previous: GlobalNotificationSettings if let current = current as? GlobalNotificationSettings { previous = current @@ -1960,7 +1960,7 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif }) }) case .groups: - modifier.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in + transaction.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in var previous: GlobalNotificationSettings if let current = current as? GlobalNotificationSettings { previous = current @@ -1975,31 +1975,31 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif case let .MergeApiChats(chats): var peers: [Peer] = [] for chat in chats { - if let groupOrChannel = mergeGroupOrChannel(lhs: modifier.getPeer(chat.peerId), rhs: chat) { + if let groupOrChannel = mergeGroupOrChannel(lhs: transaction.getPeer(chat.peerId), rhs: chat) { peers.append(groupOrChannel) } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated in + updatePeers(transaction: transaction, peers: peers, update: { _, updated in return updated }) case let .MergeApiUsers(users): var peers: [Peer] = [] for user in users { - if let telegramUser = TelegramUser.merge(modifier.getPeer(user.peerId) as? TelegramUser, rhs: user) { + if let telegramUser = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { peers.append(telegramUser) } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated in + updatePeers(transaction: transaction, peers: peers, update: { _, updated in return updated }) case let .UpdatePeer(id, f): - if let peer = f(modifier.getPeer(id)) { - updatePeers(modifier: modifier, peers: [peer], update: { _, updated in + if let peer = f(transaction.getPeer(id)) { + updatePeers(transaction: transaction, peers: [peer], update: { _, updated in return updated }) } case let .UpdateCachedPeerData(id, f): - modifier.updatePeerCachedData(peerIds: Set([id]), update: { _, current in + transaction.updatePeerCachedData(peerIds: Set([id]), update: { _, current in return f(current) }) case let .MergePeerPresences(presences): @@ -2010,17 +2010,17 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif delayNotificatonsUntil = until + 30 } } - modifier.updatePeerPresences(filteredPresences) + transaction.updatePeerPresences(filteredPresences) case let .UpdateSecretChat(chat, _): - updateSecretChat(accountPeerId: accountPeerId, modifier: modifier, chat: chat, requestData: nil) + updateSecretChat(accountPeerId: accountPeerId, transaction: transaction, chat: chat, requestData: nil) case let .AddSecretMessages(messages): for message in messages { let peerId = message.peerId - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretIncomingEncrypted, tagLocalIndex: .automatic, tagMergedIndex: .none, contents: SecretChatIncomingEncryptedOperation(message: message)) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretIncomingEncrypted, tagLocalIndex: .automatic, tagMergedIndex: .none, contents: SecretChatIncomingEncryptedOperation(message: message)) peerIdsWithAddedSecretMessages.insert(peerId) } case let .ReadSecretOutbox(peerId, maxTimestamp, actionTimestamp): - applyOutgoingReadMaxIndex(modifier: modifier, index: MessageIndex.upperBound(peerId: peerId, timestamp: maxTimestamp, namespace: Namespaces.Message.Local), beginCountdownAt: actionTimestamp) + applyOutgoingReadMaxIndex(transaction: transaction, index: MessageIndex.upperBound(peerId: peerId, timestamp: maxTimestamp, namespace: Namespaces.Message.Local), beginCountdownAt: actionTimestamp) case let .AddPeerInputActivity(chatPeerId, peerId, activity): if let peerId = peerId { if updatedTypingActivities[chatPeerId] == nil { @@ -2036,13 +2036,13 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif case let .pin(itemId): switch itemId { case let .peer(peerId): - if modifier.getPeer(peerId) == nil || modifier.getPeerChatListInclusion(peerId) == .notSpecified { - addSynchronizePinnedChatsOperation(modifier: modifier) + if transaction.getPeer(peerId) == nil || transaction.getPeerChatListInclusion(peerId) == .notSpecified { + addSynchronizePinnedChatsOperation(transaction: transaction) } else { - var currentItemIds = modifier.getPinnedItemIds() + var currentItemIds = transaction.getPinnedItemIds() if !currentItemIds.contains(.peer(peerId)) { currentItemIds.insert(.peer(peerId), at: 0) - modifier.setPinnedItemIds(currentItemIds) + transaction.setPinnedItemIds(currentItemIds) } } case let .group(groupId): @@ -2051,38 +2051,38 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif case let .unpin(itemId): switch itemId { case let .peer(peerId): - var currentItemIds = modifier.getPinnedItemIds() + var currentItemIds = transaction.getPinnedItemIds() if let index = currentItemIds.index(of: .peer(peerId)) { currentItemIds.remove(at: index) - modifier.setPinnedItemIds(currentItemIds) + transaction.setPinnedItemIds(currentItemIds) } else { - addSynchronizePinnedChatsOperation(modifier: modifier) + addSynchronizePinnedChatsOperation(transaction: transaction) } case let .group(groupId): break } case let .reorder(itemIds): - let currentItemIds = modifier.getPinnedItemIds() + let currentItemIds = transaction.getPinnedItemIds() if Set(itemIds) == Set(currentItemIds) { - modifier.setPinnedItemIds(itemIds) + transaction.setPinnedItemIds(itemIds) } else { - addSynchronizePinnedChatsOperation(modifier: modifier) + addSynchronizePinnedChatsOperation(transaction: transaction) } case .sync: - addSynchronizePinnedChatsOperation(modifier: modifier) + addSynchronizePinnedChatsOperation(transaction: transaction) } case let .ReadMessageContents(peerId, messageIds): if let peerId = peerId { for id in messageIds { - markMessageContentAsConsumedRemotely(modifier: modifier, messageId: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: id)) + markMessageContentAsConsumedRemotely(transaction: transaction, messageId: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: id)) } } else { - for messageId in modifier.messageIdsForGlobalIds(messageIds) { - markMessageContentAsConsumedRemotely(modifier: modifier, messageId: messageId) + for messageId in transaction.messageIdsForGlobalIds(messageIds) { + markMessageContentAsConsumedRemotely(transaction: transaction, messageId: messageId) } } case let .UpdateMessageImpressionCount(id, count): - modifier.updateMessage(id, update: { currentMessage in + transaction.updateMessage(id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -2101,7 +2101,7 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif case .UpdateRecentGifs: syncRecentGifs = true case let .UpdateChatInputState(peerId, inputState): - modifier.updatePeerChatInterfaceState(peerId, update: { current in + transaction.updatePeerChatInterfaceState(peerId, update: { current in return auxiliaryMethods.updatePeerChatInputState(current, inputState) }) case let .UpdateCall(call): @@ -2116,7 +2116,7 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif } for peerId in finalState.state.initialState.peerIdsWithNewMessages { - updatePeerChatInclousionWithNewMessages(modifier: modifier, id: peerId) + updatePeerChatInclousionWithNewMessages(transaction: transaction, id: peerId) } if !stickerPackOperations.isEmpty { @@ -2127,8 +2127,8 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif return false } }) { - addSynchronizeInstalledStickerPacksOperation(modifier: modifier, namespace: .stickers) - addSynchronizeInstalledStickerPacksOperation(modifier: modifier, namespace: .masks) + addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: .stickers) + addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: .masks) } else { var syncStickers = false var syncMasks = false @@ -2187,16 +2187,16 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif continue loop } - var updatedInfos = modifier.getItemCollectionsInfos(namespace: info.id.namespace).map { $0.1 as! StickerPackCollectionInfo } + var updatedInfos = transaction.getItemCollectionsInfos(namespace: info.id.namespace).map { $0.1 as! StickerPackCollectionInfo } if let index = updatedInfos.index(where: { $0.id == info.id }) { let currentInfo = updatedInfos[index] updatedInfos.remove(at: index) updatedInfos.insert(currentInfo, at: 0) } else { updatedInfos.insert(info, at: 0) - modifier.replaceItemCollectionItems(collectionId: info.id, items: items) + transaction.replaceItemCollectionItems(collectionId: info.id, items: items) } - modifier.replaceItemCollectionInfos(namespace: info.id.namespace, itemCollectionInfos: updatedInfos.map { ($0.id, $0) }) + transaction.replaceItemCollectionInfos(namespace: info.id.namespace, itemCollectionInfos: updatedInfos.map { ($0.id, $0) }) case let .reorder(namespace, ids): let collectionNamespace: ItemCollectionId.Namespace switch namespace { @@ -2205,7 +2205,7 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif case .masks: collectionNamespace = Namespaces.ItemCollection.CloudMaskPacks } - let currentInfos = modifier.getItemCollectionsInfos(namespace: collectionNamespace).map { $0.1 as! StickerPackCollectionInfo } + let currentInfos = transaction.getItemCollectionsInfos(namespace: collectionNamespace).map { $0.1 as! StickerPackCollectionInfo } if Set(currentInfos.map { $0.id.id }) != Set(ids) { switch namespace { case .stickers: @@ -2223,7 +2223,7 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif let currentInfo = currentDict[ItemCollectionId(namespace: collectionNamespace, id: id)]! updatedInfos.append(currentInfo) } - modifier.replaceItemCollectionInfos(namespace: collectionNamespace, itemCollectionInfos: updatedInfos.map { ($0.id, $0) }) + transaction.replaceItemCollectionInfos(namespace: collectionNamespace, itemCollectionInfos: updatedInfos.map { ($0.id, $0) }) } case .sync: syncStickers = true @@ -2232,10 +2232,10 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif } } if syncStickers { - addSynchronizeInstalledStickerPacksOperation(modifier: modifier, namespace: .stickers) + addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: .stickers) } if syncMasks { - addSynchronizeInstalledStickerPacksOperation(modifier: modifier, namespace: .masks) + addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: .masks) } } } @@ -2245,23 +2245,23 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif return $0.0 < $1.0 }).map({ $0.1 }) for file in stickerFiles { - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentStickers, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 20) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentStickers, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 20) } } if syncRecentGifs { - addSynchronizeSavedGifsOperation(modifier: modifier, operation: .sync) + addSynchronizeSavedGifsOperation(transaction: transaction, operation: .sync) } else { let gifFiles: [TelegramMediaFile] = recentlyUsedGifs.values.sorted(by: { return $0.0 < $1.0 }).map({ $0.1 }) for file in gifFiles { - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 200) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 200) } } for chatPeerId in updatedSecretChatTypingActivities { - if let peer = modifier.getPeer(chatPeerId) as? TelegramSecretChat { + if let peer = transaction.getPeer(chatPeerId) as? TelegramSecretChat { let authorId = peer.regularPeerId let activityValue: PeerInputActivity? = .typingText if updatedTypingActivities[chatPeerId] == nil { @@ -2277,9 +2277,9 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif for peerId in peerIdsWithAddedSecretMessages { while true { - let keychain = (modifier.getPeerChatState(peerId) as? SecretChatState)?.keychain - if processSecretChatIncomingEncryptedOperations(modifier: modifier, peerId: peerId) { - let processResult = processSecretChatIncomingDecryptedOperations(mediaBox: mediaBox, modifier: modifier, peerId: peerId) + let keychain = (transaction.getPeerChatState(peerId) as? SecretChatState)?.keychain + if processSecretChatIncomingEncryptedOperations(transaction: transaction, peerId: peerId) { + let processResult = processSecretChatIncomingDecryptedOperations(mediaBox: mediaBox, transaction: transaction, peerId: peerId) if !processResult.addedMessages.isEmpty { for message in processResult.addedMessages { if case let .Id(id) = message.id { @@ -2293,7 +2293,7 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif } } } - let updatedKeychain = (modifier.getPeerChatState(peerId) as? SecretChatState)?.keychain + let updatedKeychain = (transaction.getPeerChatState(peerId) as? SecretChatState)?.keychain if updatedKeychain == keychain { break } @@ -2310,7 +2310,7 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif } if pollLangPack { - addSynchronizeLocalizationUpdatesOperation(modifier: modifier) + addSynchronizeLocalizationUpdatesOperation(transaction: transaction) } else if !langPackDifferences.isEmpty { langPackDifferences.sort(by: { lhs, rhs in let lhsVersion: Int32 @@ -2327,8 +2327,8 @@ func replayFinalState(accountPeerId: PeerId, mediaBox: MediaBox, modifier: Modif }) for difference in langPackDifferences { - if !tryApplyingLanguageDifference(modifier: modifier, difference: difference) { - addSynchronizeLocalizationUpdatesOperation(modifier: modifier) + if !tryApplyingLanguageDifference(transaction: transaction, difference: difference) { + addSynchronizeLocalizationUpdatesOperation(transaction: transaction) break } } diff --git a/TelegramCore/AccountStateManager.swift b/TelegramCore/AccountStateManager.swift index 7c8680e83e..52f69318f2 100644 --- a/TelegramCore/AccountStateManager.swift +++ b/TelegramCore/AccountStateManager.swift @@ -287,8 +287,8 @@ public final class AccountStateManager { account.postbox.mediaBox.storeResourceData(resource.id, data: data) } } - return account.postbox.modify { modifier -> (Api.updates.Difference?, AccountReplayedFinalState?) in - if let replayedState = replayFinalState(accountPeerId: accountPeerId, mediaBox: mediaBox, modifier: modifier, auxiliaryMethods: auxiliaryMethods, finalState: finalState) { + return account.postbox.transaction { transaction -> (Api.updates.Difference?, AccountReplayedFinalState?) in + if let replayedState = replayFinalState(accountPeerId: accountPeerId, mediaBox: mediaBox, transaction: transaction, auxiliaryMethods: auxiliaryMethods, finalState: finalState) { return (difference, replayedState) } else { return (nil, nil) @@ -303,11 +303,11 @@ public final class AccountStateManager { let appliedState = account.network.request(Api.functions.updates.getState()) |> retryRequest |> mapToSignal { state in - return account.postbox.modify { modifier -> (Api.updates.Difference?, AccountReplayedFinalState?) in - if let currentState = modifier.getState() as? AuthorizedAccountState { + return account.postbox.transaction { transaction -> (Api.updates.Difference?, AccountReplayedFinalState?) in + if let currentState = transaction.getState() as? AuthorizedAccountState { switch state { case let .state(pts, qts, date, seq, _): - modifier.setState(currentState.changedState(AuthorizedAccountState.State(pts: pts, qts: qts, date: date, seq: seq))) + transaction.setState(currentState.changedState(AuthorizedAccountState.State(pts: pts, qts: qts, date: date, seq: seq))) } } return (nil, nil) @@ -387,8 +387,8 @@ public final class AccountStateManager { } } - return account.postbox.modify { modifier -> AccountReplayedFinalState? in - return replayFinalState(accountPeerId: accountPeerId, mediaBox: mediaBox, modifier: modifier, auxiliaryMethods: auxiliaryMethods, finalState: finalState) + return account.postbox.transaction { transaction -> AccountReplayedFinalState? in + return replayFinalState(accountPeerId: accountPeerId, mediaBox: mediaBox, transaction: transaction, auxiliaryMethods: auxiliaryMethods, finalState: finalState) } |> map({ ($0, finalState) }) |> deliverOn(queue) @@ -482,12 +482,12 @@ public final class AccountStateManager { let _ = self.delayNotificatonsUntil.swap(events.delayNotificatonsUntil) } - let signal = self.account.postbox.modify { modifier -> [(Message, PeerGroupId?)] in + let signal = self.account.postbox.transaction { transaction -> [(Message, PeerGroupId?)] in var messages: [(Message, PeerGroupId?)] = [] for id in events.addedIncomingMessageIds { - let (message, notify, _, _) = messageForNotification(modifier: modifier, id: id, alwaysReturnMessage: false) + let (message, notify, _, _) = messageForNotification(transaction: transaction, id: id, alwaysReturnMessage: false) if let message = message, notify { - messages.append((message, modifier.getPeerGroupId(message.id.peerId))) + messages.append((message, transaction.getPeerGroupId(message.id.peerId))) } } return messages @@ -554,8 +554,8 @@ public final class AccountStateManager { let accountPeerId = self.account.peerId let mediaBox = self.account.postbox.mediaBox let auxiliaryMethods = self.auxiliaryMethods - let signal = self.account.postbox.modify { modifier -> AccountReplayedFinalState? in - return replayFinalState(accountPeerId: accountPeerId, mediaBox: mediaBox, modifier: modifier, auxiliaryMethods: auxiliaryMethods, finalState: finalState) + let signal = self.account.postbox.transaction { transaction -> AccountReplayedFinalState? in + return replayFinalState(accountPeerId: accountPeerId, mediaBox: mediaBox, transaction: transaction, auxiliaryMethods: auxiliaryMethods, finalState: finalState) } |> map({ ($0, finalState) }) |> deliverOn(self.queue) @@ -732,8 +732,8 @@ public final class AccountStateManager { } } -public func messageForNotification(modifier: Modifier, id: MessageId, alwaysReturnMessage: Bool) -> (message: Message?, notify: Bool, sound: PeerMessageSound, displayContents: Bool) { - guard let message = modifier.getMessage(id) else { +public func messageForNotification(transaction: Transaction, id: MessageId, alwaysReturnMessage: Bool) -> (message: Message?, notify: Bool, sound: PeerMessageSound, displayContents: Bool) { + guard let message = transaction.getMessage(id) else { Logger.shared.log("AccountStateManager", "notification message doesn't exist") return (nil, false, .bundledModern(id: 0), false) } @@ -754,17 +754,17 @@ public func messageForNotification(modifier: Modifier, id: MessageId, alwaysRetu let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) var notificationPeerId = id.peerId - if let peer = modifier.getPeer(id.peerId), let associatedPeerId = peer.associatedPeerId { + if let peer = transaction.getPeer(id.peerId), let associatedPeerId = peer.associatedPeerId { notificationPeerId = associatedPeerId } if message.personal, let author = message.author { notificationPeerId = author.id } - if let notificationSettings = modifier.getPeerNotificationSettings(notificationPeerId) as? TelegramPeerNotificationSettings { + if let notificationSettings = transaction.getPeerNotificationSettings(notificationPeerId) as? TelegramPeerNotificationSettings { var defaultSound: PeerMessageSound = .bundledModern(id: 0) var defaultNotify: Bool = true - if let globalNotificationSettings = modifier.getPreferencesEntry(key: PreferencesKeys.globalNotifications) as? GlobalNotificationSettings { + if let globalNotificationSettings = transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications) as? GlobalNotificationSettings { if id.peerId.namespace == Namespaces.Peer.CloudUser { defaultNotify = globalNotificationSettings.effective.privateChats.enabled defaultSound = globalNotificationSettings.effective.privateChats.sound @@ -815,7 +815,7 @@ public func messageForNotification(modifier: Modifier, id: MessageId, alwaysRetu var foundReadState = false var isUnread = true - if let readState = modifier.getCombinedPeerReadState(id.peerId) { + if let readState = transaction.getCombinedPeerReadState(id.peerId) { if readState.isIncomingMessageIndexRead(MessageIndex(message)) { isUnread = false } diff --git a/TelegramCore/AccountStateReset.swift b/TelegramCore/AccountStateReset.swift index b567e676f6..c415270c15 100644 --- a/TelegramCore/AccountStateReset.swift +++ b/TelegramCore/AccountStateReset.swift @@ -187,15 +187,15 @@ func accountStateReset(postbox: Postbox, network: Network) -> Signal Void in - modifier.resetChatList(keepPeerNamespaces: Set([Namespaces.Peer.SecretChat]), replacementHole: replacementHole) + return postbox.transaction { transaction -> Void in + transaction.resetChatList(keepPeerNamespaces: Set([Namespaces.Peer.SecretChat]), replacementHole: replacementHole) - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) - modifier.updateCurrentPeerNotificationSettings(notificationSettings) + transaction.updateCurrentPeerNotificationSettings(notificationSettings) var allPeersWithMessages = Set() for message in storeMessages { @@ -207,43 +207,43 @@ func accountStateReset(postbox: Postbox, network: Network) -> Signal 1 { var skipHole = false - if let localTopId = modifier.getTopMesssageIndex(peerId: messageId.peerId, namespace: messageId.namespace)?.id { + if let localTopId = transaction.getTopMesssageIndex(peerId: messageId.peerId, namespace: messageId.namespace)?.id { if localTopId >= messageId { skipHole = true } } if !skipHole { - modifier.addHole(MessageId(peerId: messageId.peerId, namespace: messageId.namespace, id: messageId.id - 1)) + transaction.addHole(MessageId(peerId: messageId.peerId, namespace: messageId.namespace, id: messageId.id - 1)) } } } - let _ = modifier.addMessages(storeMessages, location: .UpperHistoryBlock) + let _ = transaction.addMessages(storeMessages, location: .UpperHistoryBlock) - modifier.resetIncomingReadStates(readStates) + transaction.resetIncomingReadStates(readStates) for (peerId, chatState) in chatStates { if let chatState = chatState as? ChannelState { - if let current = modifier.getPeerChatState(peerId) as? ChannelState { - modifier.setPeerChatState(peerId, state: current.withUpdatedPts(chatState.pts)) + if let current = transaction.getPeerChatState(peerId) as? ChannelState { + transaction.setPeerChatState(peerId, state: current.withUpdatedPts(chatState.pts)) } else { - modifier.setPeerChatState(peerId, state: chatState) + transaction.setPeerChatState(peerId, state: chatState) } } else { - modifier.setPeerChatState(peerId, state: chatState) + transaction.setPeerChatState(peerId, state: chatState) } } - modifier.setPinnedItemIds(replacePinnedItemIds) + transaction.setPinnedItemIds(replacePinnedItemIds) for (peerId, summary) in mentionTagSummaries { - modifier.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud, count: summary.count, maxId: summary.range.maxId) + transaction.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud, count: summary.count, maxId: summary.range.maxId) } - if let currentState = modifier.getState() as? AuthorizedAccountState, let embeddedState = currentState.state { + if let currentState = transaction.getState() as? AuthorizedAccountState, let embeddedState = currentState.state { switch state { case let .state(pts, _, _, seq, _): - modifier.setState(currentState.changedState(AuthorizedAccountState.State(pts: pts, qts: embeddedState.qts, date: embeddedState.date, seq: seq))) + transaction.setState(currentState.changedState(AuthorizedAccountState.State(pts: pts, qts: embeddedState.qts, date: embeddedState.date, seq: seq))) } } } diff --git a/TelegramCore/AccountViewTracker.swift b/TelegramCore/AccountViewTracker.swift index c4ecb27619..ee7f2b0431 100644 --- a/TelegramCore/AccountViewTracker.swift +++ b/TelegramCore/AccountViewTracker.swift @@ -87,7 +87,7 @@ private func fetchWebpage(account: Account, messageId: MessageId) -> Signal Void in + return account.postbox.transaction { transaction -> Void in var peers: [Peer] = [] var peerPresences: [PeerId: PeerPresence] = [:] for chat in chats { @@ -113,12 +113,12 @@ private func fetchWebpage(account: Account, messageId: MessageId) -> Signal Signal Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) } } } else { @@ -286,9 +286,9 @@ public final class AccountViewTracker { if self.webpageDisposables[messageId] == nil { if let (_, url) = localWebpages[messageId] { self.webpageDisposables[messageId] = (webpagePreview(account: account, url: url) |> mapToSignal { webpage -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if let webpage = webpage { - modifier.updateMessage(messageId, update: { currentMessage in + transaction.updateMessage(messageId, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -405,8 +405,8 @@ public final class AccountViewTracker { self.nextUpdatedViewCountDisposableId += 1 if let account = self.account { - let signal = (account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let inputPeer = apiInputPeer(peer) { + let signal = (account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) { return account.network.request(Api.functions.messages.getMessagesViews(peer: inputPeer, id: messageIds.map { $0.id }, increment: .boolTrue)) |> map { Optional($0) } |> `catch` { _ -> Signal<[Int32]?, NoError> in @@ -414,10 +414,10 @@ public final class AccountViewTracker { } |> mapToSignal { viewCounts -> Signal in if let viewCounts = viewCounts { - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in for i in 0 ..< messageIds.count { if i < viewCounts.count { - modifier.updateMessage(messageIds[i], update: { currentMessage in + transaction.updateMessage(messageIds[i], update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -468,9 +468,9 @@ public final class AccountViewTracker { } if !addedMessageIds.isEmpty { if let account = self.account { - let _ = (account.postbox.modify { modifier -> Void in + let _ = (account.postbox.transaction { transaction -> Void in for id in addedMessageIds { - if let message = modifier.getMessage(id) { + if let message = transaction.getMessage(id) { var consume = false inner: for attribute in message.attributes { if let attribute = attribute as? ConsumablePersonalMentionMessageAttribute, !attribute.consumed, !attribute.pending { @@ -479,7 +479,7 @@ public final class AccountViewTracker { } } if consume { - modifier.updateMessage(id, update: { currentMessage in + transaction.updateMessage(id, update: { currentMessage in var attributes = currentMessage.attributes loop: for j in 0 ..< attributes.count { if let attribute = attributes[j] as? ConsumablePersonalMentionMessageAttribute { @@ -490,7 +490,7 @@ public final class AccountViewTracker { return .update(StoreMessage(id: currentMessage.id, globallyUniqueId: currentMessage.globallyUniqueId, groupingKey: currentMessage.groupingKey, timestamp: currentMessage.timestamp, flags: StoreMessageFlags(currentMessage.flags), tags: currentMessage.tags, globalTags: currentMessage.globalTags, localTags: currentMessage.localTags, forwardInfo: currentMessage.forwardInfo.flatMap(StoreMessageForwardInfo.init), authorId: currentMessage.author?.id, text: currentMessage.text, attributes: attributes, media: currentMessage.media)) }) - modifier.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: id, action: ConsumePersonalMessageAction()) + transaction.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: id, action: ConsumePersonalMessageAction()) } } } diff --git a/TelegramCore/AddPeerMember.swift b/TelegramCore/AddPeerMember.swift index 924ca3e218..17d2485d11 100644 --- a/TelegramCore/AddPeerMember.swift +++ b/TelegramCore/AddPeerMember.swift @@ -14,8 +14,8 @@ public enum AddPeerMemberError { } public func addPeerMember(account: Account, peerId: PeerId, memberId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let memberPeer = modifier.getPeer(memberId), let inputUser = apiInputUser(memberPeer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let memberPeer = transaction.getPeer(memberId), let inputUser = apiInputUser(memberPeer) { if let group = peer as? TelegramGroup { return account.network.request(Api.functions.messages.addChatUser(chatId: group.id.id, userId: inputUser, fwdLimit: 100)) |> mapError { error -> AddPeerMemberError in @@ -23,9 +23,9 @@ public func addPeerMember(account: Account, peerId: PeerId, memberId: PeerId) -> } |> mapToSignal { result -> Signal in account.stateManager.addUpdates(result) - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if let message = result.messages.first, let timestamp = message.timestamp { - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in if let cachedData = cachedData as? CachedGroupData, let participants = cachedData.participants { var updatedParticipants = participants.participants var found = false @@ -53,8 +53,8 @@ public func addPeerMember(account: Account, peerId: PeerId, memberId: PeerId) -> } |> mapToSignal { result -> Signal in account.stateManager.addUpdates(result) - return account.postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in + return account.postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in if let cachedData = cachedData as? CachedChannelData, let participants = cachedData.topParticipants { var updatedParticipants = participants.participants var found = false @@ -98,8 +98,8 @@ public func addChannelMember(account: Account, peerId: PeerId, memberId: PeerId) return .generic } |> mapToSignal { currentParticipant -> Signal<(ChannelParticipant?, RenderedChannelParticipant), AddChannelMemberError> in - return account.postbox.modify { modifier -> Signal<(ChannelParticipant?, RenderedChannelParticipant), AddChannelMemberError> in - if let peer = modifier.getPeer(peerId), let memberPeer = modifier.getPeer(memberId), let inputUser = apiInputUser(memberPeer) { + return account.postbox.transaction { transaction -> Signal<(ChannelParticipant?, RenderedChannelParticipant), AddChannelMemberError> in + if let peer = transaction.getPeer(peerId), let memberPeer = transaction.getPeer(memberId), let inputUser = apiInputUser(memberPeer) { if let channel = peer as? TelegramChannel, let inputChannel = apiInputChannel(channel) { let updatedParticipant: ChannelParticipant if let currentParticipant = currentParticipant, case let .member(_, invitedAt, adminInfo, banInfo) = currentParticipant { @@ -116,8 +116,8 @@ public func addChannelMember(account: Account, peerId: PeerId, memberId: PeerId) for updates in result { account.stateManager.addUpdates(updates) } - return account.postbox.modify { modifier -> (ChannelParticipant?, RenderedChannelParticipant) in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in + return account.postbox.transaction { transaction -> (ChannelParticipant?, RenderedChannelParticipant) in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in if let cachedData = cachedData as? CachedChannelData, let memberCount = cachedData.participantsSummary.memberCount, let kickedCount = cachedData.participantsSummary.kickedCount { var updatedMemberCount = memberCount var updatedKickedCount = kickedCount @@ -151,12 +151,12 @@ public func addChannelMember(account: Account, peerId: PeerId, memberId: PeerId) var peers: [PeerId: Peer] = [:] var presences: [PeerId: PeerPresence] = [:] peers[memberPeer.id] = memberPeer - if let presence = modifier.getPeerPresence(peerId: memberPeer.id) { + if let presence = transaction.getPeerPresence(peerId: memberPeer.id) { presences[memberPeer.id] = presence } if case let .member(_, _, maybeAdminInfo, maybeBannedInfo) = updatedParticipant { if let adminInfo = maybeAdminInfo { - if let peer = modifier.getPeer(adminInfo.promotedBy) { + if let peer = transaction.getPeer(adminInfo.promotedBy) { peers[peer.id] = peer } } @@ -178,12 +178,12 @@ public func addChannelMember(account: Account, peerId: PeerId, memberId: PeerId) } public func addChannelMembers(account: Account, peerId: PeerId, memberIds: [PeerId]) -> Signal { - return account.postbox.modify { modifier -> Signal in + return account.postbox.transaction { transaction -> Signal in var memberPeerIds:[PeerId:Peer] = [:] var inputUsers:[Api.InputUser] = [] for memberId in memberIds { - if let peer = modifier.getPeer(memberId) { + if let peer = transaction.getPeer(memberId) { memberPeerIds[peerId] = peer if let inputUser = apiInputUser(peer) { inputUsers.append(inputUser) @@ -191,7 +191,7 @@ public func addChannelMembers(account: Account, peerId: PeerId, memberIds: [Peer } } - if let peer = modifier.getPeer(peerId), let channel = peer as? TelegramChannel, let inputChannel = apiInputChannel(channel) { + if let peer = transaction.getPeer(peerId), let channel = peer as? TelegramChannel, let inputChannel = apiInputChannel(channel) { return account.network.request(Api.functions.channels.inviteToChannel(channel: inputChannel, users: inputUsers)) |> retryRequest |> mapToSignal { result -> Signal in diff --git a/TelegramCore/AddressNames.swift b/TelegramCore/AddressNames.swift index 9ceb6f9f73..347370819f 100644 --- a/TelegramCore/AddressNames.swift +++ b/TelegramCore/AddressNames.swift @@ -55,7 +55,7 @@ public func checkAddressNameFormat(_ value: String, canEmpty: Bool = false) -> A } public func addressNameAvailability(account: Account, domain: AddressNameDomain, name: String) -> Signal { - return account.postbox.modify { modifier -> Signal in + return account.postbox.transaction { transaction -> Signal in switch domain { case .account: return account.network.request(Api.functions.account.checkUsername(username: name)) @@ -71,7 +71,7 @@ public func addressNameAvailability(account: Account, domain: AddressNameDomain, return .single(.invalid) } case let .peer(peerId): - if let peer = modifier.getPeer(peerId), let inputChannel = apiInputChannel(peer) { + if let peer = transaction.getPeer(peerId), let inputChannel = apiInputChannel(peer) { return account.network.request(Api.functions.channels.checkUsername(channel: inputChannel, username: name)) |> map { result -> AddressNameAvailability in switch result { @@ -96,7 +96,7 @@ public enum UpdateAddressNameError { } public func updateAddressName(account: Account, domain: AddressNameDomain, name: String?) -> Signal { - return account.postbox.modify { modifier -> Signal in + return account.postbox.transaction { transaction -> Signal in switch domain { case .account: return account.network.request(Api.functions.account.updateUsername(username: name ?? "")) @@ -104,24 +104,24 @@ public func updateAddressName(account: Account, domain: AddressNameDomain, name: return .generic } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in let user = TelegramUser(user: result) - updatePeers(modifier: modifier, peers: [user], update: { _, updated in + updatePeers(transaction: transaction, peers: [user], update: { _, updated in return updated }) } |> mapError { _ -> UpdateAddressNameError in return .generic } } case let .peer(peerId): - if let peer = modifier.getPeer(peerId), let inputChannel = apiInputChannel(peer) { + if let peer = transaction.getPeer(peerId), let inputChannel = apiInputChannel(peer) { return account.network.request(Api.functions.channels.updateUsername(channel: inputChannel, username: name ?? "")) |> mapError { _ -> UpdateAddressNameError in return .generic } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if case .boolTrue = result { - if let peer = modifier.getPeer(peerId) as? TelegramChannel { - updatePeers(modifier: modifier, peers: [peer.withUpdatedAddressName(name)], update: { _, updated in + if let peer = transaction.getPeer(peerId) as? TelegramChannel { + updatePeers(transaction: transaction, peers: [peer.withUpdatedAddressName(name)], update: { _, updated in return updated }) } @@ -165,10 +165,10 @@ public enum ChannelAddressNameAssignmentAvailability { } public func channelAddressNameAssignmentAvailability(account: Account, peerId: PeerId?) -> Signal { - return account.postbox.modify { modifier -> Signal in + return account.postbox.transaction { transaction -> Signal in var inputChannel: Api.InputChannel? if let peerId = peerId { - if let peer = modifier.getPeer(peerId), let channel = apiInputChannel(peer) { + if let peer = transaction.getPeer(peerId), let channel = apiInputChannel(peer) { inputChannel = channel } } else { diff --git a/TelegramCore/Api0.swift b/TelegramCore/Api0.swift index a1bdd46496..e21055b786 100644 --- a/TelegramCore/Api0.swift +++ b/TelegramCore/Api0.swift @@ -386,7 +386,7 @@ fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = { dict[182649427] = { return Api.MessageRange.parse_messageRange($0) } dict[946083368] = { return Api.messages.StickerSetInstallResult.parse_stickerSetInstallResultSuccess($0) } dict[904138920] = { return Api.messages.StickerSetInstallResult.parse_stickerSetInstallResultArchive($0) } - dict[474704476] = { return Api.Config.parse_config($0) } + dict[398844646] = { return Api.Config.parse_config($0) } dict[-75283823] = { return Api.TopPeerCategoryPeers.parse_topPeerCategoryPeers($0) } dict[-1107729093] = { return Api.Game.parse_game($0) } dict[-1032140601] = { return Api.BotCommand.parse_botCommand($0) } diff --git a/TelegramCore/Api1.swift b/TelegramCore/Api1.swift index 7200476c22..94b3f4627b 100644 --- a/TelegramCore/Api1.swift +++ b/TelegramCore/Api1.swift @@ -9338,13 +9338,13 @@ extension Api { } enum Config: TypeConstructorDescription { - case config(flags: Int32, date: Int32, expires: Int32, testMode: Api.Bool, thisDc: Int32, dcOptions: [Api.DcOption], dcTxtDomainName: String, chatSizeMax: Int32, megagroupSizeMax: Int32, forwardedCountMax: Int32, onlineUpdatePeriodMs: Int32, offlineBlurTimeoutMs: Int32, offlineIdleTimeoutMs: Int32, onlineCloudTimeoutMs: Int32, notifyCloudDelayMs: Int32, notifyDefaultDelayMs: Int32, pushChatPeriodMs: Int32, pushChatLimit: Int32, savedGifsLimit: Int32, editTimeLimit: Int32, revokeTimeLimit: Int32, revokePmTimeLimit: Int32, ratingEDecay: Int32, stickersRecentLimit: Int32, stickersFavedLimit: Int32, channelsReadMediaPeriod: Int32, tmpSessions: Int32?, pinnedDialogsCountMax: Int32, callReceiveTimeoutMs: Int32, callRingTimeoutMs: Int32, callConnectTimeoutMs: Int32, callPacketTimeoutMs: Int32, meUrlPrefix: String, autoupdateUrlPrefix: String?, gifSearchUsername: String?, venueSearchUsername: String?, imgSearchUsername: String?, suggestedLangCode: String?, langPackVersion: Int32?) + case config(flags: Int32, date: Int32, expires: Int32, testMode: Api.Bool, thisDc: Int32, dcOptions: [Api.DcOption], dcTxtDomainName: String, chatSizeMax: Int32, megagroupSizeMax: Int32, forwardedCountMax: Int32, onlineUpdatePeriodMs: Int32, offlineBlurTimeoutMs: Int32, offlineIdleTimeoutMs: Int32, onlineCloudTimeoutMs: Int32, notifyCloudDelayMs: Int32, notifyDefaultDelayMs: Int32, pushChatPeriodMs: Int32, pushChatLimit: Int32, savedGifsLimit: Int32, editTimeLimit: Int32, revokeTimeLimit: Int32, revokePmTimeLimit: Int32, ratingEDecay: Int32, stickersRecentLimit: Int32, stickersFavedLimit: Int32, channelsReadMediaPeriod: Int32, tmpSessions: Int32?, pinnedDialogsCountMax: Int32, callReceiveTimeoutMs: Int32, callRingTimeoutMs: Int32, callConnectTimeoutMs: Int32, callPacketTimeoutMs: Int32, meUrlPrefix: String, autoupdateUrlPrefix: String?, gifSearchUsername: String?, venueSearchUsername: String?, imgSearchUsername: String?, staticMapsProvider: String?, captionLengthMax: Int32, messageLengthMax: Int32, suggestedLangCode: String?, langPackVersion: Int32?) func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) { switch self { - case .config(let flags, let date, let expires, let testMode, let thisDc, let dcOptions, let dcTxtDomainName, let chatSizeMax, let megagroupSizeMax, let forwardedCountMax, let onlineUpdatePeriodMs, let offlineBlurTimeoutMs, let offlineIdleTimeoutMs, let onlineCloudTimeoutMs, let notifyCloudDelayMs, let notifyDefaultDelayMs, let pushChatPeriodMs, let pushChatLimit, let savedGifsLimit, let editTimeLimit, let revokeTimeLimit, let revokePmTimeLimit, let ratingEDecay, let stickersRecentLimit, let stickersFavedLimit, let channelsReadMediaPeriod, let tmpSessions, let pinnedDialogsCountMax, let callReceiveTimeoutMs, let callRingTimeoutMs, let callConnectTimeoutMs, let callPacketTimeoutMs, let meUrlPrefix, let autoupdateUrlPrefix, let gifSearchUsername, let venueSearchUsername, let imgSearchUsername, let suggestedLangCode, let langPackVersion): + case .config(let flags, let date, let expires, let testMode, let thisDc, let dcOptions, let dcTxtDomainName, let chatSizeMax, let megagroupSizeMax, let forwardedCountMax, let onlineUpdatePeriodMs, let offlineBlurTimeoutMs, let offlineIdleTimeoutMs, let onlineCloudTimeoutMs, let notifyCloudDelayMs, let notifyDefaultDelayMs, let pushChatPeriodMs, let pushChatLimit, let savedGifsLimit, let editTimeLimit, let revokeTimeLimit, let revokePmTimeLimit, let ratingEDecay, let stickersRecentLimit, let stickersFavedLimit, let channelsReadMediaPeriod, let tmpSessions, let pinnedDialogsCountMax, let callReceiveTimeoutMs, let callRingTimeoutMs, let callConnectTimeoutMs, let callPacketTimeoutMs, let meUrlPrefix, let autoupdateUrlPrefix, let gifSearchUsername, let venueSearchUsername, let imgSearchUsername, let staticMapsProvider, let captionLengthMax, let messageLengthMax, let suggestedLangCode, let langPackVersion): if boxed { - buffer.appendInt32(474704476) + buffer.appendInt32(398844646) } serializeInt32(flags, buffer: buffer, boxed: false) serializeInt32(date, buffer: buffer, boxed: false) @@ -9387,6 +9387,9 @@ extension Api { if Int(flags) & Int(1 << 9) != 0 {serializeString(gifSearchUsername!, buffer: buffer, boxed: false)} if Int(flags) & Int(1 << 10) != 0 {serializeString(venueSearchUsername!, buffer: buffer, boxed: false)} if Int(flags) & Int(1 << 11) != 0 {serializeString(imgSearchUsername!, buffer: buffer, boxed: false)} + if Int(flags) & Int(1 << 12) != 0 {serializeString(staticMapsProvider!, buffer: buffer, boxed: false)} + serializeInt32(captionLengthMax, buffer: buffer, boxed: false) + serializeInt32(messageLengthMax, buffer: buffer, boxed: false) if Int(flags) & Int(1 << 2) != 0 {serializeString(suggestedLangCode!, buffer: buffer, boxed: false)} if Int(flags) & Int(1 << 2) != 0 {serializeInt32(langPackVersion!, buffer: buffer, boxed: false)} break @@ -9395,8 +9398,8 @@ extension Api { func descriptionFields() -> (String, [(String, Any)]) { switch self { - case .config(let flags, let date, let expires, let testMode, let thisDc, let dcOptions, let dcTxtDomainName, let chatSizeMax, let megagroupSizeMax, let forwardedCountMax, let onlineUpdatePeriodMs, let offlineBlurTimeoutMs, let offlineIdleTimeoutMs, let onlineCloudTimeoutMs, let notifyCloudDelayMs, let notifyDefaultDelayMs, let pushChatPeriodMs, let pushChatLimit, let savedGifsLimit, let editTimeLimit, let revokeTimeLimit, let revokePmTimeLimit, let ratingEDecay, let stickersRecentLimit, let stickersFavedLimit, let channelsReadMediaPeriod, let tmpSessions, let pinnedDialogsCountMax, let callReceiveTimeoutMs, let callRingTimeoutMs, let callConnectTimeoutMs, let callPacketTimeoutMs, let meUrlPrefix, let autoupdateUrlPrefix, let gifSearchUsername, let venueSearchUsername, let imgSearchUsername, let suggestedLangCode, let langPackVersion): - return ("config", [("flags", flags), ("date", date), ("expires", expires), ("testMode", testMode), ("thisDc", thisDc), ("dcOptions", dcOptions), ("dcTxtDomainName", dcTxtDomainName), ("chatSizeMax", chatSizeMax), ("megagroupSizeMax", megagroupSizeMax), ("forwardedCountMax", forwardedCountMax), ("onlineUpdatePeriodMs", onlineUpdatePeriodMs), ("offlineBlurTimeoutMs", offlineBlurTimeoutMs), ("offlineIdleTimeoutMs", offlineIdleTimeoutMs), ("onlineCloudTimeoutMs", onlineCloudTimeoutMs), ("notifyCloudDelayMs", notifyCloudDelayMs), ("notifyDefaultDelayMs", notifyDefaultDelayMs), ("pushChatPeriodMs", pushChatPeriodMs), ("pushChatLimit", pushChatLimit), ("savedGifsLimit", savedGifsLimit), ("editTimeLimit", editTimeLimit), ("revokeTimeLimit", revokeTimeLimit), ("revokePmTimeLimit", revokePmTimeLimit), ("ratingEDecay", ratingEDecay), ("stickersRecentLimit", stickersRecentLimit), ("stickersFavedLimit", stickersFavedLimit), ("channelsReadMediaPeriod", channelsReadMediaPeriod), ("tmpSessions", tmpSessions), ("pinnedDialogsCountMax", pinnedDialogsCountMax), ("callReceiveTimeoutMs", callReceiveTimeoutMs), ("callRingTimeoutMs", callRingTimeoutMs), ("callConnectTimeoutMs", callConnectTimeoutMs), ("callPacketTimeoutMs", callPacketTimeoutMs), ("meUrlPrefix", meUrlPrefix), ("autoupdateUrlPrefix", autoupdateUrlPrefix), ("gifSearchUsername", gifSearchUsername), ("venueSearchUsername", venueSearchUsername), ("imgSearchUsername", imgSearchUsername), ("suggestedLangCode", suggestedLangCode), ("langPackVersion", langPackVersion)]) + case .config(let flags, let date, let expires, let testMode, let thisDc, let dcOptions, let dcTxtDomainName, let chatSizeMax, let megagroupSizeMax, let forwardedCountMax, let onlineUpdatePeriodMs, let offlineBlurTimeoutMs, let offlineIdleTimeoutMs, let onlineCloudTimeoutMs, let notifyCloudDelayMs, let notifyDefaultDelayMs, let pushChatPeriodMs, let pushChatLimit, let savedGifsLimit, let editTimeLimit, let revokeTimeLimit, let revokePmTimeLimit, let ratingEDecay, let stickersRecentLimit, let stickersFavedLimit, let channelsReadMediaPeriod, let tmpSessions, let pinnedDialogsCountMax, let callReceiveTimeoutMs, let callRingTimeoutMs, let callConnectTimeoutMs, let callPacketTimeoutMs, let meUrlPrefix, let autoupdateUrlPrefix, let gifSearchUsername, let venueSearchUsername, let imgSearchUsername, let staticMapsProvider, let captionLengthMax, let messageLengthMax, let suggestedLangCode, let langPackVersion): + return ("config", [("flags", flags), ("date", date), ("expires", expires), ("testMode", testMode), ("thisDc", thisDc), ("dcOptions", dcOptions), ("dcTxtDomainName", dcTxtDomainName), ("chatSizeMax", chatSizeMax), ("megagroupSizeMax", megagroupSizeMax), ("forwardedCountMax", forwardedCountMax), ("onlineUpdatePeriodMs", onlineUpdatePeriodMs), ("offlineBlurTimeoutMs", offlineBlurTimeoutMs), ("offlineIdleTimeoutMs", offlineIdleTimeoutMs), ("onlineCloudTimeoutMs", onlineCloudTimeoutMs), ("notifyCloudDelayMs", notifyCloudDelayMs), ("notifyDefaultDelayMs", notifyDefaultDelayMs), ("pushChatPeriodMs", pushChatPeriodMs), ("pushChatLimit", pushChatLimit), ("savedGifsLimit", savedGifsLimit), ("editTimeLimit", editTimeLimit), ("revokeTimeLimit", revokeTimeLimit), ("revokePmTimeLimit", revokePmTimeLimit), ("ratingEDecay", ratingEDecay), ("stickersRecentLimit", stickersRecentLimit), ("stickersFavedLimit", stickersFavedLimit), ("channelsReadMediaPeriod", channelsReadMediaPeriod), ("tmpSessions", tmpSessions), ("pinnedDialogsCountMax", pinnedDialogsCountMax), ("callReceiveTimeoutMs", callReceiveTimeoutMs), ("callRingTimeoutMs", callRingTimeoutMs), ("callConnectTimeoutMs", callConnectTimeoutMs), ("callPacketTimeoutMs", callPacketTimeoutMs), ("meUrlPrefix", meUrlPrefix), ("autoupdateUrlPrefix", autoupdateUrlPrefix), ("gifSearchUsername", gifSearchUsername), ("venueSearchUsername", venueSearchUsername), ("imgSearchUsername", imgSearchUsername), ("staticMapsProvider", staticMapsProvider), ("captionLengthMax", captionLengthMax), ("messageLengthMax", messageLengthMax), ("suggestedLangCode", suggestedLangCode), ("langPackVersion", langPackVersion)]) } } @@ -9480,9 +9483,15 @@ extension Api { var _37: String? if Int(_1!) & Int(1 << 11) != 0 {_37 = parseString(reader) } var _38: String? - if Int(_1!) & Int(1 << 2) != 0 {_38 = parseString(reader) } + if Int(_1!) & Int(1 << 12) != 0 {_38 = parseString(reader) } var _39: Int32? - if Int(_1!) & Int(1 << 2) != 0 {_39 = reader.readInt32() } + _39 = reader.readInt32() + var _40: Int32? + _40 = reader.readInt32() + var _41: String? + if Int(_1!) & Int(1 << 2) != 0 {_41 = parseString(reader) } + var _42: Int32? + if Int(_1!) & Int(1 << 2) != 0 {_42 = reader.readInt32() } let _c1 = _1 != nil let _c2 = _2 != nil let _c3 = _3 != nil @@ -9520,10 +9529,13 @@ extension Api { let _c35 = (Int(_1!) & Int(1 << 9) == 0) || _35 != nil let _c36 = (Int(_1!) & Int(1 << 10) == 0) || _36 != nil let _c37 = (Int(_1!) & Int(1 << 11) == 0) || _37 != nil - let _c38 = (Int(_1!) & Int(1 << 2) == 0) || _38 != nil - let _c39 = (Int(_1!) & Int(1 << 2) == 0) || _39 != nil - if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 && _c23 && _c24 && _c25 && _c26 && _c27 && _c28 && _c29 && _c30 && _c31 && _c32 && _c33 && _c34 && _c35 && _c36 && _c37 && _c38 && _c39 { - return Api.Config.config(flags: _1!, date: _2!, expires: _3!, testMode: _4!, thisDc: _5!, dcOptions: _6!, dcTxtDomainName: _7!, chatSizeMax: _8!, megagroupSizeMax: _9!, forwardedCountMax: _10!, onlineUpdatePeriodMs: _11!, offlineBlurTimeoutMs: _12!, offlineIdleTimeoutMs: _13!, onlineCloudTimeoutMs: _14!, notifyCloudDelayMs: _15!, notifyDefaultDelayMs: _16!, pushChatPeriodMs: _17!, pushChatLimit: _18!, savedGifsLimit: _19!, editTimeLimit: _20!, revokeTimeLimit: _21!, revokePmTimeLimit: _22!, ratingEDecay: _23!, stickersRecentLimit: _24!, stickersFavedLimit: _25!, channelsReadMediaPeriod: _26!, tmpSessions: _27, pinnedDialogsCountMax: _28!, callReceiveTimeoutMs: _29!, callRingTimeoutMs: _30!, callConnectTimeoutMs: _31!, callPacketTimeoutMs: _32!, meUrlPrefix: _33!, autoupdateUrlPrefix: _34, gifSearchUsername: _35, venueSearchUsername: _36, imgSearchUsername: _37, suggestedLangCode: _38, langPackVersion: _39) + let _c38 = (Int(_1!) & Int(1 << 12) == 0) || _38 != nil + let _c39 = _39 != nil + let _c40 = _40 != nil + let _c41 = (Int(_1!) & Int(1 << 2) == 0) || _41 != nil + let _c42 = (Int(_1!) & Int(1 << 2) == 0) || _42 != nil + if _c1 && _c2 && _c3 && _c4 && _c5 && _c6 && _c7 && _c8 && _c9 && _c10 && _c11 && _c12 && _c13 && _c14 && _c15 && _c16 && _c17 && _c18 && _c19 && _c20 && _c21 && _c22 && _c23 && _c24 && _c25 && _c26 && _c27 && _c28 && _c29 && _c30 && _c31 && _c32 && _c33 && _c34 && _c35 && _c36 && _c37 && _c38 && _c39 && _c40 && _c41 && _c42 { + return Api.Config.config(flags: _1!, date: _2!, expires: _3!, testMode: _4!, thisDc: _5!, dcOptions: _6!, dcTxtDomainName: _7!, chatSizeMax: _8!, megagroupSizeMax: _9!, forwardedCountMax: _10!, onlineUpdatePeriodMs: _11!, offlineBlurTimeoutMs: _12!, offlineIdleTimeoutMs: _13!, onlineCloudTimeoutMs: _14!, notifyCloudDelayMs: _15!, notifyDefaultDelayMs: _16!, pushChatPeriodMs: _17!, pushChatLimit: _18!, savedGifsLimit: _19!, editTimeLimit: _20!, revokeTimeLimit: _21!, revokePmTimeLimit: _22!, ratingEDecay: _23!, stickersRecentLimit: _24!, stickersFavedLimit: _25!, channelsReadMediaPeriod: _26!, tmpSessions: _27, pinnedDialogsCountMax: _28!, callReceiveTimeoutMs: _29!, callRingTimeoutMs: _30!, callConnectTimeoutMs: _31!, callPacketTimeoutMs: _32!, meUrlPrefix: _33!, autoupdateUrlPrefix: _34, gifSearchUsername: _35, venueSearchUsername: _36, imgSearchUsername: _37, staticMapsProvider: _38, captionLengthMax: _39!, messageLengthMax: _40!, suggestedLangCode: _41, langPackVersion: _42) } else { return nil diff --git a/TelegramCore/ApplyMaxReadIndexInteractively.swift b/TelegramCore/ApplyMaxReadIndexInteractively.swift index e4fb71f481..6cee25e7d1 100644 --- a/TelegramCore/ApplyMaxReadIndexInteractively.swift +++ b/TelegramCore/ApplyMaxReadIndexInteractively.swift @@ -8,21 +8,21 @@ import Foundation #endif public func applyMaxReadIndexInteractively(postbox: Postbox, stateManager: AccountStateManager, index: MessageIndex) -> Signal { - return postbox.modify { modifier -> Void in - applyMaxReadIndexInteractively(modifier: modifier, stateManager: stateManager, index: index) + return postbox.transaction { transaction -> Void in + applyMaxReadIndexInteractively(transaction: transaction, stateManager: stateManager, index: index) } } -func applyMaxReadIndexInteractively(modifier: Modifier, stateManager: AccountStateManager, index: MessageIndex) { - let messageIds = modifier.applyInteractiveReadMaxIndex(index) +func applyMaxReadIndexInteractively(transaction: Transaction, stateManager: AccountStateManager, index: MessageIndex) { + let messageIds = transaction.applyInteractiveReadMaxIndex(index) if index.id.peerId.namespace == Namespaces.Peer.SecretChat { let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) for id in messageIds { - if let message = modifier.getMessage(id) { + if let message = transaction.getMessage(id) { for attribute in message.attributes { if let attribute = attribute as? AutoremoveTimeoutMessageAttribute { if (attribute.countdownBeginTime == nil || attribute.countdownBeginTime == 0) && !message.containsSecretMedia { - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -36,7 +36,7 @@ func applyMaxReadIndexInteractively(modifier: Modifier, stateManager: AccountSta }) return .update(StoreMessage(id: currentMessage.id, globallyUniqueId: currentMessage.globallyUniqueId, groupingKey: currentMessage.groupingKey, timestamp: currentMessage.timestamp, flags: StoreMessageFlags(currentMessage.flags), tags: currentMessage.tags, globalTags: currentMessage.globalTags, localTags: currentMessage.localTags, forwardInfo: storeForwardInfo, authorId: currentMessage.author?.id, text: currentMessage.text, attributes: updatedAttributes, media: currentMessage.media)) }) - modifier.addTimestampBasedMessageAttribute(tag: 0, timestamp: timestamp + attribute.timeout, messageId: id) + transaction.addTimestampBasedMessageAttribute(tag: 0, timestamp: timestamp + attribute.timeout, messageId: id) } break } @@ -48,16 +48,16 @@ func applyMaxReadIndexInteractively(modifier: Modifier, stateManager: AccountSta } } -func applyOutgoingReadMaxIndex(modifier: Modifier, index: MessageIndex, beginCountdownAt timestamp: Int32) { - let messageIds = modifier.applyOutgoingReadMaxIndex(index) +func applyOutgoingReadMaxIndex(transaction: Transaction, index: MessageIndex, beginCountdownAt timestamp: Int32) { + let messageIds = transaction.applyOutgoingReadMaxIndex(index) if index.id.peerId.namespace == Namespaces.Peer.SecretChat { for id in messageIds { - applySecretOutgoingMessageReadActions(modifier: modifier, id: id, beginCountdownAt: timestamp) + applySecretOutgoingMessageReadActions(transaction: transaction, id: id, beginCountdownAt: timestamp) } } } -func maybeReadSecretOutgoingMessage(modifier: Modifier, index: MessageIndex) { +func maybeReadSecretOutgoingMessage(transaction: Transaction, index: MessageIndex) { guard index.id.peerId.namespace == Namespaces.Peer.SecretChat else { assertionFailure() return @@ -67,16 +67,16 @@ func maybeReadSecretOutgoingMessage(modifier: Modifier, index: MessageIndex) { return } - guard let combinedState = modifier.getCombinedPeerReadState(index.id.peerId) else { + guard let combinedState = transaction.getCombinedPeerReadState(index.id.peerId) else { return } if combinedState.isOutgoingMessageIndexRead(index) { - applySecretOutgoingMessageReadActions(modifier: modifier, id: index.id, beginCountdownAt: index.timestamp) + applySecretOutgoingMessageReadActions(transaction: transaction, id: index.id, beginCountdownAt: index.timestamp) } } -func applySecretOutgoingMessageReadActions(modifier: Modifier, id: MessageId, beginCountdownAt timestamp: Int32) { +func applySecretOutgoingMessageReadActions(transaction: Transaction, id: MessageId, beginCountdownAt timestamp: Int32) { guard id.peerId.namespace == Namespaces.Peer.SecretChat else { assertionFailure() return @@ -86,12 +86,12 @@ func applySecretOutgoingMessageReadActions(modifier: Modifier, id: MessageId, be return } - if let message = modifier.getMessage(id), !message.flags.contains(.Incoming) { + if let message = transaction.getMessage(id), !message.flags.contains(.Incoming) { if message.flags.intersection([.Unsent, .Sending, .Failed]).isEmpty { for attribute in message.attributes { if let attribute = attribute as? AutoremoveTimeoutMessageAttribute { if (attribute.countdownBeginTime == nil || attribute.countdownBeginTime == 0) && !message.containsSecretMedia { - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -105,7 +105,7 @@ func applySecretOutgoingMessageReadActions(modifier: Modifier, id: MessageId, be }) return .update(StoreMessage(id: currentMessage.id, globallyUniqueId: currentMessage.globallyUniqueId, groupingKey: currentMessage.groupingKey, timestamp: currentMessage.timestamp, flags: StoreMessageFlags(currentMessage.flags), tags: currentMessage.tags, globalTags: currentMessage.globalTags, localTags: currentMessage.localTags, forwardInfo: storeForwardInfo, authorId: currentMessage.author?.id, text: currentMessage.text, attributes: updatedAttributes, media: currentMessage.media)) }) - modifier.addTimestampBasedMessageAttribute(tag: 0, timestamp: timestamp + attribute.timeout, messageId: id) + transaction.addTimestampBasedMessageAttribute(tag: 0, timestamp: timestamp + attribute.timeout, messageId: id) } break } @@ -115,22 +115,22 @@ func applySecretOutgoingMessageReadActions(modifier: Modifier, id: MessageId, be } public func togglePeerUnreadMarkInteractively(postbox: Postbox, peerId: PeerId) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in let namespace: MessageId.Namespace if peerId.namespace == Namespaces.Peer.SecretChat { namespace = Namespaces.Message.SecretIncoming } else { namespace = Namespaces.Message.Cloud } - if let states = modifier.getPeerReadStates(peerId) { + if let states = transaction.getPeerReadStates(peerId) { for i in 0 ..< states.count { if states[i].0 == namespace { if states[i].1.isUnread { - if let index = modifier.getTopPeerMessageIndex(peerId: peerId, namespace: namespace) { - let _ = modifier.applyInteractiveReadMaxIndex(index) + if let index = transaction.getTopPeerMessageIndex(peerId: peerId, namespace: namespace) { + let _ = transaction.applyInteractiveReadMaxIndex(index) } } else { - modifier.applyMarkUnread(peerId: peerId, namespace: namespace, value: true, interactive: true) + transaction.applyMarkUnread(peerId: peerId, namespace: namespace, value: true, interactive: true) } } } diff --git a/TelegramCore/ApplyUpdateMessage.swift b/TelegramCore/ApplyUpdateMessage.swift index 722d4f3a44..072a2f5989 100644 --- a/TelegramCore/ApplyUpdateMessage.swift +++ b/TelegramCore/ApplyUpdateMessage.swift @@ -27,7 +27,7 @@ func applyMediaResourceChanges(from: Media, to: Media, postbox: Postbox) { } func applyUpdateMessage(postbox: Postbox, stateManager: AccountStateManager, message: Message, result: Api.Updates) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in let messageId = result.rawMessageIds.first let apiMessage = result.messages.first @@ -56,10 +56,10 @@ func applyUpdateMessage(postbox: Postbox, stateManager: AccountStateManager, mes var sentGifs: [TelegramMediaFile] = [] if let updatedTimestamp = updatedTimestamp { - modifier.offsetPendingMessagesTimestamps(lowerBound: message.id, excludeIds: Set([message.id]), timestamp: updatedTimestamp) + transaction.offsetPendingMessagesTimestamps(lowerBound: message.id, excludeIds: Set([message.id]), timestamp: updatedTimestamp) } - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in let updatedId: MessageId if let messageId = messageId { updatedId = MessageId(peerId: currentMessage.id.peerId, namespace: Namespaces.Message.Cloud, id: messageId) @@ -145,10 +145,10 @@ func applyUpdateMessage(postbox: Postbox, stateManager: AccountStateManager, mes return .update(StoreMessage(id: updatedId, globallyUniqueId: nil, groupingKey: currentMessage.groupingKey, timestamp: updatedTimestamp ?? currentMessage.timestamp, flags: [], tags: tags, globalTags: globalTags, localTags: currentMessage.localTags, forwardInfo: storeForwardInfo, authorId: currentMessage.author?.id, text: text, attributes: attributes, media: media)) }) for file in sentStickers { - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentStickers, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 20) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentStickers, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 20) } for file in sentGifs { - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 200) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 200) } stateManager.addUpdates(result) } @@ -159,7 +159,7 @@ func applyUpdateGroupMessages(postbox: Postbox, stateManager: AccountStateManage return .complete() } - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in let updatedRawMessageIds = result.updatedRawMessageIds var resultMessages: [MessageId: StoreMessage] = [:] @@ -200,11 +200,11 @@ func applyUpdateGroupMessages(postbox: Postbox, stateManager: AccountStateManage var updatedGroupingKey: Int64? if let latestIndex = mapping.last?.1 { - modifier.offsetPendingMessagesTimestamps(lowerBound: latestIndex.id, excludeIds: Set(mapping.map { $0.0.id }), timestamp: latestIndex.timestamp) + transaction.offsetPendingMessagesTimestamps(lowerBound: latestIndex.id, excludeIds: Set(mapping.map { $0.0.id }), timestamp: latestIndex.timestamp) } for (message, _, updatedMessage) in mapping { - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in let updatedId: MessageId if case let .Id(id) = updatedMessage.id { updatedId = id @@ -261,14 +261,14 @@ func applyUpdateGroupMessages(postbox: Postbox, stateManager: AccountStateManage } if let updatedGroupingKey = updatedGroupingKey { - modifier.updateMessageGroupingKeysAtomically(mapping.map { $0.1.id }, groupingKey: updatedGroupingKey) + transaction.updateMessageGroupingKeysAtomically(mapping.map { $0.1.id }, groupingKey: updatedGroupingKey) } for file in sentStickers { - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentStickers, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 20) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentStickers, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 20) } for file in sentGifs { - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 200) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 200) } stateManager.addUpdates(result) } diff --git a/TelegramCore/Authorization.swift b/TelegramCore/Authorization.swift index 1adb0b16fd..b742b24000 100644 --- a/TelegramCore/Authorization.swift +++ b/TelegramCore/Authorization.swift @@ -56,7 +56,7 @@ public func sendAuthorizationCode(account: UnauthorizedAccount, phoneNumber: Str return codeAndAccount |> mapToSignal { (sentCode, account) -> Signal in - return account.postbox.modify { modifier -> UnauthorizedAccount in + return account.postbox.transaction { transaction -> UnauthorizedAccount in switch sentCode { case let .sentCode(_, type, phoneCodeHash, nextType, timeout, termsOfService): var parsedNextType: AuthorizationCodeNextType? @@ -64,7 +64,7 @@ public func sendAuthorizationCode(account: UnauthorizedAccount, phoneNumber: Str parsedNextType = AuthorizationCodeNextType(apiType: nextType) } - modifier.setState(UnauthorizedAccountState(masterDatacenterId: account.masterDatacenterId, contents: .confirmationCodeEntry(number: phoneNumber, type: SentAuthorizationCodeType(apiType: type), hash: phoneCodeHash, timeout: timeout, nextType: parsedNextType, termsOfService: termsOfService.flatMap(UnauthorizedAccountTermsOfService.init(apiTermsOfService:))))) + transaction.setState(UnauthorizedAccountState(masterDatacenterId: account.masterDatacenterId, contents: .confirmationCodeEntry(number: phoneNumber, type: SentAuthorizationCodeType(apiType: type), hash: phoneCodeHash, timeout: timeout, nextType: parsedNextType, termsOfService: termsOfService.flatMap(UnauthorizedAccountTermsOfService.init(apiTermsOfService:))))) } return account } |> mapError { _ -> AuthorizationCodeRequestError in return .generic } @@ -72,8 +72,8 @@ public func sendAuthorizationCode(account: UnauthorizedAccount, phoneNumber: Str } public func resendAuthorizationCode(account: UnauthorizedAccount) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let state = modifier.getState() as? UnauthorizedAccountState { + return account.postbox.transaction { transaction -> Signal in + if let state = transaction.getState() as? UnauthorizedAccountState { switch state.contents { case let .confirmationCodeEntry(number, _, hash, _, nextType, _): if nextType != nil { @@ -92,7 +92,7 @@ public func resendAuthorizationCode(account: UnauthorizedAccount) -> Signal mapToSignal { sentCode -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in switch sentCode { case let .sentCode(_, type, phoneCodeHash, nextType, timeout, termsOfService): @@ -101,7 +101,7 @@ public func resendAuthorizationCode(account: UnauthorizedAccount) -> Signal mapError { _ -> AuthorizationCodeRequestError in return .generic } @@ -135,8 +135,8 @@ private enum AuthorizationCodeResult { } public func authorizeWithCode(account: UnauthorizedAccount, code: String) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let state = modifier.getState() as? UnauthorizedAccountState { + return account.postbox.transaction { transaction -> Signal in + if let state = transaction.getState() as? UnauthorizedAccountState { switch state.contents { case let .confirmationCodeEntry(number, _, hash, _, _, _): return account.network.request(Api.functions.auth.signIn(phoneNumber: number, phoneCodeHash: hash, phoneCode: code), automaticFloodWait: false) |> map { authorization in @@ -173,21 +173,21 @@ public func authorizeWithCode(account: UnauthorizedAccount, code: String) -> Sig } } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in switch result { case .signUp: - modifier.setState(UnauthorizedAccountState(masterDatacenterId: account.masterDatacenterId, contents: .signUp(number: number, codeHash: hash, code: code, firstName: "", lastName: ""))) + transaction.setState(UnauthorizedAccountState(masterDatacenterId: account.masterDatacenterId, contents: .signUp(number: number, codeHash: hash, code: code, firstName: "", lastName: ""))) case let .password(hint): - modifier.setState(UnauthorizedAccountState(masterDatacenterId: account.masterDatacenterId, contents: .passwordEntry(hint: hint, number: number, code: code))) + transaction.setState(UnauthorizedAccountState(masterDatacenterId: account.masterDatacenterId, contents: .passwordEntry(hint: hint, number: number, code: code))) case let .authorization(authorization): switch authorization { case let .authorization(_, _, user): let user = TelegramUser(user: user) let state = AuthorizedAccountState(masterDatacenterId: account.masterDatacenterId, peerId: user.id, state: nil) - /*modifier.updatePeersInternal([user], update: { current, peer -> Peer? in + /*transaction.updatePeersInternal([user], update: { current, peer -> Peer? in return peer })*/ - modifier.setState(state) + transaction.setState(state) } } } |> mapError { _ -> AuthorizationCodeVerificationError in @@ -225,15 +225,15 @@ public func authorizeWithPassword(account: UnauthorizedAccount, password: String } } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in switch result { case let .authorization(_, _, user): let user = TelegramUser(user: user) let state = AuthorizedAccountState(masterDatacenterId: account.masterDatacenterId, peerId: user.id, state: nil) - /*modifier.updatePeersInternal([user], update: { current, peer -> Peer? in + /*transaction.updatePeersInternal([user], update: { current, peer -> Peer? in return peer })*/ - modifier.setState(state) + transaction.setState(state) } } |> mapError { _ -> AuthorizationPasswordVerificationError in @@ -294,15 +294,15 @@ public func performPasswordRecovery(account: UnauthorizedAccount, code: String) } } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in switch result { case let .authorization(_, _, user): let user = TelegramUser(user: user) let state = AuthorizedAccountState(masterDatacenterId: account.masterDatacenterId, peerId: user.id, state: nil) - /*modifier.updatePeersInternal([user], update: { current, peer -> Peer? in + /*transaction.updatePeersInternal([user], update: { current, peer -> Peer? in return peer })*/ - modifier.setState(state) + transaction.setState(state) } } |> mapError { _ in return PasswordRecoveryError.expired } } @@ -328,13 +328,13 @@ public func performAccountReset(account: UnauthorizedAccount) -> Signal mapToSignal { timeout -> Signal in - return account.postbox.modify { modifier -> Void in - if let state = modifier.getState() as? UnauthorizedAccountState, case let .passwordEntry(_, number, _) = state.contents { + return account.postbox.transaction { transaction -> Void in + if let state = transaction.getState() as? UnauthorizedAccountState, case let .passwordEntry(_, number, _) = state.contents { if let timeout = timeout { let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) - modifier.setState(UnauthorizedAccountState(masterDatacenterId: state.masterDatacenterId, contents: .awaitingAccountReset(protectedUntil: timestamp + timeout, number: number))) + transaction.setState(UnauthorizedAccountState(masterDatacenterId: state.masterDatacenterId, contents: .awaitingAccountReset(protectedUntil: timestamp + timeout, number: number))) } else { - modifier.setState(UnauthorizedAccountState(masterDatacenterId: state.masterDatacenterId, contents: .empty)) + transaction.setState(UnauthorizedAccountState(masterDatacenterId: state.masterDatacenterId, contents: .empty)) } } } |> mapError { _ in return AccountResetError.generic } @@ -350,8 +350,8 @@ public enum SignUpError { } public func signUpWithName(account: UnauthorizedAccount, firstName: String, lastName: String) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let state = modifier.getState() as? UnauthorizedAccountState, case let .signUp(number, codeHash, code, _, _) = state.contents { + return account.postbox.transaction { transaction -> Signal in + if let state = transaction.getState() as? UnauthorizedAccountState, case let .signUp(number, codeHash, code, _, _) = state.contents { return account.network.request(Api.functions.auth.signUp(phoneNumber: number, phoneCodeHash: codeHash, phoneCode: code, firstName: firstName, lastName: lastName)) |> mapError { error -> SignUpError in if error.errorDescription.hasPrefix("FLOOD_WAIT") { @@ -367,12 +367,12 @@ public func signUpWithName(account: UnauthorizedAccount, firstName: String, last } } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in switch result { case let .authorization(_, _, user): let user = TelegramUser(user: user) let state = AuthorizedAccountState(masterDatacenterId: account.masterDatacenterId, peerId: user.id, state: nil) - modifier.setState(state) + transaction.setState(state) } } |> mapError { _ -> SignUpError in return .generic } } @@ -387,9 +387,9 @@ public enum AuthorizationStateReset { } public func resetAuthorizationState(account: UnauthorizedAccount, to value: AuthorizationStateReset) -> Signal { - return account.postbox.modify { modifier -> Void in - if let state = modifier.getState() as? UnauthorizedAccountState { - modifier.setState(UnauthorizedAccountState(masterDatacenterId: state.masterDatacenterId, contents: .empty)) + return account.postbox.transaction { transaction -> Void in + if let state = transaction.getState() as? UnauthorizedAccountState { + transaction.setState(UnauthorizedAccountState(masterDatacenterId: state.masterDatacenterId, contents: .empty)) } } } diff --git a/TelegramCore/BlockedPeers.swift b/TelegramCore/BlockedPeers.swift index 056bf4a6b8..22da57c34c 100644 --- a/TelegramCore/BlockedPeers.swift +++ b/TelegramCore/BlockedPeers.swift @@ -13,7 +13,7 @@ public func requestBlockedPeers(account: Account) -> Signal<[Peer], NoError> { return account.network.request(Api.functions.contacts.getBlocked(offset: 0, limit: 100)) |> retryRequest |> mapToSignal { result -> Signal<[Peer], NoError> in - return account.postbox.modify { modifier -> [Peer] in + return account.postbox.transaction { transaction -> [Peer] in var peers: [Peer] = [] let apiUsers: [Api.User] switch result { @@ -27,7 +27,7 @@ public func requestBlockedPeers(account: Account) -> Signal<[Peer], NoError> { peers.append(parsed) } - updatePeers(modifier: modifier, peers: peers, update: { _, updated in + updatePeers(transaction: transaction, peers: peers, update: { _, updated in return updated }) @@ -37,8 +37,8 @@ public func requestBlockedPeers(account: Account) -> Signal<[Peer], NoError> { } public func requestUpdatePeerIsBlocked(account: Account, peerId: PeerId, isBlocked: Bool) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let inputUser = apiInputUser(peer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) { let signal: Signal if isBlocked { signal = account.network.request(Api.functions.contacts.block(id: inputUser)) @@ -51,9 +51,9 @@ public func requestUpdatePeerIsBlocked(account: Account, peerId: PeerId, isBlock return .single(nil) } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if result != nil { - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in let previous: CachedUserData if let current = current as? CachedUserData { previous = current diff --git a/TelegramCore/BotPaymentForm.swift b/TelegramCore/BotPaymentForm.swift index 2ed3a8ff7c..0edfdf433c 100644 --- a/TelegramCore/BotPaymentForm.swift +++ b/TelegramCore/BotPaymentForm.swift @@ -201,7 +201,7 @@ public func fetchBotPaymentForm(postbox: Postbox, network: Network, messageId: M return .fail(.generic) } |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> BotPaymentForm in + return postbox.transaction { transaction -> BotPaymentForm in switch result { case let .paymentForm(flags, _, invoice, providerId, url, nativeProvider, nativeParams, savedInfo, savedCredentials, apiUsers): var peers: [Peer] = [] @@ -209,7 +209,7 @@ public func fetchBotPaymentForm(postbox: Postbox, network: Network, messageId: M let parsed = TelegramUser(user: user) peers.append(parsed) } - updatePeers(modifier: modifier, peers: peers, update: { _, updated in + updatePeers(transaction: transaction, peers: peers, update: { _, updated in return updated }) diff --git a/TelegramCore/CacheStorageSettings.swift b/TelegramCore/CacheStorageSettings.swift index 3878deaac9..5926b7c7f3 100644 --- a/TelegramCore/CacheStorageSettings.swift +++ b/TelegramCore/CacheStorageSettings.swift @@ -44,8 +44,8 @@ public struct CacheStorageSettings: PreferencesEntry, Equatable { } public func updateCacheStorageSettingsInteractively(postbox: Postbox, _ f: @escaping (CacheStorageSettings) -> CacheStorageSettings) -> Signal { - return postbox.modify { modifier -> Void in - modifier.updatePreferencesEntry(key: PreferencesKeys.cacheStorageSettings, { entry in + return postbox.transaction { transaction -> Void in + transaction.updatePreferencesEntry(key: PreferencesKeys.cacheStorageSettings, { entry in let currentSettings: CacheStorageSettings if let entry = entry as? CacheStorageSettings { currentSettings = entry diff --git a/TelegramCore/CachedSentMediaReferences.swift b/TelegramCore/CachedSentMediaReferences.swift index d69bfc449a..f2079a6d05 100644 --- a/TelegramCore/CachedSentMediaReferences.swift +++ b/TelegramCore/CachedSentMediaReferences.swift @@ -34,11 +34,11 @@ enum CachedSentMediaReferenceKey { } func cachedSentMediaReference(postbox: Postbox, key: CachedSentMediaReferenceKey) -> Signal { - return postbox.modify { modifier -> Media? in - return modifier.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSentMediaReferences, key: key.key)) as? Media + return postbox.transaction { transaction -> Media? in + return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSentMediaReferences, key: key.key)) as? Media } } -func storeCachedSentMediaReference(modifier: Modifier, key: CachedSentMediaReferenceKey, media: Media) { - modifier.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSentMediaReferences, key: key.key), entry: media, collectionSpec: cachedSentMediaCollectionSpec) +func storeCachedSentMediaReference(transaction: Transaction, key: CachedSentMediaReferenceKey, media: Media) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSentMediaReferences, key: key.key), entry: media, collectionSpec: cachedSentMediaCollectionSpec) } diff --git a/TelegramCore/CachedStickerPack.swift b/TelegramCore/CachedStickerPack.swift index 045c56a426..4c9ff64edd 100644 --- a/TelegramCore/CachedStickerPack.swift +++ b/TelegramCore/CachedStickerPack.swift @@ -51,16 +51,16 @@ public enum CachedStickerPackResult { } public func cachedStickerPack(postbox: Postbox, network: Network, reference: StickerPackReference) -> Signal { - return postbox.modify { modifier -> Signal in + return postbox.transaction { transaction -> Signal in let namespace = Namespaces.ItemCollection.CloudStickerPacks - if case let .id(id, _) = reference, let currentInfo = modifier.getItemCollectionInfo(collectionId: ItemCollectionId(namespace: namespace, id: id)) as? StickerPackCollectionInfo { - let items = modifier.getItemCollectionItems(collectionId: ItemCollectionId(namespace: namespace, id: id)) + if case let .id(id, _) = reference, let currentInfo = transaction.getItemCollectionInfo(collectionId: ItemCollectionId(namespace: namespace, id: id)) as? StickerPackCollectionInfo { + let items = transaction.getItemCollectionItems(collectionId: ItemCollectionId(namespace: namespace, id: id)) return .single(.result(currentInfo, items, true)) } else { let current: Signal var loadRemote = false - if case let .id(id, _) = reference, let cached = modifier.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { + if case let .id(id, _) = reference, let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { current = .single(.result(info, cached.items, false)) if cached.hash != info.hash { loadRemote = true @@ -74,11 +74,11 @@ public func cachedStickerPack(postbox: Postbox, network: Network, reference: Sti if loadRemote { let appliedRemote = remoteStickerPack(network: network, reference: reference) |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> CachedStickerPackResult in + return postbox.transaction { transaction -> CachedStickerPackResult in if let result = result { - modifier.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(result.0.id)), entry: CachedStickerPack(info: result.0, items: result.1.map { $0 as! StickerPackItem }, hash: result.0.hash), collectionSpec: collectionSpec) + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(result.0.id)), entry: CachedStickerPack(info: result.0, items: result.1.map { $0 as! StickerPackItem }, hash: result.0.hash), collectionSpec: collectionSpec) - let currentInfo = modifier.getItemCollectionInfo(collectionId: result.0.id) as? StickerPackCollectionInfo + let currentInfo = transaction.getItemCollectionInfo(collectionId: result.0.id) as? StickerPackCollectionInfo return .result(result.0, result.1, currentInfo != nil) } else { diff --git a/TelegramCore/CallSessionManager.swift b/TelegramCore/CallSessionManager.swift index 3e6a66d5df..a708027186 100644 --- a/TelegramCore/CallSessionManager.swift +++ b/TelegramCore/CallSessionManager.swift @@ -789,14 +789,14 @@ private func acceptCallSession(postbox: Postbox, network: Network, stableId: Cal } |> mapToSignal { call -> Signal in if let call = call { - return postbox.modify { modifier -> AcceptCallResult in + return postbox.transaction { transaction -> AcceptCallResult in switch call { case let .phoneCall(phoneCall, users): var parsedUsers: [Peer] = [] for user in users { parsedUsers.append(TelegramUser(user: user)) } - updatePeers(modifier: modifier, peers: parsedUsers, update: { _, updated in + updatePeers(transaction: transaction, peers: parsedUsers, update: { _, updated in return updated }) @@ -832,8 +832,8 @@ private enum RequestCallSessionResult { private func requestCallSession(postbox: Postbox, network: Network, peerId: PeerId, a: Data) -> Signal { return validatedEncryptionConfig(postbox: postbox, network: network) |> mapToSignal { config -> Signal in - return postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let inputUser = apiInputUser(peer) { + return postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) { var gValue: Int32 = config.g.byteSwapped let g = Data(bytes: &gValue, count: 4) let p = config.p.makeData() diff --git a/TelegramCore/ChangeAccountPhoneNumber.swift b/TelegramCore/ChangeAccountPhoneNumber.swift index cfdb2eabba..b50eb7c96e 100644 --- a/TelegramCore/ChangeAccountPhoneNumber.swift +++ b/TelegramCore/ChangeAccountPhoneNumber.swift @@ -110,9 +110,9 @@ public func requestChangeAccountPhoneNumber(account: Account, phoneNumber: Strin } } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in let user = TelegramUser(user: result) - updatePeers(modifier: modifier, peers: [user], update: { _, updated in + updatePeers(transaction: transaction, peers: [user], update: { _, updated in return updated }) } |> mapError { _ -> ChangeAccountPhoneNumberError in return .generic } diff --git a/TelegramCore/ChangePeerNotificationSettings.swift b/TelegramCore/ChangePeerNotificationSettings.swift index 86c5b66d91..38fcf1915b 100644 --- a/TelegramCore/ChangePeerNotificationSettings.swift +++ b/TelegramCore/ChangePeerNotificationSettings.swift @@ -8,14 +8,14 @@ import Foundation #endif public func togglePeerMuted(account: Account, peerId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Void in - if let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Void in + if let peer = transaction.getPeer(peerId) { var notificationPeerId = peerId if let associatedPeerId = peer.associatedPeerId { notificationPeerId = associatedPeerId } - let currentSettings = modifier.getPeerNotificationSettings(notificationPeerId) as? TelegramPeerNotificationSettings + let currentSettings = transaction.getPeerNotificationSettings(notificationPeerId) as? TelegramPeerNotificationSettings let previousSettings: TelegramPeerNotificationSettings if let currentSettings = currentSettings { previousSettings = currentSettings @@ -30,20 +30,20 @@ public func togglePeerMuted(account: Account, peerId: PeerId) -> Signal Signal { - return account.postbox.modify { modifier -> Void in - if let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Void in + if let peer = transaction.getPeer(peerId) { var notificationPeerId = peerId if let associatedPeerId = peer.associatedPeerId { notificationPeerId = associatedPeerId } - let currentSettings = modifier.getPeerNotificationSettings(notificationPeerId) as? TelegramPeerNotificationSettings + let currentSettings = transaction.getPeerNotificationSettings(notificationPeerId) as? TelegramPeerNotificationSettings let previousSettings: TelegramPeerNotificationSettings if let currentSettings = currentSettings { previousSettings = currentSettings @@ -69,20 +69,20 @@ public func updatePeerMuteSetting(account: Account, peerId: PeerId, muteInterval } let updatedSettings = previousSettings.withUpdatedMuteState(muteState) - modifier.updatePendingPeerNotificationSettings(peerId: peerId, settings: updatedSettings) + transaction.updatePendingPeerNotificationSettings(peerId: peerId, settings: updatedSettings) } } } public func updatePeerNotificationSoundInteractive(account: Account, peerId: PeerId, sound: PeerMessageSound) -> Signal { - return account.postbox.modify { modifier -> Void in - if let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Void in + if let peer = transaction.getPeer(peerId) { var notificationPeerId = peerId if let associatedPeerId = peer.associatedPeerId { notificationPeerId = associatedPeerId } - let currentSettings = modifier.getPeerNotificationSettings(notificationPeerId) as? TelegramPeerNotificationSettings + let currentSettings = transaction.getPeerNotificationSettings(notificationPeerId) as? TelegramPeerNotificationSettings let previousSettings: TelegramPeerNotificationSettings if let currentSettings = currentSettings { previousSettings = currentSettings @@ -91,7 +91,7 @@ public func updatePeerNotificationSoundInteractive(account: Account, peerId: Pee } let updatedSettings = previousSettings.withUpdatedMessageSound(sound) - modifier.updatePendingPeerNotificationSettings(peerId: peerId, settings: updatedSettings) + transaction.updatePendingPeerNotificationSettings(peerId: peerId, settings: updatedSettings) } } } diff --git a/TelegramCore/ChannelAdminEventLogs.swift b/TelegramCore/ChannelAdminEventLogs.swift index 7cc6610fe1..b9aa3673e7 100644 --- a/TelegramCore/ChannelAdminEventLogs.swift +++ b/TelegramCore/ChannelAdminEventLogs.swift @@ -99,8 +99,8 @@ private func boolFromApiValue(_ value: Api.Bool) -> Bool { } public func channelAdminLogEvents(postbox: Postbox, network: Network, peerId: PeerId, maxId: AdminLogEventId, minId: AdminLogEventId, limit: Int32 = 100, query: String? = nil, filter: AdminLogEventsFlags? = nil, admins: [PeerId]? = nil) -> Signal { - return postbox.modify { modifier -> (Peer?, [Peer]?) in - return (modifier.getPeer(peerId), admins?.flatMap { modifier.getPeer($0) }) + return postbox.transaction { transaction -> (Peer?, [Peer]?) in + return (transaction.getPeer(peerId), admins?.flatMap { transaction.getPeer($0) }) } |> mapError { return .generic } |> mapToSignal { (peer, admins) -> Signal in diff --git a/TelegramCore/ChannelAdmins.swift b/TelegramCore/ChannelAdmins.swift index a47cd5505b..eb66c68599 100644 --- a/TelegramCore/ChannelAdmins.swift +++ b/TelegramCore/ChannelAdmins.swift @@ -10,8 +10,8 @@ import Foundation #endif public func channelAdmins(account: Account, peerId: PeerId) -> Signal<[RenderedChannelParticipant], NoError> { - return account.postbox.modify { modifier -> Signal<[RenderedChannelParticipant], NoError> in - if let peer = modifier.getPeer(peerId), let inputChannel = apiInputChannel(peer) { + return account.postbox.transaction { transaction -> Signal<[RenderedChannelParticipant], NoError> in + if let peer = transaction.getPeer(peerId), let inputChannel = apiInputChannel(peer) { return account.network.request(Api.functions.channels.getParticipants(channel: inputChannel, filter: .channelParticipantsAdmins, offset: 0, limit: 100, hash: 0)) |> retryRequest |> mapToSignal { result -> Signal<[RenderedChannelParticipant], NoError> in @@ -36,8 +36,8 @@ public func channelAdmins(account: Account, peerId: PeerId) -> Signal<[RenderedC } - return account.postbox.modify { modifier -> [RenderedChannelParticipant] in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in + return account.postbox.transaction { transaction -> [RenderedChannelParticipant] in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in if let cachedData = cachedData as? CachedChannelData { return cachedData.withUpdatedParticipantsSummary(cachedData.participantsSummary.withUpdatedAdminCount(count)) } else { diff --git a/TelegramCore/ChannelBlacklist.swift b/TelegramCore/ChannelBlacklist.swift index 6b9c446c95..59d708fb96 100644 --- a/TelegramCore/ChannelBlacklist.swift +++ b/TelegramCore/ChannelBlacklist.swift @@ -15,8 +15,8 @@ private enum ChannelBlacklistFilter { } private func fetchChannelBlacklist(account: Account, peerId: PeerId, filter: ChannelBlacklistFilter) -> Signal<[RenderedChannelParticipant], NoError> { - return account.postbox.modify { modifier -> Signal<[RenderedChannelParticipant], NoError> in - if let peer = modifier.getPeer(peerId), let inputChannel = apiInputChannel(peer) { + return account.postbox.transaction { transaction -> Signal<[RenderedChannelParticipant], NoError> in + if let peer = transaction.getPeer(peerId), let inputChannel = apiInputChannel(peer) { let apiFilter: Api.ChannelParticipantsFilter switch filter { case .restricted: @@ -135,8 +135,8 @@ public func channelBlacklistParticipants(account: Account, peerId: PeerId) -> Si public func updateChannelMemberBannedRights(account: Account, peerId: PeerId, memberId: PeerId, rights: TelegramChannelBannedRights?) -> Signal<(ChannelParticipant?, RenderedChannelParticipant), NoError> { return fetchChannelParticipant(account: account, peerId: peerId, participantId: memberId) |> mapToSignal { currentParticipant -> Signal<(ChannelParticipant?, RenderedChannelParticipant), NoError> in - return account.postbox.modify { modifier -> Signal<(ChannelParticipant?, RenderedChannelParticipant), NoError> in - if let peer = modifier.getPeer(peerId), let inputChannel = apiInputChannel(peer), let _ = modifier.getPeer(account.peerId), let memberPeer = modifier.getPeer(memberId), let inputUser = apiInputUser(memberPeer) { + return account.postbox.transaction { transaction -> Signal<(ChannelParticipant?, RenderedChannelParticipant), NoError> in + if let peer = transaction.getPeer(peerId), let inputChannel = apiInputChannel(peer), let _ = transaction.getPeer(account.peerId), let memberPeer = transaction.getPeer(memberId), let inputUser = apiInputUser(memberPeer) { let updatedParticipant: ChannelParticipant if let currentParticipant = currentParticipant, case let .member(_, invitedAt, _, currentBanInfo) = currentParticipant { let banInfo: ChannelParticipantBannedInfo? @@ -161,8 +161,8 @@ public func updateChannelMemberBannedRights(account: Account, peerId: PeerId, me return account.network.request(Api.functions.channels.editBanned(channel: inputChannel, userId: inputUser, bannedRights: effectiveRights.apiBannedRights)) |> retryRequest |> mapToSignal { result -> Signal<(ChannelParticipant?, RenderedChannelParticipant), NoError> in - return account.postbox.modify { modifier -> (ChannelParticipant?, RenderedChannelParticipant) in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in + return account.postbox.transaction { transaction -> (ChannelParticipant?, RenderedChannelParticipant) in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in if let cachedData = cachedData as? CachedChannelData { var updatedData = cachedData var wasKicked = false @@ -240,11 +240,11 @@ public func updateChannelMemberBannedRights(account: Account, peerId: PeerId, me var peers: [PeerId: Peer] = [:] var presences: [PeerId: PeerPresence] = [:] peers[memberPeer.id] = memberPeer - if let presence = modifier.getPeerPresence(peerId: memberPeer.id) { + if let presence = transaction.getPeerPresence(peerId: memberPeer.id) { presences[memberPeer.id] = presence } if case let .member(_, _, _, maybeBanInfo) = updatedParticipant, let banInfo = maybeBanInfo { - if let peer = modifier.getPeer(banInfo.restrictedBy) { + if let peer = transaction.getPeer(banInfo.restrictedBy) { peers[peer.id] = peer } } diff --git a/TelegramCore/ChannelHistoryAvailabilitySettings.swift b/TelegramCore/ChannelHistoryAvailabilitySettings.swift index a7635fe65f..c15e336a88 100644 --- a/TelegramCore/ChannelHistoryAvailabilitySettings.swift +++ b/TelegramCore/ChannelHistoryAvailabilitySettings.swift @@ -7,13 +7,13 @@ #endif public func updateChannelHistoryAvailabilitySettingsInteractively(postbox: Postbox, network: Network, peerId: PeerId, historyAvailableForNewMembers: Bool) -> Signal { - return postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let inputChannel = apiInputChannel(peer) { + return postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let inputChannel = apiInputChannel(peer) { return network.request(Api.functions.channels.togglePreHistoryHidden(channel: inputChannel, enabled: historyAvailableForNewMembers ? .boolFalse : .boolTrue)) |> mapError {_ in} |> mapToSignal { _ -> Signal in - return postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: [peerId], update: { peerId, currentData in + return postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: [peerId], update: { peerId, currentData in if let currentData = currentData as? CachedChannelData { var flags = currentData.flags if historyAvailableForNewMembers { diff --git a/TelegramCore/ChannelMembers.swift b/TelegramCore/ChannelMembers.swift index a07e91af62..5d69e559e9 100644 --- a/TelegramCore/ChannelMembers.swift +++ b/TelegramCore/ChannelMembers.swift @@ -22,8 +22,8 @@ public enum ChannelMembersCategory { } public func channelMembers(postbox: Postbox, network: Network, peerId: PeerId, category: ChannelMembersCategory = .recent(.all), offset: Int32 = 0, limit: Int32 = 64, hash: Int32 = 0) -> Signal<[RenderedChannelParticipant]?, NoError> { - return postbox.modify { modifier -> Signal<[RenderedChannelParticipant]?, NoError> in - if let peer = modifier.getPeer(peerId), let inputChannel = apiInputChannel(peer) { + return postbox.transaction { transaction -> Signal<[RenderedChannelParticipant]?, NoError> in + if let peer = transaction.getPeer(peerId), let inputChannel = apiInputChannel(peer) { let apiFilter: Api.ChannelParticipantsFilter switch category { case let .recent(filter): @@ -53,7 +53,7 @@ public func channelMembers(postbox: Postbox, network: Network, peerId: PeerId, c return network.request(Api.functions.channels.getParticipants(channel: inputChannel, filter: apiFilter, offset: offset, limit: limit, hash: hash)) |> retryRequest |> mapToSignal { result -> Signal<[RenderedChannelParticipant]?, NoError> in - return postbox.modify { modifier -> [RenderedChannelParticipant]? in + return postbox.transaction { transaction -> [RenderedChannelParticipant]? in var items: [RenderedChannelParticipant] = [] switch result { case let .channelParticipants(_, participants, users): @@ -66,10 +66,10 @@ public func channelMembers(postbox: Postbox, network: Network, peerId: PeerId, c presences[peer.id] = presence } } - updatePeers(modifier: modifier, peers: Array(peers.values), update: { _, updated in + updatePeers(transaction: transaction, peers: Array(peers.values), update: { _, updated in return updated }) - modifier.updatePeerPresences(presences) + transaction.updatePeerPresences(presences) for participant in CachedChannelParticipants(apiParticipants: participants).participants { if let peer = peers[participant.peerId] { diff --git a/TelegramCore/ChannelParticipants.swift b/TelegramCore/ChannelParticipants.swift index df953a15c4..87047ab1d2 100644 --- a/TelegramCore/ChannelParticipants.swift +++ b/TelegramCore/ChannelParticipants.swift @@ -27,16 +27,16 @@ public struct RenderedChannelParticipant: Equatable { } func updateChannelParticipantsSummary(account: Account, peerId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let inputChannel = apiInputChannel(peer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let inputChannel = apiInputChannel(peer) { let admins = account.network.request(Api.functions.channels.getParticipants(channel: inputChannel, filter: .channelParticipantsAdmins, offset: 0, limit: 0, hash: 0)) let members = account.network.request(Api.functions.channels.getParticipants(channel: inputChannel, filter: .channelParticipantsRecent, offset: 0, limit: 0, hash: 0)) let banned = account.network.request(Api.functions.channels.getParticipants(channel: inputChannel, filter: .channelParticipantsBanned(q: ""), offset: 0, limit: 0, hash: 0)) let kicked = account.network.request(Api.functions.channels.getParticipants(channel: inputChannel, filter: .channelParticipantsKicked(q: ""), offset: 0, limit: 0, hash: 0)) return combineLatest(admins, members, banned, kicked) |> mapToSignal { admins, members, banned, kicked -> Signal in - return account.postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + return account.postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedChannelData { let adminCount: Int32 switch admins { diff --git a/TelegramCore/CheckPeerChatServiceActions.swift b/TelegramCore/CheckPeerChatServiceActions.swift index e16e98e3fa..bb486eff97 100644 --- a/TelegramCore/CheckPeerChatServiceActions.swift +++ b/TelegramCore/CheckPeerChatServiceActions.swift @@ -8,12 +8,12 @@ import Foundation #endif public func checkPeerChatServiceActions(postbox: Postbox, peerId: PeerId) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in if peerId.namespace == Namespaces.Peer.SecretChat { - if let state = modifier.getPeerChatState(peerId) as? SecretChatState { - let updatedState = secretChatCheckLayerNegotiationIfNeeded(modifier: modifier, peerId: peerId, state: state) + if let state = transaction.getPeerChatState(peerId) as? SecretChatState { + let updatedState = secretChatCheckLayerNegotiationIfNeeded(transaction: transaction, peerId: peerId, state: state) if state != updatedState { - modifier.setPeerChatState(peerId, state: updatedState) + transaction.setPeerChatState(peerId, state: updatedState) } } } diff --git a/TelegramCore/CloudChatRemoveMessagesOperation.swift b/TelegramCore/CloudChatRemoveMessagesOperation.swift index 0954956582..ca632fd7f9 100644 --- a/TelegramCore/CloudChatRemoveMessagesOperation.swift +++ b/TelegramCore/CloudChatRemoveMessagesOperation.swift @@ -101,22 +101,22 @@ final class CloudChatClearHistoryOperation: PostboxCoding { } } -func cloudChatAddRemoveMessagesOperation(modifier: Modifier, peerId: PeerId, messageIds: [MessageId], type: CloudChatRemoveMessagesType) { - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: CloudChatRemoveMessagesOperation(messageIds: messageIds, type: type)) +func cloudChatAddRemoveMessagesOperation(transaction: Transaction, peerId: PeerId, messageIds: [MessageId], type: CloudChatRemoveMessagesType) { + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: CloudChatRemoveMessagesOperation(messageIds: messageIds, type: type)) } -func cloudChatAddRemoveChatOperation(modifier: Modifier, peerId: PeerId, reportChatSpam: Bool) { - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: CloudChatRemoveChatOperation(peerId: peerId, reportChatSpam: reportChatSpam, topMessageId: modifier.getTopPeerMessageId(peerId: peerId, namespace: Namespaces.Message.Cloud))) +func cloudChatAddRemoveChatOperation(transaction: Transaction, peerId: PeerId, reportChatSpam: Bool) { + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: CloudChatRemoveChatOperation(peerId: peerId, reportChatSpam: reportChatSpam, topMessageId: transaction.getTopPeerMessageId(peerId: peerId, namespace: Namespaces.Message.Cloud))) } -func cloudChatAddClearHistoryOperation(modifier: Modifier, peerId: PeerId, explicitTopMessageId: MessageId?) { +func cloudChatAddClearHistoryOperation(transaction: Transaction, peerId: PeerId, explicitTopMessageId: MessageId?) { let topMessageId: MessageId? if let explicitTopMessageId = explicitTopMessageId { topMessageId = explicitTopMessageId } else { - topMessageId = modifier.getTopPeerMessageId(peerId: peerId, namespace: Namespaces.Message.Cloud) + topMessageId = transaction.getTopPeerMessageId(peerId: peerId, namespace: Namespaces.Message.Cloud) } if let topMessageId = topMessageId { - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: CloudChatClearHistoryOperation(peerId: peerId, topMessageId: topMessageId)) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: CloudChatClearHistoryOperation(peerId: peerId, topMessageId: topMessageId)) } } diff --git a/TelegramCore/CollectCacheUsageStats.swift b/TelegramCore/CollectCacheUsageStats.swift index 0580ad2645..596e31e679 100644 --- a/TelegramCore/CollectCacheUsageStats.swift +++ b/TelegramCore/CollectCacheUsageStats.swift @@ -56,8 +56,8 @@ private final class CacheUsageStatsState { public func collectCacheUsageStats(account: Account) -> Signal { let state = Atomic(value: CacheUsageStatsState()) - let fetch = account.postbox.modify { modifier -> ([PeerId : Set], [MediaId : Media], MessageIndex?) in - return modifier.enumerateMedia(lowerBound: state.with { $0.lowerBound }, limit: 1000) + let fetch = account.postbox.transaction { transaction -> ([PeerId : Set], [MediaId : Media], MessageIndex?) in + return transaction.enumerateMedia(lowerBound: state.with { $0.lowerBound }, limit: 1000) } |> mapError { _ -> CollectCacheUsageStatsError in preconditionFailure() } let process: ([PeerId : Set], [MediaId : Media], MessageIndex?) -> Signal = { mediaByPeer, mediaRefs, updatedLowerBound in @@ -160,12 +160,12 @@ public func collectCacheUsageStats(account: Account) -> Signal CacheUsageStats in + return account.postbox.transaction { transaction -> CacheUsageStats in var peers: [PeerId: Peer] = [:] for peerId in finalMedia.keys { - if let peer = modifier.getPeer(peerId) { + if let peer = transaction.getPeer(peerId) { peers[peer.id] = peer - if let associatedPeerId = peer.associatedPeerId, let associatedPeer = modifier.getPeer(associatedPeerId) { + if let associatedPeerId = peer.associatedPeerId, let associatedPeer = transaction.getPeer(associatedPeerId) { peers[associatedPeer.id] = associatedPeer } } diff --git a/TelegramCore/ContactManagement.swift b/TelegramCore/ContactManagement.swift index 0ce56ffaba..5a86d048c6 100644 --- a/TelegramCore/ContactManagement.swift +++ b/TelegramCore/ContactManagement.swift @@ -69,11 +69,11 @@ func manageContacts(network: Network, postbox: Postbox) -> Signal let appliedUpdatedPeers = updatedPeers |> mapToSignal { peersAndPresences -> Signal in if let (peers, peerPresences, totalCount) = peersAndPresences { - return postbox.modify { modifier in - updatePeers(modifier: modifier, peers: peers, update: { return $1 }) - modifier.updatePeerPresences(peerPresences) - modifier.replaceContactPeerIds(Set(peers.map { $0.id })) - modifier.replaceRemoteContactCount(totalCount) + return postbox.transaction { transaction in + updatePeers(transaction: transaction, peers: peers, update: { return $1 }) + transaction.updatePeerPresences(peerPresences) + transaction.replaceContactPeerIds(Set(peers.map { $0.id })) + transaction.replaceRemoteContactCount(totalCount) } } else { return .complete() @@ -84,27 +84,27 @@ func manageContacts(network: Network, postbox: Postbox) -> Signal } public func addContactPeerInteractively(account: Account, peerId: PeerId, phone: String?) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) as? TelegramUser, let phone = phone ?? peer.phone, !phone.isEmpty { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) as? TelegramUser, let phone = phone ?? peer.phone, !phone.isEmpty { return account.network.request(Api.functions.contacts.importContacts(contacts: [Api.InputContact.inputPhoneContact(clientId: 1, phone: phone, firstName: peer.firstName ?? "", lastName: peer.lastName ?? "")])) |> map { Optional($0) } |> `catch` { _ -> Signal in return .single(nil) } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if let result = result { switch result { case let .importedContacts(_, _, _, users): if let first = users.first { let user = TelegramUser(user: first) - updatePeers(modifier: modifier, peers: [user], update: { _, updated in + updatePeers(transaction: transaction, peers: [user], update: { _, updated in return updated }) - var peerIds = modifier.getContactPeerIds() + var peerIds = transaction.getContactPeerIds() if !peerIds.contains(peerId) { peerIds.insert(peerId) - modifier.replaceContactPeerIds(peerIds) + transaction.replaceContactPeerIds(peerIds) } } } @@ -118,19 +118,19 @@ public func addContactPeerInteractively(account: Account, peerId: PeerId, phone: } public func deleteContactPeerInteractively(account: Account, peerId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let inputUser = apiInputUser(peer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) { return account.network.request(Api.functions.contacts.deleteContact(id: inputUser)) |> map { Optional($0) } |> `catch` { _ -> Signal in return .single(nil) } |> mapToSignal { _ -> Signal in - return account.postbox.modify { modifier -> Void in - var peerIds = modifier.getContactPeerIds() + return account.postbox.transaction { transaction -> Void in + var peerIds = transaction.getContactPeerIds() if peerIds.contains(peerId) { peerIds.remove(peerId) - modifier.replaceContactPeerIds(peerIds) + transaction.replaceContactPeerIds(peerIds) } } } @@ -141,8 +141,8 @@ public func deleteContactPeerInteractively(account: Account, peerId: PeerId) -> } public func deleteAllContacts(postbox: Postbox, network: Network) -> Signal { - return postbox.modify { modifier -> [Api.InputUser] in - return modifier.getContactPeerIds().compactMap(modifier.getPeer).compactMap({ apiInputUser($0) }).compactMap({ $0 }) + return postbox.transaction { transaction -> [Api.InputUser] in + return transaction.getContactPeerIds().compactMap(transaction.getPeer).compactMap({ apiInputUser($0) }).compactMap({ $0 }) } |> mapToSignal { users -> Signal in return network.request(Api.functions.contacts.deleteContacts(id: users)) diff --git a/TelegramCore/ContentPrivacySettings.swift b/TelegramCore/ContentPrivacySettings.swift index 84a3985ad9..d9a601d3bf 100644 --- a/TelegramCore/ContentPrivacySettings.swift +++ b/TelegramCore/ContentPrivacySettings.swift @@ -51,9 +51,9 @@ public final class ContentPrivacySettings: PreferencesEntry, Equatable { } public func updateContentPrivacySettings(postbox: Postbox, _ f: @escaping (ContentPrivacySettings) -> ContentPrivacySettings) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in var updated: ContentPrivacySettings? - modifier.updatePreferencesEntry(key: PreferencesKeys.contentPrivacySettings, { current in + transaction.updatePreferencesEntry(key: PreferencesKeys.contentPrivacySettings, { current in if let current = current as? ContentPrivacySettings { updated = f(current) return updated diff --git a/TelegramCore/CoreSettings.swift b/TelegramCore/CoreSettings.swift index a77e8860c1..e0ff5728e4 100644 --- a/TelegramCore/CoreSettings.swift +++ b/TelegramCore/CoreSettings.swift @@ -47,9 +47,9 @@ public final class CoreSettings: PreferencesEntry, Equatable { } public func updateCoreSettings(postbox: Postbox, _ f: @escaping (CoreSettings) -> CoreSettings) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in var updated: CoreSettings? - modifier.updatePreferencesEntry(key: PreferencesKeys.coreSettings, { current in + transaction.updatePreferencesEntry(key: PreferencesKeys.coreSettings, { current in if let current = current as? CoreSettings { updated = f(current) return updated diff --git a/TelegramCore/CreateChannel.swift b/TelegramCore/CreateChannel.swift index a18cf6c93d..47abd237b1 100644 --- a/TelegramCore/CreateChannel.swift +++ b/TelegramCore/CreateChannel.swift @@ -10,7 +10,7 @@ import Foundation #endif public func createChannel(account: Account, title: String, description: String?) -> Signal { - return account.postbox.modify { modifier -> Signal in + return account.postbox.transaction { transaction -> Signal in return account.network.request(Api.functions.channels.createChannel(flags: 1 << 0, title: title, about: description ?? ""), automaticFloodWait: false) |> map { Optional($0) } |> `catch` { _ in diff --git a/TelegramCore/CreateGroup.swift b/TelegramCore/CreateGroup.swift index fda824e1f8..fb38e637b1 100644 --- a/TelegramCore/CreateGroup.swift +++ b/TelegramCore/CreateGroup.swift @@ -10,10 +10,10 @@ import Foundation #endif public func createGroup(account: Account, title: String, peerIds: [PeerId]) -> Signal { - return account.postbox.modify { modifier -> Signal in + return account.postbox.transaction { transaction -> Signal in var inputUsers: [Api.InputUser] = [] for peerId in peerIds { - if let peer = modifier.getPeer(peerId), let inputUser = apiInputUser(peer) { + if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) { inputUsers.append(inputUser) } else { return .single(nil) diff --git a/TelegramCore/CreateSecretChat.swift b/TelegramCore/CreateSecretChat.swift index 923ae895f7..2ed3fadf91 100644 --- a/TelegramCore/CreateSecretChat.swift +++ b/TelegramCore/CreateSecretChat.swift @@ -14,8 +14,8 @@ public enum CreateSecretChatError { } public func createSecretChat(account: Account, peerId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let inputUser = apiInputUser(peer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) { return validatedEncryptionConfig(postbox: account.postbox, network: account.network) |> mapError { _ -> CreateSecretChatError in return .generic } |> mapToSignal { config -> Signal in @@ -35,8 +35,8 @@ public func createSecretChat(account: Account, peerId: PeerId) -> Signal mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> PeerId in - updateSecretChat(accountPeerId: account.peerId, modifier: modifier, chat: result, requestData: SecretChatRequestData(g: config.g, p: config.p, a: a)) + return account.postbox.transaction { transaction -> PeerId in + updateSecretChat(accountPeerId: account.peerId, transaction: transaction, chat: result, requestData: SecretChatRequestData(g: config.g, p: config.p, a: a)) return result.peerId } |> mapError { _ -> CreateSecretChatError in return .generic } diff --git a/TelegramCore/DeleteMessagesInteractively.swift b/TelegramCore/DeleteMessagesInteractively.swift index 20f28fdc5e..c6f13b0a8d 100644 --- a/TelegramCore/DeleteMessagesInteractively.swift +++ b/TelegramCore/DeleteMessagesInteractively.swift @@ -15,7 +15,7 @@ public enum InteractiveMessagesDeletionType { } public func deleteMessagesInteractively(postbox: Postbox, messageIds: [MessageId], type: InteractiveMessagesDeletionType) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in var messageIdsByPeerId: [PeerId: [MessageId]] = [:] for id in messageIds { if messageIdsByPeerId[id.peerId] == nil { @@ -26,9 +26,9 @@ public func deleteMessagesInteractively(postbox: Postbox, messageIds: [MessageId } for (peerId, peerMessageIds) in messageIdsByPeerId { if peerId.namespace == Namespaces.Peer.CloudChannel || peerId.namespace == Namespaces.Peer.CloudGroup || peerId.namespace == Namespaces.Peer.CloudUser { - cloudChatAddRemoveMessagesOperation(modifier: modifier, peerId: peerId, messageIds: peerMessageIds, type: CloudChatRemoveMessagesType(type)) + cloudChatAddRemoveMessagesOperation(transaction: transaction, peerId: peerId, messageIds: peerMessageIds, type: CloudChatRemoveMessagesType(type)) } else if peerId.namespace == Namespaces.Peer.SecretChat { - if let state = modifier.getPeerChatState(peerId) as? SecretChatState { + if let state = transaction.getPeerChatState(peerId) as? SecretChatState { var layer: SecretChatLayer? switch state.embeddedState { case .terminated, .handshake: @@ -41,42 +41,42 @@ public func deleteMessagesInteractively(postbox: Postbox, messageIds: [MessageId if let layer = layer { var globallyUniqueIds: [Int64] = [] for messageId in peerMessageIds { - if let message = modifier.getMessage(messageId), let globallyUniqueId = message.globallyUniqueId { + if let message = transaction.getMessage(messageId), let globallyUniqueId = message.globallyUniqueId { globallyUniqueIds.append(globallyUniqueId) } } - let updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: SecretChatOutgoingOperationContents.deleteMessages(layer: layer, actionGloballyUniqueId: arc4random64(), globallyUniqueIds: globallyUniqueIds), state: state) + let updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: SecretChatOutgoingOperationContents.deleteMessages(layer: layer, actionGloballyUniqueId: arc4random64(), globallyUniqueIds: globallyUniqueIds), state: state) if updatedState != state { - modifier.setPeerChatState(peerId, state: updatedState) + transaction.setPeerChatState(peerId, state: updatedState) } } } } } - modifier.deleteMessages(messageIds) + transaction.deleteMessages(messageIds) } } public func clearHistoryInteractively(postbox: Postbox, peerId: PeerId) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup || peerId.namespace == Namespaces.Peer.CloudChannel { var topTimestamp: Int32? - if let topIndex = modifier.getTopMesssageIndex(peerId: peerId, namespace: Namespaces.Message.Cloud) { + if let topIndex = transaction.getTopMesssageIndex(peerId: peerId, namespace: Namespaces.Message.Cloud) { topTimestamp = topIndex.timestamp } - cloudChatAddClearHistoryOperation(modifier: modifier, peerId: peerId, explicitTopMessageId: nil) - modifier.clearHistory(peerId) - if let cachedData = modifier.getPeerCachedData(peerId: peerId) as? CachedChannelData, let migrationReference = cachedData.migrationReference { - cloudChatAddClearHistoryOperation(modifier: modifier, peerId: migrationReference.maxMessageId.peerId, explicitTopMessageId: MessageId(peerId: migrationReference.maxMessageId.peerId, namespace: migrationReference.maxMessageId.namespace, id: migrationReference.maxMessageId.id + 1)) - modifier.clearHistory(migrationReference.maxMessageId.peerId) + cloudChatAddClearHistoryOperation(transaction: transaction, peerId: peerId, explicitTopMessageId: nil) + transaction.clearHistory(peerId) + if let cachedData = transaction.getPeerCachedData(peerId: peerId) as? CachedChannelData, let migrationReference = cachedData.migrationReference { + cloudChatAddClearHistoryOperation(transaction: transaction, peerId: migrationReference.maxMessageId.peerId, explicitTopMessageId: MessageId(peerId: migrationReference.maxMessageId.peerId, namespace: migrationReference.maxMessageId.namespace, id: migrationReference.maxMessageId.id + 1)) + transaction.clearHistory(migrationReference.maxMessageId.peerId) } if let topTimestamp = topTimestamp { - updatePeerChatInclusionWithMinTimestamp(modifier: modifier, id: peerId, minTimestamp: topTimestamp) + updatePeerChatInclusionWithMinTimestamp(transaction: transaction, id: peerId, minTimestamp: topTimestamp) } } else if peerId.namespace == Namespaces.Peer.SecretChat { - modifier.clearHistory(peerId) + transaction.clearHistory(peerId) - if let state = modifier.getPeerChatState(peerId) as? SecretChatState { + if let state = transaction.getPeerChatState(peerId) as? SecretChatState { var layer: SecretChatLayer? switch state.embeddedState { case .terminated, .handshake: @@ -88,9 +88,9 @@ public func clearHistoryInteractively(postbox: Postbox, peerId: PeerId) -> Signa } if let layer = layer { - let updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: SecretChatOutgoingOperationContents.clearHistory(layer: layer, actionGloballyUniqueId: arc4random64()), state: state) + let updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: SecretChatOutgoingOperationContents.clearHistory(layer: layer, actionGloballyUniqueId: arc4random64()), state: state) if updatedState != state { - modifier.setPeerChatState(peerId, state: updatedState) + transaction.setPeerChatState(peerId, state: updatedState) } } } @@ -99,8 +99,8 @@ public func clearHistoryInteractively(postbox: Postbox, peerId: PeerId) -> Signa } public func clearAuthorHistory(account: Account, peerId: PeerId, memberId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let memberPeer = modifier.getPeer(memberId), let inputChannel = apiInputChannel(peer), let inputUser = apiInputUser(memberPeer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let memberPeer = transaction.getPeer(memberId), let inputChannel = apiInputChannel(peer), let inputUser = apiInputUser(memberPeer) { let signal = account.network.request(Api.functions.channels.deleteUserHistory(channel: inputChannel, userId: inputUser)) |> map { result -> Api.messages.AffectedHistory? in @@ -127,8 +127,8 @@ public func clearAuthorHistory(account: Account, peerId: PeerId, memberId: PeerI return (signal |> restart) |> `catch` { success -> Signal in if success { - return account.postbox.modify { modifier -> Void in - modifier.removeAllMessagesWithAuthor(peerId, authorId: memberId) + return account.postbox.transaction { transaction -> Void in + transaction.removeAllMessagesWithAuthor(peerId, authorId: memberId) } } else { return .complete() diff --git a/TelegramCore/EarliestUnseenPersonalMentionMessage.swift b/TelegramCore/EarliestUnseenPersonalMentionMessage.swift index 2cf9786f0e..ad2d2262d5 100644 --- a/TelegramCore/EarliestUnseenPersonalMentionMessage.swift +++ b/TelegramCore/EarliestUnseenPersonalMentionMessage.swift @@ -19,10 +19,10 @@ public func earliestUnseenPersonalMentionMessage(postbox: Postbox, network: Netw } private func earliestUnseenPersonalMentionMessage(postbox: Postbox, network: Network, peerId: PeerId, locally: Bool) -> Signal { - return postbox.modify { modifier -> Signal in + return postbox.transaction { transaction -> Signal in var resultMessage: Message? var resultHole: MessageHistoryHole? - modifier.scanMessages(peerId: peerId, tagMask: .unseenPersonalMessage, { entry in + transaction.scanMessages(peerId: peerId, tagMask: .unseenPersonalMessage, { entry in switch entry { case let .message(message): for attribute in message.attributes { @@ -42,7 +42,7 @@ private func earliestUnseenPersonalMentionMessage(postbox: Postbox, network: Net var invalidateHistoryPts: Int32? if peerId.namespace == Namespaces.Peer.CloudChannel { - if let channelState = modifier.getPeerChatState(peerId) as? ChannelState { + if let channelState = transaction.getPeerChatState(peerId) as? ChannelState { if let invalidatedPts = channelState.invalidatedPts { var messagePts: Int32? for attribute in resultMessage.attributes { @@ -80,8 +80,8 @@ private func earliestUnseenPersonalMentionMessage(postbox: Postbox, network: Net } |> then(earliestUnseenPersonalMentionMessage(postbox: postbox, network: network, peerId: peerId, locally: true)) return .single(.loading) |> then(validateSignal) - } else if let summary = modifier.getMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud), summary.count > 0 { - modifier.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud, count: 0, maxId: summary.range.maxId) + } else if let summary = transaction.getMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud), summary.count > 0 { + transaction.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud, count: 0, maxId: summary.range.maxId) } return .single(.result(nil)) diff --git a/TelegramCore/EnqueueMessage.swift b/TelegramCore/EnqueueMessage.swift index 2c69f2bc0c..ea1dc6981c 100644 --- a/TelegramCore/EnqueueMessage.swift +++ b/TelegramCore/EnqueueMessage.swift @@ -127,8 +127,8 @@ public func enqueueMessages(account: Account, peerId: PeerId, messages: [Enqueue } return signal |> mapToSignal { messages -> Signal<[MessageId?], NoError> in - return account.postbox.modify { modifier -> [MessageId?] in - return enqueueMessages(modifier: modifier, account: account, peerId: peerId, messages: messages) + return account.postbox.transaction { transaction -> [MessageId?] in + return enqueueMessages(transaction: transaction, account: account, peerId: peerId, messages: messages) } } } @@ -142,10 +142,10 @@ public func enqueueMessagesToMultiplePeers(account: Account, peerIds: [PeerId], } return signal |> mapToSignal { messages -> Signal<[MessageId], NoError> in - return account.postbox.modify { modifier -> [MessageId] in + return account.postbox.transaction { transaction -> [MessageId] in var messageIds: [MessageId] = [] for peerId in peerIds { - for id in enqueueMessages(modifier: modifier, account: account, peerId: peerId, messages: messages) { + for id in enqueueMessages(transaction: transaction, account: account, peerId: peerId, messages: messages) { if let id = id { messageIds.append(id) } @@ -157,12 +157,12 @@ public func enqueueMessagesToMultiplePeers(account: Account, peerIds: [PeerId], } public func resendMessages(account: Account, messageIds: [MessageId]) -> Signal { - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in var removeMessageIds: [MessageId] = [] for (peerId, ids) in messagesIdsGroupedByPeerId(messageIds) { var messages: [EnqueueMessage] = [] for id in ids { - if let message = modifier.getMessage(id), !message.flags.contains(.Incoming) { + if let message = transaction.getMessage(id), !message.flags.contains(.Incoming) { removeMessageIds.append(id) var replyToMessageId: MessageId? @@ -175,19 +175,19 @@ public func resendMessages(account: Account, messageIds: [MessageId]) -> Signal< messages.append(.message(text: message.text, attributes: message.attributes, media: message.media.first, replyToMessageId: replyToMessageId, localGroupingKey: message.groupingKey)) } } - let _ = enqueueMessages(modifier: modifier, account: account, peerId: peerId, messages: messages.map { (false, $0) }) + let _ = enqueueMessages(transaction: transaction, account: account, peerId: peerId, messages: messages.map { (false, $0) }) } - modifier.deleteMessages(removeMessageIds) + transaction.deleteMessages(removeMessageIds) } } -func enqueueMessages(modifier: Modifier, account: Account, peerId: PeerId, messages: [(Bool, EnqueueMessage)]) -> [MessageId?] { - if let peer = modifier.getPeer(peerId), let accountPeer = modifier.getPeer(account.peerId) { +func enqueueMessages(transaction: Transaction, account: Account, peerId: PeerId, messages: [(Bool, EnqueueMessage)]) -> [MessageId?] { + if let peer = transaction.getPeer(peerId), let accountPeer = transaction.getPeer(account.peerId) { var storeMessages: [StoreMessage] = [] var timestamp = Int32(account.network.context.globalTime()) switch peerId.namespace { case Namespaces.Peer.CloudChannel, Namespaces.Peer.CloudGroup, Namespaces.Peer.CloudUser: - if let topIndex = modifier.getTopPeerMessageIndex(peerId: peerId, namespace: Namespaces.Message.Cloud) { + if let topIndex = transaction.getTopPeerMessageIndex(peerId: peerId, namespace: Namespaces.Message.Cloud) { timestamp = max(timestamp, topIndex.timestamp) } default: @@ -301,7 +301,7 @@ func enqueueMessages(modifier: Modifier, account: Account, peerId: PeerId, messa storeMessages.append(StoreMessage(peerId: peerId, namespace: Namespaces.Message.Local, globallyUniqueId: randomId, groupingKey: localGroupingKey, timestamp: timestamp, flags: flags, tags: tags, globalTags: globalTags, localTags: localTags, forwardInfo: nil, authorId: authorId, text: text, attributes: attributes, media: mediaList)) case let .forward(source, grouping): - let sourceMessage = modifier.getMessage(source) + let sourceMessage = transaction.getMessage(source) if let sourceMessage = sourceMessage, let author = sourceMessage.author ?? sourceMessage.peers[sourceMessage.id.peerId] { if let peer = peer as? TelegramSecretChat { var isAction = false @@ -395,13 +395,13 @@ func enqueueMessages(modifier: Modifier, account: Account, peerId: PeerId, messa } var messageIds: [MessageId?] = [] if !storeMessages.isEmpty { - let globallyUniqueIdToMessageId = modifier.addMessages(storeMessages, location: .Random) + let globallyUniqueIdToMessageId = transaction.addMessages(storeMessages, location: .Random) for globallyUniqueId in globallyUniqueIds { messageIds.append(globallyUniqueIdToMessageId[globallyUniqueId]) } } for hashtag in addedHashtags { - addRecentlyUsedHashtag(modifier: modifier, string: hashtag) + addRecentlyUsedHashtag(transaction: transaction, string: hashtag) } return messageIds } else { diff --git a/TelegramCore/ExportMessageLink.swift b/TelegramCore/ExportMessageLink.swift index 5ccd85a316..755725d4f3 100644 --- a/TelegramCore/ExportMessageLink.swift +++ b/TelegramCore/ExportMessageLink.swift @@ -9,8 +9,8 @@ public func exportMessageLink(account:Account, peerId:PeerId, messageId:MessageId) -> Signal { - return account.postbox.modify { modifier -> Peer? in - return modifier.getPeer(peerId) + return account.postbox.transaction { transaction -> Peer? in + return transaction.getPeer(peerId) } |> mapToSignal { peer -> Signal in if let peer = peer, let input = apiInputChannel(peer) { return account.network.request(Api.functions.channels.exportMessageLink(channel: input, id: messageId.id, grouped: .boolTrue)) |> mapError {_ in return } |> map { res in diff --git a/TelegramCore/ForwardGame.swift b/TelegramCore/ForwardGame.swift index b4ffd27ed3..b4d09b4e95 100644 --- a/TelegramCore/ForwardGame.swift +++ b/TelegramCore/ForwardGame.swift @@ -8,8 +8,8 @@ import Foundation #endif public func forwardGameWithScore(account: Account, messageId: MessageId, to peerId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let message = modifier.getMessage(messageId), let fromPeer = modifier.getPeer(messageId.peerId), let fromInputPeer = apiInputPeer(fromPeer), let toPeer = modifier.getPeer(peerId), let toInputPeer = apiInputPeer(toPeer) { + return account.postbox.transaction { transaction -> Signal in + if let message = transaction.getMessage(messageId), let fromPeer = transaction.getPeer(messageId.peerId), let fromInputPeer = apiInputPeer(fromPeer), let toPeer = transaction.getPeer(peerId), let toInputPeer = apiInputPeer(toPeer) { return account.network.request(Api.functions.messages.forwardMessages(flags: 1 << 8, fromPeer: fromInputPeer, id: [messageId.id], randomId: [arc4random64()], toPeer: toInputPeer)) |> map(Optional.init) |> `catch` { _ -> Signal in diff --git a/TelegramCore/GroupFeedPeers.swift b/TelegramCore/GroupFeedPeers.swift index 5382b4443e..b8bc9f4212 100644 --- a/TelegramCore/GroupFeedPeers.swift +++ b/TelegramCore/GroupFeedPeers.swift @@ -13,7 +13,7 @@ public func availableGroupFeedPeers(postbox: Postbox, network: Network, groupId: /*return network.request(Api.functions.channels.getFeedSources(flags: 0, feedId: groupId.rawValue, hash: 0)) |> retryRequest |> mapToSignal { result -> Signal<[(Peer, Bool)], NoError> in - return postbox.modify { modifier -> [(Peer, Bool)] in + return postbox.transaction { transaction -> [(Peer, Bool)] in switch result { case .feedSourcesNotModified: return [] @@ -36,12 +36,12 @@ public func availableGroupFeedPeers(postbox: Postbox, network: Network, groupId: } var peers: [(Peer, Bool)] = [] for peerId in includedPeerIds { - if let peer = modifier.getPeer(peerId) { + if let peer = transaction.getPeer(peerId) { peers.append((peer, true)) } } for peerId in excludedPeerIds { - if let peer = modifier.getPeer(peerId) { + if let peer = transaction.getPeer(peerId) { peers.append((peer, false)) } } diff --git a/TelegramCore/GroupsInCommon.swift b/TelegramCore/GroupsInCommon.swift index 018adda06d..6080da06d0 100644 --- a/TelegramCore/GroupsInCommon.swift +++ b/TelegramCore/GroupsInCommon.swift @@ -8,8 +8,8 @@ import Foundation #endif public func groupsInCommon(account:Account, peerId:PeerId) -> Signal<[PeerId], Void> { - return account.postbox.modify { modifier -> Signal<[PeerId], Void> in - if let peer = modifier.getPeer(peerId), let inputUser = apiInputUser(peer) { + return account.postbox.transaction { transaction -> Signal<[PeerId], Void> in + if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) { return account.network.request(Api.functions.messages.getCommonChats(userId: inputUser, maxId: 0, limit: 100)) |> mapError {_ in} |> mapToSignal { result -> Signal<[PeerId], Void> in let chats:[Api.Chat] switch result { @@ -19,14 +19,14 @@ public func groupsInCommon(account:Account, peerId:PeerId) -> Signal<[PeerId], V chats = apiChats } - return account.postbox.modify { modifier -> [PeerId] in + return account.postbox.transaction { transaction -> [PeerId] in var peers:[Peer] = [] for chat in chats { if let peer = parseTelegramGroupOrChannel(chat: chat) { peers.append(peer) } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer? in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer? in return updated }) return peers.map {$0.id} diff --git a/TelegramCore/HistoryViewChannelStateValidation.swift b/TelegramCore/HistoryViewChannelStateValidation.swift index d64b520c34..4ad627ea38 100644 --- a/TelegramCore/HistoryViewChannelStateValidation.swift +++ b/TelegramCore/HistoryViewChannelStateValidation.swift @@ -313,11 +313,11 @@ private enum ValidatedMessages { } private func validateBatch(postbox: Postbox, network: Network, accountPeerId: PeerId, messageIds: [MessageId], historyState: HistoryState) -> Signal { - return postbox.modify { modifier -> Signal in + return postbox.transaction { transaction -> Signal in var previousMessages: [Message] = [] var previous: [MessageId: Message] = [:] for messageId in messageIds { - if let message = modifier.getMessage(messageId) { + if let message = transaction.getMessage(messageId) { previousMessages.append(message) previous[message.id] = message } @@ -327,7 +327,7 @@ private func validateBatch(postbox: Postbox, network: Network, accountPeerId: Pe switch historyState { case let .channel(peerId, _): let hash = hashForMessages(previousMessages, withChannelIds: false) - if let peer = modifier.getPeer(peerId), let inputPeer = apiInputPeer(peer) { + if let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) { signal = network.request(Api.functions.messages.getHistory(peer: inputPeer, offsetId: messageIds[messageIds.count - 1].id + 1, offsetDate: 0, addOffset: 0, limit: Int32(messageIds.count), maxId: messageIds[messageIds.count - 1].id + 1, minId: messageIds[0].id - 1, hash: hash)) |> map { result -> ValidatedMessages in let messages: [Api.Message] @@ -394,7 +394,7 @@ private func validateBatch(postbox: Postbox, network: Network, accountPeerId: Pe return .single(nil) } |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in if let result = result { switch result { case let .messages(messages, chats, users, channelPts): @@ -429,7 +429,7 @@ private func validateBatch(postbox: Postbox, network: Network, accountPeerId: Pe for message in storeMessages { if case let .Id(id) = message.id { validMessageIds.insert(id) - let previousMessage = previous[id] ?? modifier.getMessage(id) + let previousMessage = previous[id] ?? transaction.getMessage(id) if let previousMessage = previousMessage { var updatedTimestamp = message.timestamp @@ -448,7 +448,7 @@ private func validateBatch(postbox: Postbox, network: Network, accountPeerId: Pe } } - modifier.updateMessage(id, update: { currentMessage in + transaction.updateMessage(id, update: { currentMessage in if updatedTimestamp != timestamp { var updatedLocalTags = message.localTags if currentMessage.localTags.contains(.OutgoingLiveLocation) { @@ -494,11 +494,11 @@ private func validateBatch(postbox: Postbox, network: Network, accountPeerId: Pe if previous[id] == nil { print("\(id) missing") if case let .group(groupId, _) = historyState { - let _ = modifier.addMessagesToGroupFeedIndex(groupId: groupId, ids: [id]) + let _ = transaction.addMessagesToGroupFeedIndex(groupId: groupId, ids: [id]) } } } else { - let _ = modifier.addMessages([message], location: .Random) + let _ = transaction.addMessages([message], location: .Random) } } } @@ -507,15 +507,15 @@ private func validateBatch(postbox: Postbox, network: Network, accountPeerId: Pe if !validMessageIds.contains(id) { switch historyState { case .channel: - modifier.deleteMessages([id]) + transaction.deleteMessages([id]) case let .group(groupId, _): - modifier.removeMessagesFromGroupFeedIndex(groupId: groupId, ids: [id]) + transaction.removeMessagesFromGroupFeedIndex(groupId: groupId, ids: [id]) } } } case .notModified: for id in previous.keys { - modifier.updateMessage(id, update: { currentMessage in + transaction.updateMessage(id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) diff --git a/TelegramCore/Holes.swift b/TelegramCore/Holes.swift index b2f7ad9da2..051a9f827a 100644 --- a/TelegramCore/Holes.swift +++ b/TelegramCore/Holes.swift @@ -208,7 +208,7 @@ func fetchMessageHistoryHole(source: FetchMessageHistoryHoleSource, postbox: Pos } } } - return postbox.modify { modifier in + return postbox.transaction { transaction in var storeMessages: [StoreMessage] = [] for message in messages { @@ -235,7 +235,7 @@ func fetchMessageHistoryHole(source: FetchMessageHistoryHoleSource, postbox: Pos fillDirection = .AroundId(index.id, lowerComplete: false, upperComplete: false) } - modifier.fillMultipleHoles(hole, fillType: HoleFill(complete: messages.count == 0 || implicitelyFillHole, direction: fillDirection), tagMask: tagMask, messages: storeMessages) + transaction.fillMultipleHoles(hole, fillType: HoleFill(complete: messages.count == 0 || implicitelyFillHole, direction: fillDirection), tagMask: tagMask, messages: storeMessages) var peers: [Peer] = [] var peerPresences: [PeerId: PeerPresence] = [:] @@ -252,10 +252,10 @@ func fetchMessageHistoryHole(source: FetchMessageHistoryHoleSource, postbox: Pos } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) print("fetchMessageHistoryHole for \(peer.displayTitle) done") @@ -284,8 +284,8 @@ func groupBoundaryPeer(_ peerId: PeerId, accountPeerId: PeerId) -> Api.Peer { func fetchGroupFeedHole(source: FetchMessageHistoryHoleSource, accountPeerId: PeerId, postbox: Postbox, groupId: PeerGroupId, minIndex: MessageIndex, maxIndex: MessageIndex, direction: MessageHistoryViewRelativeHoleDirection, limit: Int = 100) -> Signal { /*feed*/ return .complete() - /*return postbox.modify { modifier -> (Peer?, Peer?) in - return (modifier.getPeer(minIndex.id.peerId), modifier.getPeer(maxIndex.id.peerId)) + /*return postbox.transaction { transaction -> (Peer?, Peer?) in + return (transaction.getPeer(minIndex.id.peerId), transaction.getPeer(maxIndex.id.peerId)) } |> mapToSignal { lowerPeer, upperPeer in print("fetchGroupFeedHole for \(groupId)") @@ -391,7 +391,7 @@ func fetchGroupFeedHole(source: FetchMessageHistoryHoleSource, accountPeerId: Pe users = [] } - return postbox.modify { modifier in + return postbox.transaction { transaction in var storeMessages: [StoreMessage] = [] loop: for message in messages { @@ -429,7 +429,7 @@ func fetchGroupFeedHole(source: FetchMessageHistoryHoleSource, accountPeerId: Pe fillDirection = .AroundIndex(index, lowerComplete: updatedMinIndex == nil, upperComplete: updatedMaxIndex == nil, clippingMinIndex: updatedMinIndex, clippingMaxIndex: updatedMaxIndex) } - modifier.fillMultipleGroupFeedHoles(groupId: groupId, mainHoleMaxIndex: maxIndex, fillType: HoleFill(complete: messages.count == 0 || complete, direction: fillDirection), messages: storeMessages) + transaction.fillMultipleGroupFeedHoles(groupId: groupId, mainHoleMaxIndex: maxIndex, fillType: HoleFill(complete: messages.count == 0 || complete, direction: fillDirection), messages: storeMessages) var peers: [Peer] = [] var peerPresences: [PeerId: PeerPresence] = [:] @@ -446,10 +446,10 @@ func fetchGroupFeedHole(source: FetchMessageHistoryHoleSource, accountPeerId: Pe } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) print("fetchGroupFeedHole for \(groupId) done") @@ -468,43 +468,43 @@ func fetchChatListHole(postbox: Postbox, network: Network, groupId: PeerGroupId? } return fetchChatList(postbox: postbox, network: network, location: location, upperBound: hole.index) |> mapToSignal { fetchedChats -> Signal in - return postbox.modify { modifier in + return postbox.transaction { transaction in for peer in fetchedChats.peers { - updatePeers(modifier: modifier, peers: [peer], update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: [peer], update: { _, updated -> Peer in return updated }) } - modifier.updatePeerPresences(fetchedChats.peerPresences) - modifier.updateCurrentPeerNotificationSettings(fetchedChats.notificationSettings) - let _ = modifier.addMessages(fetchedChats.storeMessages, location: .UpperHistoryBlock) - modifier.resetIncomingReadStates(fetchedChats.readStates) + transaction.updatePeerPresences(fetchedChats.peerPresences) + transaction.updateCurrentPeerNotificationSettings(fetchedChats.notificationSettings) + let _ = transaction.addMessages(fetchedChats.storeMessages, location: .UpperHistoryBlock) + transaction.resetIncomingReadStates(fetchedChats.readStates) - modifier.replaceChatListHole(groupId: groupId, index: hole.index, hole: fetchedChats.lowerNonPinnedIndex.flatMap(ChatListHole.init)) + transaction.replaceChatListHole(groupId: groupId, index: hole.index, hole: fetchedChats.lowerNonPinnedIndex.flatMap(ChatListHole.init)) for (feedGroupId, lowerIndex) in fetchedChats.feeds { if let hole = postbox.seedConfiguration.initializeChatListWithHoles.first { - modifier.replaceChatListHole(groupId: feedGroupId, index: hole.index, hole: lowerIndex.flatMap(ChatListHole.init)) + transaction.replaceChatListHole(groupId: feedGroupId, index: hole.index, hole: lowerIndex.flatMap(ChatListHole.init)) } } for (peerId, chatState) in fetchedChats.chatStates { if let chatState = chatState as? ChannelState { - if let current = modifier.getPeerChatState(peerId) as? ChannelState { - modifier.setPeerChatState(peerId, state: current.withUpdatedPts(chatState.pts)) + if let current = transaction.getPeerChatState(peerId) as? ChannelState { + transaction.setPeerChatState(peerId, state: current.withUpdatedPts(chatState.pts)) } else { - modifier.setPeerChatState(peerId, state: chatState) + transaction.setPeerChatState(peerId, state: chatState) } } else { - modifier.setPeerChatState(peerId, state: chatState) + transaction.setPeerChatState(peerId, state: chatState) } } if let replacePinnedItemIds = fetchedChats.pinnedItemIds { - modifier.setPinnedItemIds(replacePinnedItemIds) + transaction.setPinnedItemIds(replacePinnedItemIds) } for (peerId, summary) in fetchedChats.mentionTagSummaries { - modifier.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud, count: summary.count, maxId: summary.range.maxId) + transaction.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud, count: summary.count, maxId: summary.range.maxId) } } } @@ -539,7 +539,7 @@ func fetchCallListHole(network: Network, postbox: Postbox, holeIndex: MessageInd chats = [] users = [] } - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in var storeMessages: [StoreMessage] = [] var topIndex: MessageIndex? @@ -557,7 +557,7 @@ func fetchCallListHole(network: Network, postbox: Postbox, holeIndex: MessageInd updatedIndex = topIndex.predecessor() } - modifier.replaceGlobalMessageTagsHole(globalTags: [.Calls, .MissedCalls], index: holeIndex, with: updatedIndex, messages: storeMessages) + transaction.replaceGlobalMessageTagsHole(globalTags: [.Calls, .MissedCalls], index: holeIndex, with: updatedIndex, messages: storeMessages) var peers: [Peer] = [] var peerPresences: [PeerId: PeerPresence] = [:] @@ -574,10 +574,10 @@ func fetchCallListHole(network: Network, postbox: Postbox, holeIndex: MessageInd } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) } } return searchResult diff --git a/TelegramCore/ImportAccount.swift b/TelegramCore/ImportAccount.swift index 84aebbfc56..7f38b05535 100644 --- a/TelegramCore/ImportAccount.swift +++ b/TelegramCore/ImportAccount.swift @@ -30,15 +30,15 @@ public func importAccount(account: UnauthorizedAccount, provider: ImportAccountP let importAccountState = provider.accountState() |> mapToSignal { accountState -> Signal in - return account.postbox.modify { modifier -> Void in - modifier.setState(accountState) + return account.postbox.transaction { transaction -> Void in + transaction.setState(accountState) } } let importPeers = provider.peers() |> mapToSignal { peers -> Signal in - return account.postbox.modify { modifier -> Void in - updatePeers(modifier: modifier, peers: peers, update: { _, updated in + return account.postbox.transaction { transaction -> Void in + updatePeers(transaction: transaction, peers: peers, update: { _, updated in return updated }) } diff --git a/TelegramCore/ImportContact.swift b/TelegramCore/ImportContact.swift index 33e3407480..0c194b40b9 100644 --- a/TelegramCore/ImportContact.swift +++ b/TelegramCore/ImportContact.swift @@ -16,20 +16,20 @@ public func importContact(account:Account, firstName:String, lastName:String, ph return .single(nil) } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> PeerId? in + return account.postbox.transaction { transaction -> PeerId? in if let result = result { switch result { case let .importedContacts(_, _, _, users): if let first = users.first { let user = TelegramUser(user: first) let peerId = user.id - updatePeers(modifier: modifier, peers: [user], update: { _, updated in + updatePeers(transaction: transaction, peers: [user], update: { _, updated in return updated }) - var peerIds = modifier.getContactPeerIds() + var peerIds = transaction.getContactPeerIds() if !peerIds.contains(peerId) { peerIds.insert(peerId) - modifier.replaceContactPeerIds(peerIds) + transaction.replaceContactPeerIds(peerIds) } return peerId } diff --git a/TelegramCore/InstallInteractiveReadMessagesAction.swift b/TelegramCore/InstallInteractiveReadMessagesAction.swift index ee24420703..5ad59d37cd 100644 --- a/TelegramCore/InstallInteractiveReadMessagesAction.swift +++ b/TelegramCore/InstallInteractiveReadMessagesAction.swift @@ -8,7 +8,7 @@ import Foundation #endif public func installInteractiveReadMessagesAction(postbox: Postbox, stateManager: AccountStateManager, peerId: PeerId) -> Disposable { - return postbox.installStoreMessageAction(peerId: peerId, { messages, modifier in + return postbox.installStoreMessageAction(peerId: peerId, { messages, transaction in var consumeMessageIds: [MessageId] = [] var readMessageIndexByNamespace: [MessageId.Namespace: MessageIndex] = [:] @@ -43,7 +43,7 @@ public func installInteractiveReadMessagesAction(postbox: Postbox, stateManager: } for id in consumeMessageIds { - modifier.updateMessage(id, update: { currentMessage in + transaction.updateMessage(id, update: { currentMessage in var attributes = currentMessage.attributes loop: for j in 0 ..< attributes.count { if let attribute = attributes[j] as? ConsumablePersonalMentionMessageAttribute { @@ -54,11 +54,11 @@ public func installInteractiveReadMessagesAction(postbox: Postbox, stateManager: return .update(StoreMessage(id: currentMessage.id, globallyUniqueId: currentMessage.globallyUniqueId, groupingKey: currentMessage.groupingKey, timestamp: currentMessage.timestamp, flags: StoreMessageFlags(currentMessage.flags), tags: currentMessage.tags, globalTags: currentMessage.globalTags, localTags: currentMessage.localTags, forwardInfo: currentMessage.forwardInfo.flatMap(StoreMessageForwardInfo.init), authorId: currentMessage.author?.id, text: currentMessage.text, attributes: attributes, media: currentMessage.media)) }) - modifier.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: id, action: ConsumePersonalMessageAction()) + transaction.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: id, action: ConsumePersonalMessageAction()) } for (_, index) in readMessageIndexByNamespace { - applyMaxReadIndexInteractively(modifier: modifier, stateManager: stateManager, index: index) + applyMaxReadIndexInteractively(transaction: transaction, stateManager: stateManager, index: index) } }) } diff --git a/TelegramCore/InvitationLinks.swift b/TelegramCore/InvitationLinks.swift index b8dec63b2f..8751ea4cc5 100644 --- a/TelegramCore/InvitationLinks.swift +++ b/TelegramCore/InvitationLinks.swift @@ -10,18 +10,18 @@ import Foundation #endif public func ensuredExistingPeerExportedInvitation(account: Account, peerId: PeerId, revokeExisted: Bool = false) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) { if let channel = peer as? TelegramChannel, let inputChannel = apiInputChannel(channel) { - if let cachedData = modifier.getPeerCachedData(peerId: peerId) as? CachedChannelData, cachedData.exportedInvitation != nil && !revokeExisted { + if let cachedData = transaction.getPeerCachedData(peerId: peerId) as? CachedChannelData, cachedData.exportedInvitation != nil && !revokeExisted { return .complete() } else { return account.network.request(Api.functions.channels.exportInvite(channel: inputChannel)) |> retryRequest |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if let invitation = ExportedInvitation(apiExportedInvite: result) { - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedChannelData { return current.withUpdatedExportedInvitation(invitation) } else { @@ -33,15 +33,15 @@ public func ensuredExistingPeerExportedInvitation(account: Account, peerId: Peer } } } else if let group = peer as? TelegramGroup { - if let cachedData = modifier.getPeerCachedData(peerId: peerId) as? CachedGroupData, cachedData.exportedInvitation != nil && !revokeExisted { + if let cachedData = transaction.getPeerCachedData(peerId: peerId) as? CachedGroupData, cachedData.exportedInvitation != nil && !revokeExisted { return .complete() } else { return account.network.request(Api.functions.messages.exportChatInvite(chatId: group.id.id)) |> retryRequest |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if let invitation = ExportedInvitation(apiExportedInvite: result) { - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedGroupData { return current.withUpdatedExportedInvitation(invitation) } else { diff --git a/TelegramCore/JoinLink.swift b/TelegramCore/JoinLink.swift index 809daef4ed..22d2950fb9 100644 --- a/TelegramCore/JoinLink.swift +++ b/TelegramCore/JoinLink.swift @@ -76,8 +76,8 @@ public func joinLinkInformation(_ hash: String, account: Account) -> Signal ExternalJoiningChatState in - updatePeers(modifier: modifier, peers: [peer], update: { (previous, updated) -> Peer? in + return account.postbox.transaction({ (transaction) -> ExternalJoiningChatState in + updatePeers(transaction: transaction, peers: [peer], update: { (previous, updated) -> Peer? in return updated }) diff --git a/TelegramCore/LimitsConfiguration.swift b/TelegramCore/LimitsConfiguration.swift index 9094612157..8fcdde317c 100644 --- a/TelegramCore/LimitsConfiguration.swift +++ b/TelegramCore/LimitsConfiguration.swift @@ -70,16 +70,16 @@ public final class LimitsConfiguration: PreferencesEntry { } } -public func currentLimitsConfiguration(modifier: Modifier) -> LimitsConfiguration { - if let entry = modifier.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration { +public func currentLimitsConfiguration(transaction: Transaction) -> LimitsConfiguration { + if let entry = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration { return entry } else { return LimitsConfiguration.defaultValue } } -func updateLimitsConfiguration(modifier: Modifier, configuration: LimitsConfiguration) { - if !currentLimitsConfiguration(modifier: modifier).isEqual(to: configuration) { - modifier.setPreferencesEntry(key: PreferencesKeys.limitsConfiguration, value: configuration) +func updateLimitsConfiguration(transaction: Transaction, configuration: LimitsConfiguration) { + if !currentLimitsConfiguration(transaction: transaction).isEqual(to: configuration) { + transaction.setPreferencesEntry(key: PreferencesKeys.limitsConfiguration, value: configuration) } } diff --git a/TelegramCore/LoadMessagesIfNecessary.swift b/TelegramCore/LoadMessagesIfNecessary.swift index 83151b3199..76e62fd136 100644 --- a/TelegramCore/LoadMessagesIfNecessary.swift +++ b/TelegramCore/LoadMessagesIfNecessary.swift @@ -17,11 +17,11 @@ public enum GetMessagesStrategy { public func getMessagesLoadIfNecessary(_ messageIds:[MessageId], postbox:Postbox, network:Network, strategy:GetMessagesStrategy = .cloud) -> Signal <[Message], Void> { - let postboxSignal = postbox.modify { modifier -> ([Message], Set, SimpleDictionary) in + let postboxSignal = postbox.transaction { transaction -> ([Message], Set, SimpleDictionary) in var ids = messageIds - if let cachedData = modifier.getPeerCachedData(peerId: messageIds[0].peerId) as? CachedChannelData { + if let cachedData = transaction.getPeerCachedData(peerId: messageIds[0].peerId) as? CachedChannelData { if let minAvailableMessageId = cachedData.minAvailableMessageId { ids = ids.filter({$0 < minAvailableMessageId}) } @@ -31,11 +31,11 @@ public func getMessagesLoadIfNecessary(_ messageIds:[MessageId], postbox:Postbox var missingMessageIds:Set = Set() var supportPeers:SimpleDictionary = SimpleDictionary() for messageId in ids { - if let message = modifier.getMessage(messageId) { + if let message = transaction.getMessage(messageId) { messages.append(message) } else { missingMessageIds.insert(messageId) - if let peer = modifier.getPeer(messageId.peerId) { + if let peer = transaction.getPeer(messageId.peerId) { supportPeers[messageId.peerId] = peer } } @@ -78,7 +78,7 @@ public func getMessagesLoadIfNecessary(_ messageIds:[MessageId], postbox:Postbox return combineLatest(signals) |> mapToSignal { results -> Signal<[Message], Void> in - return postbox.modify { modifier -> [Message] in + return postbox.transaction { transaction -> [Message] in for (messages, chats, users) in results { if !messages.isEmpty { @@ -89,7 +89,7 @@ public func getMessagesLoadIfNecessary(_ messageIds:[MessageId], postbox:Postbox storeMessages.append(message) } } - _ = modifier.addMessages(storeMessages, location: .Random) + _ = transaction.addMessages(storeMessages, location: .Random) } var peers: [Peer] = [] @@ -107,14 +107,14 @@ public func getMessagesLoadIfNecessary(_ messageIds:[MessageId], postbox:Postbox } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) } var loadedMessages:[Message] = [] for messageId in missingMessageIds { - if let message = modifier.getMessage(messageId) { + if let message = transaction.getMessage(messageId) { loadedMessages.append(message) } } diff --git a/TelegramCore/LoadedPeer.swift b/TelegramCore/LoadedPeer.swift index d820cdbbfc..d0a8c86565 100644 --- a/TelegramCore/LoadedPeer.swift +++ b/TelegramCore/LoadedPeer.swift @@ -7,10 +7,10 @@ #endif public func actualizedPeer(postbox: Postbox, network: Network, peer: Peer) -> Signal { - return postbox.modify { modifier -> Signal in + return postbox.transaction { transaction -> Signal in var signal: Signal var actualizeChannel: Api.InputChannel? - if let currentPeer = modifier.getPeer(peer.id) { + if let currentPeer = transaction.getPeer(peer.id) { signal = .single(currentPeer) if let currentPeer = currentPeer as? TelegramChannel { switch currentPeer.participationStatus { @@ -49,8 +49,8 @@ public func actualizedPeer(postbox: Postbox, network: Network, peer: Peer) -> Si } } if let remotePeer = remotePeer { - return postbox.modify { modifier -> Peer in - updatePeers(modifier: modifier, peers: [remotePeer], update: { _, updated in + return postbox.transaction { transaction -> Peer in + updatePeers(transaction: transaction, peers: [remotePeer], update: { _, updated in return updated }) return remotePeer diff --git a/TelegramCore/LoadedPeerFromMessage.swift b/TelegramCore/LoadedPeerFromMessage.swift index ff1fe565e5..6d662431f9 100644 --- a/TelegramCore/LoadedPeerFromMessage.swift +++ b/TelegramCore/LoadedPeerFromMessage.swift @@ -8,8 +8,8 @@ import Foundation #endif public func loadedPeerFromMessage(account: Account, peerId: PeerId, messageId: MessageId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) { if let user = peer as? TelegramUser { if user.accessHash != 0 { return .single(user) @@ -21,7 +21,7 @@ public func loadedPeerFromMessage(account: Account, peerId: PeerId, messageId: M |> `catch` { _ -> Signal in return .single(nil) } - } else if messageId.peerId.namespace == Namespaces.Peer.CloudChannel, let channelPeer = modifier.getPeer(messageId.peerId), let inputChannel = apiInputChannel(channelPeer) { + } else if messageId.peerId.namespace == Namespaces.Peer.CloudChannel, let channelPeer = transaction.getPeer(messageId.peerId), let inputChannel = apiInputChannel(channelPeer) { messageSignal = account.network.request(Api.functions.channels.getMessages(channel: inputChannel, id: [Api.InputMessage.inputMessageID(id: messageId.id)])) |> map { Optional($0) } |> `catch` { _ -> Signal in @@ -33,7 +33,7 @@ public func loadedPeerFromMessage(account: Account, peerId: PeerId, messageId: M if let messageSignal = messageSignal { return messageSignal |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Peer? in + return account.postbox.transaction { transaction -> Peer? in if let result = result { let apiUsers: [Api.User] switch result { @@ -51,10 +51,10 @@ public func loadedPeerFromMessage(account: Account, peerId: PeerId, messageId: M let telegramUser = TelegramUser(user: user) if telegramUser.id == peerId && telegramUser.accessHash != 0 { if let presence = TelegramUserPresence(apiUser: user) { - modifier.updatePeerPresences([telegramUser.id: presence]) + transaction.updatePeerPresences([telegramUser.id: presence]) } - updatePeers(modifier: modifier, peers: [telegramUser], update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: [telegramUser], update: { _, updated -> Peer in return updated }) diff --git a/TelegramCore/Localizations.swift b/TelegramCore/Localizations.swift index 79fe814af9..c420c5d009 100644 --- a/TelegramCore/Localizations.swift +++ b/TelegramCore/Localizations.swift @@ -67,8 +67,8 @@ final class CachedLocalizationInfos: PostboxCoding { public func availableLocalizations(postbox: Postbox, network: Network, allowCached: Bool) -> Signal<[LocalizationInfo], NoError> { let cached: Signal<[LocalizationInfo], NoError> if allowCached { - cached = postbox.modify { modifier -> Signal<[LocalizationInfo], NoError> in - if let entry = modifier.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAvailableLocalizations, key: ValueBoxKey(length: 0))) as? CachedLocalizationInfos { + cached = postbox.transaction { transaction -> Signal<[LocalizationInfo], NoError> in + if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAvailableLocalizations, key: ValueBoxKey(length: 0))) as? CachedLocalizationInfos { return .single(entry.list) } return .complete() @@ -86,8 +86,8 @@ public func availableLocalizations(postbox: Postbox, network: Network, allowCach infos.append(LocalizationInfo(languageCode: langCode, title: name, localizedTitle: nativeName)) } } - return postbox.modify { modifier -> [LocalizationInfo] in - modifier.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAvailableLocalizations, key: ValueBoxKey(length: 0)), entry: CachedLocalizationInfos(list: infos), collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + return postbox.transaction { transaction -> [LocalizationInfo] in + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAvailableLocalizations, key: ValueBoxKey(length: 0)), entry: CachedLocalizationInfos(list: infos), collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) return infos } } @@ -123,8 +123,8 @@ public func downloadLocalization(network: Network, languageCode: String) -> Sign public func downoadAndApplyLocalization(postbox: Postbox, network: Network, languageCode: String) -> Signal { return downloadLocalization(network: network, languageCode: languageCode) |> mapToSignal { language -> Signal in - return postbox.modify { modifier -> Signal in - modifier.updatePreferencesEntry(key: PreferencesKeys.localizationSettings, { _ in + return postbox.transaction { transaction -> Signal in + transaction.updatePreferencesEntry(key: PreferencesKeys.localizationSettings, { _ in return LocalizationSettings(languageCode: languageCode, localization: language) }) diff --git a/TelegramCore/LoggingSettings.swift b/TelegramCore/LoggingSettings.swift index edec0eb65c..0bde852c3b 100644 --- a/TelegramCore/LoggingSettings.swift +++ b/TelegramCore/LoggingSettings.swift @@ -62,9 +62,9 @@ public final class LoggingSettings: PreferencesEntry, Equatable { } public func updateLoggingSettings(postbox: Postbox, _ f: @escaping (LoggingSettings) -> LoggingSettings) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in var updated: LoggingSettings? - modifier.updatePreferencesEntry(key: PreferencesKeys.loggingSettings, { current in + transaction.updatePreferencesEntry(key: PreferencesKeys.loggingSettings, { current in if let current = current as? LoggingSettings { updated = f(current) return updated diff --git a/TelegramCore/ManagedAutoremoveMessageOperations.swift b/TelegramCore/ManagedAutoremoveMessageOperations.swift index fe856d3c7d..cd1cc7d011 100644 --- a/TelegramCore/ManagedAutoremoveMessageOperations.swift +++ b/TelegramCore/ManagedAutoremoveMessageOperations.swift @@ -63,12 +63,12 @@ func managedAutoremoveMessageOperations(postbox: Postbox) -> Signal.complete() |> delay(max(0.0, Double(entry.timestamp) - timestamp), queue: Queue.concurrentDefaultQueue()) - |> then(postbox.modify { modifier -> Void in - if let message = modifier.getMessage(entry.messageId) { + |> then(postbox.transaction { transaction -> Void in + if let message = transaction.getMessage(entry.messageId) { if message.id.peerId.namespace == Namespaces.Peer.SecretChat { - modifier.deleteMessages([entry.messageId]) + transaction.deleteMessages([entry.messageId]) } else { - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -85,7 +85,7 @@ func managedAutoremoveMessageOperations(postbox: Postbox) -> Signal Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, (entry.contents is CloudChatRemoveMessagesOperation || entry.contents is CloudChatRemoveChatOperation || entry.contents is CloudChatClearHistoryOperation) { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tagLocalIndex: } }) - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -83,23 +83,23 @@ func managedCloudChatRemoveMessagesOperations(postbox: Postbox, network: Network } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let operation = entry.contents as? CloudChatRemoveMessagesOperation { - if let peer = modifier.getPeer(entry.peerId) { + if let peer = transaction.getPeer(entry.peerId) { return removeMessages(postbox: postbox, network: network, stateManager: stateManager, peer: peer, operation: operation) } else { return .complete() } } else if let operation = entry.contents as? CloudChatRemoveChatOperation { - if let peer = modifier.getPeer(entry.peerId) { - return removeChat(modifier: modifier, postbox: postbox, network: network, stateManager: stateManager, peer: peer, operation: operation) + if let peer = transaction.getPeer(entry.peerId) { + return removeChat(transaction: transaction, postbox: postbox, network: network, stateManager: stateManager, peer: peer, operation: operation) } else { return .complete() } } else if let operation = entry.contents as? CloudChatClearHistoryOperation { - if let peer = modifier.getPeer(entry.peerId) { - return clearHistory(modifier: modifier, postbox: postbox, network: network, stateManager: stateManager, peer: peer, operation: operation) + if let peer = transaction.getPeer(entry.peerId) { + return clearHistory(transaction: transaction, postbox: postbox, network: network, stateManager: stateManager, peer: peer, operation: operation) } else { return .complete() } @@ -109,8 +109,8 @@ func managedCloudChatRemoveMessagesOperations(postbox: Postbox, network: Network } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: OperationLogTags.CloudChatRemoveMessages, tagLocalIndex: entry.tagLocalIndex) }) disposable.set(signal.start()) @@ -178,7 +178,7 @@ private func removeMessages(postbox: Postbox, network: Network, stateManager: Ac } } -private func removeChat(modifier: Modifier, postbox: Postbox, network: Network, stateManager: AccountStateManager, peer: Peer, operation: CloudChatRemoveChatOperation) -> Signal { +private func removeChat(transaction: Transaction, postbox: Postbox, network: Network, stateManager: AccountStateManager, peer: Peer, operation: CloudChatRemoveChatOperation) -> Signal { if peer.id.namespace == Namespaces.Peer.CloudChannel { if let inputChannel = apiInputChannel(peer) { let signal = network.request(Api.functions.channels.leaveChannel(channel: inputChannel)) @@ -236,13 +236,13 @@ private func removeChat(modifier: Modifier, postbox: Postbox, network: Network, reportSignal = .complete() } let deleteMessages: Signal - if let inputPeer = apiInputPeer(peer), let topMessageId = modifier.getTopPeerMessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud) { + if let inputPeer = apiInputPeer(peer), let topMessageId = transaction.getTopPeerMessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud) { deleteMessages = requestClearHistory(postbox: postbox, network: network, stateManager: stateManager, inputPeer: inputPeer, maxId: topMessageId.id, justClear: false) } else { deleteMessages = .complete() } - return deleteMessages |> then(deleteUser) |> then(reportSignal) |> then(postbox.modify { modifier -> Void in - modifier.clearHistory(peer.id) + return deleteMessages |> then(deleteUser) |> then(reportSignal) |> then(postbox.transaction { transaction -> Void in + transaction.clearHistory(peer.id) }) } else if peer.id.namespace == Namespaces.Peer.CloudUser { if let inputPeer = apiInputPeer(peer) { @@ -258,8 +258,8 @@ private func removeChat(modifier: Modifier, postbox: Postbox, network: Network, } else { reportSignal = .complete() } - return requestClearHistory(postbox: postbox, network: network, stateManager: stateManager, inputPeer: inputPeer, maxId: operation.topMessageId?.id ?? Int32.max - 1, justClear: false) |> then(reportSignal) |> then(postbox.modify { modifier -> Void in - modifier.clearHistory(peer.id) + return requestClearHistory(postbox: postbox, network: network, stateManager: stateManager, inputPeer: inputPeer, maxId: operation.topMessageId?.id ?? Int32.max - 1, justClear: false) |> then(reportSignal) |> then(postbox.transaction { transaction -> Void in + transaction.clearHistory(peer.id) }) } else { return .complete() @@ -298,7 +298,7 @@ private func requestClearHistory(postbox: Postbox, network: Network, stateManage } } -private func clearHistory(modifier: Modifier, postbox: Postbox, network: Network, stateManager: AccountStateManager, peer: Peer, operation: CloudChatClearHistoryOperation) -> Signal { +private func clearHistory(transaction: Transaction, postbox: Postbox, network: Network, stateManager: AccountStateManager, peer: Peer, operation: CloudChatClearHistoryOperation) -> Signal { if peer.id.namespace == Namespaces.Peer.CloudGroup || peer.id.namespace == Namespaces.Peer.CloudUser { if let inputPeer = apiInputPeer(peer) { return requestClearHistory(postbox: postbox, network: network, stateManager: stateManager, inputPeer: inputPeer, maxId: operation.topMessageId.id, justClear: true) diff --git a/TelegramCore/ManagedConfigurationUpdates.swift b/TelegramCore/ManagedConfigurationUpdates.swift index 70817f718c..8ea938195b 100644 --- a/TelegramCore/ManagedConfigurationUpdates.swift +++ b/TelegramCore/ManagedConfigurationUpdates.swift @@ -12,11 +12,11 @@ import Foundation func managedConfigurationUpdates(postbox: Postbox, network: Network) -> Signal { let poll = Signal { subscriber in return (network.request(Api.functions.help.getConfig()) |> retryRequest |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in switch result { - case let .config(flags, _, _, _, _, dcOptions, dcTxtDomainName, chatSizeMax, megagroupSizeMax, forwardedCountMax, _, _, _, onlineCloudTimeoutMs, notifyCloudDelayMs, notifyDefaultDelayMs, pushChatPeriodMs, pushChatLimit, savedGifsLimit, editTimeLimit, revokeTimeLimit, revokePmTimeLimit, ratingEDecay, stickersRecentLimit, stickersFavedLimit, channelsReadMediaPeriod, tmpSessions, pinnedDialogsCountMax, callReceiveTimeoutMs, callRingTimeoutMs, callConnectTimeoutMs, callPacketTimeoutMs, meUrlPrefix, autoupdateUrlPrefix, gifSearchUsername, venueSearchUsername, imgSearchUsername, suggestedLangCode, langPackVersion): + case let .config(config): var addressList: [Int: [MTDatacenterAddress]] = [:] - for option in dcOptions { + for option in config.dcOptions { switch option { case let .dcOption(flags, id, ipAddress, port, secret): let preferForMedia = (flags & (1 << 1)) != 0 @@ -35,21 +35,21 @@ func managedConfigurationUpdates(postbox: Postbox, network: Network) -> Signal Signal Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenAction(postbox: Postbox, type: PendingMessageActionType, id: MessageId, _ f: @escaping (Transaction, PendingMessageActionsEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PendingMessageActionsEntry? - if let action = modifier.getPendingMessageAction(type: type, id: id) as? ConsumePersonalMessageAction { + if let action = transaction.getPendingMessageAction(type: type, id: id) as? ConsumePersonalMessageAction { result = PendingMessageActionsEntry(id: id, action: action) } - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -117,18 +117,18 @@ func managedConsumePersonalMessagesActions(postbox: Postbox, network: Network, s } for (entry, disposable) in beginOperations { - let signal = withTakenAction(postbox: postbox, type: .consumeUnseenPersonalMessage, id: entry.id, { modifier, entry -> Signal in + let signal = withTakenAction(postbox: postbox, type: .consumeUnseenPersonalMessage, id: entry.id, { transaction, entry -> Signal in if let entry = entry { if let _ = entry.action as? ConsumePersonalMessageAction { - return synchronizeConsumeMessageContents(modifier: modifier, postbox: postbox, network: network, stateManager: stateManager, id: entry.id) + return synchronizeConsumeMessageContents(transaction: transaction, postbox: postbox, network: network, stateManager: stateManager, id: entry.id) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - modifier.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: entry.id, action: nil) + |> then(postbox.transaction { transaction -> Void in + transaction.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: entry.id, action: nil) }) disposable.set(signal.start()) @@ -136,8 +136,8 @@ func managedConsumePersonalMessagesActions(postbox: Postbox, network: Network, s for (entry, disposable) in beginValidateOperations { let signal = synchronizeUnseenPersonalMentionsTag(postbox: postbox, network: network, entry: entry) - |> then(postbox.modify { modifier -> Void in - modifier.removeInvalidatedMessageHistoryTagsSummaryEntry(entry) + |> then(postbox.transaction { transaction -> Void in + transaction.removeInvalidatedMessageHistoryTagsSummaryEntry(entry) }) disposable.set(signal.start()) } @@ -155,7 +155,7 @@ func managedConsumePersonalMessagesActions(postbox: Postbox, network: Network, s } } -private func synchronizeConsumeMessageContents(modifier: Modifier, postbox: Postbox, network: Network, stateManager: AccountStateManager, id: MessageId) -> Signal { +private func synchronizeConsumeMessageContents(transaction: Transaction, postbox: Postbox, network: Network, stateManager: AccountStateManager, id: MessageId) -> Signal { if id.peerId.namespace == Namespaces.Peer.CloudUser || id.peerId.namespace == Namespaces.Peer.CloudGroup { return network.request(Api.functions.messages.readMessageContents(id: [id.id])) |> map { Optional($0) } @@ -169,9 +169,9 @@ private func synchronizeConsumeMessageContents(modifier: Modifier, postbox: Post stateManager.addUpdateGroups([.updatePts(pts: pts, ptsCount: ptsCount)]) } } - return postbox.modify { modifier -> Void in - modifier.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: id, action: nil) - modifier.updateMessage(id, update: { currentMessage in + return postbox.transaction { transaction -> Void in + transaction.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: id, action: nil) + transaction.updateMessage(id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -190,14 +190,14 @@ private func synchronizeConsumeMessageContents(modifier: Modifier, postbox: Post } } } else if id.peerId.namespace == Namespaces.Peer.CloudChannel { - if let peer = modifier.getPeer(id.peerId), let inputChannel = apiInputChannel(peer) { + if let peer = transaction.getPeer(id.peerId), let inputChannel = apiInputChannel(peer) { return network.request(Api.functions.channels.readMessageContents(channel: inputChannel, id: [id.id])) |> `catch` { _ -> Signal in return .single(.boolFalse) } |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in - modifier.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: id, action: nil) - modifier.updateMessage(id, update: { currentMessage in + return postbox.transaction { transaction -> Void in + transaction.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: id, action: nil) + transaction.updateMessage(id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -224,8 +224,8 @@ private func synchronizeConsumeMessageContents(modifier: Modifier, postbox: Post } private func synchronizeUnseenPersonalMentionsTag(postbox: Postbox, network: Network, entry: InvalidatedMessageHistoryTagsSummaryEntry) -> Signal { - return postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(entry.key.peerId), let inputPeer = apiInputPeer(peer) { + return postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(entry.key.peerId), let inputPeer = apiInputPeer(peer) { return network.request(Api.functions.messages.getPeerDialogs(peers: [.inputDialogPeer(peer: inputPeer)])) |> map(Optional.init) |> `catch` { _ -> Signal in @@ -248,8 +248,8 @@ private func synchronizeUnseenPersonalMentionsTag(postbox: Postbox, network: Net return .complete()*/ } - return postbox.modify { modifier -> Void in - modifier.replaceMessageTagSummary(peerId: entry.key.peerId, tagMask: entry.key.tagMask, namespace: entry.key.namespace, count: apiUnreadMentionsCount, maxId: apiTopMessage) + return postbox.transaction { transaction -> Void in + transaction.replaceMessageTagSummary(peerId: entry.key.peerId, tagMask: entry.key.tagMask, namespace: entry.key.namespace, count: apiUnreadMentionsCount, maxId: apiTopMessage) } } else { return .complete() diff --git a/TelegramCore/ManagedDeviceContacts.swift b/TelegramCore/ManagedDeviceContacts.swift index 1d6b09fd15..09ca76a89d 100644 --- a/TelegramCore/ManagedDeviceContacts.swift +++ b/TelegramCore/ManagedDeviceContacts.swift @@ -118,12 +118,12 @@ func managedDeviceContacts(postbox: Postbox, network: Network, deviceContacts: S for (id, entry) in entries { infos[id] = UnorderedItemListEntryInfo(hashValue: entry.info.hashValue) } - let appliedDifference = postbox.modify { modifier -> Signal in - let (metaInfo, added, removed, updated) = modifier.unorderedItemListDifference(tag: Namespaces.UnorderedItemList.synchronizedDeviceContacts, updatedEntryInfos: infos) + let appliedDifference = postbox.transaction { transaction -> Signal in + let (metaInfo, added, removed, updated) = transaction.unorderedItemListDifference(tag: Namespaces.UnorderedItemList.synchronizedDeviceContacts, updatedEntryInfos: infos) let timestamp = Int32(CFAbsoluteTimeGetCurrent()) var reimportKeys = Set() - modifier.unorderedItemListScan(tag: Namespaces.UnorderedItemList.synchronizedDeviceContacts, { entry in + transaction.unorderedItemListScan(tag: Namespaces.UnorderedItemList.synchronizedDeviceContacts, { entry in if let contents = entry.contents as? ManagedDeviceContactEntryContents { if let importDelayedUntil = contents.importDelayedUntil, importDelayedUntil <= timestamp { reimportKeys.insert(entry.id) @@ -177,9 +177,9 @@ func managedDeviceContacts(postbox: Postbox, network: Network, deviceContacts: S } |> then(applyAddedOrUpdatedContacts(network: network, contacts: addedOrUpdatedContacts))) |> mapToSignal { peers, peerPresences, importedContents, importedByCounts -> Signal in - return postbox.modify { modifier -> Signal in + return postbox.transaction { transaction -> Signal in for (phone, count) in importedByCounts { - modifier.setDeviceContactImportInfo(TelegramDeviceContactImportIdentifier.phoneNumber(phone), value: TelegramDeviceContactImportInfo(importedByCount: count)) + transaction.setDeviceContactImportInfo(TelegramDeviceContactImportIdentifier.phoneNumber(phone), value: TelegramDeviceContactImportInfo(importedByCount: count)) } let updatedInfo: UnorderedItemListTagMetaInfo @@ -197,21 +197,21 @@ func managedDeviceContacts(postbox: Postbox, network: Network, deviceContacts: S } setItems.append(UnorderedItemListEntry(id: ValueBoxKey(contents.phoneNumber), info: UnorderedItemListEntryInfo(hashValue: Int64(stringToHash.hashValue)), contents: contents)) } - if modifier.unorderedItemListApplyDifference(tag: Namespaces.UnorderedItemList.synchronizedDeviceContacts, previousInfo: metaInfo, updatedInfo: updatedInfo, setItems: setItems, removeItemIds: removed.map { $0.id }) { - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + if transaction.unorderedItemListApplyDifference(tag: Namespaces.UnorderedItemList.synchronizedDeviceContacts, previousInfo: metaInfo, updatedInfo: updatedInfo, setItems: setItems, removeItemIds: removed.map { $0.id }) { + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) if !removedPeerIds.isEmpty || !addedPeerIds.isEmpty { - var updatedPeerIds = modifier.getContactPeerIds() + var updatedPeerIds = transaction.getContactPeerIds() for peerId in removedPeerIds { updatedPeerIds.remove(peerId) } for peerId in addedPeerIds { updatedPeerIds.insert(peerId) } - modifier.replaceContactPeerIds(updatedPeerIds) + transaction.replaceContactPeerIds(updatedPeerIds) } if importedContents.count == addedOrUpdatedContacts.count { @@ -245,10 +245,10 @@ private func applyRemovedContacts(postbox: Postbox, network: Network, peerIds: [ return .complete() } - return postbox.modify { modifier -> Signal in + return postbox.transaction { transaction -> Signal in var inputUsers: [Api.InputUser] = [] for peerId in peerIds { - if let peer = modifier.getPeer(peerId), let inputUser = apiInputUser(peer) { + if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) { inputUsers.append(inputUser) } } diff --git a/TelegramCore/ManagedGlobalNotificationSettings.swift b/TelegramCore/ManagedGlobalNotificationSettings.swift index 02b9a7e6b9..30eb0f85f3 100644 --- a/TelegramCore/ManagedGlobalNotificationSettings.swift +++ b/TelegramCore/ManagedGlobalNotificationSettings.swift @@ -10,8 +10,8 @@ import Foundation #endif public func updateGlobalNotificationSettingsInteractively(postbox: Postbox, _ f: @escaping (GlobalNotificationSettingsSet) -> GlobalNotificationSettingsSet) -> Signal { - return postbox.modify { modifier -> Void in - modifier.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in + return postbox.transaction { transaction -> Void in + transaction.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in if let current = current as? GlobalNotificationSettings { return GlobalNotificationSettings(toBeSynchronized: f(current.effective), remote: current.remote) } else { @@ -79,8 +79,8 @@ func managedGlobalNotificationSettings(postbox: Postbox, network: Network) -> Si case .fetch: return fetchedNotificationSettings(network: network) |> mapToSignal { settings -> Signal in - return postbox.modify { modifier -> Void in - modifier.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in + return postbox.transaction { transaction -> Void in + transaction.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in if let current = current as? GlobalNotificationSettings { return GlobalNotificationSettings(toBeSynchronized: current.toBeSynchronized, remote: settings) } else { @@ -91,8 +91,8 @@ func managedGlobalNotificationSettings(postbox: Postbox, network: Network) -> Si } case let .push(settings): return pushedNotificationSettings(network: network, settings: settings) - |> then(postbox.modify { modifier -> Void in - modifier.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in + |> then(postbox.transaction { transaction -> Void in + transaction.updatePreferencesEntry(key: PreferencesKeys.globalNotifications, { current in if let current = current as? GlobalNotificationSettings, current.toBeSynchronized == settings { return GlobalNotificationSettings(toBeSynchronized: nil, remote: settings) } else { diff --git a/TelegramCore/ManagedGroupFeedReadStateSyncOperations.swift b/TelegramCore/ManagedGroupFeedReadStateSyncOperations.swift index 996f3990a2..a3b962b5e9 100644 --- a/TelegramCore/ManagedGroupFeedReadStateSyncOperations.swift +++ b/TelegramCore/ManagedGroupFeedReadStateSyncOperations.swift @@ -174,8 +174,8 @@ private func pushReadState(network: Network, accountPeerId: PeerId, groupId: Pee } private func performSyncOperation(postbox: Postbox, network: Network, accountPeerId: PeerId, stateManager: AccountStateManager, groupId: PeerGroupId, operation: GroupFeedReadStateSyncOperation) -> Signal { - return postbox.modify { modifier -> GroupFeedReadState? in - return modifier.getGroupFeedReadState(groupId: groupId) + return postbox.transaction { transaction -> GroupFeedReadState? in + return transaction.getGroupFeedReadState(groupId: groupId) } |> mapToSignal { currentState -> Signal<(GroupFeedReadState?, GroupFeedReadState?), NoError> in if operation.validate { return fetchReadState(network: network, groupId: groupId) @@ -187,14 +187,14 @@ private func performSyncOperation(postbox: Postbox, network: Network, accountPee if operation.push, let currentState = currentState { return pushReadState(network: network, accountPeerId: accountPeerId, groupId: groupId, state: currentState) |> mapToSignal { updates -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in var resultingState: GroupFeedReadState if let remoteState = remoteState, remoteState.maxReadIndex > currentState.maxReadIndex { resultingState = remoteState } else { resultingState = currentState } - modifier.applyGroupFeedReadMaxIndex(groupId: groupId, index: resultingState.maxReadIndex) + transaction.applyGroupFeedReadMaxIndex(groupId: groupId, index: resultingState.maxReadIndex) if let updates = updates { stateManager.addUpdates(updates) @@ -202,8 +202,8 @@ private func performSyncOperation(postbox: Postbox, network: Network, accountPee } } } else if operation.validate, let remoteState = remoteState { - return postbox.modify { modifier -> Void in - modifier.applyGroupFeedReadMaxIndex(groupId: groupId, index: remoteState.maxReadIndex) + return postbox.transaction { transaction -> Void in + transaction.applyGroupFeedReadMaxIndex(groupId: groupId, index: remoteState.maxReadIndex) } } else { return .complete() diff --git a/TelegramCore/ManagedLocalInputActivities.swift b/TelegramCore/ManagedLocalInputActivities.swift index d153f976ef..7277741a9a 100644 --- a/TelegramCore/ManagedLocalInputActivities.swift +++ b/TelegramCore/ManagedLocalInputActivities.swift @@ -110,8 +110,8 @@ private func actionFromActivity(_ activity: PeerInputActivity?) -> Api.SendMessa } private func requestActivity(postbox: Postbox, network: Network, accountPeerId: PeerId, peerId: PeerId, activity: PeerInputActivity?) -> Signal { - return postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) { + return postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) { if peerId == accountPeerId { return .complete() } diff --git a/TelegramCore/ManagedLocalizationUpdatesOperations.swift b/TelegramCore/ManagedLocalizationUpdatesOperations.swift index 40447103a1..4827730f7a 100644 --- a/TelegramCore/ManagedLocalizationUpdatesOperations.swift +++ b/TelegramCore/ManagedLocalizationUpdatesOperations.swift @@ -53,10 +53,10 @@ private final class ManagedLocalizationUpdatesOperationsHelper { } } -private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Modifier, PeerMergedOperationLogEntry?) -> Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, entry.contents is SynchronizeLocalizationUpdatesOperation { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOpera } }) - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -85,18 +85,18 @@ func managedLocalizationUpdatesOperations(postbox: Postbox, network: Network) -> } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let _ = entry.contents as? SynchronizeLocalizationUpdatesOperation { - return synchronizeLocalizationUpdates(modifier: modifier, postbox: postbox, network: network) + return synchronizeLocalizationUpdates(transaction: transaction, postbox: postbox, network: network) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) }) disposable.set(signal.start()) @@ -120,9 +120,9 @@ private enum SynchronizeLocalizationUpdatesError { case reset } -func getLocalization(_ modifier: Modifier) -> (String, Int32, [LocalizationEntry]) { +func getLocalization(_ transaction: Transaction) -> (String, Int32, [LocalizationEntry]) { let localizationSettings: LocalizationSettings? - if let current = modifier.getPreferencesEntry(key: PreferencesKeys.localizationSettings) as? LocalizationSettings { + if let current = transaction.getPreferencesEntry(key: PreferencesKeys.localizationSettings) as? LocalizationSettings { localizationSettings = current } else { localizationSettings = nil @@ -134,9 +134,9 @@ func getLocalization(_ modifier: Modifier) -> (String, Int32, [LocalizationEntry } } -private func synchronizeLocalizationUpdates(modifier: Modifier, postbox: Postbox, network: Network) -> Signal { - let currentLanguageAndVersion = postbox.modify { modifier -> (String, Int32) in - let (code, version, _) = getLocalization(modifier) +private func synchronizeLocalizationUpdates(transaction: Transaction, postbox: Postbox, network: Network) -> Signal { + let currentLanguageAndVersion = postbox.transaction { transaction -> (String, Int32) in + let (code, version, _) = getLocalization(transaction) return (code, version) } @@ -165,8 +165,8 @@ private func synchronizeLocalizationUpdates(modifier: Modifier, postbox: Postbox } } - return postbox.modify { modifier -> Signal in - let (code, version, entries) = getLocalization(modifier) + return postbox.transaction { transaction -> Signal in + let (code, version, entries) = getLocalization(transaction) if code == updatedCode { if fromVersion == version { @@ -183,7 +183,7 @@ private func synchronizeLocalizationUpdates(modifier: Modifier, postbox: Postbox } mergedEntries.append(contentsOf: updatedEntries) - modifier.setPreferencesEntry(key: PreferencesKeys.localizationSettings, value: LocalizationSettings(languageCode: updatedCode, localization: Localization(version: updatedVersion, entries: mergedEntries))) + transaction.setPreferencesEntry(key: PreferencesKeys.localizationSettings, value: LocalizationSettings(languageCode: updatedCode, localization: Localization(version: updatedVersion, entries: mergedEntries))) return .fail(.done) } else { @@ -203,8 +203,8 @@ private func synchronizeLocalizationUpdates(modifier: Modifier, postbox: Postbox case .done: return .fail(NoError()) case .reset: - return postbox.modify { modifier -> Signal in - let (code, _, _) = getLocalization(modifier) + return postbox.transaction { transaction -> Signal in + let (code, _, _) = getLocalization(transaction) return downoadAndApplyLocalization(postbox: postbox, network: network, languageCode: code) } |> switchToLatest } @@ -213,8 +213,8 @@ private func synchronizeLocalizationUpdates(modifier: Modifier, postbox: Postbox } } -func tryApplyingLanguageDifference(modifier: Modifier, difference: Api.LangPackDifference) -> Bool { - let (code, version, entries) = getLocalization(modifier) +func tryApplyingLanguageDifference(transaction: Transaction, difference: Api.LangPackDifference) -> Bool { + let (code, version, entries) = getLocalization(transaction) switch difference { case let .langPackDifference(updatedCode, fromVersion, updatedVersion, strings): if fromVersion == version && updatedCode == code { @@ -244,7 +244,7 @@ func tryApplyingLanguageDifference(modifier: Modifier, difference: Api.LangPackD } mergedEntries.append(contentsOf: updatedEntries) - modifier.setPreferencesEntry(key: PreferencesKeys.localizationSettings, value: LocalizationSettings(languageCode: updatedCode, localization: Localization(version: updatedVersion, entries: mergedEntries))) + transaction.setPreferencesEntry(key: PreferencesKeys.localizationSettings, value: LocalizationSettings(languageCode: updatedCode, localization: Localization(version: updatedVersion, entries: mergedEntries))) return true } else { diff --git a/TelegramCore/ManagedPendingPeerNotificationSettings.swift b/TelegramCore/ManagedPendingPeerNotificationSettings.swift index 3bcfbaa5c4..4aff329325 100644 --- a/TelegramCore/ManagedPendingPeerNotificationSettings.swift +++ b/TelegramCore/ManagedPendingPeerNotificationSettings.swift @@ -94,14 +94,14 @@ func managedPendingPeerNotificationSettings(postbox: Postbox, network: Network) } private func pushPeerNotificationSettings(postbox: Postbox, network: Network, peerId: PeerId, settings: PeerNotificationSettings) -> Signal { - return postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) { + return postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) { var notificationPeerId = peerId if let associatedPeerId = peer.associatedPeerId { notificationPeerId = associatedPeerId } - if let notificationPeer = modifier.getPeer(notificationPeerId), let inputPeer = apiInputPeer(notificationPeer), let settings = settings as? TelegramPeerNotificationSettings { + if let notificationPeer = transaction.getPeer(notificationPeerId), let inputPeer = apiInputPeer(notificationPeer), let settings = settings as? TelegramPeerNotificationSettings { let muteUntil: Int32? switch settings.muteState { case let .muted(until): @@ -123,22 +123,22 @@ private func pushPeerNotificationSettings(postbox: Postbox, network: Network, pe return network.request(Api.functions.account.updateNotifySettings(peer: .inputNotifyPeer(peer: inputPeer), settings: inputSettings)) |> retryRequest |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in - modifier.updateCurrentPeerNotificationSettings([notificationPeerId: settings]) - if let pending = modifier.getPendingPeerNotificationSettings(peerId), pending.isEqual(to: settings) { - modifier.updatePendingPeerNotificationSettings(peerId: peerId, settings: nil) + return postbox.transaction { transaction -> Void in + transaction.updateCurrentPeerNotificationSettings([notificationPeerId: settings]) + if let pending = transaction.getPendingPeerNotificationSettings(peerId), pending.isEqual(to: settings) { + transaction.updatePendingPeerNotificationSettings(peerId: peerId, settings: nil) } } } } else { - if let pending = modifier.getPendingPeerNotificationSettings(peerId), pending.isEqual(to: settings) { - modifier.updatePendingPeerNotificationSettings(peerId: peerId, settings: nil) + if let pending = transaction.getPendingPeerNotificationSettings(peerId), pending.isEqual(to: settings) { + transaction.updatePendingPeerNotificationSettings(peerId: peerId, settings: nil) } return .complete() } } else { - if let pending = modifier.getPendingPeerNotificationSettings(peerId), pending.isEqual(to: settings) { - modifier.updatePendingPeerNotificationSettings(peerId: peerId, settings: nil) + if let pending = transaction.getPendingPeerNotificationSettings(peerId), pending.isEqual(to: settings) { + transaction.updatePendingPeerNotificationSettings(peerId: peerId, settings: nil) } return .complete() } diff --git a/TelegramCore/ManagedProxyInfoUpdates.swift b/TelegramCore/ManagedProxyInfoUpdates.swift index bba7a22e41..99602fb664 100644 --- a/TelegramCore/ManagedProxyInfoUpdates.swift +++ b/TelegramCore/ManagedProxyInfoUpdates.swift @@ -22,10 +22,10 @@ func managedProxyInfoUpdates(postbox: Postbox, network: Network, viewTracker: Ac return .single(.proxyDataEmpty(expires: 10 * 60)) } |> mapToSignal { data -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in switch data { case .proxyDataEmpty: - modifier.replaceAdditionalChatListItems([]) + transaction.replaceAdditionalChatListItems([]) case let .proxyDataPromo(_, peer, chats, users): var peers: [Peer] = [] var peerPresences: [PeerId: PeerPresence] = [:] @@ -42,16 +42,16 @@ func managedProxyInfoUpdates(postbox: Postbox, network: Network, viewTracker: Ac } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) var additionalChatListItems: [PeerId] = [] - if let channel = modifier.getPeer(peer.peerId) as? TelegramChannel { + if let channel = transaction.getPeer(peer.peerId) as? TelegramChannel { additionalChatListItems.append(channel.id) } - modifier.replaceAdditionalChatListItems(additionalChatListItems) + transaction.replaceAdditionalChatListItems(additionalChatListItems) } } } @@ -63,8 +63,8 @@ func managedProxyInfoUpdates(postbox: Postbox, network: Network, viewTracker: Ac ) |> restart } else { - return postbox.modify { modifier -> Void in - modifier.replaceAdditionalChatListItems([]) + return postbox.transaction { transaction -> Void in + transaction.replaceAdditionalChatListItems([]) } } } diff --git a/TelegramCore/ManagedRecentStickers.swift b/TelegramCore/ManagedRecentStickers.swift index 135809407e..e8efea9390 100644 --- a/TelegramCore/ManagedRecentStickers.swift +++ b/TelegramCore/ManagedRecentStickers.swift @@ -21,8 +21,8 @@ private func hashForIds(_ ids: [Int64]) -> Int32 { } private func managedRecentMedia(postbox: Postbox, network: Network, collectionId: Int32, reverseHashOrder: Bool, fetch: @escaping (Int32) -> Signal<[OrderedItemListEntry]?, NoError>) -> Signal { - return postbox.modify { modifier -> Signal in - var itemIds = modifier.getOrderedListItemIds(collectionId: collectionId).map { + return postbox.transaction { transaction -> Signal in + var itemIds = transaction.getOrderedListItemIds(collectionId: collectionId).map { RecentMediaItemId($0).mediaId.id } if reverseHashOrder { @@ -31,8 +31,8 @@ private func managedRecentMedia(postbox: Postbox, network: Network, collectionId return fetch(hashForIds(itemIds)) |> mapToSignal { items in if let items = items { - return postbox.modify { modifier -> Void in - modifier.replaceOrderedItemListItems(collectionId: collectionId, items: items) + return postbox.transaction { transaction -> Void in + transaction.replaceOrderedItemListItems(collectionId: collectionId, items: items) } } else { return .complete() diff --git a/TelegramCore/ManagedSecretChatOutgoingOperations.swift b/TelegramCore/ManagedSecretChatOutgoingOperations.swift index 24335e2556..63ddfdf033 100644 --- a/TelegramCore/ManagedSecretChatOutgoingOperations.swift +++ b/TelegramCore/ManagedSecretChatOutgoingOperations.swift @@ -9,11 +9,11 @@ import Foundation import MtProtoKitDynamic #endif -func addSecretChatOutgoingOperation(modifier: Modifier, peerId: PeerId, operation: SecretChatOutgoingOperationContents, state: SecretChatState) -> SecretChatState { +func addSecretChatOutgoingOperation(transaction: Transaction, peerId: PeerId, operation: SecretChatOutgoingOperationContents, state: SecretChatState) -> SecretChatState { var updatedState = state switch updatedState.embeddedState { case let .sequenceBasedLayer(sequenceState): - let keyValidityOperationIndex = modifier.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing) + let keyValidityOperationIndex = transaction.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing) let keyValidityOperationCanonicalIndex = sequenceState.canonicalIncomingOperationIndex(keyValidityOperationIndex) if let key = state.keychain.latestKey(validForSequenceBasedCanonicalIndex: keyValidityOperationCanonicalIndex) { updatedState = updatedState.withUpdatedKeychain(updatedState.keychain.withUpdatedKey(fingerprint: key.fingerprint, { key in @@ -23,8 +23,8 @@ func addSecretChatOutgoingOperation(modifier: Modifier, peerId: PeerId, operatio default: break } - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: operation, mutable: true, delivered: false)) - return secretChatInitiateRekeySessionIfNeeded(modifier: modifier, peerId: peerId, state: updatedState) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: operation, mutable: true, delivered: false)) + return secretChatInitiateRekeySessionIfNeeded(transaction: transaction, peerId: peerId, state: updatedState) } private final class ManagedSecretChatOutgoingOperationsHelper { @@ -89,9 +89,9 @@ private final class ManagedSecretChatOutgoingOperationsHelper { } private func takenImmutableOperation(postbox: Postbox, peerId: PeerId, tagLocalIndex: Int32) -> Signal { - return postbox.modify { modifier -> PeerMergedOperationLogEntry? in + return postbox.transaction { transaction -> PeerMergedOperationLogEntry? in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, let operation = entry.contents as? SecretChatOutgoingOperation { if operation.mutable { let updatedContents = SecretChatOutgoingOperation(contents: operation.contents, mutable: false, delivered: operation.delivered) @@ -222,10 +222,10 @@ private func initialHandshakeAccept(postbox: Postbox, network: Network, peerId: return response |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in - let removed = modifier.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex) + return postbox.transaction { transaction -> Void in + let removed = transaction.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex) assert(removed) - if let state = modifier.getPeerChatState(peerId) as? SecretChatState { + if let state = transaction.getPeerChatState(peerId) as? SecretChatState { var updatedState = state.withUpdatedKeychain(SecretChatKeychain(keys: [SecretChatKey(fingerprint: keyFingerprint, key: MemoryBuffer(data: key), validity: .indefinite, useCount: 0)])).withUpdatedEmbeddedState(.basicLayer).withUpdatedKeyFingerprint(SecretChatKeyFingerprint(sha1: SecretChatKeySha1Fingerprint(digest: sha1Digest(key)), sha256: SecretChatKeySha256Fingerprint(digest: sha256Digest(key)))) var layer: SecretChatLayer? switch updatedState.embeddedState { @@ -237,11 +237,11 @@ private func initialHandshakeAccept(postbox: Postbox, network: Network, peerId: layer = sequenceState.layerNegotiationState.activeLayer.secretChatLayer } if let layer = layer { - updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: .reportLayerSupport(layer: layer, actionGloballyUniqueId: arc4random64(), layerSupport: 46), state: updatedState) + updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: .reportLayerSupport(layer: layer, actionGloballyUniqueId: arc4random64(), layerSupport: 46), state: updatedState) } - modifier.setPeerChatState(peerId, state: updatedState) - if let peer = modifier.getPeer(peerId) as? TelegramSecretChat { - updatePeers(modifier: modifier, peers: [peer.withUpdatedEmbeddedState(updatedState.embeddedState.peerState)], update: { _, updated in + transaction.setPeerChatState(peerId, state: updatedState) + if let peer = transaction.getPeer(peerId) as? TelegramSecretChat { + updatePeers(transaction: transaction, peers: [peer.withUpdatedEmbeddedState(updatedState.embeddedState.peerState)], update: { _, updated in return updated }) } @@ -263,12 +263,12 @@ private func pfsRequestKey(postbox: Postbox, network: Network, peerId: PeerId, l let aData = a.makeData() let ga = MTExp(g, aData, p)! - return postbox.modify { modifier -> Signal in - if let state = modifier.getPeerChatState(peerId) as? SecretChatState { + return postbox.transaction { transaction -> Signal in + if let state = transaction.getPeerChatState(peerId) as? SecretChatState { switch state.embeddedState { case let .sequenceBasedLayer(sequenceState): if let rekeyState = sequenceState.rekeyState, case .requesting = rekeyState.data { - modifier.setPeerChatState(peerId, state: state.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedRekeyState(SecretChatRekeySessionState(id: rekeyState.id, data: .requested(a: a, config: config)))))) + transaction.setPeerChatState(peerId, state: state.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedRekeyState(SecretChatRekeySessionState(id: rekeyState.id, data: .requested(a: a, config: config)))))) } default: break @@ -307,12 +307,12 @@ private func pfsAcceptKey(postbox: Postbox, network: Network, peerId: PeerId, la memcpy(&keyFingerprint, bytes.advanced(by: keyHash.count - 8), 8) } - return postbox.modify { modifier -> Signal in - if let state = modifier.getPeerChatState(peerId) as? SecretChatState { + return postbox.transaction { transaction -> Signal in + if let state = transaction.getPeerChatState(peerId) as? SecretChatState { switch state.embeddedState { case let .sequenceBasedLayer(sequenceState): if let rekeyState = sequenceState.rekeyState, case .accepting = rekeyState.data { - modifier.setPeerChatState(peerId, state: state.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedRekeyState(SecretChatRekeySessionState(id: rekeyState.id, data: .accepted(key: MemoryBuffer(data: key), keyFingerprint: keyFingerprint)))))) + transaction.setPeerChatState(peerId, state: state.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedRekeyState(SecretChatRekeySessionState(id: rekeyState.id, data: .accepted(key: MemoryBuffer(data: key), keyFingerprint: keyFingerprint)))))) } default: break @@ -558,7 +558,7 @@ private func decryptedEntities73(_ entities: [MessageTextEntity]?) -> [SecretApi return result } -private func boxedDecryptedMessage(modifier: Modifier, message: Message, globallyUniqueId: Int64, uploadedFile: SecretChatOutgoingFile?, thumbnailData: [MediaId: Data], layer: SecretChatLayer) -> BoxedDecryptedMessage { +private func boxedDecryptedMessage(transaction: Transaction, message: Message, globallyUniqueId: Int64, uploadedFile: SecretChatOutgoingFile?, thumbnailData: [MediaId: Data], layer: SecretChatLayer) -> BoxedDecryptedMessage { let media: Media? = message.media.first var messageAutoremoveTimeout: Int32 = 0 var replyGlobalId: Int64? = nil @@ -582,7 +582,7 @@ private func boxedDecryptedMessage(modifier: Modifier, message: Message, globall } else if let attribute = attribute as? InlineBotMessageAttribute { if let title = attribute.title { viaBotName = title - } else if let peerId = attribute.peerId, let peer = modifier.getPeer(peerId), let addressName = peer.addressName { + } else if let peerId = attribute.peerId, let peer = transaction.getPeer(peerId), let addressName = peer.addressName { viaBotName = addressName } } else if let attribute = attribute as? TextEntitiesMessageAttribute { @@ -926,9 +926,9 @@ private func boxedDecryptedSecretMessageAction(action: SecretMessageAction) -> B } } -private func markOutgoingOperationAsCompleted(modifier: Modifier, peerId: PeerId, tagLocalIndex: Int32, forceRemove: Bool) { +private func markOutgoingOperationAsCompleted(transaction: Transaction, peerId: PeerId, tagLocalIndex: Int32, forceRemove: Bool) { var removeFromTagMergedIndexOnly = false - if let state = modifier.getPeerChatState(peerId) as? SecretChatState { + if let state = transaction.getPeerChatState(peerId) as? SecretChatState { switch state.embeddedState { case let .sequenceBasedLayer(sequenceState): if tagLocalIndex >= sequenceState.baseOutgoingOperationIndex { @@ -939,7 +939,7 @@ private func markOutgoingOperationAsCompleted(modifier: Modifier, peerId: PeerId } } if removeFromTagMergedIndexOnly && !forceRemove { - modifier.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex, { entry in if let operation = entry?.contents as? SecretChatOutgoingOperation { return PeerOperationLogEntryUpdate(mergedIndex: .remove, contents: .update(operation.withUpdatedDelivered(true))) } else { @@ -948,13 +948,13 @@ private func markOutgoingOperationAsCompleted(modifier: Modifier, peerId: PeerId } }) } else { - let _ = modifier.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex) } } -private func replaceOutgoingOperationWithEmptyMessage(modifier: Modifier, peerId: PeerId, tagLocalIndex: Int32, globallyUniqueId: Int64) { +private func replaceOutgoingOperationWithEmptyMessage(transaction: Transaction, peerId: PeerId, tagLocalIndex: Int32, globallyUniqueId: Int64) { var layer: SecretChatLayer? - let state = modifier.getPeerChatState(peerId) as? SecretChatState + let state = transaction.getPeerChatState(peerId) as? SecretChatState if let state = state { switch state.embeddedState { case .terminated, .handshake: @@ -966,7 +966,7 @@ private func replaceOutgoingOperationWithEmptyMessage(modifier: Modifier, peerId } } if let layer = layer { - modifier.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex, { entry in if let _ = entry?.contents as? SecretChatOutgoingOperation { return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .update(SecretChatOutgoingOperation(contents: SecretChatOutgoingOperationContents.deleteMessages(layer: layer, actionGloballyUniqueId: arc4random64(), globallyUniqueIds: [globallyUniqueId]), mutable: true, delivered: false))) } else { @@ -976,7 +976,7 @@ private func replaceOutgoingOperationWithEmptyMessage(modifier: Modifier, peerId }) } else { assertionFailure() - let _ = modifier.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: tagLocalIndex) } } @@ -1018,8 +1018,8 @@ private func messageWithThumbnailData(mediaBox: MediaBox, message: Message) -> S } private func sendMessage(postbox: Postbox, network: Network, messageId: MessageId, file: SecretChatOutgoingFile?, tagLocalIndex: Int32, wasDelivered: Bool, layer: SecretChatLayer) -> Signal { - return postbox.modify { modifier -> Signal<[MediaId: Data], NoError> in - if let message = modifier.getMessage(messageId) { + return postbox.transaction { transaction -> Signal<[MediaId: Data], NoError> in + if let message = transaction.getMessage(messageId) { return messageWithThumbnailData(mediaBox: postbox.mediaBox, message: message) } else { return .single([:]) @@ -1027,17 +1027,17 @@ private func sendMessage(postbox: Postbox, network: Network, messageId: MessageI } |> switchToLatest |> mapToSignal { thumbnailData -> Signal in - return postbox.modify { modifier -> Signal in - if let state = modifier.getPeerChatState(messageId.peerId) as? SecretChatState, let peer = modifier.getPeer(messageId.peerId) as? TelegramSecretChat { - if let message = modifier.getMessage(messageId), let globallyUniqueId = message.globallyUniqueId { - let decryptedMessage = boxedDecryptedMessage(modifier: modifier, message: message, globallyUniqueId: globallyUniqueId, uploadedFile: file, thumbnailData: thumbnailData, layer: layer) + return postbox.transaction { transaction -> Signal in + if let state = transaction.getPeerChatState(messageId.peerId) as? SecretChatState, let peer = transaction.getPeer(messageId.peerId) as? TelegramSecretChat { + if let message = transaction.getMessage(messageId), let globallyUniqueId = message.globallyUniqueId { + let decryptedMessage = boxedDecryptedMessage(transaction: transaction, message: message, globallyUniqueId: globallyUniqueId, uploadedFile: file, thumbnailData: thumbnailData, layer: layer) return sendBoxedDecryptedMessage(postbox: postbox, network: network, peer: peer, state: state, operationIndex: tagLocalIndex, decryptedMessage: decryptedMessage, globallyUniqueId: globallyUniqueId, file: file, asService: wasDelivered, wasDelivered: wasDelivered) |> mapToSignal { result in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in if result == nil { - replaceOutgoingOperationWithEmptyMessage(modifier: modifier, peerId: messageId.peerId, tagLocalIndex: tagLocalIndex, globallyUniqueId: globallyUniqueId) + replaceOutgoingOperationWithEmptyMessage(transaction: transaction, peerId: messageId.peerId, tagLocalIndex: tagLocalIndex, globallyUniqueId: globallyUniqueId) } else { - markOutgoingOperationAsCompleted(modifier: modifier, peerId: messageId.peerId, tagLocalIndex: tagLocalIndex, forceRemove: result == nil) + markOutgoingOperationAsCompleted(transaction: transaction, peerId: messageId.peerId, tagLocalIndex: tagLocalIndex, forceRemove: result == nil) } var timestamp = message.timestamp @@ -1052,9 +1052,9 @@ private func sendMessage(postbox: Postbox, network: Network, messageId: MessageI } } - modifier.offsetPendingMessagesTimestamps(lowerBound: message.id, excludeIds: Set([messageId]), timestamp: timestamp) + transaction.offsetPendingMessagesTimestamps(lowerBound: message.id, excludeIds: Set([messageId]), timestamp: timestamp) - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in var flags = StoreMessageFlags(currentMessage.flags) if let _ = result { flags.remove(.Unsent) @@ -1085,12 +1085,12 @@ private func sendMessage(postbox: Postbox, network: Network, messageId: MessageI return .update(StoreMessage(id: currentMessage.id, globallyUniqueId: currentMessage.globallyUniqueId, groupingKey: currentMessage.groupingKey, timestamp: timestamp, flags: flags, tags: currentMessage.tags, globalTags: currentMessage.globalTags, localTags: currentMessage.localTags, forwardInfo: storeForwardInfo, authorId: currentMessage.author?.id, text: currentMessage.text, attributes: currentMessage.attributes, media: updatedMedia)) }) - maybeReadSecretOutgoingMessage(modifier: modifier, index: MessageIndex(id: message.id, timestamp: timestamp)) + maybeReadSecretOutgoingMessage(transaction: transaction, index: MessageIndex(id: message.id, timestamp: timestamp)) } } } else { - replaceOutgoingOperationWithEmptyMessage(modifier: modifier, peerId: messageId.peerId, tagLocalIndex: tagLocalIndex, globallyUniqueId: arc4random64()) - modifier.deleteMessages([messageId]) + replaceOutgoingOperationWithEmptyMessage(transaction: transaction, peerId: messageId.peerId, tagLocalIndex: tagLocalIndex, globallyUniqueId: arc4random64()) + transaction.deleteMessages([messageId]) //assertionFailure() return .complete() } @@ -1102,20 +1102,20 @@ private func sendMessage(postbox: Postbox, network: Network, messageId: MessageI } private func sendServiceActionMessage(postbox: Postbox, network: Network, peerId: PeerId, action: SecretMessageAction, tagLocalIndex: Int32, wasDelivered: Bool) -> Signal { - return postbox.modify { modifier -> Signal in - if let state = modifier.getPeerChatState(peerId) as? SecretChatState, let peer = modifier.getPeer(peerId) as? TelegramSecretChat { + return postbox.transaction { transaction -> Signal in + if let state = transaction.getPeerChatState(peerId) as? SecretChatState, let peer = transaction.getPeer(peerId) as? TelegramSecretChat { let decryptedMessage = boxedDecryptedSecretMessageAction(action: action) return sendBoxedDecryptedMessage(postbox: postbox, network: network, peer: peer, state: state, operationIndex: tagLocalIndex, decryptedMessage: decryptedMessage, globallyUniqueId: action.globallyUniqueId, file: nil, asService: true, wasDelivered: wasDelivered) |> mapToSignal { result in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in if result == nil { - replaceOutgoingOperationWithEmptyMessage(modifier: modifier, peerId: peerId, tagLocalIndex: tagLocalIndex, globallyUniqueId: action.globallyUniqueId) + replaceOutgoingOperationWithEmptyMessage(transaction: transaction, peerId: peerId, tagLocalIndex: tagLocalIndex, globallyUniqueId: action.globallyUniqueId) } else { - markOutgoingOperationAsCompleted(modifier: modifier, peerId: peerId, tagLocalIndex: tagLocalIndex, forceRemove: result == nil) + markOutgoingOperationAsCompleted(transaction: transaction, peerId: peerId, tagLocalIndex: tagLocalIndex, forceRemove: result == nil) } if let messageId = action.messageId { var resultTimestamp: Int32? - modifier.updateMessage(messageId, update: { currentMessage in + transaction.updateMessage(messageId, update: { currentMessage in var flags = StoreMessageFlags(currentMessage.flags) var timestamp = currentMessage.timestamp if let result = result { @@ -1139,7 +1139,7 @@ private func sendServiceActionMessage(postbox: Postbox, network: Network, peerId }) if let resultTimestamp = resultTimestamp { - maybeReadSecretOutgoingMessage(modifier: modifier, index: MessageIndex(id: messageId, timestamp: resultTimestamp)) + maybeReadSecretOutgoingMessage(transaction: transaction, index: MessageIndex(id: messageId, timestamp: resultTimestamp)) } } } @@ -1227,8 +1227,8 @@ private func requestTerminateSecretChat(postbox: Postbox, network: Network, peer } |> mapToSignal { _ -> Signal in if reportSpam { - return postbox.modify { modifier -> TelegramSecretChat? in - if let peer = modifier.getPeer(peerId) as? TelegramSecretChat { + return postbox.transaction { transaction -> TelegramSecretChat? in + if let peer = transaction.getPeer(peerId) as? TelegramSecretChat { return peer } else { return nil @@ -1242,9 +1242,9 @@ private func requestTerminateSecretChat(postbox: Postbox, network: Network, peer return .single(nil) } |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in if result != nil { - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedSecretChatData { return current.withUpdatedReportStatus(.didReport) } else { @@ -1263,8 +1263,8 @@ private func requestTerminateSecretChat(postbox: Postbox, network: Network, peer } } |> mapToSignal { _ -> Signal in - return postbox.modify { modifier -> Void in - markOutgoingOperationAsCompleted(modifier: modifier, peerId: peerId, tagLocalIndex: tagLocalIndex, forceRemove: true) + return postbox.transaction { transaction -> Void in + markOutgoingOperationAsCompleted(transaction: transaction, peerId: peerId, tagLocalIndex: tagLocalIndex, forceRemove: true) } } } diff --git a/TelegramCore/ManagedSynchronizeChatInputStateOperations.swift b/TelegramCore/ManagedSynchronizeChatInputStateOperations.swift index f0ccab2657..e7eb8470a9 100644 --- a/TelegramCore/ManagedSynchronizeChatInputStateOperations.swift +++ b/TelegramCore/ManagedSynchronizeChatInputStateOperations.swift @@ -61,10 +61,10 @@ private final class ManagedSynchronizeChatInputStateOperationsHelper { } } -private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Modifier, PeerMergedOperationLogEntry?) -> Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, entry.contents is SynchronizeChatInputStateOperation { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -73,8 +73,8 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOpera } }) - return f(modifier, result) - } |> switchToLatest + return f(transaction, result) + } |> switchToLatest } func managedSynchronizeChatInputStateOperations(postbox: Postbox, network: Network) -> Signal { @@ -94,18 +94,18 @@ func managedSynchronizeChatInputStateOperations(postbox: Postbox, network: Netwo } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let operation = entry.contents as? SynchronizeChatInputStateOperation { - return synchronizeChatInputState(modifier: modifier, postbox: postbox, network: network, peerId: entry.peerId, operation: operation) + return synchronizeChatInputState(transaction: transaction, postbox: postbox, network: network, peerId: entry.peerId, operation: operation) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) }) disposable.set(signal.start()) @@ -129,9 +129,9 @@ func managedSynchronizeChatInputStateOperations(postbox: Postbox, network: Netwo } } -private func synchronizeChatInputState(modifier: Modifier, postbox: Postbox, network: Network, peerId: PeerId, operation: SynchronizeChatInputStateOperation) -> Signal { - let inputState = (modifier.getPeerChatInterfaceState(peerId) as? SynchronizeableChatInterfaceState)?.synchronizeableInputState - if let peer = modifier.getPeer(peerId), let inputPeer = apiInputPeer(peer) { +private func synchronizeChatInputState(transaction: Transaction, postbox: Postbox, network: Network, peerId: PeerId, operation: SynchronizeChatInputStateOperation) -> Signal { + let inputState = (transaction.getPeerChatInterfaceState(peerId) as? SynchronizeableChatInterfaceState)?.synchronizeableInputState + if let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) { var flags: Int32 = 0 if inputState?.replyToMessageId != nil { flags |= (1 << 0) diff --git a/TelegramCore/ManagedSynchronizeConsumeMessageContentsOperations.swift b/TelegramCore/ManagedSynchronizeConsumeMessageContentsOperations.swift index cb44e1c611..680f5c5908 100644 --- a/TelegramCore/ManagedSynchronizeConsumeMessageContentsOperations.swift +++ b/TelegramCore/ManagedSynchronizeConsumeMessageContentsOperations.swift @@ -53,10 +53,10 @@ private final class ManagedSynchronizeConsumeMessageContentsOperationHelper { } } -private func withTakenOperation(postbox: Postbox, peerId: PeerId, tagLocalIndex: Int32, _ f: @escaping (Modifier, PeerMergedOperationLogEntry?) -> Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, entry.contents is SynchronizeConsumeMessageContentsOperation { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tagLocalIndex: } }) - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -83,18 +83,18 @@ func managedSynchronizeConsumeMessageContentOperations(postbox: Postbox, network } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let operation = entry.contents as? SynchronizeConsumeMessageContentsOperation { - return synchronizeConsumeMessageContents(modifier: modifier, network: network, stateManager: stateManager, peerId: entry.peerId, operation: operation) + return synchronizeConsumeMessageContents(transaction: transaction, network: network, stateManager: stateManager, peerId: entry.peerId, operation: operation) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, tagLocalIndex: entry.tagLocalIndex) }) disposable.set(signal.start()) @@ -113,7 +113,7 @@ func managedSynchronizeConsumeMessageContentOperations(postbox: Postbox, network } } -private func synchronizeConsumeMessageContents(modifier: Modifier, network: Network, stateManager: AccountStateManager, peerId: PeerId, operation: SynchronizeConsumeMessageContentsOperation) -> Signal { +private func synchronizeConsumeMessageContents(transaction: Transaction, network: Network, stateManager: AccountStateManager, peerId: PeerId, operation: SynchronizeConsumeMessageContentsOperation) -> Signal { if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup { return network.request(Api.functions.messages.readMessageContents(id: operation.messageIds.map { $0.id })) |> map { Optional($0) } @@ -130,7 +130,7 @@ private func synchronizeConsumeMessageContents(modifier: Modifier, network: Netw return .complete() } } else if peerId.namespace == Namespaces.Peer.CloudChannel { - if let peer = modifier.getPeer(peerId), let inputChannel = apiInputChannel(peer) { + if let peer = transaction.getPeer(peerId), let inputChannel = apiInputChannel(peer) { return network.request(Api.functions.channels.readMessageContents(channel: inputChannel, id: operation.messageIds.map { $0.id })) |> map { Optional($0) } |> `catch` { _ -> Signal in diff --git a/TelegramCore/ManagedSynchronizeGroupedPeersOperations.swift b/TelegramCore/ManagedSynchronizeGroupedPeersOperations.swift index cfbbb3cfbc..4a4484aa74 100644 --- a/TelegramCore/ManagedSynchronizeGroupedPeersOperations.swift +++ b/TelegramCore/ManagedSynchronizeGroupedPeersOperations.swift @@ -53,10 +53,10 @@ private final class ManagedSynchronizeGroupedPeersOperationsHelper { } } -private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Modifier, PeerMergedOperationLogEntry?) -> Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, entry.contents is SynchronizeGroupedPeersOperation { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOpera } }) - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -85,18 +85,18 @@ func managedSynchronizeGroupedPeersOperations(postbox: Postbox, network: Network } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let operation = entry.contents as? SynchronizeGroupedPeersOperation { - return synchronizeGroupedPeers(modifier: modifier, postbox: postbox, network: network, operation: operation) + return synchronizeGroupedPeers(transaction: transaction, postbox: postbox, network: network, operation: operation) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) }) disposable.set(signal.start()) @@ -125,11 +125,11 @@ private func hashForIds(_ ids: [Int32]) -> Int32 { return Int32(bitPattern: acc & UInt32(0x7FFFFFFF)) } -private func synchronizeGroupedPeers(modifier: Modifier, postbox: Postbox, network: Network, operation: SynchronizeGroupedPeersOperation) -> Signal { +private func synchronizeGroupedPeers(transaction: Transaction, postbox: Postbox, network: Network, operation: SynchronizeGroupedPeersOperation) -> Signal { /*feed*/ return .complete() /*let initialRemotePeerIds = operation.initialPeerIds - let localPeerIds = modifier.getPeerIdsInGroup(operation.groupId) + let localPeerIds = transaction.getPeerIdsInGroup(operation.groupId) return network.request(Api.functions.channels.getFeedSources(flags: 1 << 0, feedId: operation.groupId.rawValue, hash: hashForIds(localPeerIds.map({ $0.id }).sorted()))) |> retryRequest @@ -159,7 +159,7 @@ private func synchronizeGroupedPeers(modifier: Modifier, postbox: Postbox, netwo finalPeerIds.subtract(remoteRemoved) //channels.setFeedBroadcasts feed_id:int channels:Vector also_newly_joined:Bool = Bool; - return postbox.modify { modifier -> Signal in + return postbox.transaction { transaction -> Signal in var peers: [PeerId: Peer] = [:] var peerPresences: [PeerId: PeerPresence] = [:] for chat in chats { @@ -177,32 +177,32 @@ private func synchronizeGroupedPeers(modifier: Modifier, postbox: Postbox, netwo var inputChannels: [Api.InputChannel] = [] for peerId in finalPeerIds { - if let peer = modifier.getPeer(peerId) ?? peers[peerId], let inputChannel = apiInputChannel(peer) { + if let peer = transaction.getPeer(peerId) ?? peers[peerId], let inputChannel = apiInputChannel(peer) { inputChannels.append(inputChannel) } else { assertionFailure() } } - updatePeers(modifier: modifier, peers: Array(peers.values), update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: Array(peers.values), update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) return network.request(Api.functions.channels.setFeedBroadcasts(flags: 1 << 0, feedId: operation.groupId.rawValue, channels: inputChannels, alsoNewlyJoined: nil)) |> retryRequest |> mapToSignal { _ -> Signal in - return postbox.modify { modifier -> Void in - let currentLocalPeerIds = modifier.getPeerIdsInGroup(operation.groupId) + return postbox.transaction { transaction -> Void in + let currentLocalPeerIds = transaction.getPeerIdsInGroup(operation.groupId) for peerId in currentLocalPeerIds { if !finalPeerIds.contains(peerId) { - modifier.updatePeerGroupId(peerId, groupId: nil) + transaction.updatePeerGroupId(peerId, groupId: nil) } } for peerId in finalPeerIds { - modifier.updatePeerGroupId(peerId, groupId: operation.groupId) + transaction.updatePeerGroupId(peerId, groupId: operation.groupId) } } } diff --git a/TelegramCore/ManagedSynchronizeInstalledStickerPacksOperations.swift b/TelegramCore/ManagedSynchronizeInstalledStickerPacksOperations.swift index 9d1d0b406e..f352cbab24 100644 --- a/TelegramCore/ManagedSynchronizeInstalledStickerPacksOperations.swift +++ b/TelegramCore/ManagedSynchronizeInstalledStickerPacksOperations.swift @@ -53,10 +53,10 @@ private final class ManagedSynchronizeInstalledStickerPacksOperationsHelper { } } -private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Modifier, PeerMergedOperationLogEntry?) -> Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, entry.contents is SynchronizeInstalledStickerPacksOperation { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOpera } }) - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -91,18 +91,18 @@ func managedSynchronizeInstalledStickerPacksOperations(postbox: Postbox, network } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let operation = entry.contents as? SynchronizeInstalledStickerPacksOperation { - return synchronizeInstalledStickerPacks(modifier: modifier, postbox: postbox, network: network, stateManager: stateManager, namespace: namespace, operation: operation) + return synchronizeInstalledStickerPacks(transaction: transaction, postbox: postbox, network: network, stateManager: stateManager, namespace: namespace, operation: operation) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) }) disposable.set((signal |> delay(2.0, queue: Queue.concurrentDefaultQueue())).start()) @@ -265,7 +265,7 @@ private func reorderRemoteStickerPacks(network: Network, namespace: SynchronizeI } } -private func synchronizeInstalledStickerPacks(modifier: Modifier, postbox: Postbox, network: Network, stateManager: AccountStateManager, namespace: SynchronizeInstalledStickerPacksOperationNamespace, operation: SynchronizeInstalledStickerPacksOperation) -> Signal { +private func synchronizeInstalledStickerPacks(transaction: Transaction, postbox: Postbox, network: Network, stateManager: AccountStateManager, namespace: SynchronizeInstalledStickerPacksOperationNamespace, operation: SynchronizeInstalledStickerPacksOperation) -> Signal { let collectionNamespace: ItemCollectionId.Namespace switch namespace { case .stickers: @@ -274,7 +274,7 @@ private func synchronizeInstalledStickerPacks(modifier: Modifier, postbox: Postb collectionNamespace = Namespaces.ItemCollection.CloudMaskPacks } - let localCollectionInfos = modifier.getItemCollectionsInfos(namespace: collectionNamespace).map { $0.1 as! StickerPackCollectionInfo } + let localCollectionInfos = transaction.getItemCollectionsInfos(namespace: collectionNamespace).map { $0.1 as! StickerPackCollectionInfo } let initialLocalHash = hashForStickerPackInfos(localCollectionInfos) let request: Signal @@ -291,8 +291,8 @@ private func synchronizeInstalledStickerPacks(modifier: Modifier, postbox: Postb return .restart } |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Signal in - let checkLocalCollectionInfos = modifier.getItemCollectionsInfos(namespace: collectionNamespace).map { $0.1 as! StickerPackCollectionInfo } + return postbox.transaction { transaction -> Signal in + let checkLocalCollectionInfos = transaction.getItemCollectionsInfos(namespace: collectionNamespace).map { $0.1 as! StickerPackCollectionInfo } if checkLocalCollectionInfos != localCollectionInfos { return .fail(.restart) } @@ -335,13 +335,13 @@ private func synchronizeInstalledStickerPacks(modifier: Modifier, postbox: Postb return .restart } |> mapToSignal { replaceItems -> Signal in - return (postbox.modify { modifier -> Void in - modifier.replaceItemCollectionInfos(namespace: collectionNamespace, itemCollectionInfos: remoteCollectionInfos.map { ($0.id, $0) }) + return (postbox.transaction { transaction -> Void in + transaction.replaceItemCollectionInfos(namespace: collectionNamespace, itemCollectionInfos: remoteCollectionInfos.map { ($0.id, $0) }) for (id, items) in replaceItems { - modifier.replaceItemCollectionItems(collectionId: id, items: items) + transaction.replaceItemCollectionItems(collectionId: id, items: items) } for id in localCollectionIds.subtracting(remoteCollectionIds) { - modifier.replaceItemCollectionItems(collectionId: id, items: []) + transaction.replaceItemCollectionItems(collectionId: id, items: []) } } |> mapError { _ -> SynchronizeInstalledStickerPacksError in return .restart }) |> then(.fail(.done)) } @@ -404,22 +404,22 @@ private func synchronizeInstalledStickerPacks(modifier: Modifier, postbox: Postb return combineLatest(archivedIds, resolvedItems) |> mapError { _ -> SynchronizeInstalledStickerPacksError in return .restart } |> mapToSignal { archivedIds, replaceItems -> Signal in - return (postbox.modify { modifier -> Signal in - let finalCheckLocalCollectionInfos = modifier.getItemCollectionsInfos(namespace: collectionNamespace).map { $0.1 as! StickerPackCollectionInfo } + return (postbox.transaction { transaction -> Signal in + let finalCheckLocalCollectionInfos = transaction.getItemCollectionsInfos(namespace: collectionNamespace).map { $0.1 as! StickerPackCollectionInfo } if finalCheckLocalCollectionInfos != localCollectionInfos { return .fail(.restart) } - modifier.replaceItemCollectionInfos(namespace: collectionNamespace, itemCollectionInfos: resultingCollectionInfos.filter({ info in + transaction.replaceItemCollectionInfos(namespace: collectionNamespace, itemCollectionInfos: resultingCollectionInfos.filter({ info in return !archivedIds.contains(info.id) }).map({ ($0.id, $0) })) for (id, items) in replaceItems { if !archivedIds.contains(id) { - modifier.replaceItemCollectionItems(collectionId: id, items: items) + transaction.replaceItemCollectionItems(collectionId: id, items: items) } } for id in localCollectionIds.subtracting(resultingCollectionIds).union(archivedIds) { - modifier.replaceItemCollectionItems(collectionId: id, items: []) + transaction.replaceItemCollectionItems(collectionId: id, items: []) } return .complete() diff --git a/TelegramCore/ManagedSynchronizeMarkFeaturedStickerPacksAsSeenOperations.swift b/TelegramCore/ManagedSynchronizeMarkFeaturedStickerPacksAsSeenOperations.swift index fa8a6f0212..9a1ced00cf 100644 --- a/TelegramCore/ManagedSynchronizeMarkFeaturedStickerPacksAsSeenOperations.swift +++ b/TelegramCore/ManagedSynchronizeMarkFeaturedStickerPacksAsSeenOperations.swift @@ -53,10 +53,10 @@ private final class ManagedSynchronizeMarkFeaturedStickerPacksAsSeenOperationsHe } } -private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Modifier, PeerMergedOperationLogEntry?) -> Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, entry.contents is SynchronizeMarkFeaturedStickerPacksAsSeenOperation { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOpera } }) - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -85,18 +85,18 @@ func managedSynchronizeMarkFeaturedStickerPacksAsSeenOperations(postbox: Postbox } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let operation = entry.contents as? SynchronizeMarkFeaturedStickerPacksAsSeenOperation { - return synchronizeMarkFeaturedStickerPacksAsSeen(modifier: modifier, postbox: postbox, network: network, operation: operation) + return synchronizeMarkFeaturedStickerPacksAsSeen(transaction: transaction, postbox: postbox, network: network, operation: operation) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) }) disposable.set(signal.start()) @@ -115,7 +115,7 @@ func managedSynchronizeMarkFeaturedStickerPacksAsSeenOperations(postbox: Postbox } } -private func synchronizeMarkFeaturedStickerPacksAsSeen(modifier: Modifier, postbox: Postbox, network: Network, operation: SynchronizeMarkFeaturedStickerPacksAsSeenOperation) -> Signal { +private func synchronizeMarkFeaturedStickerPacksAsSeen(transaction: Transaction, postbox: Postbox, network: Network, operation: SynchronizeMarkFeaturedStickerPacksAsSeenOperation) -> Signal { return network.request(Api.functions.messages.readFeaturedStickers(id: operation.ids.map { $0.id })) |> `catch` { _ -> Signal in return .single(.boolFalse) diff --git a/TelegramCore/ManagedSynchronizePinnedChatsOperations.swift b/TelegramCore/ManagedSynchronizePinnedChatsOperations.swift index 559b2eb26e..356df3db16 100644 --- a/TelegramCore/ManagedSynchronizePinnedChatsOperations.swift +++ b/TelegramCore/ManagedSynchronizePinnedChatsOperations.swift @@ -53,10 +53,10 @@ private final class ManagedSynchronizePinnedChatsOperationsHelper { } } -private func withTakenOperation(postbox: Postbox, peerId: PeerId, tagLocalIndex: Int32, _ f: @escaping (Modifier, PeerMergedOperationLogEntry?) -> Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, entry.contents is SynchronizePinnedChatsOperation { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tagLocalIndex: } }) - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -83,18 +83,18 @@ func managedSynchronizePinnedChatsOperations(postbox: Postbox, network: Network, } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let operation = entry.contents as? SynchronizePinnedChatsOperation { - return synchronizePinnedChats(modifier: modifier, postbox: postbox, network: network, stateManager: stateManager, operation: operation) + return synchronizePinnedChats(transaction: transaction, postbox: postbox, network: network, stateManager: stateManager, operation: operation) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: entry.tagLocalIndex) }) disposable.set((signal |> delay(2.0, queue: Queue.concurrentDefaultQueue())).start()) @@ -113,7 +113,7 @@ func managedSynchronizePinnedChatsOperations(postbox: Postbox, network: Network, } } -private func synchronizePinnedChats(modifier: Modifier, postbox: Postbox, network: Network, stateManager: AccountStateManager, operation: SynchronizePinnedChatsOperation) -> Signal { +private func synchronizePinnedChats(transaction: Transaction, postbox: Postbox, network: Network, stateManager: AccountStateManager, operation: SynchronizePinnedChatsOperation) -> Signal { let initialRemoteItemIds = operation.previousItemIds let initialRemoteItemIdsWithoutSecretChats = initialRemoteItemIds.filter { item in switch item { @@ -123,7 +123,7 @@ private func synchronizePinnedChats(modifier: Modifier, postbox: Postbox, networ return true } } - let localItemIds = modifier.getPinnedItemIds() + let localItemIds = transaction.getPinnedItemIds() let localItemIdsWithoutSecretChats = localItemIds.filter { item in switch item { case let .peer(peerId): @@ -230,16 +230,16 @@ private func synchronizePinnedChats(modifier: Modifier, postbox: Postbox, networ var resultingItemIds = localItemIds.filter { !remotelyRemovedItemIds.contains($0) } resultingItemIds.append(contentsOf: remoteItemIds.filter { !locallyRemovedFromRemoteItemIds.contains($0) && !resultingItemIds.contains($0) }) - return postbox.modify { modifier -> Signal in - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + return postbox.transaction { transaction -> Signal in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.setPinnedItemIds(resultingItemIds) + transaction.setPinnedItemIds(resultingItemIds) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) - modifier.updateCurrentPeerNotificationSettings(notificationSettings) + transaction.updateCurrentPeerNotificationSettings(notificationSettings) var allPeersWithMessages = Set() for message in storeMessages { @@ -247,19 +247,19 @@ private func synchronizePinnedChats(modifier: Modifier, postbox: Postbox, networ allPeersWithMessages.insert(message.id.peerId) } } - let _ = modifier.addMessages(storeMessages, location: .UpperHistoryBlock) + let _ = transaction.addMessages(storeMessages, location: .UpperHistoryBlock) - modifier.resetIncomingReadStates(readStates) + transaction.resetIncomingReadStates(readStates) for (peerId, chatState) in chatStates { if let chatState = chatState as? ChannelState { - if let _ = modifier.getPeerChatState(peerId) as? ChannelState { + if let _ = transaction.getPeerChatState(peerId) as? ChannelState { // skip changing state } else { - modifier.setPeerChatState(peerId, state: chatState) + transaction.setPeerChatState(peerId, state: chatState) } } else { - modifier.setPeerChatState(peerId, state: chatState) + transaction.setPeerChatState(peerId, state: chatState) } } @@ -270,7 +270,7 @@ private func synchronizePinnedChats(modifier: Modifier, postbox: Postbox, networ for itemId in resultingItemIds { switch itemId { case let .peer(peerId): - if let peer = modifier.getPeer(peerId), let inputPeer = apiInputPeer(peer) { + if let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) { inputDialogPeers.append(Api.InputDialogPeer.inputDialogPeer(peer: inputPeer)) } case let .group(groupId): @@ -285,7 +285,7 @@ private func synchronizePinnedChats(modifier: Modifier, postbox: Postbox, networ return .single(Api.Bool.boolFalse) } |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in } } } diff --git a/TelegramCore/ManagedSynchronizeSavedGifsOperations.swift b/TelegramCore/ManagedSynchronizeSavedGifsOperations.swift index 51df36be27..66f3ea5190 100644 --- a/TelegramCore/ManagedSynchronizeSavedGifsOperations.swift +++ b/TelegramCore/ManagedSynchronizeSavedGifsOperations.swift @@ -53,10 +53,10 @@ private final class ManagedSynchronizeSavedGifsOperationsHelper { } } -private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Modifier, PeerMergedOperationLogEntry?) -> Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, entry.contents is SynchronizeSavedGifsOperation { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOpera } }) - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -85,18 +85,18 @@ func managedSynchronizeSavedGifsOperations(postbox: Postbox, network: Network) - } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let operation = entry.contents as? SynchronizeSavedGifsOperation { - return synchronizeSavedGifs(modifier: modifier, postbox: postbox, network: network, operation: operation) + return synchronizeSavedGifs(transaction: transaction, postbox: postbox, network: network, operation: operation) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) }) disposable.set(signal.start()) @@ -115,7 +115,7 @@ func managedSynchronizeSavedGifsOperations(postbox: Postbox, network: Network) - } } -private func synchronizeSavedGifs(modifier: Modifier, postbox: Postbox, network: Network, operation: SynchronizeSavedGifsOperation) -> Signal { +private func synchronizeSavedGifs(transaction: Transaction, postbox: Postbox, network: Network, operation: SynchronizeSavedGifsOperation) -> Signal { switch operation.content { case let .add(id, accessHash): return network.request(Api.functions.messages.saveGif(id: .inputDocument(id: id, accessHash: accessHash), unsave: .boolFalse)) diff --git a/TelegramCore/ManagedSynchronizeSavedStickersOperations.swift b/TelegramCore/ManagedSynchronizeSavedStickersOperations.swift index b15a810a2d..f51151b214 100644 --- a/TelegramCore/ManagedSynchronizeSavedStickersOperations.swift +++ b/TelegramCore/ManagedSynchronizeSavedStickersOperations.swift @@ -53,10 +53,10 @@ private final class ManagedSynchronizeSavedStickersOperationsHelper { } } -private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Modifier, PeerMergedOperationLogEntry?) -> Signal) -> Signal { - return postbox.modify { modifier -> Signal in +private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ f: @escaping (Transaction, PeerMergedOperationLogEntry?) -> Signal) -> Signal { + return postbox.transaction { transaction -> Signal in var result: PeerMergedOperationLogEntry? - modifier.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, { entry in if let entry = entry, let _ = entry.mergedIndex, entry.contents is SynchronizeSavedStickersOperation { result = entry.mergedEntry! return PeerOperationLogEntryUpdate(mergedIndex: .none, contents: .none) @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOpera } }) - return f(modifier, result) + return f(transaction, result) } |> switchToLatest } @@ -85,18 +85,18 @@ func managedSynchronizeSavedStickersOperations(postbox: Postbox, network: Networ } for (entry, disposable) in beginOperations { - let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { modifier, entry -> Signal in + let signal = withTakenOperation(postbox: postbox, peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex, { transaction, entry -> Signal in if let entry = entry { if let operation = entry.contents as? SynchronizeSavedStickersOperation { - return synchronizeSavedStickers(modifier: modifier, postbox: postbox, network: network, operation: operation) + return synchronizeSavedStickers(transaction: transaction, postbox: postbox, network: network, operation: operation) } else { assertionFailure() } } return .complete() }) - |> then(postbox.modify { modifier -> Void in - let _ = modifier.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) + |> then(postbox.transaction { transaction -> Void in + let _ = transaction.operationLogRemoveEntry(peerId: entry.peerId, tag: tag, tagLocalIndex: entry.tagLocalIndex) }) disposable.set(signal.start()) @@ -115,7 +115,7 @@ func managedSynchronizeSavedStickersOperations(postbox: Postbox, network: Networ } } -private func synchronizeSavedStickers(modifier: Modifier, postbox: Postbox, network: Network, operation: SynchronizeSavedStickersOperation) -> Signal { +private func synchronizeSavedStickers(transaction: Transaction, postbox: Postbox, network: Network, operation: SynchronizeSavedStickersOperation) -> Signal { switch operation.content { case let .add(id, accessHash): return network.request(Api.functions.messages.faveSticker(id: .inputDocument(id: id, accessHash: accessHash), unfave: .boolFalse)) diff --git a/TelegramCore/MarkAllChatsAsRead.swift b/TelegramCore/MarkAllChatsAsRead.swift index c99bfb5405..34b9f8de66 100644 --- a/TelegramCore/MarkAllChatsAsRead.swift +++ b/TelegramCore/MarkAllChatsAsRead.swift @@ -20,14 +20,14 @@ public func markAllChatsAsRead(postbox: Postbox, network: Network, stateManager: return .complete() } - return postbox.modify { modifier -> Signal in + return postbox.transaction { transaction -> Signal in var signals: [Signal] = [] for peer in result { switch peer { case let .dialogPeer(peer): let peerId = peer.peerId if peerId.namespace == Namespaces.Peer.CloudChannel { - if let inputChannel = modifier.getPeer(peerId).flatMap(apiInputChannel) { + if let inputChannel = transaction.getPeer(peerId).flatMap(apiInputChannel) { signals.append(network.request(Api.functions.channels.readHistory(channel: inputChannel, maxId: Int32.max - 1)) |> `catch` { _ -> Signal in return .single(.boolFalse) @@ -37,7 +37,7 @@ public func markAllChatsAsRead(postbox: Postbox, network: Network, stateManager: }) } } else if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup { - if let inputPeer = modifier.getPeer(peerId).flatMap(apiInputPeer) { + if let inputPeer = transaction.getPeer(peerId).flatMap(apiInputPeer) { signals.append(network.request(Api.functions.messages.readHistory(peer: inputPeer, maxId: Int32.max - 1)) |> map(Optional.init) |> `catch` { _ -> Signal in @@ -59,7 +59,7 @@ public func markAllChatsAsRead(postbox: Postbox, network: Network, stateManager: } } - let applyLocally = postbox.modify { modifier -> Void in + let applyLocally = postbox.transaction { transaction -> Void in } diff --git a/TelegramCore/MarkMessageContentAsConsumedInteractively.swift b/TelegramCore/MarkMessageContentAsConsumedInteractively.swift index e5a755d714..19b6247ce8 100644 --- a/TelegramCore/MarkMessageContentAsConsumedInteractively.swift +++ b/TelegramCore/MarkMessageContentAsConsumedInteractively.swift @@ -8,8 +8,8 @@ import Foundation #endif public func markMessageContentAsConsumedInteractively(postbox: Postbox, messageId: MessageId) -> Signal { - return postbox.modify { modifier -> Void in - if let message = modifier.getMessage(messageId), message.flags.contains(.Incoming) { + return postbox.transaction { transaction -> Void in + if let message = transaction.getMessage(messageId), message.flags.contains(.Incoming) { var updateMessage = false var updatedAttributes = message.attributes @@ -19,10 +19,10 @@ public func markMessageContentAsConsumedInteractively(postbox: Postbox, messageI updatedAttributes[i] = ConsumableContentMessageAttribute(consumed: true) updateMessage = true - addSynchronizeConsumeMessageContentsOperation(modifier: modifier, messageIds: [message.id]) + addSynchronizeConsumeMessageContentsOperation(transaction: transaction, messageIds: [message.id]) } } else if let attribute = updatedAttributes[i] as? ConsumablePersonalMentionMessageAttribute, !attribute.consumed { - modifier.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: messageId, action: ConsumePersonalMessageAction()) + transaction.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: messageId, action: ConsumePersonalMessageAction()) updatedAttributes[i] = ConsumablePersonalMentionMessageAttribute(consumed: attribute.consumed, pending: true) } } @@ -34,11 +34,11 @@ public func markMessageContentAsConsumedInteractively(postbox: Postbox, messageI updatedAttributes[i] = AutoremoveTimeoutMessageAttribute(timeout: attribute.timeout, countdownBeginTime: timestamp) updateMessage = true - modifier.addTimestampBasedMessageAttribute(tag: 0, timestamp: timestamp + attribute.timeout, messageId: messageId) + transaction.addTimestampBasedMessageAttribute(tag: 0, timestamp: timestamp + attribute.timeout, messageId: messageId) if messageId.peerId.namespace == Namespaces.Peer.SecretChat { var layer: SecretChatLayer? - let state = modifier.getPeerChatState(message.id.peerId) as? SecretChatState + let state = transaction.getPeerChatState(message.id.peerId) as? SecretChatState if let state = state { switch state.embeddedState { case .terminated, .handshake: @@ -51,9 +51,9 @@ public func markMessageContentAsConsumedInteractively(postbox: Postbox, messageI } if let state = state, let layer = layer, let globallyUniqueId = message.globallyUniqueId { - let updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: messageId.peerId, operation: .readMessagesContent(layer: layer, actionGloballyUniqueId: arc4random64(), globallyUniqueIds: [globallyUniqueId]), state: state) + let updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: messageId.peerId, operation: .readMessagesContent(layer: layer, actionGloballyUniqueId: arc4random64(), globallyUniqueIds: [globallyUniqueId]), state: state) if updatedState != state { - modifier.setPeerChatState(messageId.peerId, state: updatedState) + transaction.setPeerChatState(messageId.peerId, state: updatedState) } } } @@ -63,7 +63,7 @@ public func markMessageContentAsConsumedInteractively(postbox: Postbox, messageI } if updateMessage { - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -75,8 +75,8 @@ public func markMessageContentAsConsumedInteractively(postbox: Postbox, messageI } } -func markMessageContentAsConsumedRemotely(modifier: Modifier, messageId: MessageId) { - if let message = modifier.getMessage(messageId) { +func markMessageContentAsConsumedRemotely(transaction: Transaction, messageId: MessageId) { + if let message = transaction.getMessage(messageId) { var updateMessage = false var updatedAttributes = message.attributes var updatedMedia = message.media @@ -90,7 +90,7 @@ func markMessageContentAsConsumedRemotely(modifier: Modifier, messageId: Message } } else if let attribute = updatedAttributes[i] as? ConsumablePersonalMentionMessageAttribute, !attribute.consumed { if attribute.pending { - modifier.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: messageId, action: nil) + transaction.setPendingMessageAction(type: .consumeUnseenPersonalMessage, id: messageId, action: nil) } updatedAttributes[i] = ConsumablePersonalMentionMessageAttribute(consumed: true, pending: false) updatedTags.remove(.unseenPersonalMessage) @@ -106,7 +106,7 @@ func markMessageContentAsConsumedRemotely(modifier: Modifier, messageId: Message updateMessage = true if message.id.peerId.namespace == Namespaces.Peer.SecretChat { - modifier.addTimestampBasedMessageAttribute(tag: 0, timestamp: timestamp + attribute.timeout, messageId: messageId) + transaction.addTimestampBasedMessageAttribute(tag: 0, timestamp: timestamp + attribute.timeout, messageId: messageId) } else { for i in 0 ..< updatedMedia.count { if let _ = updatedMedia[i] as? TelegramMediaImage { @@ -122,7 +122,7 @@ func markMessageContentAsConsumedRemotely(modifier: Modifier, messageId: Message } if updateMessage { - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) diff --git a/TelegramCore/Network.swift b/TelegramCore/Network.swift index 7f1e1de112..3a208c9f41 100644 --- a/TelegramCore/Network.swift +++ b/TelegramCore/Network.swift @@ -394,7 +394,7 @@ func initializedNetwork(arguments: NetworkInitializationArguments, supplementary let mtProto = MTProto(context: context, datacenterId: datacenterId, usageCalculationInfo: usageCalculationInfo(basePath: basePath, category: nil))! mtProto.useTempAuthKeys = context.useTempAuthKeys - mtProto.checkForProxyConnectionIssues = true + mtProto.checkForProxyConnectionIssues = false let connectionStatus = Promise(.waitingForNetwork) diff --git a/TelegramCore/NetworkSettings.swift b/TelegramCore/NetworkSettings.swift index 9fa432f017..45333ddd5b 100644 --- a/TelegramCore/NetworkSettings.swift +++ b/TelegramCore/NetworkSettings.swift @@ -46,8 +46,8 @@ public struct NetworkSettings: PreferencesEntry, Equatable { } public func updateNetworkSettingsInteractively(postbox: Postbox, network: Network, _ f: @escaping (NetworkSettings) -> NetworkSettings) -> Signal { - return postbox.modify { modifier -> Void in - updateNetworkSettingsInteractively(modifier: modifier, network: network, f) + return postbox.transaction { transaction -> Void in + updateNetworkSettingsInteractively(transaction: transaction, network: network, f) } } @@ -57,10 +57,10 @@ extension NetworkSettings { } } -public func updateNetworkSettingsInteractively(modifier: Modifier, network: Network, _ f: @escaping (NetworkSettings) -> NetworkSettings) { +public func updateNetworkSettingsInteractively(transaction: Transaction, network: Network, _ f: @escaping (NetworkSettings) -> NetworkSettings) { var updateNetwork = false var updatedSettings: NetworkSettings? - modifier.updatePreferencesEntry(key: PreferencesKeys.networkSettings, { current in + transaction.updatePreferencesEntry(key: PreferencesKeys.networkSettings, { current in let previous = (current as? NetworkSettings) ?? NetworkSettings.defaultSettings let updated = f(previous) updatedSettings = updated diff --git a/TelegramCore/PeerAdmins.swift b/TelegramCore/PeerAdmins.swift index 2a26a69d8d..10cff39c98 100644 --- a/TelegramCore/PeerAdmins.swift +++ b/TelegramCore/PeerAdmins.swift @@ -15,8 +15,8 @@ public enum GroupManagementType { } public func updateGroupManagementType(account: Account, peerId: PeerId, type: GroupManagementType) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) { if let channel = peer as? TelegramChannel, let inputChannel = apiInputChannel(channel) { return account.network.request(Api.functions.channels.toggleInvites(channel: inputChannel, enabled: type == .unrestricted ? .boolTrue : .boolFalse)) |> map { Optional($0) } @@ -55,8 +55,8 @@ public enum RemovePeerAdminError { } public func removePeerAdmin(account: Account, peerId: PeerId, adminId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let adminPeer = modifier.getPeer(adminId), let inputUser = apiInputUser(adminPeer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let adminPeer = transaction.getPeer(adminId), let inputUser = apiInputUser(adminPeer) { if let channel = peer as? TelegramChannel, let inputChannel = apiInputChannel(channel) { return account.network.request(Api.functions.channels.editAdmin(channel: inputChannel, userId: inputUser, adminRights: TelegramChannelAdminRights(flags: []).apiAdminRights)) |> mapError { _ -> RemovePeerAdminError in @@ -64,8 +64,8 @@ public func removePeerAdmin(account: Account, peerId: PeerId, adminId: PeerId) - } |> mapToSignal { result -> Signal in account.stateManager.addUpdates(result) - return account.postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: [peerId], update: { _, current in + return account.postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: [peerId], update: { _, current in if let current = current as? CachedChannelData, let adminCount = current.participantsSummary.adminCount { return current.withUpdatedParticipantsSummary(current.participantsSummary.withUpdatedAdminCount(max(1, adminCount - 1))) } else { @@ -78,8 +78,8 @@ public func removePeerAdmin(account: Account, peerId: PeerId, adminId: PeerId) - return account.network.request(Api.functions.messages.editChatAdmin(chatId: group.id.id, userId: inputUser, isAdmin: .boolFalse)) |> mapError { _ -> RemovePeerAdminError in return .generic } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + return account.postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedGroupData, let participants = current.participants { var updatedParticipants = participants.participants if case .boolTrue = result { @@ -117,8 +117,8 @@ public enum AddPeerAdminError { } public func addPeerAdmin(account: Account, peerId: PeerId, adminId: PeerId, adminRightsFlags:TelegramChannelAdminRightsFlags = []) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let adminPeer = modifier.getPeer(adminId), let inputUser = apiInputUser(adminPeer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let adminPeer = transaction.getPeer(adminId), let inputUser = apiInputUser(adminPeer) { let defaultRights:TelegramChannelAdminRightsFlags = [.canChangeInfo, .canPostMessages, .canEditMessages, .canDeleteMessages, .canBanUsers, .canInviteUsers, .canChangeInviteLink, .canPinMessages] @@ -146,8 +146,8 @@ public func addPeerAdmin(account: Account, peerId: PeerId, adminId: PeerId, admi for updates in result { account.stateManager.addUpdates(updates) } - return account.postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in + return account.postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in if let cachedData = cachedData as? CachedChannelData { var updatedAdminCount: Int32? if let adminCount = cachedData.participantsSummary.adminCount { @@ -164,8 +164,8 @@ public func addPeerAdmin(account: Account, peerId: PeerId, adminId: PeerId, admi return account.network.request(Api.functions.messages.editChatAdmin(chatId: group.id.id, userId: inputUser, isAdmin: .boolTrue)) |> mapError { _ -> AddPeerAdminError in return .generic } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + return account.postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedGroupData, let participants = current.participants { var updatedParticipants = participants.participants if case .boolTrue = result { @@ -203,8 +203,8 @@ public enum UpdatePeerAdminRightsError { } public func fetchChannelParticipant(account: Account, peerId: PeerId, participantId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let adminPeer = modifier.getPeer(participantId), let inputUser = apiInputUser(adminPeer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let adminPeer = transaction.getPeer(participantId), let inputUser = apiInputUser(adminPeer) { if let channel = peer as? TelegramChannel, let inputChannel = apiInputChannel(channel) { return account.network.request(Api.functions.channels.getParticipant(channel: inputChannel, userId: inputUser)) |> map { result -> ChannelParticipant? in @@ -231,9 +231,9 @@ public func updatePeerAdminRights(account: Account, peerId: PeerId, adminId: Pee return .generic } |> mapToSignal { currentParticipant -> Signal<(ChannelParticipant?, RenderedChannelParticipant), UpdatePeerAdminRightsError> in - return account.postbox.modify { modifier -> Signal<(ChannelParticipant?, RenderedChannelParticipant), UpdatePeerAdminRightsError> in + return account.postbox.transaction { transaction -> Signal<(ChannelParticipant?, RenderedChannelParticipant), UpdatePeerAdminRightsError> in - if let peer = modifier.getPeer(peerId), let adminPeer = modifier.getPeer(adminId), let inputUser = apiInputUser(adminPeer) { + if let peer = transaction.getPeer(peerId), let adminPeer = transaction.getPeer(adminId), let inputUser = apiInputUser(adminPeer) { if let channel = peer as? TelegramChannel, let inputChannel = apiInputChannel(channel) { let updatedParticipant: ChannelParticipant if let currentParticipant = currentParticipant, case let .member(_, invitedAt, currentAdminInfo, _) = currentParticipant { @@ -276,8 +276,8 @@ public func updatePeerAdminRights(account: Account, peerId: PeerId, adminId: Pee for updates in result { account.stateManager.addUpdates(updates) } - return account.postbox.modify { modifier -> (ChannelParticipant?, RenderedChannelParticipant) in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in + return account.postbox.transaction { transaction -> (ChannelParticipant?, RenderedChannelParticipant) in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in if let cachedData = cachedData as? CachedChannelData, let adminCount = cachedData.participantsSummary.adminCount { var updatedAdminCount = adminCount var wasAdmin = false @@ -305,11 +305,11 @@ public func updatePeerAdminRights(account: Account, peerId: PeerId, adminId: Pee var peers: [PeerId: Peer] = [:] var presences: [PeerId: PeerPresence] = [:] peers[adminPeer.id] = adminPeer - if let presence = modifier.getPeerPresence(peerId: adminPeer.id) { + if let presence = transaction.getPeerPresence(peerId: adminPeer.id) { presences[adminPeer.id] = presence } if case let .member(_, _, maybeAdminInfo, _) = updatedParticipant, let adminInfo = maybeAdminInfo { - if let peer = modifier.getPeer(adminInfo.promotedBy) { + if let peer = transaction.getPeer(adminInfo.promotedBy) { peers[peer.id] = peer } } diff --git a/TelegramCore/PeerPhotoUpdater.swift b/TelegramCore/PeerPhotoUpdater.swift index 80204e6838..1ec031d6cb 100644 --- a/TelegramCore/PeerPhotoUpdater.swift +++ b/TelegramCore/PeerPhotoUpdater.swift @@ -62,9 +62,9 @@ public func updatePeerPhoto(account: Account, peerId: PeerId, resource: MediaRes } } - return account.postbox.modify { modifier -> UpdatePeerPhotoStatus in - if let peer = modifier.getPeer(peer.id) { - updatePeers(modifier: modifier, peers: [peer], update: { (_, peer) -> Peer? in + return account.postbox.transaction { transaction -> UpdatePeerPhotoStatus in + if let peer = transaction.getPeer(peer.id) { + updatePeers(transaction: transaction, peers: [peer], update: { (_, peer) -> Peer? in if let peer = peer as? TelegramUser { return peer.withUpdatedPhoto(representations) } else { @@ -92,8 +92,8 @@ public func updatePeerPhoto(account: Account, peerId: PeerId, resource: MediaRes for chat in updates.chats { if chat.peerId == peerId { if let groupOrChannel = parseTelegramGroupOrChannel(chat: chat) { - return account.postbox.modify { modifier -> UpdatePeerPhotoStatus in - updatePeers(modifier: modifier, peers: [groupOrChannel], update: { _, updated in + return account.postbox.transaction { transaction -> UpdatePeerPhotoStatus in + updatePeers(transaction: transaction, peers: [groupOrChannel], update: { _, updated in return updated }) return .complete(groupOrChannel.profileImageRepresentations) @@ -149,8 +149,8 @@ public func updatePeerPhoto(account: Account, peerId: PeerId, resource: MediaRes for chat in updates.chats { if chat.peerId == peerId { if let groupOrChannel = parseTelegramGroupOrChannel(chat: chat) { - return account.postbox.modify { modifier -> UpdatePeerPhotoStatus in - updatePeers(modifier: modifier, peers: [groupOrChannel], update: { _, updated in + return account.postbox.transaction { transaction -> UpdatePeerPhotoStatus in + updatePeers(transaction: transaction, peers: [groupOrChannel], update: { _, updated in return updated }) return .complete(groupOrChannel.profileImageRepresentations) diff --git a/TelegramCore/PendingMessageManager.swift b/TelegramCore/PendingMessageManager.swift index 5c8a33ee46..fcd26b996e 100644 --- a/TelegramCore/PendingMessageManager.swift +++ b/TelegramCore/PendingMessageManager.swift @@ -55,9 +55,9 @@ private enum PendingMessageResult { } private func failMessages(postbox: Postbox, ids: [MessageId]) -> Signal { - let modify = postbox.modify { modifier -> Void in + let modify = postbox.transaction { transaction -> Void in for id in ids { - modifier.updateMessage(id, update: { currentMessage in + transaction.updateMessage(id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -408,8 +408,8 @@ public final class PendingMessageManager { messageContext.disposable.set((uploadSignal |> deliverOn(self.queue) |> `catch` { [weak self] _ -> Signal in if let strongSelf = self { - let modify = strongSelf.postbox.modify { modifier -> Void in - modifier.updateMessage(id, update: { currentMessage in + let modify = strongSelf.postbox.transaction { transaction -> Void in + transaction.updateMessage(id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -492,7 +492,7 @@ public final class PendingMessageManager { } private func sendGroupMessagesContent(network: Network, postbox: Postbox, stateManager: AccountStateManager, group: [(messageId: MessageId, content: PendingMessageUploadedContent)]) -> Signal { - return postbox.modify { [weak self] modifier -> Signal in + return postbox.transaction { [weak self] transaction -> Signal in if group.isEmpty { return .complete() } @@ -501,7 +501,7 @@ public final class PendingMessageManager { var messages: [(Message, PendingMessageUploadedContent)] = [] for (id, content) in group { - if let message = modifier.getMessage(id) { + if let message = transaction.getMessage(id) { messages.append((message, content)) } else { return failMessages(postbox: postbox, ids: group.map { $0.0 }) @@ -512,11 +512,11 @@ public final class PendingMessageManager { if peerId.namespace == Namespaces.Peer.SecretChat { for (message, content) in messages { - PendingMessageManager.sendSecretMessageContent(modifier: modifier, message: message, content: content) + PendingMessageManager.sendSecretMessageContent(transaction: transaction, message: message, content: content) } return .complete() - } else if let peer = modifier.getPeer(peerId), let inputPeer = apiInputPeer(peer) { + } else if let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) { var isForward = false var replyMessageId: Int32? @@ -564,7 +564,7 @@ public final class PendingMessageManager { if forwardPeerIds.count != 1 { assertionFailure() sendMessageRequest = .fail(NoError()) - } else if let inputSourcePeerId = forwardPeerIds.first, let inputSourcePeer = modifier.getPeer(inputSourcePeerId).flatMap(apiInputPeer) { + } else if let inputSourcePeerId = forwardPeerIds.first, let inputSourcePeer = transaction.getPeer(inputSourcePeerId).flatMap(apiInputPeer) { let dependencyTag = PendingMessageRequestDependencyTag(messageId: messages[0].0.id) sendMessageRequest = network.request(Api.functions.messages.forwardMessages(flags: flags, fromPeer: inputSourcePeer, id: forwardIds.map { $0.0.id }, randomId: forwardIds.map { $0.1 }, toPeer: inputPeer), tag: dependencyTag) @@ -641,7 +641,7 @@ public final class PendingMessageManager { } |> switchToLatest } - private static func sendSecretMessageContent(modifier: Modifier, message: Message, content: PendingMessageUploadedContent) { + private static func sendSecretMessageContent(transaction: Transaction, message: Message, content: PendingMessageUploadedContent) { var secretFile: SecretChatOutgoingFile? switch content { case let .secretMedia(file, size, key): @@ -653,7 +653,7 @@ public final class PendingMessageManager { } var layer: SecretChatLayer? - let state = modifier.getPeerChatState(message.id.peerId) as? SecretChatState + let state = transaction.getPeerChatState(message.id.peerId) as? SecretChatState if let state = state { switch state.embeddedState { case .terminated, .handshake: @@ -671,15 +671,15 @@ public final class PendingMessageManager { if let media = media as? TelegramMediaAction { if case let .messageAutoremoveTimeoutUpdated(value) = media.action { sentAsAction = true - let updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: message.id.peerId, operation: .setMessageAutoremoveTimeout(layer: layer, actionGloballyUniqueId: message.globallyUniqueId!, timeout: value, messageId: message.id), state: state) + let updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: message.id.peerId, operation: .setMessageAutoremoveTimeout(layer: layer, actionGloballyUniqueId: message.globallyUniqueId!, timeout: value, messageId: message.id), state: state) if updatedState != state { - modifier.setPeerChatState(message.id.peerId, state: updatedState) + transaction.setPeerChatState(message.id.peerId, state: updatedState) } } else if case .historyScreenshot = media.action { sentAsAction = true - let updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: message.id.peerId, operation: .screenshotMessages(layer: layer, actionGloballyUniqueId: message.globallyUniqueId!, globallyUniqueIds: [], messageId: message.id), state: state) + let updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: message.id.peerId, operation: .screenshotMessages(layer: layer, actionGloballyUniqueId: message.globallyUniqueId!, globallyUniqueIds: [], messageId: message.id), state: state) if updatedState != state { - modifier.setPeerChatState(message.id.peerId, state: updatedState) + transaction.setPeerChatState(message.id.peerId, state: updatedState) } } break @@ -687,7 +687,7 @@ public final class PendingMessageManager { } if sentAsAction { - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in var flags = StoreMessageFlags(message.flags) if !flags.contains(.Failed) { flags.insert(.Sending) @@ -699,11 +699,11 @@ public final class PendingMessageManager { return .update(StoreMessage(id: currentMessage.id, globallyUniqueId: currentMessage.globallyUniqueId, groupingKey: currentMessage.groupingKey, timestamp: currentMessage.timestamp, flags: flags, tags: currentMessage.tags, globalTags: currentMessage.globalTags, localTags: currentMessage.localTags, forwardInfo: storeForwardInfo, authorId: currentMessage.author?.id, text: currentMessage.text, attributes: currentMessage.attributes, media: currentMessage.media)) }) } else { - let updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: message.id.peerId, operation: .sendMessage(layer: layer, id: message.id, file: secretFile), state: state) + let updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: message.id.peerId, operation: .sendMessage(layer: layer, id: message.id, file: secretFile), state: state) if updatedState != state { - modifier.setPeerChatState(message.id.peerId, state: updatedState) + transaction.setPeerChatState(message.id.peerId, state: updatedState) } - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in var flags = StoreMessageFlags(message.flags) if !flags.contains(.Failed) { flags.insert(.Sending) @@ -716,7 +716,7 @@ public final class PendingMessageManager { }) } } else { - modifier.updateMessage(message.id, update: { currentMessage in + transaction.updateMessage(message.id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -727,15 +727,15 @@ public final class PendingMessageManager { } private func sendMessageContent(network: Network, postbox: Postbox, stateManager: AccountStateManager, messageId: MessageId, content: PendingMessageUploadedContent) -> Signal { - return postbox.modify { [weak self] modifier -> Signal in - guard let message = modifier.getMessage(messageId) else { + return postbox.transaction { [weak self] transaction -> Signal in + guard let message = transaction.getMessage(messageId) else { return .complete() } if messageId.peerId.namespace == Namespaces.Peer.SecretChat { - PendingMessageManager.sendSecretMessageContent(modifier: modifier, message: message, content: content) + PendingMessageManager.sendSecretMessageContent(transaction: transaction, message: message, content: content) return .complete() - } else if let peer = modifier.getPeer(messageId.peerId), let inputPeer = apiInputPeer(peer) { + } else if let peer = transaction.getPeer(messageId.peerId), let inputPeer = apiInputPeer(peer) { var uniqueId: Int64 = 0 var forwardSourceInfoAttribute: ForwardSourceInfoAttribute? var messageEntities: [Api.MessageEntity]? @@ -787,7 +787,7 @@ public final class PendingMessageManager { return NoError() } case let .forward(sourceInfo): - if let forwardSourceInfoAttribute = forwardSourceInfoAttribute, let sourcePeer = modifier.getPeer(forwardSourceInfoAttribute.messageId.peerId), let sourceInputPeer = apiInputPeer(sourcePeer) { + if let forwardSourceInfoAttribute = forwardSourceInfoAttribute, let sourcePeer = transaction.getPeer(forwardSourceInfoAttribute.messageId.peerId), let sourceInputPeer = apiInputPeer(sourcePeer) { sendMessageRequest = network.request(Api.functions.messages.forwardMessages(flags: 0, fromPeer: sourceInputPeer, id: [sourceInfo.messageId.id], randomId: [uniqueId], toPeer: inputPeer), tag: dependencyTag) |> mapError { _ -> NoError in return NoError() @@ -814,8 +814,8 @@ public final class PendingMessageManager { } } |> `catch` { _ -> Signal in - let modify = postbox.modify { modifier -> Void in - modifier.updateMessage(message.id, update: { currentMessage in + let modify = postbox.transaction { transaction -> Void in + transaction.updateMessage(message.id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) @@ -827,8 +827,8 @@ public final class PendingMessageManager { return modify } } else { - return postbox.modify { modifier -> Void in - modifier.updateMessage(message.id, update: { currentMessage in + return postbox.transaction { transaction -> Void in + transaction.updateMessage(message.id, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) diff --git a/TelegramCore/PendingMessageUploadedContent.swift b/TelegramCore/PendingMessageUploadedContent.swift index c7e78e0e33..5e2aa983dc 100644 --- a/TelegramCore/PendingMessageUploadedContent.swift +++ b/TelegramCore/PendingMessageUploadedContent.swift @@ -185,8 +185,8 @@ private func maybePredownloadedFileResource(postbox: Postbox, auxiliaryMethods: private func maybeCacheUploadedResource(postbox: Postbox, key: CachedSentMediaReferenceKey?, result: PendingMessageUploadedContentResult, media: Media) -> Signal { if let key = key { - return postbox.modify { modifier -> PendingMessageUploadedContentResult in - storeCachedSentMediaReference(modifier: modifier, key: key, media: media) + return postbox.transaction { transaction -> PendingMessageUploadedContentResult in + storeCachedSentMediaReference(transaction: transaction, key: key, media: media) return result } |> mapError { _ -> PendingMessageUploadError in return .generic } } else { @@ -229,8 +229,8 @@ private func uploadedMediaImageContent(network: Network, postbox: Postbox, trans flags |= 1 << 1 ttlSeconds = autoremoveAttribute.timeout } - return postbox.modify { modifier -> Api.InputPeer? in - return modifier.getPeer(peerId).flatMap(apiInputPeer) + return postbox.transaction { transaction -> Api.InputPeer? in + return transaction.getPeer(peerId).flatMap(apiInputPeer) } |> mapError { _ -> PendingMessageUploadError in return .generic } |> mapToSignal { inputPeer -> Signal in @@ -413,11 +413,11 @@ private func uploadedMediaFileContent(network: Network, postbox: Postbox, auxili if let transformOutgoingMessageMedia = transformOutgoingMessageMedia, let messageId = messageId, !alreadyTransformed { transform = .single(.pending) |> then(transformOutgoingMessageMedia(postbox, network, file, false) |> mapToSignal { media -> Signal in - return postbox.modify { modifier -> UploadedMediaTransform in + return postbox.transaction { transaction -> UploadedMediaTransform in if let media = media { if let id = media.id { - modifier.updateMedia(id, update: media) - modifier.updateMessage(messageId, update: { currentMessage in + transaction.updateMedia(id, update: media) + transaction.updateMessage(messageId, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: nil) @@ -498,8 +498,8 @@ private func uploadedMediaFileContent(network: Network, postbox: Postbox, auxili return .single(.content(.media(.inputMediaUploadedDocument(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: nil, ttlSeconds: ttlSeconds), text))) } - return postbox.modify { modifier -> Api.InputPeer? in - return modifier.getPeer(peerId).flatMap(apiInputPeer) + return postbox.transaction { transaction -> Api.InputPeer? in + return transaction.getPeer(peerId).flatMap(apiInputPeer) } |> mapError { _ -> PendingMessageUploadError in return .generic } |> mapToSignal { inputPeer -> Signal in diff --git a/TelegramCore/ProcessSecretChatIncomingDecryptedOperations.swift b/TelegramCore/ProcessSecretChatIncomingDecryptedOperations.swift index 8270380d25..3f8a506271 100644 --- a/TelegramCore/ProcessSecretChatIncomingDecryptedOperations.swift +++ b/TelegramCore/ProcessSecretChatIncomingDecryptedOperations.swift @@ -57,8 +57,8 @@ struct SecretChatOperationProcessResult { let addedMessages: [StoreMessage] } -func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: Modifier, peerId: PeerId) -> SecretChatOperationProcessResult { - if let state = modifier.getPeerChatState(peerId) as? SecretChatState, let peer = modifier.getPeer(peerId) as? TelegramSecretChat { +func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, transaction: Transaction, peerId: PeerId) -> SecretChatOperationProcessResult { + if let state = transaction.getPeerChatState(peerId) as? SecretChatState, let peer = transaction.getPeer(peerId) as? TelegramSecretChat { var removeTagLocalIndices: [Int32] = [] var addedDecryptedOperations = false var updatedState = state @@ -67,7 +67,7 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: var updatedPeer = peer var addedMessages: [StoreMessage] = [] - modifier.operationLogEnumerateEntries(peerId: peerId, tag: OperationLogTags.SecretIncomingDecrypted, { entry in + transaction.operationLogEnumerateEntries(peerId: peerId, tag: OperationLogTags.SecretIncomingDecrypted, { entry in if let operation = entry.contents as? SecretChatIncomingDecryptedOperation, let serviceAction = parsedServiceAction(operation), case let .resendOperations(fromSeq, toSeq) = serviceAction { switch updatedState.role { case .creator: @@ -86,7 +86,7 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: if fromOperationIndex <= toOperationIndex { for index in fromOperationIndex ... toOperationIndex { var notFound = false - modifier.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: index, { entry in + transaction.operationLogUpdateEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: index, { entry in if let _ = entry { return PeerOperationLogEntryUpdate(mergedIndex: .newAutomatic, contents: .none) } else { notFound = true @@ -107,7 +107,7 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: }) if !couldNotResendRequestedMessages { - modifier.operationLogEnumerateEntries(peerId: peerId, tag: OperationLogTags.SecretIncomingDecrypted, { entry in + transaction.operationLogEnumerateEntries(peerId: peerId, tag: OperationLogTags.SecretIncomingDecrypted, { entry in if let operation = entry.contents as? SecretChatIncomingDecryptedOperation { do { var message: StoreMessage? @@ -129,7 +129,7 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: case .layer46: if let parsedObject = SecretApi46.parse(Buffer(bufferNoCopy: operation.contents)), let apiMessage = parsedObject as? SecretApi46.DecryptedMessage { if let (parsedMessage, parsedResources) = parseMessage(peerId: peerId, authorId: updatedPeer.regularPeerId, tagLocalIndex: entry.tagLocalIndex, timestamp: operation.timestamp, apiMessage: apiMessage, file: operation.file, messageIdForGloballyUniqueMessageId: { id in - return modifier.messageIdForGloballyUniqueMessageId(peerId: peerId, id: id) + return transaction.messageIdForGloballyUniqueMessageId(peerId: peerId, id: id) }) { message = parsedMessage resources = parsedResources @@ -141,7 +141,7 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: case .layer73: if let parsedObject = SecretApi73.parse(Buffer(bufferNoCopy: operation.contents)), let apiMessage = parsedObject as? SecretApi73.DecryptedMessage { if let (parsedMessage, parsedResources) = parseMessage(peerId: peerId, authorId: updatedPeer.regularPeerId, tagLocalIndex: entry.tagLocalIndex, timestamp: operation.timestamp, apiMessage: apiMessage, file: operation.file, messageIdForGloballyUniqueMessageId: { id in - return modifier.messageIdForGloballyUniqueMessageId(peerId: peerId, id: id) + return transaction.messageIdForGloballyUniqueMessageId(peerId: peerId, id: id) }) { message = parsedMessage resources = parsedResources @@ -174,7 +174,7 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: let role = updatedState.role let fromSeqNo: Int32 = (topProcessedCanonicalIncomingOperationIndex + 1) * 2 + (role == .creator ? 0 : 1) let toSeqNo: Int32 = (canonicalIncomingIndex - 1) * 2 + (role == .creator ? 0 : 1) - updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: SecretChatOutgoingOperationContents.resendOperations(layer: layer, actionGloballyUniqueId: arc4random64(), fromSeqNo: fromSeqNo, toSeqNo: toSeqNo), state: updatedState) + updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: SecretChatOutgoingOperationContents.resendOperations(layer: layer, actionGloballyUniqueId: arc4random64(), fromSeqNo: fromSeqNo, toSeqNo: toSeqNo), state: updatedState) } else { assertionFailure() } @@ -188,7 +188,7 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: let role = updatedState.role let fromSeqNo: Int32 = Int32(0 * 2) + (role == .creator ? Int32(0) : Int32(1)) let toSeqNo: Int32 = (canonicalIncomingIndex - 1) * 2 + (role == .creator ? 0 : 1) - updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: SecretChatOutgoingOperationContents.resendOperations(layer: layer, actionGloballyUniqueId: arc4random64(), fromSeqNo: fromSeqNo, toSeqNo: toSeqNo), state: updatedState) + updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: SecretChatOutgoingOperationContents.resendOperations(layer: layer, actionGloballyUniqueId: arc4random64(), fromSeqNo: fromSeqNo, toSeqNo: toSeqNo), state: updatedState) } else { assertionFailure() } @@ -212,13 +212,13 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: throw MessageParsingError.invalidChatState case .basicLayer: if layerSupport >= 73 { - let sequenceBasedLayerState = SecretChatSequenceBasedLayerState(layerNegotiationState: SecretChatLayerNegotiationState(activeLayer: .layer73, locallyRequestedLayer: 73, remotelyRequestedLayer: layerSupport), rekeyState: nil, baseIncomingOperationIndex: entry.tagLocalIndex, baseOutgoingOperationIndex: modifier.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing), topProcessedCanonicalIncomingOperationIndex: nil) + let sequenceBasedLayerState = SecretChatSequenceBasedLayerState(layerNegotiationState: SecretChatLayerNegotiationState(activeLayer: .layer73, locallyRequestedLayer: 73, remotelyRequestedLayer: layerSupport), rekeyState: nil, baseIncomingOperationIndex: entry.tagLocalIndex, baseOutgoingOperationIndex: transaction.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing), topProcessedCanonicalIncomingOperationIndex: nil) updatedState = updatedState.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceBasedLayerState)) - updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: .reportLayerSupport(layer: .layer73, actionGloballyUniqueId: arc4random64(), layerSupport: 73), state: updatedState) + updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: .reportLayerSupport(layer: .layer73, actionGloballyUniqueId: arc4random64(), layerSupport: 73), state: updatedState) } else if layerSupport >= 46 { - let sequenceBasedLayerState = SecretChatSequenceBasedLayerState(layerNegotiationState: SecretChatLayerNegotiationState(activeLayer: .layer46, locallyRequestedLayer: 46, remotelyRequestedLayer: layerSupport), rekeyState: nil, baseIncomingOperationIndex: entry.tagLocalIndex, baseOutgoingOperationIndex: modifier.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing), topProcessedCanonicalIncomingOperationIndex: nil) + let sequenceBasedLayerState = SecretChatSequenceBasedLayerState(layerNegotiationState: SecretChatLayerNegotiationState(activeLayer: .layer46, locallyRequestedLayer: 46, remotelyRequestedLayer: layerSupport), rekeyState: nil, baseIncomingOperationIndex: entry.tagLocalIndex, baseOutgoingOperationIndex: transaction.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing), topProcessedCanonicalIncomingOperationIndex: nil) updatedState = updatedState.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceBasedLayerState)) - updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: .reportLayerSupport(layer: .layer46, actionGloballyUniqueId: arc4random64(), layerSupport: 73), state: updatedState) + updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: .reportLayerSupport(layer: .layer46, actionGloballyUniqueId: arc4random64(), layerSupport: 73), state: updatedState) } else { throw MessageParsingError.contentParsingError } @@ -227,35 +227,35 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: let updatedNegotiationState = sequenceState.layerNegotiationState.withUpdatedRemotelyRequestedLayer(layerSupport) updatedState = updatedState.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedLayerNegotiationState(updatedNegotiationState))) - updatedState = secretChatCheckLayerNegotiationIfNeeded(modifier: modifier, peerId: peerId, state: updatedState) + updatedState = secretChatCheckLayerNegotiationIfNeeded(transaction: transaction, peerId: peerId, state: updatedState) } } case let .setMessageAutoremoveTimeout(timeout): updatedPeer = updatedPeer.withUpdatedMessageAutoremoveTimeout(timeout == 0 ? nil : timeout) updatedState = updatedState.withUpdatedMessageAutoremoveTimeout(timeout == 0 ? nil : timeout) case let .rekeyAction(action): - updatedState = secretChatAdvanceRekeySessionIfNeeded(modifier: modifier, peerId: peerId, state: updatedState, action: action) + updatedState = secretChatAdvanceRekeySessionIfNeeded(transaction: transaction, peerId: peerId, state: updatedState, action: action) case let .deleteMessages(globallyUniqueIds): var messageIds: [MessageId] = [] for id in globallyUniqueIds { - if let messageId = modifier.messageIdForGloballyUniqueMessageId(peerId: peerId, id: id) { + if let messageId = transaction.messageIdForGloballyUniqueMessageId(peerId: peerId, id: id) { messageIds.append(messageId) } } if !messageIds.isEmpty { - modifier.deleteMessages(messageIds) + transaction.deleteMessages(messageIds) } case .clearHistory: - modifier.clearHistory(peerId) + transaction.clearHistory(peerId) case let .markMessagesContentAsConsumed(globallyUniqueIds): var messageIds: [MessageId] = [] for id in globallyUniqueIds { - if let messageId = modifier.messageIdForGloballyUniqueMessageId(peerId: peerId, id: id) { + if let messageId = transaction.messageIdForGloballyUniqueMessageId(peerId: peerId, id: id) { messageIds.append(messageId) } } for messageId in messageIds { - markMessageContentAsConsumedRemotely(modifier: modifier, messageId: messageId) + markMessageContentAsConsumedRemotely(transaction: transaction, messageId: messageId) } default: break @@ -274,7 +274,7 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: for (resource, data) in resources { mediaBox.storeResourceData(resource.id, data: data) } - let _ = modifier.addMessages([message], location: .Random) + let _ = transaction.addMessages([message], location: .Random) addedMessages.append(message) } } catch let error { @@ -310,7 +310,7 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: }) } for index in removeTagLocalIndices { - let removed = modifier.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretIncomingDecrypted, tagLocalIndex: index) + let removed = transaction.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretIncomingDecrypted, tagLocalIndex: index) assert(removed) } if let maxAcknowledgedCanonicalOperationIndex = maxAcknowledgedCanonicalOperationIndex { @@ -318,17 +318,17 @@ func processSecretChatIncomingDecryptedOperations(mediaBox: MediaBox, modifier: case let .sequenceBasedLayer(sequenceState): let tagLocalIndex = max(0, sequenceState.outgoingOperationIndexFromCanonicalOperationIndex(maxAcknowledgedCanonicalOperationIndex) - 1) //Logger.shared.log("SecretChat", "peer \(peerId) dropping acknowledged operations <= \(tagLocalIndex)") - modifier.operationLogRemoveEntries(peerId: peerId, tag: OperationLogTags.SecretOutgoing, withTagLocalIndicesEqualToOrLowerThan: tagLocalIndex) + transaction.operationLogRemoveEntries(peerId: peerId, tag: OperationLogTags.SecretOutgoing, withTagLocalIndicesEqualToOrLowerThan: tagLocalIndex) default: break } } if updatedState != state { - modifier.setPeerChatState(peerId, state: updatedState) + transaction.setPeerChatState(peerId, state: updatedState) updatedPeer = updatedPeer.withUpdatedEmbeddedState(updatedState.embeddedState.peerState) } if !peer.isEqual(updatedPeer) { - updatePeers(modifier: modifier, peers: [updatedPeer], update: { _, updated in + updatePeers(transaction: transaction, peers: [updatedPeer], update: { _, updated in return updated }) } diff --git a/TelegramCore/ProcessSecretChatIncomingEncryptedOperations.swift b/TelegramCore/ProcessSecretChatIncomingEncryptedOperations.swift index 8c35215651..562cf0b7e2 100644 --- a/TelegramCore/ProcessSecretChatIncomingEncryptedOperations.swift +++ b/TelegramCore/ProcessSecretChatIncomingEncryptedOperations.swift @@ -11,12 +11,12 @@ private enum MessagePreParsingError: Error { case protocolViolation } -func processSecretChatIncomingEncryptedOperations(modifier: Modifier, peerId: PeerId) -> Bool { - if let state = modifier.getPeerChatState(peerId) as? SecretChatState { +func processSecretChatIncomingEncryptedOperations(transaction: Transaction, peerId: PeerId) -> Bool { + if let state = transaction.getPeerChatState(peerId) as? SecretChatState { var updatedState = state var removeTagLocalIndices: [Int32] = [] var addedDecryptedOperations = false - modifier.operationLogEnumerateEntries(peerId: peerId, tag: OperationLogTags.SecretIncomingEncrypted, { entry in + transaction.operationLogEnumerateEntries(peerId: peerId, tag: OperationLogTags.SecretIncomingEncrypted, { entry in if let operation = entry.contents as? SecretChatIncomingEncryptedOperation { if let key = updatedState.keychain.key(fingerprint: operation.keyFingerprint) { var decryptedContents = withDecryptedMessageContents(parameters: SecretChatEncryptionParameters(key: key, mode: .v2(role: updatedState.role)), data: operation.contents) @@ -92,9 +92,9 @@ func processSecretChatIncomingEncryptedOperations(modifier: Modifier, peerId: Pe throw MessagePreParsingError.protocolViolation } - let sequenceBasedLayerState = SecretChatSequenceBasedLayerState(layerNegotiationState: SecretChatLayerNegotiationState(activeLayer: secretChatCommonSupportedLayer(remoteLayer: parsedLayer), locallyRequestedLayer: nil, remotelyRequestedLayer: nil), rekeyState: nil, baseIncomingOperationIndex: entry.tagLocalIndex, baseOutgoingOperationIndex: modifier.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing), topProcessedCanonicalIncomingOperationIndex: nil) + let sequenceBasedLayerState = SecretChatSequenceBasedLayerState(layerNegotiationState: SecretChatLayerNegotiationState(activeLayer: secretChatCommonSupportedLayer(remoteLayer: parsedLayer), locallyRequestedLayer: nil, remotelyRequestedLayer: nil), rekeyState: nil, baseIncomingOperationIndex: entry.tagLocalIndex, baseOutgoingOperationIndex: transaction.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing), topProcessedCanonicalIncomingOperationIndex: nil) updatedState = updatedState.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceBasedLayerState)) - modifier.setPeerChatState(peerId, state: updatedState) + transaction.setPeerChatState(peerId, state: updatedState) entryTagLocalIndex = .manual(sequenceBasedLayerState.baseIncomingOperationIndex + sequenceInfo.operationIndex) } else { if parsedLayer != 8 && parsedLayer != 17 { @@ -110,7 +110,7 @@ func processSecretChatIncomingEncryptedOperations(modifier: Modifier, peerId: Pe entryTagLocalIndex = .manual(sequenceState.baseIncomingOperationIndex + sequenceInfo!.operationIndex) } - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretIncomingDecrypted, tagLocalIndex: entryTagLocalIndex, tagMergedIndex: .none, contents: SecretChatIncomingDecryptedOperation(timestamp: operation.timestamp, layer: parsedLayer, sequenceInfo: sequenceInfo, contents: MemoryBuffer(messageContents), file: operation.mediaFileReference)) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretIncomingDecrypted, tagLocalIndex: entryTagLocalIndex, tagMergedIndex: .none, contents: SecretChatIncomingDecryptedOperation(timestamp: operation.timestamp, layer: parsedLayer, sequenceInfo: sequenceInfo, contents: MemoryBuffer(messageContents), file: operation.mediaFileReference)) addedDecryptedOperations = true } catch let error { if let error = error as? MessagePreParsingError { @@ -139,7 +139,7 @@ func processSecretChatIncomingEncryptedOperations(modifier: Modifier, peerId: Pe return true }) for index in removeTagLocalIndices { - let removed = modifier.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretIncomingEncrypted, tagLocalIndex: index) + let removed = transaction.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SecretIncomingEncrypted, tagLocalIndex: index) assert(removed) } return addedDecryptedOperations diff --git a/TelegramCore/ProxySettings.swift b/TelegramCore/ProxySettings.swift index b1b3369003..47fcc356fc 100644 --- a/TelegramCore/ProxySettings.swift +++ b/TelegramCore/ProxySettings.swift @@ -160,8 +160,8 @@ public struct ProxySettings: PreferencesEntry, Equatable { } public func updateProxySettingsInteractively(postbox: Postbox, network: Network, _ f: @escaping (ProxySettings) -> ProxySettings) -> Signal { - return postbox.modify { modifier -> Void in - updateProxySettingsInteractively(modifier: modifier, network: network, f) + return postbox.transaction { transaction -> Void in + updateProxySettingsInteractively(transaction: transaction, network: network, f) } } @@ -176,10 +176,10 @@ extension ProxyServerSettings { } } -public func updateProxySettingsInteractively(modifier: Modifier, network: Network, _ f: @escaping (ProxySettings) -> ProxySettings) { +public func updateProxySettingsInteractively(transaction: Transaction, network: Network, _ f: @escaping (ProxySettings) -> ProxySettings) { var updateNetwork = false var updatedSettings: ProxySettings? - modifier.updatePreferencesEntry(key: PreferencesKeys.proxySettings, { current in + transaction.updatePreferencesEntry(key: PreferencesKeys.proxySettings, { current in let previous = (current as? ProxySettings) ?? ProxySettings.defaultSettings let updated = f(previous) updatedSettings = updated diff --git a/TelegramCore/RecentPeers.swift b/TelegramCore/RecentPeers.swift index 1dfe619d35..9c605222b6 100644 --- a/TelegramCore/RecentPeers.swift +++ b/TelegramCore/RecentPeers.swift @@ -35,10 +35,10 @@ public func recentPeers(account: Account) -> Signal<[Peer], NoError> { let updatedRemotePeers = remotePeers |> mapToSignal { peersAndPresences -> Signal<[Peer], NoError> in if let (peers, peerPresences) = peersAndPresences { - return account.postbox.modify { modifier -> [Peer] in - updatePeers(modifier: modifier, peers: peers, update: { return $1 }) - modifier.updatePeerPresences(peerPresences) - modifier.replaceRecentPeerIds(peers.map({ $0.id })) + return account.postbox.transaction { transaction -> [Peer] in + updatePeers(transaction: transaction, peers: peers, update: { return $1 }) + transaction.updatePeerPresences(peerPresences) + transaction.replaceRecentPeerIds(peers.map({ $0.id })) return peers } } else { @@ -53,13 +53,13 @@ public func recentPeers(account: Account) -> Signal<[Peer], NoError> { } public func removeRecentPeer(account: Account, peerId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - var peerIds = modifier.getRecentPeerIds() + return account.postbox.transaction { transaction -> Signal in + var peerIds = transaction.getRecentPeerIds() if let index = peerIds.index(of: peerId) { peerIds.remove(at: index) - modifier.replaceRecentPeerIds(peerIds) + transaction.replaceRecentPeerIds(peerIds) } - if let peer = modifier.getPeer(peerId), let apiPeer = apiInputPeer(peer) { + if let peer = transaction.getPeer(peerId), let apiPeer = apiInputPeer(peer) { return account.network.request(Api.functions.contacts.resetTopPeerRating(category: .topPeerCategoryCorrespondents, peer: apiPeer)) |> `catch` { _ -> Signal in return .single(.boolFalse) @@ -110,13 +110,13 @@ public func managedRecentlyUsedInlineBots(postbox: Postbox, network: Network) -> let updatedRemotePeers = remotePeers |> mapToSignal { peersAndPresences -> Signal in if let (peers, peerPresences, peersWithRating) = peersAndPresences { - return postbox.modify { modifier -> Void in - updatePeers(modifier: modifier, peers: peers, update: { return $1 }) - modifier.updatePeerPresences(peerPresences) + return postbox.transaction { transaction -> Void in + updatePeers(transaction: transaction, peers: peers, update: { return $1 }) + transaction.updatePeerPresences(peerPresences) let sortedPeersWithRating = peersWithRating.sorted(by: { $0.1 > $1.1 }) - modifier.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.CloudRecentInlineBots, items: sortedPeersWithRating.map { (peerId, rating) in + transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.CloudRecentInlineBots, items: sortedPeersWithRating.map { (peerId, rating) in return OrderedItemListEntry(id: RecentPeerItemId(peerId).rawValue, contents: RecentPeerItem(rating: rating)) }) } @@ -129,14 +129,14 @@ public func managedRecentlyUsedInlineBots(postbox: Postbox, network: Network) -> } public func addRecentlyUsedInlineBot(postbox: Postbox, peerId: PeerId) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in var maxRating = 1.0 - for entry in modifier.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudRecentInlineBots) { + for entry in transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudRecentInlineBots) { if let contents = entry.contents as? RecentPeerItem { maxRating = max(maxRating, contents.rating) } } - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentInlineBots, item: OrderedItemListEntry(id: RecentPeerItemId(peerId).rawValue, contents: RecentPeerItem(rating: maxRating)), removeTailIfCountExceeds: 20) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentInlineBots, item: OrderedItemListEntry(id: RecentPeerItemId(peerId).rawValue, contents: RecentPeerItem(rating: maxRating)), removeTailIfCountExceeds: 20) } } @@ -144,12 +144,12 @@ public func recentlyUsedInlineBots(postbox: Postbox) -> Signal<[(Peer, Double)], return postbox.combinedView(keys: [.orderedItemList(id: Namespaces.OrderedItemList.CloudRecentInlineBots)]) |> take(1) |> mapToSignal { view -> Signal<[(Peer, Double)], NoError> in - return postbox.modify { modifier -> [(Peer, Double)] in + return postbox.transaction { transaction -> [(Peer, Double)] in var peers: [(Peer, Double)] = [] if let view = view.views[.orderedItemList(id: Namespaces.OrderedItemList.CloudRecentInlineBots)] as? OrderedItemListView { for item in view.items { let peerId = RecentPeerItemId(item.id).peerId - if let peer = modifier.getPeer(peerId), let contents = item.contents as? RecentPeerItem { + if let peer = transaction.getPeer(peerId), let contents = item.contents as? RecentPeerItem { peers.append((peer, contents.rating)) } } diff --git a/TelegramCore/RecentlySearchedPeerIds.swift b/TelegramCore/RecentlySearchedPeerIds.swift index 15a970ab35..5e2649f139 100644 --- a/TelegramCore/RecentlySearchedPeerIds.swift +++ b/TelegramCore/RecentlySearchedPeerIds.swift @@ -8,36 +8,36 @@ import Foundation #endif public func addRecentlySearchedPeer(postbox: Postbox, peerId: PeerId) -> Signal { - return postbox.modify { modifier -> Void in - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlySearchedPeerIds, item: OrderedItemListEntry(id: RecentPeerItemId(peerId).rawValue, contents: RecentPeerItem(rating: 0.0)), removeTailIfCountExceeds: 20) + return postbox.transaction { transaction -> Void in + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlySearchedPeerIds, item: OrderedItemListEntry(id: RecentPeerItemId(peerId).rawValue, contents: RecentPeerItem(rating: 0.0)), removeTailIfCountExceeds: 20) } } public func removeRecentlySearchedPeer(postbox: Postbox, peerId: PeerId) -> Signal { - return postbox.modify { modifier -> Void in - modifier.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlySearchedPeerIds, itemId: RecentPeerItemId(peerId).rawValue) + return postbox.transaction { transaction -> Void in + transaction.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlySearchedPeerIds, itemId: RecentPeerItemId(peerId).rawValue) } } public func clearRecentlySearchedPeers(postbox: Postbox) -> Signal { - return postbox.modify { modifier -> Void in - modifier.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.RecentlySearchedPeerIds, items: []) + return postbox.transaction { transaction -> Void in + transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.RecentlySearchedPeerIds, items: []) } } public func recentlySearchedPeers(postbox: Postbox) -> Signal<[RenderedPeer], NoError> { return postbox.combinedView(keys: [.orderedItemList(id: Namespaces.OrderedItemList.RecentlySearchedPeerIds)]) |> mapToSignal { view -> Signal<[RenderedPeer], NoError> in - return postbox.modify { modifier -> [RenderedPeer] in + return postbox.transaction { transaction -> [RenderedPeer] in var result: [RenderedPeer] = [] if let view = view.views[.orderedItemList(id: Namespaces.OrderedItemList.RecentlySearchedPeerIds)] as? OrderedItemListView { for item in view.items { let peerId = RecentPeerItemId(item.id).peerId - if let peer = modifier.getPeer(peerId) { + if let peer = transaction.getPeer(peerId) { var peers = SimpleDictionary() peers[peer.id] = peer if let associatedPeerId = peer.associatedPeerId { - if let associatedPeer = modifier.getPeer(associatedPeerId) { + if let associatedPeer = transaction.getPeer(associatedPeerId) { peers[associatedPeer.id] = associatedPeer } } diff --git a/TelegramCore/RecentlyUsedHashtags.swift b/TelegramCore/RecentlyUsedHashtags.swift index 75f830c4cc..4e21bf102c 100644 --- a/TelegramCore/RecentlyUsedHashtags.swift +++ b/TelegramCore/RecentlyUsedHashtags.swift @@ -38,16 +38,16 @@ final class RecentHashtagItem: OrderedItemListEntryContents { } } -func addRecentlyUsedHashtag(modifier: Modifier, string: String) { +func addRecentlyUsedHashtag(transaction: Transaction, string: String) { if let itemId = RecentHashtagItemId(string) { - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlyUsedHashtags, item: OrderedItemListEntry(id: itemId.rawValue, contents: RecentHashtagItem()), removeTailIfCountExceeds: 100) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlyUsedHashtags, item: OrderedItemListEntry(id: itemId.rawValue, contents: RecentHashtagItem()), removeTailIfCountExceeds: 100) } } public func removeRecentlyUsedHashtag(postbox: Postbox, string: String) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in if let itemId = RecentHashtagItemId(string) { - modifier.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlyUsedHashtags, itemId: itemId.rawValue) + transaction.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlyUsedHashtags, itemId: itemId.rawValue) } } } @@ -55,7 +55,7 @@ public func removeRecentlyUsedHashtag(postbox: Postbox, string: String) -> Signa public func recentlyUsedHashtags(postbox: Postbox) -> Signal<[String], NoError> { return postbox.combinedView(keys: [.orderedItemList(id: Namespaces.OrderedItemList.RecentlyUsedHashtags)]) |> mapToSignal { view -> Signal<[String], NoError> in - return postbox.modify { modifier -> [String] in + return postbox.transaction { transaction -> [String] in var result: [String] = [] if let view = view.views[.orderedItemList(id: Namespaces.OrderedItemList.RecentlyUsedHashtags)] as? OrderedItemListView { for item in view.items { diff --git a/TelegramCore/RemovePeerChat.swift b/TelegramCore/RemovePeerChat.swift index 30a22bb660..a4035be671 100644 --- a/TelegramCore/RemovePeerChat.swift +++ b/TelegramCore/RemovePeerChat.swift @@ -8,33 +8,33 @@ import Foundation #endif public func removePeerChat(postbox: Postbox, peerId: PeerId, reportChatSpam: Bool) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in if peerId.namespace == Namespaces.Peer.SecretChat { - if let state = modifier.getPeerChatState(peerId) as? SecretChatState { + if let state = transaction.getPeerChatState(peerId) as? SecretChatState { - let updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: SecretChatOutgoingOperationContents.terminate(reportSpam: reportChatSpam), state: state).withUpdatedEmbeddedState(.terminated) + let updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: SecretChatOutgoingOperationContents.terminate(reportSpam: reportChatSpam), state: state).withUpdatedEmbeddedState(.terminated) if updatedState != state { - modifier.setPeerChatState(peerId, state: updatedState) - if let peer = modifier.getPeer(peerId) as? TelegramSecretChat { - updatePeers(modifier: modifier, peers: [peer.withUpdatedEmbeddedState(updatedState.embeddedState.peerState)], update: { _, updated in + transaction.setPeerChatState(peerId, state: updatedState) + if let peer = transaction.getPeer(peerId) as? TelegramSecretChat { + updatePeers(transaction: transaction, peers: [peer.withUpdatedEmbeddedState(updatedState.embeddedState.peerState)], update: { _, updated in return updated }) } } } - modifier.clearHistory(peerId) - modifier.updatePeerChatListInclusion(peerId, inclusion: .never) - modifier.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlySearchedPeerIds, itemId: RecentPeerItemId(peerId).rawValue) + transaction.clearHistory(peerId) + transaction.updatePeerChatListInclusion(peerId, inclusion: .never) + transaction.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentlySearchedPeerIds, itemId: RecentPeerItemId(peerId).rawValue) } else { - cloudChatAddRemoveChatOperation(modifier: modifier, peerId: peerId, reportChatSpam: reportChatSpam) + cloudChatAddRemoveChatOperation(transaction: transaction, peerId: peerId, reportChatSpam: reportChatSpam) if peerId.namespace == Namespaces.Peer.CloudUser { - modifier.updatePeerChatListInclusion(peerId, inclusion: .ifHasMessages) - modifier.clearHistory(peerId) + transaction.updatePeerChatListInclusion(peerId, inclusion: .ifHasMessages) + transaction.clearHistory(peerId) } else if peerId.namespace == Namespaces.Peer.CloudGroup { - modifier.updatePeerChatListInclusion(peerId, inclusion: .never) - modifier.clearHistory(peerId) + transaction.updatePeerChatListInclusion(peerId, inclusion: .never) + transaction.clearHistory(peerId) } else { - modifier.updatePeerChatListInclusion(peerId, inclusion: .never) + transaction.updatePeerChatListInclusion(peerId, inclusion: .never) } } } diff --git a/TelegramCore/RemovePeerMember.swift b/TelegramCore/RemovePeerMember.swift index 45ca21171e..e59b866ff1 100644 --- a/TelegramCore/RemovePeerMember.swift +++ b/TelegramCore/RemovePeerMember.swift @@ -18,8 +18,8 @@ public func removePeerMember(account: Account, peerId: PeerId, memberId: PeerId) } } - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let memberPeer = modifier.getPeer(memberId), let inputUser = apiInputUser(memberPeer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let memberPeer = transaction.getPeer(memberId), let inputUser = apiInputUser(memberPeer) { if let group = peer as? TelegramGroup { return account.network.request(Api.functions.messages.deleteChatUser(chatId: group.id.id, userId: inputUser)) |> mapError { error -> Void in @@ -31,8 +31,8 @@ public func removePeerMember(account: Account, peerId: PeerId, memberId: PeerId) |> mapToSignal { result -> Signal in account.stateManager.addUpdates(result) - return account.postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in + return account.postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in if let cachedData = cachedData as? CachedGroupData, let participants = cachedData.participants { var updatedParticipants = participants.participants for i in 0 ..< participants.participants.count { diff --git a/TelegramCore/ReportPeer.swift b/TelegramCore/ReportPeer.swift index 2f715b7a74..84ea58bd07 100644 --- a/TelegramCore/ReportPeer.swift +++ b/TelegramCore/ReportPeer.swift @@ -10,8 +10,8 @@ import Foundation #endif public func reportPeer(account: Account, peerId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) { if let peer = peer as? TelegramSecretChat { return account.network.request(Api.functions.messages.reportEncryptedSpam(peer: Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id, accessHash: peer.accessHash))) |> map { Optional($0) } @@ -19,9 +19,9 @@ public func reportPeer(account: Account, peerId: PeerId) -> Signal mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if result != nil { - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedUserData { return current.withUpdatedReportStatus(.didReport) } else if let current = current as? CachedGroupData { @@ -42,9 +42,9 @@ public func reportPeer(account: Account, peerId: PeerId) -> Signal mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if result != nil { - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedUserData { return current.withUpdatedReportStatus(.didReport) } else if let current = current as? CachedGroupData { @@ -119,8 +119,8 @@ private extension ReportReason { } public func reportPeer(account: Account, peerId:PeerId, reason:ReportReason) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let inputPeer = apiInputPeer(peer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) { return account.network.request(Api.functions.account.reportPeer(peer: inputPeer, reason: reason.apiReason)) |> mapError {_ in} |> map {_ in} } else { return .complete() @@ -129,8 +129,8 @@ public func reportPeer(account: Account, peerId:PeerId, reason:ReportReason) -> } public func reportSupergroupPeer(account: Account, peerId:PeerId, memberId:PeerId, messageIds:[MessageId]) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId), let inputPeer = apiInputChannel(peer), let memberPeer = modifier.getPeer(memberId), let inputMember = apiInputUser(memberPeer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId), let inputPeer = apiInputChannel(peer), let memberPeer = transaction.getPeer(memberId), let inputMember = apiInputUser(memberPeer) { return account.network.request(Api.functions.channels.reportSpam(channel: inputPeer, userId: inputMember, id: messageIds.map({$0.id}))) |> mapError {_ in} |> map {_ in} } else { return .complete() @@ -139,8 +139,8 @@ public func reportSupergroupPeer(account: Account, peerId:PeerId, memberId:PeerI } public func dismissReportPeer(account: Account, peerId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Signal in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + return account.postbox.transaction { transaction -> Signal in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedUserData { return current.withUpdatedReportStatus(.none) } else if let current = current as? CachedGroupData { @@ -154,7 +154,7 @@ public func dismissReportPeer(account: Account, peerId: PeerId) -> Signal `catch` { _ -> Signal in return .single(.boolFalse) diff --git a/TelegramCore/RequestChatContextResults.swift b/TelegramCore/RequestChatContextResults.swift index 5701c7d56a..0edcda8ff4 100644 --- a/TelegramCore/RequestChatContextResults.swift +++ b/TelegramCore/RequestChatContextResults.swift @@ -10,8 +10,8 @@ import Foundation #endif public func requestChatContextResults(account: Account, botId: PeerId, peerId: PeerId, query: String, location: Signal<(Double, Double)?, NoError> = .single(nil), offset: String) -> Signal { - return combineLatest(account.postbox.modify { modifier -> (bot: Peer, peer: Peer)? in - if let bot = modifier.getPeer(botId), let peer = modifier.getPeer(peerId) { + return combineLatest(account.postbox.transaction { transaction -> (bot: Peer, peer: Peer)? in + if let bot = transaction.getPeer(botId), let peer = transaction.getPeer(peerId) { return (bot, peer) } else { return nil diff --git a/TelegramCore/RequestEditMessage.swift b/TelegramCore/RequestEditMessage.swift index 2f689c29af..6cdaa615e0 100644 --- a/TelegramCore/RequestEditMessage.swift +++ b/TelegramCore/RequestEditMessage.swift @@ -58,8 +58,8 @@ public func requestEditMessage(account: Account, messageId: MessageId, text: Str pendingMediaContent = content } } - return account.postbox.modify { modifier -> (Peer?, SimpleDictionary) in - guard let message = modifier.getMessage(messageId) else { + return account.postbox.transaction { transaction -> (Peer?, SimpleDictionary) in + guard let message = transaction.getMessage(messageId) else { return (nil, SimpleDictionary()) } @@ -78,12 +78,12 @@ public func requestEditMessage(account: Account, messageId: MessageId, text: Str if let entities = entities { for peerId in entities.associatedPeerIds { - if let peer = modifier.getPeer(peerId) { + if let peer = transaction.getPeer(peerId) { peers[peer.id] = peer } } } - return (modifier.getPeer(messageId.peerId), peers) + return (transaction.getPeer(messageId.peerId), peers) } |> mapToSignal { peer, associatedPeers -> Signal in if let peer = peer, let inputPeer = apiInputPeer(peer) { @@ -128,7 +128,7 @@ public func requestEditMessage(account: Account, messageId: MessageId, text: Str } |> mapToSignal { result -> Signal in if let result = result { - return account.postbox.modify { modifier -> RequestEditMessageResult in + return account.postbox.transaction { transaction -> RequestEditMessageResult in var toMedia: Media? if let message = result.messages.first.flatMap(StoreMessage.init(apiMessage:)) { toMedia = message.media.first @@ -154,8 +154,8 @@ public func requestEditMessage(account: Account, messageId: MessageId, text: Str } public func requestEditLiveLocation(postbox: Postbox, network: Network, stateManager: AccountStateManager, messageId: MessageId, coordinate: (latitude: Double, longitude: Double)?) -> Signal { - return postbox.modify { modifier -> Api.InputPeer? in - return modifier.getPeer(messageId.peerId).flatMap(apiInputPeer) + return postbox.transaction { transaction -> Api.InputPeer? in + return transaction.getPeer(messageId.peerId).flatMap(apiInputPeer) } |> mapToSignal { inputPeer -> Signal in if let inputPeer = inputPeer { @@ -175,8 +175,8 @@ public func requestEditLiveLocation(postbox: Postbox, network: Network, stateMan stateManager.addUpdates(updates) } if coordinate == nil { - return postbox.modify { modifier -> Void in - modifier.updateMessage(messageId, update: { currentMessage in + return postbox.transaction { transaction -> Void in + transaction.updateMessage(messageId, update: { currentMessage in var storeForwardInfo: StoreMessageForwardInfo? if let forwardInfo = currentMessage.forwardInfo { storeForwardInfo = StoreMessageForwardInfo(authorId: forwardInfo.author.id, sourceId: forwardInfo.source?.id, sourceMessageId: forwardInfo.sourceMessageId, date: forwardInfo.date, authorSignature: forwardInfo.authorSignature) diff --git a/TelegramCore/RequestSecureIdForm.swift b/TelegramCore/RequestSecureIdForm.swift index 38b5909b8e..f4c19ec30a 100644 --- a/TelegramCore/RequestSecureIdForm.swift +++ b/TelegramCore/RequestSecureIdForm.swift @@ -241,7 +241,7 @@ public func requestSecureIdForm(postbox: Postbox, network: Network, peerId: Peer return .serverError(error.errorDescription) } |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> EncryptedSecureIdForm in + return postbox.transaction { transaction -> EncryptedSecureIdForm in switch result { case let .authorizationForm(flags, requiredTypes, values, errors, users, termsUrl): var peers: [Peer] = [] @@ -249,7 +249,7 @@ public func requestSecureIdForm(postbox: Postbox, network: Network, peerId: Peer let parsed = TelegramUser(user: user) peers.append(parsed) } - updatePeers(modifier: modifier, peers: peers, update: { _, updated in + updatePeers(transaction: transaction, peers: peers, update: { _, updated in return updated }) diff --git a/TelegramCore/RequestUserPhotos.swift b/TelegramCore/RequestUserPhotos.swift index 1632000afb..74e1d53b24 100644 --- a/TelegramCore/RequestUserPhotos.swift +++ b/TelegramCore/RequestUserPhotos.swift @@ -19,8 +19,8 @@ public struct TelegramPeerPhoto { } public func requestPeerPhotos(account:Account, peerId:PeerId) -> Signal<[TelegramPeerPhoto], Void> { - return account.postbox.modify{ modifier -> Peer? in - return modifier.getPeer(peerId) + return account.postbox.transaction{ transaction -> Peer? in + return transaction.getPeer(peerId) } |> mapToSignal { peer -> Signal<[TelegramPeerPhoto], Void> in if let peer = peer as? TelegramUser, let inputUser = apiInputUser(peer) { return account.network.request(Api.functions.photos.getUserPhotos(userId: inputUser, offset: 0, maxId: 0, limit: 100)) @@ -93,11 +93,11 @@ public func requestPeerPhotos(account:Account, peerId:PeerId) -> Signal<[Telegra users = [] } - return account.postbox.modify { modifier -> [Message] in + return account.postbox.transaction { transaction -> [Message] in var peers: [PeerId: Peer] = [:] for user in users { - if let user = TelegramUser.merge(modifier.getPeer(user.peerId) as? TelegramUser, rhs: user) { + if let user = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { peers[user.id] = user } } diff --git a/TelegramCore/ResolvePeerByName.swift b/TelegramCore/ResolvePeerByName.swift index b822561217..0b54b09f56 100644 --- a/TelegramCore/ResolvePeerByName.swift +++ b/TelegramCore/ResolvePeerByName.swift @@ -67,8 +67,8 @@ public func resolvePeerByName(account: Account, name: String, ageLimit: Int32 = normalizedName = String(normalizedName[name.index(after: name.startIndex)...]) } - return account.postbox.modify { modifier -> CachedResolvedByNamePeer? in - return modifier.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.resolvedByNamePeers, key: CachedResolvedByNamePeer.key(name: normalizedName))) as? CachedResolvedByNamePeer + return account.postbox.transaction { transaction -> CachedResolvedByNamePeer? in + return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.resolvedByNamePeers, key: CachedResolvedByNamePeer.key(name: normalizedName))) as? CachedResolvedByNamePeer } |> mapToSignal { cachedEntry -> Signal in let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) if let cachedEntry = cachedEntry, cachedEntry.timestamp <= timestamp && cachedEntry.timestamp >= timestamp - ageLimit { @@ -79,7 +79,7 @@ public func resolvePeerByName(account: Account, name: String, ageLimit: Int32 = return NoError() } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> PeerId? in + return account.postbox.transaction { transaction -> PeerId? in var peerId: PeerId? = nil switch result { @@ -87,7 +87,7 @@ public func resolvePeerByName(account: Account, name: String, ageLimit: Int32 = var peers: [PeerId: Peer] = [:] for user in users { - if let user = TelegramUser.merge(modifier.getPeer(user.peerId) as? TelegramUser, rhs: user) { + if let user = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { peers[user.id] = user } } @@ -101,14 +101,14 @@ public func resolvePeerByName(account: Account, name: String, ageLimit: Int32 = if let peer = peers[apiPeer.peerId] { peerId = peer.id - updatePeers(modifier: modifier, peers: Array(peers.values), update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: Array(peers.values), update: { _, updated -> Peer in return updated }) } } let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) - modifier.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.resolvedByNamePeers, key: CachedResolvedByNamePeer.key(name: normalizedName)), entry: CachedResolvedByNamePeer(peerId: peerId, timestamp: timestamp), collectionSpec: resolvedByNamePeersCollectionSpec) + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.resolvedByNamePeers, key: CachedResolvedByNamePeer.key(name: normalizedName)), entry: CachedResolvedByNamePeer(peerId: peerId, timestamp: timestamp), collectionSpec: resolvedByNamePeersCollectionSpec) return peerId } } diff --git a/TelegramCore/SearchMessages.swift b/TelegramCore/SearchMessages.swift index 572871ab9f..ce1cb4ceb3 100644 --- a/TelegramCore/SearchMessages.swift +++ b/TelegramCore/SearchMessages.swift @@ -43,8 +43,8 @@ public func searchMessages(account: Account, location: SearchMessagesLocation, q switch location { case let .peer(peerId, fromId, tags): if peerId.namespace == Namespaces.Peer.SecretChat { - return account.postbox.modify { modifier -> [Message] in - return modifier.searchMessages(peerId: peerId, query: query, tags: tags) + return account.postbox.transaction { transaction -> [Message] in + return transaction.searchMessages(peerId: peerId, query: query, tags: tags) } } @@ -64,11 +64,11 @@ public func searchMessages(account: Account, location: SearchMessagesLocation, q filter = .inputMessagesFilterEmpty } - remoteSearchResult = account.postbox.modify { modifier -> (peer:Peer?, from: Peer?) in + remoteSearchResult = account.postbox.transaction { transaction -> (peer:Peer?, from: Peer?) in if let fromId = fromId { - return (peer: modifier.getPeer(peerId), from: modifier.getPeer(fromId)) + return (peer: transaction.getPeer(peerId), from: transaction.getPeer(fromId)) } - return (peer: modifier.getPeer(peerId), from: nil) + return (peer: transaction.getPeer(peerId), from: nil) } |> mapToSignal { values -> Signal in if let peer = values.peer, let inputPeer = apiInputPeer(peer) { var fromInputUser:Api.InputUser? = nil @@ -125,11 +125,11 @@ public func searchMessages(account: Account, location: SearchMessagesLocation, q users = [] } - return account.postbox.modify { modifier -> [Message] in + return account.postbox.transaction { transaction -> [Message] in var peers: [PeerId: Peer] = [:] for user in users { - if let user = TelegramUser.merge(modifier.getPeer(user.peerId) as? TelegramUser, rhs: user) { + if let user = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { peers[user.id] = user } } @@ -148,7 +148,7 @@ public func searchMessages(account: Account, location: SearchMessagesLocation, q } if case .general = location { - let secretMessages = modifier.searchMessages(peerId: nil, query: query, tags: nil) + let secretMessages = transaction.searchMessages(peerId: nil, query: query, tags: nil) renderedMessages.append(contentsOf: secretMessages) } @@ -166,8 +166,8 @@ public func searchMessages(account: Account, location: SearchMessagesLocation, q public func downloadMessage(account: Account, messageId: MessageId) -> Signal { - return account.postbox.modify { modifier -> Message? in - return modifier.getMessage(messageId) + return account.postbox.transaction { transaction -> Message? in + return transaction.getMessage(messageId) } |> mapToSignal { message in if let _ = message { return .single(message) @@ -207,17 +207,17 @@ public func downloadMessage(account: Account, messageId: MessageId) -> Signal Message? in + let postboxSignal = account.postbox.transaction { transaction -> Message? in var peers: [PeerId: Peer] = [:] for user in users { - if let user = TelegramUser.merge(modifier.getPeer(user.peerId) as? TelegramUser, rhs: user) { + if let user = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { peers[user.id] = user } } for chat in chats { - if let groupOrChannel = mergeGroupOrChannel(lhs: modifier.getPeer(chat.peerId), rhs: chat) { + if let groupOrChannel = mergeGroupOrChannel(lhs: transaction.getPeer(chat.peerId), rhs: chat) { peers[groupOrChannel.id] = groupOrChannel } } @@ -245,10 +245,10 @@ public func downloadMessage(account: Account, messageId: MessageId) -> Signal Signal { - return account.postbox.modify { modifier -> Signal in + return account.postbox.transaction { transaction -> Signal in if peerId.namespace == Namespaces.Peer.SecretChat { - return .single(modifier.findClosestMessageIdByTimestamp(peerId: peerId, timestamp: timestamp)) - } else if let peer = modifier.getPeer(peerId), let inputPeer = apiInputPeer(peer) { + return .single(transaction.findClosestMessageIdByTimestamp(peerId: peerId, timestamp: timestamp)) + } else if let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) { return account.network.request(Api.functions.messages.getHistory(peer: inputPeer, offsetId: 0, offsetDate: timestamp, addOffset: -1, limit: 1, maxId: 0, minId: 0, hash: 0)) |> map { result -> MessageId? in let messages: [Api.Message] diff --git a/TelegramCore/SearchPeers.swift b/TelegramCore/SearchPeers.swift index b292324c7c..cdb9994832 100644 --- a/TelegramCore/SearchPeers.swift +++ b/TelegramCore/SearchPeers.swift @@ -34,11 +34,11 @@ public func searchPeers(account: Account, query: String) -> Signal<([FoundPeer], if let result = result { switch result { case let .found(myResults, results, chats, users): - return account.postbox.modify { modifier -> ([FoundPeer], [FoundPeer]) in + return account.postbox.transaction { transaction -> ([FoundPeer], [FoundPeer]) in var peers: [PeerId: Peer] = [:] var subscribers:[PeerId : Int32] = [:] for user in users { - if let user = TelegramUser.merge(modifier.getPeer(user.peerId) as? TelegramUser, rhs: user) { + if let user = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { peers[user.id] = user } } diff --git a/TelegramCore/SearchStickers.swift b/TelegramCore/SearchStickers.swift index be2c081a7c..88b532b617 100644 --- a/TelegramCore/SearchStickers.swift +++ b/TelegramCore/SearchStickers.swift @@ -75,9 +75,9 @@ final class CachedStickerQueryResult: PostboxCoding { private let collectionSpec = ItemCacheCollectionSpec(lowWaterItemCount: 100, highWaterItemCount: 200) public func searchStickers(account: Account, query: String) -> Signal<[FoundStickerItem], NoError> { - return account.postbox.modify { modifier -> ([FoundStickerItem], CachedStickerQueryResult?) in + return account.postbox.transaction { transaction -> ([FoundStickerItem], CachedStickerQueryResult?) in var result: [FoundStickerItem] = [] - for item in modifier.searchItemCollection(namespace: Namespaces.ItemCollection.CloudStickerPacks, key: ValueBoxKey(query).toMemoryBuffer()) { + for item in transaction.searchItemCollection(namespace: Namespaces.ItemCollection.CloudStickerPacks, key: ValueBoxKey(query).toMemoryBuffer()) { if let item = item as? StickerPackItem { var stringRepresentations: [String] = [] for key in item.indexKeys { @@ -91,7 +91,7 @@ public func searchStickers(account: Account, query: String) -> Signal<[FoundStic } } - let cached = modifier.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query))) as? CachedStickerQueryResult + let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query))) as? CachedStickerQueryResult return (result, cached) } |> mapToSignal { localItems, cached -> Signal<[FoundStickerItem], NoError> in @@ -110,7 +110,7 @@ public func searchStickers(account: Account, query: String) -> Signal<[FoundStic return .single(.stickersNotModified) } |> mapToSignal { result -> Signal<[FoundStickerItem], NoError> in - return account.postbox.modify { modifier -> [FoundStickerItem] in + return account.postbox.transaction { transaction -> [FoundStickerItem] in switch result { case let .stickers(hash, stickers): var items: [FoundStickerItem] = localItems @@ -125,7 +125,7 @@ public func searchStickers(account: Account, query: String) -> Signal<[FoundStic } } } - modifier.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query)), entry: CachedStickerQueryResult(items: files, hash: hash), collectionSpec: collectionSpec) + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query)), entry: CachedStickerQueryResult(items: files, hash: hash), collectionSpec: collectionSpec) return items case .stickersNotModified: @@ -185,8 +185,8 @@ public func searchStickerSetsRemotely(network: Network, query: String) -> Signal } public func searchStickerSets(postbox: Postbox, query: String) -> Signal { - return postbox.modify { modifier -> Signal in - let infos = modifier.getItemCollectionsInfos(namespace: Namespaces.ItemCollection.CloudStickerPacks) + return postbox.transaction { transaction -> Signal in + let infos = transaction.getItemCollectionsInfos(namespace: Namespaces.ItemCollection.CloudStickerPacks) var collections: [(ItemCollectionId, ItemCollectionInfo)] = [] var topItems: [ItemCollectionId: ItemCollectionItem] = [:] @@ -202,7 +202,7 @@ public func searchStickerSets(postbox: Postbox, query: String) -> Signal SecretChatSequenceBas } } -func secretChatAddReportCurrentLayerSupportOperationAndUpdateRequestedLayer(modifier: Modifier, peerId: PeerId, state: SecretChatState) -> SecretChatState { +func secretChatAddReportCurrentLayerSupportOperationAndUpdateRequestedLayer(transaction: Transaction, peerId: PeerId, state: SecretChatState) -> SecretChatState { switch state.embeddedState { case .basicLayer: var updatedState = state - updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: .reportLayerSupport(layer: .layer8, actionGloballyUniqueId: arc4random64(), layerSupport: topSupportedLayer.rawValue), state: updatedState) + updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: .reportLayerSupport(layer: .layer8, actionGloballyUniqueId: arc4random64(), layerSupport: topSupportedLayer.rawValue), state: updatedState) return updatedState case let .sequenceBasedLayer(sequenceState): var updatedState = state - updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: peerId, operation: .reportLayerSupport(layer: sequenceState.layerNegotiationState.activeLayer.secretChatLayer, actionGloballyUniqueId: arc4random64(), layerSupport: topSupportedLayer.rawValue), state: updatedState) + updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: peerId, operation: .reportLayerSupport(layer: sequenceState.layerNegotiationState.activeLayer.secretChatLayer, actionGloballyUniqueId: arc4random64(), layerSupport: topSupportedLayer.rawValue), state: updatedState) updatedState = updatedState.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedLayerNegotiationState(sequenceState.layerNegotiationState.withUpdatedLocallyRequestedLayer(topSupportedLayer.rawValue)))) return updatedState default: @@ -36,7 +36,7 @@ func secretChatAddReportCurrentLayerSupportOperationAndUpdateRequestedLayer(modi } } -func secretChatCheckLayerNegotiationIfNeeded(modifier: Modifier, peerId: PeerId, state: SecretChatState) -> SecretChatState { +func secretChatCheckLayerNegotiationIfNeeded(transaction: Transaction, peerId: PeerId, state: SecretChatState) -> SecretChatState { switch state.embeddedState { case let .sequenceBasedLayer(sequenceState): if sequenceState.layerNegotiationState.activeLayer != topSupportedLayer { @@ -48,7 +48,7 @@ func secretChatCheckLayerNegotiationIfNeeded(modifier: Modifier, peerId: PeerId, } if (sequenceState.layerNegotiationState.locallyRequestedLayer ?? 0) < topSupportedLayer.rawValue { - updatedState = secretChatAddReportCurrentLayerSupportOperationAndUpdateRequestedLayer(modifier: modifier, peerId: peerId, state: updatedState) + updatedState = secretChatAddReportCurrentLayerSupportOperationAndUpdateRequestedLayer(transaction: transaction, peerId: peerId, state: updatedState) } return updatedState diff --git a/TelegramCore/SecretChatRekeySession.swift b/TelegramCore/SecretChatRekeySession.swift index 0f7416c7c9..e5f751615c 100644 --- a/TelegramCore/SecretChatRekeySession.swift +++ b/TelegramCore/SecretChatRekeySession.swift @@ -9,13 +9,13 @@ import Foundation private let keyUseCountThreshold: Int32 = 100 -func secretChatInitiateRekeySessionIfNeeded(modifier: Modifier, peerId: PeerId, state: SecretChatState) -> SecretChatState { +func secretChatInitiateRekeySessionIfNeeded(transaction: Transaction, peerId: PeerId, state: SecretChatState) -> SecretChatState { switch state.embeddedState { case let .sequenceBasedLayer(sequenceState): if let _ = sequenceState.rekeyState { return state } - let tagLocalIndex = modifier.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing) + let tagLocalIndex = transaction.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing) let canonicalIndex = sequenceState.canonicalOutgoingOperationIndex(tagLocalIndex) if let key = state.keychain.latestKey(validForSequenceBasedCanonicalIndex: canonicalIndex), key.useCount >= keyUseCountThreshold { let sessionId = arc4random64() @@ -23,7 +23,7 @@ func secretChatInitiateRekeySessionIfNeeded(modifier: Modifier, peerId: PeerId, let _ = SecRandomCopyBytes(nil, 256, aBytes.assumingMemoryBound(to: UInt8.self)) let a = MemoryBuffer(memory: aBytes, capacity: 256, length: 256, freeWhenDone: true) - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .pfsRequestKey(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64(), rekeySessionId: sessionId, a: a), mutable: true, delivered: false)) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .pfsRequestKey(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64(), rekeySessionId: sessionId, a: a), mutable: true, delivered: false)) return state.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedRekeyState(SecretChatRekeySessionState(id: sessionId, data: .requesting)))) } default: @@ -32,7 +32,7 @@ func secretChatInitiateRekeySessionIfNeeded(modifier: Modifier, peerId: PeerId, return state } -func secretChatAdvanceRekeySessionIfNeeded(modifier: Modifier, peerId: PeerId, state: SecretChatState, action: SecretChatRekeyServiceAction) -> SecretChatState { +func secretChatAdvanceRekeySessionIfNeeded(transaction: Transaction, peerId: PeerId, state: SecretChatState, action: SecretChatRekeyServiceAction) -> SecretChatState { switch state.embeddedState { case let .sequenceBasedLayer(sequenceState): switch action { @@ -69,9 +69,9 @@ func secretChatAdvanceRekeySessionIfNeeded(modifier: Modifier, peerId: PeerId, s assert(remoteKeyFingerprint == keyFingerprint) - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .pfsCommitKey(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64(), rekeySessionId: rekeySession.id, keyFingerprint: keyFingerprint), mutable: true, delivered: false)) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .pfsCommitKey(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64(), rekeySessionId: rekeySession.id, keyFingerprint: keyFingerprint), mutable: true, delivered: false)) - let keyValidityOperationIndex = modifier.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing) + let keyValidityOperationIndex = transaction.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing) let keyValidityOperationCanonicalIndex = sequenceState.canonicalOutgoingOperationIndex(keyValidityOperationIndex) return state.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedRekeyState(nil))).withUpdatedKeychain(state.keychain.withUpdatedKey(fingerprint: keyFingerprint, { _ in @@ -85,14 +85,14 @@ func secretChatAdvanceRekeySessionIfNeeded(modifier: Modifier, peerId: PeerId, s case let .pfsCommitKey(rekeySessionId, keyFingerprint): if let rekeySession = sequenceState.rekeyState, rekeySession.id == rekeySessionId { if case let .accepted(key, localKeyFingerprint) = rekeySession.data, keyFingerprint == localKeyFingerprint { - let keyValidityOperationIndex = modifier.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing) + let keyValidityOperationIndex = transaction.operationLogGetNextEntryLocalIndex(peerId: peerId, tag: OperationLogTags.SecretOutgoing) let keyValidityOperationCanonicalIndex = sequenceState.canonicalOutgoingOperationIndex(keyValidityOperationIndex) let updatedState = state.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedRekeyState(nil))).withUpdatedKeychain(state.keychain.withUpdatedKey(fingerprint: keyFingerprint, { _ in return SecretChatKey(fingerprint: keyFingerprint, key: key, validity: .sequenceBasedIndexRange(fromCanonicalIndex: keyValidityOperationCanonicalIndex), useCount: 0) })) - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .noop(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64()), mutable: true, delivered: false)) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .noop(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64()), mutable: true, delivered: false)) return updatedState } else { @@ -107,7 +107,7 @@ func secretChatAdvanceRekeySessionIfNeeded(modifier: Modifier, peerId: PeerId, s switch rekeySession.data { case .requesting, .requested: if rekeySessionId < rekeySession.id { - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .pfsAbortSession(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64(), rekeySessionId: rekeySession.id), mutable: true, delivered: false)) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .pfsAbortSession(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64(), rekeySessionId: rekeySession.id), mutable: true, delivered: false)) } else { acceptSession = false } @@ -123,7 +123,7 @@ func secretChatAdvanceRekeySessionIfNeeded(modifier: Modifier, peerId: PeerId, s let rekeySession = SecretChatRekeySessionState(id: rekeySessionId, data: .accepting) - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .pfsAcceptKey(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64(), rekeySessionId: rekeySession.id, gA: gA, b: b), mutable: true, delivered: false)) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SecretOutgoing, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SecretChatOutgoingOperation(contents: .pfsAcceptKey(layer: sequenceState.layerNegotiationState.activeLayer, actionGloballyUniqueId: arc4random64(), rekeySessionId: rekeySession.id, gA: gA, b: b), mutable: true, delivered: false)) return state.withUpdatedEmbeddedState(.sequenceBasedLayer(sequenceState.withUpdatedRekeyState(rekeySession))) } } diff --git a/TelegramCore/SetSecretChatMessageAutoremoveTimeoutInteractively.swift b/TelegramCore/SetSecretChatMessageAutoremoveTimeoutInteractively.swift index b9100e32bb..a5f3e8b96a 100644 --- a/TelegramCore/SetSecretChatMessageAutoremoveTimeoutInteractively.swift +++ b/TelegramCore/SetSecretChatMessageAutoremoveTimeoutInteractively.swift @@ -8,28 +8,28 @@ import Foundation #endif public func setSecretChatMessageAutoremoveTimeoutInteractively(account: Account, peerId: PeerId, timeout: Int32?) -> Signal { - return account.postbox.modify { modifier -> Void in - if let peer = modifier.getPeer(peerId) as? TelegramSecretChat, let state = modifier.getPeerChatState(peerId) as? SecretChatState { + return account.postbox.transaction { transaction -> Void in + if let peer = transaction.getPeer(peerId) as? TelegramSecretChat, let state = transaction.getPeerChatState(peerId) as? SecretChatState { if state.messageAutoremoveTimeout != timeout { let updatedPeer = peer.withUpdatedMessageAutoremoveTimeout(timeout) let updatedState = state.withUpdatedMessageAutoremoveTimeout(timeout) if !updatedPeer.isEqual(peer) { - updatePeers(modifier: modifier, peers: [updatedPeer], update: { $1 }) + updatePeers(transaction: transaction, peers: [updatedPeer], update: { $1 }) } if updatedState != state { - modifier.setPeerChatState(peerId, state: updatedState) + transaction.setPeerChatState(peerId, state: updatedState) } - let _ = enqueueMessages(modifier: modifier, account: account, peerId: peerId, messages: [(true, .message(text: "", attributes: [], media: TelegramMediaAction(action: TelegramMediaActionType.messageAutoremoveTimeoutUpdated(timeout == nil ? 0 : timeout!)), replyToMessageId: nil, localGroupingKey: nil))]) + let _ = enqueueMessages(transaction: transaction, account: account, peerId: peerId, messages: [(true, .message(text: "", attributes: [], media: TelegramMediaAction(action: TelegramMediaActionType.messageAutoremoveTimeoutUpdated(timeout == nil ? 0 : timeout!)), replyToMessageId: nil, localGroupingKey: nil))]) } } } } public func addSecretChatMessageScreenshot(account: Account, peerId: PeerId) -> Signal { - return account.postbox.modify { modifier -> Void in - if let peer = modifier.getPeer(peerId) as? TelegramSecretChat, let state = modifier.getPeerChatState(peerId) as? SecretChatState { - let _ = enqueueMessages(modifier: modifier, account: account, peerId: peerId, messages: [(true, .message(text: "", attributes: [], media: TelegramMediaAction(action: TelegramMediaActionType.historyScreenshot), replyToMessageId: nil, localGroupingKey: nil))]) + return account.postbox.transaction { transaction -> Void in + if let peer = transaction.getPeer(peerId) as? TelegramSecretChat, let state = transaction.getPeerChatState(peerId) as? SecretChatState { + let _ = enqueueMessages(transaction: transaction, account: account, peerId: peerId, messages: [(true, .message(text: "", attributes: [], media: TelegramMediaAction(action: TelegramMediaActionType.historyScreenshot), replyToMessageId: nil, localGroupingKey: nil))]) } } } diff --git a/TelegramCore/SingleMessageView.swift b/TelegramCore/SingleMessageView.swift index 04c5fa419d..e0fa1bd1fd 100644 --- a/TelegramCore/SingleMessageView.swift +++ b/TelegramCore/SingleMessageView.swift @@ -11,9 +11,9 @@ import Foundation public func singleMessageView(account: Account, messageId: MessageId, loadIfNotExists: Bool) -> Signal { return Signal { subscriber in - let loadedMessage = account.postbox.modify { modifier -> Signal in - if modifier.getMessage(messageId) == nil, loadIfNotExists { - return fetchMessage(modifier: modifier, account: account, messageId: messageId) + let loadedMessage = account.postbox.transaction { transaction -> Signal in + if transaction.getMessage(messageId) == nil, loadIfNotExists { + return fetchMessage(transaction: transaction, account: account, messageId: messageId) } else { return .complete() } @@ -31,8 +31,8 @@ public func singleMessageView(account: Account, messageId: MessageId, loadIfNotE } } -private func fetchMessage(modifier: Modifier, account: Account, messageId: MessageId) -> Signal { - if let peer = modifier.getPeer(messageId.peerId) { +private func fetchMessage(transaction: Transaction, account: Account, messageId: MessageId) -> Signal { + if let peer = transaction.getPeer(messageId.peerId) { var signal: Signal? if messageId.peerId.namespace == Namespaces.Peer.CloudUser || messageId.peerId.namespace == Namespaces.Peer.CloudGroup { signal = account.network.request(Api.functions.messages.getMessages(id: [Api.InputMessage.inputMessageID(id: messageId.id)])) @@ -47,7 +47,7 @@ private func fetchMessage(modifier: Modifier, account: Account, messageId: Messa return .single(.messages(messages: [], chats: [], users: [])) } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in let apiMessages: [Api.Message] let apiChats: [Api.Chat] let apiUsers: [Api.User] @@ -73,7 +73,7 @@ private func fetchMessage(modifier: Modifier, account: Account, messageId: Messa var peers: [PeerId: Peer] = [:] for user in apiUsers { - if let user = TelegramUser.merge(modifier.getPeer(user.peerId) as? TelegramUser, rhs: user) { + if let user = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { peers[user.id] = user } } @@ -84,13 +84,13 @@ private func fetchMessage(modifier: Modifier, account: Account, messageId: Messa } } - updatePeers(modifier: modifier, peers: Array(peers.values), update: { _, updated in + updatePeers(transaction: transaction, peers: Array(peers.values), update: { _, updated in return updated }) for message in apiMessages { if let message = StoreMessage(apiMessage: message) { - let _ = modifier.addMessages([message], location: .Random) + let _ = transaction.addMessages([message], location: .Random) } } } diff --git a/TelegramCore/StandaloneSendMessage.swift b/TelegramCore/StandaloneSendMessage.swift index 817785dd97..6080cb94a7 100644 --- a/TelegramCore/StandaloneSendMessage.swift +++ b/TelegramCore/StandaloneSendMessage.swift @@ -73,10 +73,10 @@ public func standaloneSendMessage(account: Account, peerId: PeerId, text: String } private func sendMessageContent(account: Account, peerId: PeerId, attributes: [MessageAttribute], content: StandaloneMessageContent) -> Signal { - return account.postbox.modify { modifier -> Signal in + return account.postbox.transaction { transaction -> Signal in if peerId.namespace == Namespaces.Peer.SecretChat { return .complete() - } else if let peer = modifier.getPeer(peerId), let inputPeer = apiInputPeer(peer) { + } else if let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) { var uniqueId: Int64 = arc4random64() //var forwardSourceInfoAttribute: ForwardSourceInfoAttribute? var messageEntities: [Api.MessageEntity]? diff --git a/TelegramCore/StandaloneUploadedMedia.swift b/TelegramCore/StandaloneUploadedMedia.swift index ac64a858df..034a10fa77 100644 --- a/TelegramCore/StandaloneUploadedMedia.swift +++ b/TelegramCore/StandaloneUploadedMedia.swift @@ -22,8 +22,8 @@ public func standaloneUploadedImage(account: Account, peerId: PeerId, text: Stri |> mapToSignal { next -> Signal in switch next { case let .inputFile(inputFile): - return account.postbox.modify { modifier -> Api.InputPeer? in - return modifier.getPeer(peerId).flatMap(apiInputPeer) + return account.postbox.transaction { transaction -> Api.InputPeer? in + return transaction.getPeer(peerId).flatMap(apiInputPeer) } |> mapError { _ -> StandaloneUploadMediaError in return .generic } |> mapToSignal { inputPeer -> Signal in @@ -61,8 +61,8 @@ public func standaloneUploadedFile(account: Account, peerId: PeerId, text: Strin |> mapToSignal { next -> Signal in switch next { case let .inputFile(inputFile): - return account.postbox.modify { modifier -> Api.InputPeer? in - return modifier.getPeer(peerId).flatMap(apiInputPeer) + return account.postbox.transaction { transaction -> Api.InputPeer? in + return transaction.getPeer(peerId).flatMap(apiInputPeer) } |> mapError { _ -> StandaloneUploadMediaError in return .generic } |> mapToSignal { inputPeer -> Signal in diff --git a/TelegramCore/StickerManagement.swift b/TelegramCore/StickerManagement.swift index 744b4f66a6..c33a4b09f4 100644 --- a/TelegramCore/StickerManagement.swift +++ b/TelegramCore/StickerManagement.swift @@ -22,17 +22,17 @@ private func hashForIdsReverse(_ ids: [Int64]) -> Int32 { } func manageStickerPacks(network: Network, postbox: Postbox) -> Signal { - return (postbox.modify { modifier -> Void in - addSynchronizeInstalledStickerPacksOperation(modifier: modifier, namespace: .stickers) - addSynchronizeInstalledStickerPacksOperation(modifier: modifier, namespace: .masks) - addSynchronizeSavedGifsOperation(modifier: modifier, operation: .sync) - addSynchronizeSavedStickersOperation(modifier: modifier, operation: .sync) + return (postbox.transaction { transaction -> Void in + addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: .stickers) + addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: .masks) + addSynchronizeSavedGifsOperation(transaction: transaction, operation: .sync) + addSynchronizeSavedStickersOperation(transaction: transaction, operation: .sync) } |> then(.complete() |> delay(1.0 * 60.0 * 60.0, queue: Queue.concurrentDefaultQueue()))) |> restart } func updatedFeaturedStickerPacks(network: Network, postbox: Postbox) -> Signal { - return postbox.modify { modifier -> Signal in - let initialPacks = modifier.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks) + return postbox.transaction { transaction -> Signal in + let initialPacks = transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks) var initialPackMap: [Int64: FeaturedStickerPackItem] = [:] for entry in initialPacks { let item = entry.contents as! FeaturedStickerPackItem @@ -46,7 +46,7 @@ func updatedFeaturedStickerPacks(network: Network, postbox: Postbox) -> Signal retryRequest |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in switch result { case .featuredStickersNotModified: break @@ -62,7 +62,7 @@ func updatedFeaturedStickerPacks(network: Network, postbox: Postbox) -> Signal Signal Signal { - return postbox.modify { modifier -> Signal in - if let pack = modifier.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks, itemId: FeaturedStickerPackItemId(id.id).rawValue)?.contents as? FeaturedStickerPackItem { + return postbox.transaction { transaction -> Signal in + if let pack = transaction.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks, itemId: FeaturedStickerPackItemId(id.id).rawValue)?.contents as? FeaturedStickerPackItem { if pack.topItems.count < 5 && pack.topItems.count < pack.info.count { return requestStickerSet(postbox: postbox, network: network, reference: .id(id: pack.info.id.id, accessHash: pack.info.accessHash)) |> map(Optional.init) @@ -80,13 +80,13 @@ public func preloadedFeaturedStickerSet(network: Network, postbox: Postbox, id: } |> mapToSignal { result -> Signal in if let result = result { - return postbox.modify { modifier -> Void in - if let pack = modifier.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks, itemId: FeaturedStickerPackItemId(id.id).rawValue)?.contents as? FeaturedStickerPackItem { + return postbox.transaction { transaction -> Void in + if let pack = transaction.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks, itemId: FeaturedStickerPackItemId(id.id).rawValue)?.contents as? FeaturedStickerPackItem { var items = result.items.map({ $0 as? StickerPackItem }).flatMap({ $0 }) if items.count > 5 { items.removeSubrange(5 ..< items.count) } - modifier.updateOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks, itemId: FeaturedStickerPackItemId(id.id).rawValue, item: FeaturedStickerPackItem(info: pack.info, topItems: items, unread: pack.unread)) + transaction.updateOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks, itemId: FeaturedStickerPackItemId(id.id).rawValue, item: FeaturedStickerPackItem(info: pack.info, topItems: items, unread: pack.unread)) } } } else { diff --git a/TelegramCore/StickerPackInteractiveOperations.swift b/TelegramCore/StickerPackInteractiveOperations.swift index 1fabbadb75..747a7178ed 100644 --- a/TelegramCore/StickerPackInteractiveOperations.swift +++ b/TelegramCore/StickerPackInteractiveOperations.swift @@ -8,7 +8,7 @@ import Foundation #endif public func addStickerPackInteractively(postbox: Postbox, info: StickerPackCollectionInfo, items: [ItemCollectionItem]) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in let namespace: SynchronizeInstalledStickerPacksOperationNamespace? switch info.id.namespace { case Namespaces.ItemCollection.CloudStickerPacks: @@ -19,24 +19,24 @@ public func addStickerPackInteractively(postbox: Postbox, info: StickerPackColle namespace = nil } if let namespace = namespace { - addSynchronizeInstalledStickerPacksOperation(modifier: modifier, namespace: namespace) - var updatedInfos = modifier.getItemCollectionsInfos(namespace: info.id.namespace).map { $0.1 as! StickerPackCollectionInfo } + addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: namespace) + var updatedInfos = transaction.getItemCollectionsInfos(namespace: info.id.namespace).map { $0.1 as! StickerPackCollectionInfo } if let index = updatedInfos.index(where: { $0.id == info.id }) { let currentInfo = updatedInfos[index] updatedInfos.remove(at: index) updatedInfos.insert(currentInfo, at: 0) } else { updatedInfos.insert(info, at: 0) - modifier.replaceItemCollectionItems(collectionId: info.id, items: items) + transaction.replaceItemCollectionItems(collectionId: info.id, items: items) } - modifier.replaceItemCollectionInfos(namespace: info.id.namespace, itemCollectionInfos: updatedInfos.map { ($0.id, $0) }) + transaction.replaceItemCollectionInfos(namespace: info.id.namespace, itemCollectionInfos: updatedInfos.map { ($0.id, $0) }) } } } public func removeStickerPackInteractively(postbox: Postbox, id: ItemCollectionId) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in let namespace: SynchronizeInstalledStickerPacksOperationNamespace? switch id.namespace { case Namespaces.ItemCollection.CloudStickerPacks: @@ -47,16 +47,16 @@ public func removeStickerPackInteractively(postbox: Postbox, id: ItemCollectionI namespace = nil } if let namespace = namespace { - addSynchronizeInstalledStickerPacksOperation(modifier: modifier, namespace: namespace) - modifier.removeItemCollection(collectionId: id) + addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: namespace) + transaction.removeItemCollection(collectionId: id) } } } public func markFeaturedStickerPacksAsSeenInteractively(postbox: Postbox, ids: [ItemCollectionId]) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in let idsSet = Set(ids) - var items = modifier.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks) + var items = transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks) var readIds = Set() for i in 0 ..< items.count { let item = (items[i].contents as! FeaturedStickerPackItem) @@ -66,8 +66,8 @@ public func markFeaturedStickerPacksAsSeenInteractively(postbox: Postbox, ids: [ } } if !readIds.isEmpty { - modifier.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks, items: items) - addSynchronizeMarkFeaturedStickerPacksAsSeenOperation(modifier: modifier, ids: Array(readIds)) + transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.CloudFeaturedStickerPacks, items: items) + addSynchronizeMarkFeaturedStickerPacksAsSeenOperation(transaction: transaction, ids: Array(readIds)) } } } diff --git a/TelegramCore/StickerSetInstallation.swift b/TelegramCore/StickerSetInstallation.swift index fc1ff232da..f8b24fdeee 100644 --- a/TelegramCore/StickerSetInstallation.swift +++ b/TelegramCore/StickerSetInstallation.swift @@ -41,8 +41,8 @@ public func requestStickerSet(postbox: Postbox, network: Network, reference: Sti } let localSignal: (ItemCollectionId) -> Signal<(ItemCollectionInfo, [ItemCollectionItem])?, Void> = { collectionId in - return postbox.modify { modifier -> (ItemCollectionInfo, [ItemCollectionItem])? in - return modifier.getItemCollectionInfoItems(namespace: Namespaces.ItemCollection.CloudStickerPacks, id: collectionId) + return postbox.transaction { transaction -> (ItemCollectionInfo, [ItemCollectionItem])? in + return transaction.getItemCollectionInfoItems(namespace: Namespaces.ItemCollection.CloudStickerPacks, id: collectionId) } } @@ -167,8 +167,8 @@ public func installStickerSetInteractively(account:Account, info: StickerPackCol } - return account.postbox.modify { modifier -> Void in - var collections = modifier.getCollectionsItems(namespace: info.id.namespace) + return account.postbox.transaction { transaction -> Void in + var collections = transaction.getCollectionsItems(namespace: info.id.namespace) var removableIndexes:[Int] = [] for i in 0 ..< collections.count { @@ -190,7 +190,7 @@ public func installStickerSetInteractively(account:Account, info: StickerPackCol collections.insert((info.id, info, items), at: 0) - modifier.replaceItemCollections(namespace: info.id.namespace, itemCollections: collections) + transaction.replaceItemCollections(namespace: info.id.namespace, itemCollections: collections) } |> map { _ in return addResult} |> mapError {_ in return .generic} } } @@ -204,8 +204,8 @@ public func uninstallStickerSetInteractively(account:Account, info:StickerPackCo |> mapToSignal { result-> Signal in switch result { case .boolTrue: - return account.postbox.modify { modifier -> Void in - var collections = modifier.getCollectionsItems(namespace: info.id.namespace) + return account.postbox.transaction { transaction -> Void in + var collections = transaction.getCollectionsItems(namespace: info.id.namespace) for i in 0 ..< collections.count { if collections[i].0 == info.id { @@ -214,7 +214,7 @@ public func uninstallStickerSetInteractively(account:Account, info:StickerPackCo } } - modifier.replaceItemCollections(namespace: info.id.namespace, itemCollections: collections) + transaction.replaceItemCollections(namespace: info.id.namespace, itemCollections: collections) } case .boolFalse: return .complete() diff --git a/TelegramCore/SuggestedLocalizationEntry.swift b/TelegramCore/SuggestedLocalizationEntry.swift index 979a0369d4..b165799eaf 100644 --- a/TelegramCore/SuggestedLocalizationEntry.swift +++ b/TelegramCore/SuggestedLocalizationEntry.swift @@ -40,8 +40,8 @@ public final class SuggestedLocalizationEntry: PreferencesEntry { } public func markSuggestedLocalizationAsSeenInteractively(postbox: Postbox, languageCode: String) -> Signal { - return postbox.modify { modifier -> Void in - modifier.updatePreferencesEntry(key: PreferencesKeys.suggestedLocalization, { current in + return postbox.transaction { transaction -> Void in + transaction.updatePreferencesEntry(key: PreferencesKeys.suggestedLocalization, { current in if let current = current as? SuggestedLocalizationEntry { if current.languageCode == languageCode, !current.isSeen { return SuggestedLocalizationEntry(languageCode: languageCode, isSeen: true) diff --git a/TelegramCore/SupportPeerId.swift b/TelegramCore/SupportPeerId.swift index 15bc7670c0..3ed5be9b8e 100644 --- a/TelegramCore/SupportPeerId.swift +++ b/TelegramCore/SupportPeerId.swift @@ -20,8 +20,8 @@ public func supportPeerId(account:Account) -> Signal { switch support { case let .support(phoneNumber: _, user: user): let user = TelegramUser(user: user) - return account.postbox.modify { modifier -> PeerId in - updatePeers(modifier: modifier, peers: [user], update: { (previous, updated) -> Peer? in + return account.postbox.transaction { transaction -> PeerId in + updatePeers(transaction: transaction, peers: [user], update: { (previous, updated) -> Peer? in return updated }) return user.id diff --git a/TelegramCore/SynchronizeChatInputStateOperation.swift b/TelegramCore/SynchronizeChatInputStateOperation.swift index 1b4185e262..c00e5ffc4c 100644 --- a/TelegramCore/SynchronizeChatInputStateOperation.swift +++ b/TelegramCore/SynchronizeChatInputStateOperation.swift @@ -25,12 +25,12 @@ final class SynchronizeChatInputStateOperation: PostboxCoding { } } -func addSynchronizeChatInputStateOperation(modifier: Modifier, peerId: PeerId) { +func addSynchronizeChatInputStateOperation(transaction: Transaction, peerId: PeerId) { var updateLocalIndex: Int32? let tag: PeerOperationLogTag = OperationLogTags.SynchronizeChatInputStates var previousOperation: SynchronizeChatInputStateOperation? - modifier.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in + transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in updateLocalIndex = entry.tagLocalIndex if let operation = entry.contents as? SynchronizeChatInputStateOperation { previousOperation = operation @@ -40,12 +40,12 @@ func addSynchronizeChatInputStateOperation(modifier: Modifier, peerId: PeerId) { var previousState: SynchronizeableChatInputState? if let previousOperation = previousOperation { previousState = previousOperation.previousState - } else if let peerChatInterfaceState = modifier.getPeerChatInterfaceState(peerId) as? SynchronizeableChatInterfaceState { + } else if let peerChatInterfaceState = transaction.getPeerChatInterfaceState(peerId) as? SynchronizeableChatInterfaceState { previousState = peerChatInterfaceState.synchronizeableInputState } let operationContents = SynchronizeChatInputStateOperation(previousState: previousState) if let updateLocalIndex = updateLocalIndex { - let _ = modifier.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: updateLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: updateLocalIndex) } - modifier.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) + transaction.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) } diff --git a/TelegramCore/SynchronizeConsumeMessageContentsOperation.swift b/TelegramCore/SynchronizeConsumeMessageContentsOperation.swift index 5598d245e2..23c3bf7943 100644 --- a/TelegramCore/SynchronizeConsumeMessageContentsOperation.swift +++ b/TelegramCore/SynchronizeConsumeMessageContentsOperation.swift @@ -23,17 +23,17 @@ final class SynchronizeConsumeMessageContentsOperation: PostboxCoding { } } -func addSynchronizeConsumeMessageContentsOperation(modifier: Modifier, messageIds: [MessageId]) { +func addSynchronizeConsumeMessageContentsOperation(transaction: Transaction, messageIds: [MessageId]) { for (peerId, messageIds) in messagesIdsGroupedByPeerId(Set(messageIds)) { var updateLocalIndex: Int32? - /*modifier.operationLogEnumerateEntries(peerId: peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, { entry in + /*transaction.operationLogEnumerateEntries(peerId: peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, { entry in updateLocalIndex = entry.tagLocalIndex return false })*/ let operationContents = SynchronizeConsumeMessageContentsOperation(messageIds: messageIds) if let updateLocalIndex = updateLocalIndex { - let _ = modifier.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, tagLocalIndex: updateLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, tagLocalIndex: updateLocalIndex) } - modifier.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) + transaction.operationLogAddEntry(peerId: peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) } } diff --git a/TelegramCore/SynchronizeGroupedPeersOperation.swift b/TelegramCore/SynchronizeGroupedPeersOperation.swift index e9190df359..af5becc25e 100644 --- a/TelegramCore/SynchronizeGroupedPeersOperation.swift +++ b/TelegramCore/SynchronizeGroupedPeersOperation.swift @@ -30,50 +30,50 @@ final class SynchronizeGroupedPeersOperation: PostboxCoding { } public func updatePeerGroupIdInteractively(postbox: Postbox, peerId: PeerId, groupId: PeerGroupId?) -> Signal { - return postbox.modify { modifier -> Void in - let previousGroupId = modifier.getPeerGroupId(peerId) + return postbox.transaction { transaction -> Void in + let previousGroupId = transaction.getPeerGroupId(peerId) if previousGroupId != groupId { var previousGroupPeerIds = Set() if let previousGroupId = previousGroupId { - previousGroupPeerIds = modifier.getPeerIdsInGroup(previousGroupId) + previousGroupPeerIds = transaction.getPeerIdsInGroup(previousGroupId) } var updatedGroupPeerIds = Set() if let groupId = groupId { - updatedGroupPeerIds = modifier.getPeerIdsInGroup(groupId) + updatedGroupPeerIds = transaction.getPeerIdsInGroup(groupId) } - modifier.updatePeerGroupId(peerId, groupId: groupId) + transaction.updatePeerGroupId(peerId, groupId: groupId) if let previousGroupId = previousGroupId { - addSynchronizeGroupedPeersOperation(modifier: modifier, groupId: previousGroupId, initialPeerIds: previousGroupPeerIds) + addSynchronizeGroupedPeersOperation(transaction: transaction, groupId: previousGroupId, initialPeerIds: previousGroupPeerIds) } if let groupId = groupId { - addSynchronizeGroupedPeersOperation(modifier: modifier, groupId: groupId, initialPeerIds: updatedGroupPeerIds) + addSynchronizeGroupedPeersOperation(transaction: transaction, groupId: groupId, initialPeerIds: updatedGroupPeerIds) } } } } public func clearPeerGroupInteractively(postbox: Postbox, groupId: PeerGroupId) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in var previousGroupPeerIds = Set() - previousGroupPeerIds = modifier.getPeerIdsInGroup(groupId) + previousGroupPeerIds = transaction.getPeerIdsInGroup(groupId) - for peerId in modifier.getPeerIdsInGroup(groupId) { - modifier.updatePeerGroupId(peerId, groupId: nil) + for peerId in transaction.getPeerIdsInGroup(groupId) { + transaction.updatePeerGroupId(peerId, groupId: nil) } - addSynchronizeGroupedPeersOperation(modifier: modifier, groupId: groupId, initialPeerIds: previousGroupPeerIds) + addSynchronizeGroupedPeersOperation(transaction: transaction, groupId: groupId, initialPeerIds: previousGroupPeerIds) } } -private func addSynchronizeGroupedPeersOperation(modifier: Modifier, groupId: PeerGroupId, initialPeerIds: Set) { +private func addSynchronizeGroupedPeersOperation(transaction: Transaction, groupId: PeerGroupId, initialPeerIds: Set) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeGroupedPeers let peerId = PeerId(namespace: 0, id: groupId.rawValue) var topLocalIndex: Int32? var previousInitialPeerIds: Set? - modifier.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in + transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in topLocalIndex = entry.tagLocalIndex if let operation = entry.contents as? SynchronizeGroupedPeersOperation { previousInitialPeerIds = operation.initialPeerIds @@ -82,10 +82,10 @@ private func addSynchronizeGroupedPeersOperation(modifier: Modifier, groupId: Pe }) if let topLocalIndex = topLocalIndex { - let _ = modifier.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: topLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: topLocalIndex) } let initialPeerIds: Set = previousInitialPeerIds ?? initialPeerIds - modifier.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeGroupedPeersOperation(groupId: groupId, initialPeerIds: initialPeerIds)) + transaction.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeGroupedPeersOperation(groupId: groupId, initialPeerIds: initialPeerIds)) } diff --git a/TelegramCore/SynchronizeInstalledStickerPacksOperations.swift b/TelegramCore/SynchronizeInstalledStickerPacksOperations.swift index d529e89bd7..eae81a8290 100644 --- a/TelegramCore/SynchronizeInstalledStickerPacksOperations.swift +++ b/TelegramCore/SynchronizeInstalledStickerPacksOperations.swift @@ -46,7 +46,7 @@ final class SynchronizeMarkFeaturedStickerPacksAsSeenOperation: PostboxCoding { } } -public func addSynchronizeInstalledStickerPacksOperation(modifier: Modifier, namespace: ItemCollectionId.Namespace) { +public func addSynchronizeInstalledStickerPacksOperation(transaction: Transaction, namespace: ItemCollectionId.Namespace) { let operationNamespace: SynchronizeInstalledStickerPacksOperationNamespace switch namespace { case Namespaces.ItemCollection.CloudStickerPacks: @@ -56,10 +56,10 @@ public func addSynchronizeInstalledStickerPacksOperation(modifier: Modifier, nam default: return } - addSynchronizeInstalledStickerPacksOperation(modifier: modifier, namespace: operationNamespace) + addSynchronizeInstalledStickerPacksOperation(transaction: transaction, namespace: operationNamespace) } -func addSynchronizeInstalledStickerPacksOperation(modifier: Modifier, namespace: SynchronizeInstalledStickerPacksOperationNamespace) { +func addSynchronizeInstalledStickerPacksOperation(transaction: Transaction, namespace: SynchronizeInstalledStickerPacksOperationNamespace) { var updateLocalIndex: Int32? let tag: PeerOperationLogTag let itemCollectionNamespace: ItemCollectionId.Namespace @@ -72,7 +72,7 @@ func addSynchronizeInstalledStickerPacksOperation(modifier: Modifier, namespace: itemCollectionNamespace = Namespaces.ItemCollection.CloudMaskPacks } var previousSrickerPackIds: [ItemCollectionId]? - modifier.operationLogEnumerateEntries(peerId: PeerId(namespace: 0, id: 0), tag: tag, { entry in + transaction.operationLogEnumerateEntries(peerId: PeerId(namespace: 0, id: 0), tag: tag, { entry in updateLocalIndex = entry.tagLocalIndex if let operation = entry.contents as? SynchronizeInstalledStickerPacksOperation { previousSrickerPackIds = operation.previousPacks @@ -81,18 +81,18 @@ func addSynchronizeInstalledStickerPacksOperation(modifier: Modifier, namespace: } return false }) - let operationContents = SynchronizeInstalledStickerPacksOperation(previousPacks: previousSrickerPackIds ?? modifier.getItemCollectionsInfos(namespace: itemCollectionNamespace).map { $0.0 }) + let operationContents = SynchronizeInstalledStickerPacksOperation(previousPacks: previousSrickerPackIds ?? transaction.getItemCollectionsInfos(namespace: itemCollectionNamespace).map { $0.0 }) if let updateLocalIndex = updateLocalIndex { - let _ = modifier.operationLogRemoveEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: updateLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: updateLocalIndex) } - modifier.operationLogAddEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) + transaction.operationLogAddEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) } -func addSynchronizeMarkFeaturedStickerPacksAsSeenOperation(modifier: Modifier, ids: [ItemCollectionId]) { +func addSynchronizeMarkFeaturedStickerPacksAsSeenOperation(transaction: Transaction, ids: [ItemCollectionId]) { var updateLocalIndex: Int32? let tag: PeerOperationLogTag = OperationLogTags.SynchronizeMarkFeaturedStickerPacksAsSeen var previousIds = Set() - modifier.operationLogEnumerateEntries(peerId: PeerId(namespace: 0, id: 0), tag: tag, { entry in + transaction.operationLogEnumerateEntries(peerId: PeerId(namespace: 0, id: 0), tag: tag, { entry in updateLocalIndex = entry.tagLocalIndex if let operation = entry.contents as? SynchronizeMarkFeaturedStickerPacksAsSeenOperation { previousIds = Set(operation.ids) @@ -103,7 +103,7 @@ func addSynchronizeMarkFeaturedStickerPacksAsSeenOperation(modifier: Modifier, i }) let operationContents = SynchronizeMarkFeaturedStickerPacksAsSeenOperation(ids: Array(previousIds.union(Set(ids)))) if let updateLocalIndex = updateLocalIndex { - let _ = modifier.operationLogRemoveEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: updateLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: updateLocalIndex) } - modifier.operationLogAddEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) + transaction.operationLogAddEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) } diff --git a/TelegramCore/SynchronizeLocalizationUpdatesOperation.swift b/TelegramCore/SynchronizeLocalizationUpdatesOperation.swift index f48ecd8934..ae5ea727e7 100644 --- a/TelegramCore/SynchronizeLocalizationUpdatesOperation.swift +++ b/TelegramCore/SynchronizeLocalizationUpdatesOperation.swift @@ -18,19 +18,19 @@ final class SynchronizeLocalizationUpdatesOperation: PostboxCoding { } } -func addSynchronizeLocalizationUpdatesOperation(modifier: Modifier) { +func addSynchronizeLocalizationUpdatesOperation(transaction: Transaction) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeLocalizationUpdates let peerId = PeerId(namespace: 0, id: 0) var topLocalIndex: Int32? - modifier.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in + transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in topLocalIndex = entry.tagLocalIndex return false }) if let topLocalIndex = topLocalIndex { - let _ = modifier.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: topLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: topLocalIndex) } - modifier.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeLocalizationUpdatesOperation()) + transaction.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeLocalizationUpdatesOperation()) } diff --git a/TelegramCore/SynchronizePeerReadState.swift b/TelegramCore/SynchronizePeerReadState.swift index a12501772c..5403e0628d 100644 --- a/TelegramCore/SynchronizePeerReadState.swift +++ b/TelegramCore/SynchronizePeerReadState.swift @@ -175,15 +175,15 @@ private func ==(lhs: PeerReadStateMarker, rhs: PeerReadStateMarker) -> Bool { } } -private func localReadStateMarker(modifier: Modifier, peerId: PeerId) -> PeerReadStateMarker? { +private func localReadStateMarker(transaction: Transaction, peerId: PeerId) -> PeerReadStateMarker? { if peerId.namespace == Namespaces.Peer.CloudChannel { - if let state = modifier.getPeerChatState(peerId) as? ChannelState { + if let state = transaction.getPeerChatState(peerId) as? ChannelState { return .Channel(state.pts) } else { return nil } } else { - if let state = (modifier.getState() as? AuthorizedAccountState)?.state { + if let state = (transaction.getState() as? AuthorizedAccountState)?.state { return .Global(state.pts) } else { return nil @@ -192,8 +192,8 @@ private func localReadStateMarker(modifier: Modifier, peerId: PeerId) -> PeerRea } private func localReadStateMarker(network: Network, postbox: Postbox, peerId: PeerId) -> Signal { - return postbox.modify { modifier -> PeerReadStateMarker? in - return localReadStateMarker(modifier: modifier, peerId: peerId) + return postbox.transaction { transaction -> PeerReadStateMarker? in + return localReadStateMarker(transaction: transaction, peerId: peerId) } |> mapToSignalPromotingError { marker -> Signal in if let marker = marker { return .single(marker) @@ -211,9 +211,9 @@ private func validatePeerReadState(network: Network, postbox: Postbox, stateMana } let maybeAppliedReadState = readStateWithInitialState |> mapToSignal { (readState, initialMarker, finalMarker) -> Signal in - return stateManager.addCustomOperation(postbox.modify { modifier -> VerifyReadStateError? in + return stateManager.addCustomOperation(postbox.transaction { transaction -> VerifyReadStateError? in if initialMarker == finalMarker { - modifier.resetIncomingReadStates([peerId: [Namespaces.Message.Cloud: readState]]) + transaction.resetIncomingReadStates([peerId: [Namespaces.Message.Cloud: readState]]) return nil } else { return .Retry @@ -337,8 +337,8 @@ private func pushPeerReadState(network: Network, postbox: Postbox, stateManager: } private func pushPeerReadState(network: Network, postbox: Postbox, stateManager: AccountStateManager, peerId: PeerId) -> Signal { - let currentReadState = postbox.modify { modifier -> PeerReadState? in - if let readStates = modifier.getPeerReadStates(peerId) { + let currentReadState = postbox.transaction { transaction -> PeerReadState? in + if let readStates = transaction.getPeerReadStates(peerId) { for (namespace, readState) in readStates { if namespace == Namespaces.Message.Cloud || namespace == Namespaces.Message.SecretIncoming { return readState @@ -359,17 +359,17 @@ private func pushPeerReadState(network: Network, postbox: Postbox, stateManager: let verifiedState = pushedState |> mapToSignal { readState -> Signal in - return stateManager.addCustomOperation(postbox.modify { modifier -> VerifyReadStateError? in - if let readStates = modifier.getPeerReadStates(peerId) { + return stateManager.addCustomOperation(postbox.transaction { transaction -> VerifyReadStateError? in + if let readStates = transaction.getPeerReadStates(peerId) { for (namespace, currentReadState) in readStates where namespace == Namespaces.Message.Cloud { if currentReadState == readState { - modifier.confirmSynchronizedIncomingReadState(peerId) + transaction.confirmSynchronizedIncomingReadState(peerId) return nil } } return .Retry } else { - modifier.confirmSynchronizedIncomingReadState(peerId) + transaction.confirmSynchronizedIncomingReadState(peerId) return nil } } diff --git a/TelegramCore/SynchronizePinnedChatsOperation.swift b/TelegramCore/SynchronizePinnedChatsOperation.swift index 8193d1324a..34a62623bc 100644 --- a/TelegramCore/SynchronizePinnedChatsOperation.swift +++ b/TelegramCore/SynchronizePinnedChatsOperation.swift @@ -52,15 +52,15 @@ final class SynchronizePinnedChatsOperation: PostboxCoding { } } -func addSynchronizePinnedChatsOperation(modifier: Modifier) { +func addSynchronizePinnedChatsOperation(transaction: Transaction) { var updateLocalIndex: Int32? - modifier.operationLogEnumerateEntries(peerId: PeerId(namespace: 0, id: 0), tag: OperationLogTags.SynchronizePinnedChats, { entry in + transaction.operationLogEnumerateEntries(peerId: PeerId(namespace: 0, id: 0), tag: OperationLogTags.SynchronizePinnedChats, { entry in updateLocalIndex = entry.tagLocalIndex return false }) - let operationContents = SynchronizePinnedChatsOperation(previousItemIds: modifier.getPinnedItemIds()) + let operationContents = SynchronizePinnedChatsOperation(previousItemIds: transaction.getPinnedItemIds()) if let updateLocalIndex = updateLocalIndex { - let _ = modifier.operationLogRemoveEntry(peerId: PeerId(namespace: 0, id: 0), tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: updateLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: PeerId(namespace: 0, id: 0), tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: updateLocalIndex) } - modifier.operationLogAddEntry(peerId: PeerId(namespace: 0, id: 0), tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) + transaction.operationLogAddEntry(peerId: PeerId(namespace: 0, id: 0), tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) } diff --git a/TelegramCore/SynchronizeSavedGifsOperation.swift b/TelegramCore/SynchronizeSavedGifsOperation.swift index aa5417f7b4..8623e5b539 100644 --- a/TelegramCore/SynchronizeSavedGifsOperation.swift +++ b/TelegramCore/SynchronizeSavedGifsOperation.swift @@ -64,12 +64,12 @@ final class SynchronizeSavedGifsOperation: PostboxCoding { } } -func addSynchronizeSavedGifsOperation(modifier: Modifier, operation: SynchronizeSavedGifsOperationContent) { +func addSynchronizeSavedGifsOperation(transaction: Transaction, operation: SynchronizeSavedGifsOperationContent) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeSavedGifs let peerId = PeerId(namespace: 0, id: 0) var topOperation: (SynchronizeSavedGifsOperation, Int32)? - modifier.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in + transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in if let operation = entry.contents as? SynchronizeSavedGifsOperation { topOperation = (operation, entry.tagLocalIndex) } @@ -77,28 +77,28 @@ func addSynchronizeSavedGifsOperation(modifier: Modifier, operation: Synchronize }) if let (topOperation, topLocalIndex) = topOperation, case .sync = topOperation.content { - let _ = modifier.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: topLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: topLocalIndex) } - modifier.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeSavedGifsOperation(content: operation)) - modifier.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeSavedGifsOperation(content: .sync)) + transaction.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeSavedGifsOperation(content: operation)) + transaction.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeSavedGifsOperation(content: .sync)) } public func addSavedGif(postbox: Postbox, file: TelegramMediaFile) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in if let resource = file.resource as? CloudDocumentMediaResource { - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 200) - addSynchronizeSavedGifsOperation(modifier: modifier, operation: .add(id: resource.fileId, accessHash: resource.accessHash)) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: RecentMediaItem(file)), removeTailIfCountExceeds: 200) + addSynchronizeSavedGifsOperation(transaction: transaction, operation: .add(id: resource.fileId, accessHash: resource.accessHash)) } } } public func removeSavedGif(postbox: Postbox, mediaId: MediaId) -> Signal { - return postbox.modify { modifier -> Void in - if let entry = modifier.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, itemId: RecentMediaItemId(mediaId).rawValue), let item = entry.contents as? RecentMediaItem { + return postbox.transaction { transaction -> Void in + if let entry = transaction.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, itemId: RecentMediaItemId(mediaId).rawValue), let item = entry.contents as? RecentMediaItem { if let file = item.media as? TelegramMediaFile, let resource = file.resource as? CloudDocumentMediaResource { - modifier.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, itemId: entry.id) - addSynchronizeSavedGifsOperation(modifier: modifier, operation: .remove(id: resource.fileId, accessHash: resource.accessHash)) + transaction.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudRecentGifs, itemId: entry.id) + addSynchronizeSavedGifsOperation(transaction: transaction, operation: .remove(id: resource.fileId, accessHash: resource.accessHash)) } } } diff --git a/TelegramCore/SynchronizeSavedStickersOperation.swift b/TelegramCore/SynchronizeSavedStickersOperation.swift index eb8a62ea8a..5941996c8d 100644 --- a/TelegramCore/SynchronizeSavedStickersOperation.swift +++ b/TelegramCore/SynchronizeSavedStickersOperation.swift @@ -64,12 +64,12 @@ final class SynchronizeSavedStickersOperation: PostboxCoding { } } -func addSynchronizeSavedStickersOperation(modifier: Modifier, operation: SynchronizeSavedStickersOperationContent) { +func addSynchronizeSavedStickersOperation(transaction: Transaction, operation: SynchronizeSavedStickersOperationContent) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeSavedStickers let peerId = PeerId(namespace: 0, id: 0) var topOperation: (SynchronizeSavedStickersOperation, Int32)? - modifier.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in + transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in if let operation = entry.contents as? SynchronizeSavedStickersOperation { topOperation = (operation, entry.tagLocalIndex) } @@ -77,11 +77,11 @@ func addSynchronizeSavedStickersOperation(modifier: Modifier, operation: Synchro }) if let (topOperation, topLocalIndex) = topOperation, case .sync = topOperation.content { - let _ = modifier.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: topLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: peerId, tag: tag, tagLocalIndex: topLocalIndex) } - modifier.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeSavedStickersOperation(content: operation)) - modifier.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeSavedStickersOperation(content: .sync)) + transaction.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeSavedStickersOperation(content: operation)) + transaction.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeSavedStickersOperation(content: .sync)) } public enum AddSavedStickerError { @@ -89,8 +89,8 @@ public enum AddSavedStickerError { case notFound } -public func getIsStickerSaved(modifier: Modifier, fileId: MediaId) -> Bool { - if let _ = modifier.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: RecentMediaItemId(fileId).rawValue) { +public func getIsStickerSaved(transaction: Transaction, fileId: MediaId) -> Bool { + if let _ = transaction.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: RecentMediaItemId(fileId).rawValue) { return true } else{ return false @@ -98,7 +98,7 @@ public func getIsStickerSaved(modifier: Modifier, fileId: MediaId) -> Bool { } public func addSavedSticker(postbox: Postbox, network: Network, file: TelegramMediaFile) -> Signal { - return postbox.modify { modifier -> Signal in + return postbox.transaction { transaction -> Signal in for attribute in file.attributes { if case let .Sticker(_, maybePackReference, _) = attribute, let packReference = maybePackReference { var fetchReference: StickerPackReference? @@ -106,14 +106,14 @@ public func addSavedSticker(postbox: Postbox, network: Network, file: TelegramMe case .name: fetchReference = packReference case let .id(id, _): - let items = modifier.getItemCollectionItems(collectionId: ItemCollectionId(namespace: Namespaces.ItemCollection.CloudStickerPacks, id: id)) + let items = transaction.getItemCollectionItems(collectionId: ItemCollectionId(namespace: Namespaces.ItemCollection.CloudStickerPacks, id: id)) var found = false inner: for item in items { if let stickerItem = item as? StickerPackItem { if stickerItem.file.fileId == file.fileId { let stringRepresentations = stickerItem.getStringRepresentationsOfIndexKeys() found = true - addSavedSticker(modifier: modifier, file: stickerItem.file, stringRepresentations: stringRepresentations) + addSavedSticker(transaction: transaction, file: stickerItem.file, stringRepresentations: stringRepresentations) break inner } } @@ -148,8 +148,8 @@ public func addSavedSticker(postbox: Postbox, network: Network, file: TelegramMe stickerStringRepresentations = stringRepresentationsByFile[file.fileId] } if let stickerStringRepresentations = stickerStringRepresentations { - return postbox.modify { modifier -> Void in - addSavedSticker(modifier: modifier, file: file, stringRepresentations: stickerStringRepresentations) + return postbox.transaction { transaction -> Void in + addSavedSticker(transaction: transaction, file: file, stringRepresentations: stickerStringRepresentations) } |> mapError { _ in return AddSavedStickerError.generic } } else { return .fail(.notFound) @@ -163,28 +163,28 @@ public func addSavedSticker(postbox: Postbox, network: Network, file: TelegramMe } |> mapError { _ in return AddSavedStickerError.generic } |> switchToLatest } -public func addSavedSticker(modifier: Modifier, file: TelegramMediaFile, stringRepresentations: [String]) { +public func addSavedSticker(transaction: Transaction, file: TelegramMediaFile, stringRepresentations: [String]) { if let resource = file.resource as? CloudDocumentMediaResource { - modifier.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: SavedStickerItem(file: file, stringRepresentations: stringRepresentations)), removeTailIfCountExceeds: 5) - addSynchronizeSavedStickersOperation(modifier: modifier, operation: .add(id: resource.fileId, accessHash: resource.accessHash)) + transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, item: OrderedItemListEntry(id: RecentMediaItemId(file.fileId).rawValue, contents: SavedStickerItem(file: file, stringRepresentations: stringRepresentations)), removeTailIfCountExceeds: 5) + addSynchronizeSavedStickersOperation(transaction: transaction, operation: .add(id: resource.fileId, accessHash: resource.accessHash)) } } -public func removeSavedSticker(modifier: Modifier, mediaId: MediaId) { - if let entry = modifier.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: RecentMediaItemId(mediaId).rawValue), let item = entry.contents as? SavedStickerItem { +public func removeSavedSticker(transaction: Transaction, mediaId: MediaId) { + if let entry = transaction.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: RecentMediaItemId(mediaId).rawValue), let item = entry.contents as? SavedStickerItem { if let resource = item.file.resource as? CloudDocumentMediaResource { - modifier.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: entry.id) - addSynchronizeSavedStickersOperation(modifier: modifier, operation: .remove(id: resource.fileId, accessHash: resource.accessHash)) + transaction.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: entry.id) + addSynchronizeSavedStickersOperation(transaction: transaction, operation: .remove(id: resource.fileId, accessHash: resource.accessHash)) } } } public func removeSavedSticker(postbox: Postbox, mediaId: MediaId) -> Signal { - return postbox.modify { modifier in - if let entry = modifier.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: RecentMediaItemId(mediaId).rawValue), let item = entry.contents as? SavedStickerItem { + return postbox.transaction { transaction in + if let entry = transaction.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: RecentMediaItemId(mediaId).rawValue), let item = entry.contents as? SavedStickerItem { if let resource = item.file.resource as? CloudDocumentMediaResource { - modifier.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: entry.id) - addSynchronizeSavedStickersOperation(modifier: modifier, operation: .remove(id: resource.fileId, accessHash: resource.accessHash)) + transaction.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.CloudSavedStickers, itemId: entry.id) + addSynchronizeSavedStickersOperation(transaction: transaction, operation: .remove(id: resource.fileId, accessHash: resource.accessHash)) } } } diff --git a/TelegramCore/TelegramDeviceContactImportInfo.swift b/TelegramCore/TelegramDeviceContactImportInfo.swift index 1f97b825a7..99bb648972 100644 --- a/TelegramCore/TelegramDeviceContactImportInfo.swift +++ b/TelegramCore/TelegramDeviceContactImportInfo.swift @@ -54,12 +54,12 @@ final class TelegramDeviceContactImportInfo: PostboxCoding { } public func deviceContactsImportedByCount(postbox: Postbox, contacts: [DeviceContact]) -> Signal<[String: Int32], NoError> { - return postbox.modify { modifier -> [String: Int32] in + return postbox.transaction { transaction -> [String: Int32] in var result: [String: Int32] = [:] for contact in contacts { var maxCount: Int32 = 0 for number in contact.phoneNumbers { - if let value = modifier.getDeviceContactImportInfo(TelegramDeviceContactImportIdentifier.phoneNumber(number.number.normalized.rawValue)) as? TelegramDeviceContactImportInfo { + if let value = transaction.getDeviceContactImportInfo(TelegramDeviceContactImportIdentifier.phoneNumber(number.number.normalized.rawValue)) as? TelegramDeviceContactImportInfo { maxCount = max(maxCount, value.importedByCount) } } diff --git a/TelegramCore/ToggleChannelSignatures.swift b/TelegramCore/ToggleChannelSignatures.swift index 6adc735479..d32e35e9d1 100644 --- a/TelegramCore/ToggleChannelSignatures.swift +++ b/TelegramCore/ToggleChannelSignatures.swift @@ -10,8 +10,8 @@ import Foundation #endif public func toggleShouldChannelMessagesSignatures(account:Account, peerId:PeerId, enabled: Bool) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) as? TelegramChannel, let inputChannel = apiInputChannel(peer) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) as? TelegramChannel, let inputChannel = apiInputChannel(peer) { return account.network.request(Api.functions.channels.toggleSignatures(channel: inputChannel, enabled: enabled ? .boolTrue : .boolFalse)) |> retryRequest |> map { updates -> Void in account.stateManager.addUpdates(updates) } diff --git a/TelegramCore/TogglePeerChatPinned.swift b/TelegramCore/TogglePeerChatPinned.swift index 7a4807d50e..885da068aa 100644 --- a/TelegramCore/TogglePeerChatPinned.swift +++ b/TelegramCore/TogglePeerChatPinned.swift @@ -13,8 +13,8 @@ public enum TogglePeerChatPinnedResult { } public func toggleItemPinned(postbox: Postbox, itemId: PinnedItemId) -> Signal { - return postbox.modify { modifier -> TogglePeerChatPinnedResult in - var itemIds = modifier.getPinnedItemIds() + return postbox.transaction { transaction -> TogglePeerChatPinnedResult in + var itemIds = transaction.getPinnedItemIds() let sameKind = itemIds.filter { item in switch itemId { case let .peer(lhsPeerId): @@ -41,14 +41,14 @@ public func toggleItemPinned(postbox: Postbox, itemId: PinnedItemId) -> Signal Signal { - return postbox.modify { modifier -> TemporaryTwoStepPasswordToken? in + return postbox.transaction { transaction -> TemporaryTwoStepPasswordToken? in let key = ValueBoxKey(length: 1) key.setUInt8(0, value: 0) - return modifier.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key)) as? TemporaryTwoStepPasswordToken + return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key)) as? TemporaryTwoStepPasswordToken } } public func cacheTwoStepPasswordToken(postbox: Postbox, token: TemporaryTwoStepPasswordToken?) -> Signal { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in let key = ValueBoxKey(length: 1) key.setUInt8(0, value: 0) if let token = token { - modifier.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key), entry: token, collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key), entry: token, collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) } else { - modifier.removeItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key)) + transaction.removeItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key)) } } } diff --git a/TelegramCore/UpdateAccountPeerName.swift b/TelegramCore/UpdateAccountPeerName.swift index ae8eb80dd5..c7ed4e71db 100644 --- a/TelegramCore/UpdateAccountPeerName.swift +++ b/TelegramCore/UpdateAccountPeerName.swift @@ -18,10 +18,10 @@ public func updateAccountPeerName(account: Account, firstName: String, lastName: return .single(nil) } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if let result = result { let peer = TelegramUser(user: result) - updatePeers(modifier: modifier, peers: [peer], update: { $1 }) + updatePeers(transaction: transaction, peers: [peer], update: { $1 }) } } } @@ -38,8 +38,8 @@ public func updateAbout(account: Account, about: String?) -> Signal mapToSignal { apiUser -> Signal in - return account.postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: Set([account.peerId]), update: { _, current in + return account.postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: Set([account.peerId]), update: { _, current in if let current = current as? CachedUserData { return current.withUpdatedAbout(about) } else { diff --git a/TelegramCore/UpdateCachedChannelParticipants.swift b/TelegramCore/UpdateCachedChannelParticipants.swift index 7c4124abd2..a3c29adfa9 100644 --- a/TelegramCore/UpdateCachedChannelParticipants.swift +++ b/TelegramCore/UpdateCachedChannelParticipants.swift @@ -14,7 +14,7 @@ func fetchAndUpdateCachedParticipants(peerId: PeerId, network: Network, postbox: return network.request(Api.functions.channels.getParticipants(channel: inputChannel, filter: .channelParticipantsRecent, offset: 0, limit: 200, hash: 0)) |> retryRequest |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in switch result { case let .channelParticipants(count, participants, users): var peers: [Peer] = [] @@ -27,15 +27,15 @@ func fetchAndUpdateCachedParticipants(peerId: PeerId, network: Network, postbox: } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) let parsedParticipants = CachedChannelParticipants(apiParticipants: participants) - modifier.updatePeerCachedData(peerIds: [peerId], update: { peerId, currentData in + transaction.updatePeerCachedData(peerIds: [peerId], update: { peerId, currentData in if let currentData = currentData as? CachedChannelData { return currentData.withUpdatedTopParticipants(parsedParticipants) } else { diff --git a/TelegramCore/UpdateCachedPeerData.swift b/TelegramCore/UpdateCachedPeerData.swift index 81782fa21e..50a1ae9d1e 100644 --- a/TelegramCore/UpdateCachedPeerData.swift +++ b/TelegramCore/UpdateCachedPeerData.swift @@ -8,9 +8,9 @@ import Foundation #endif func fetchAndUpdateSupplementalCachedPeerData(peerId: PeerId, network: Network, postbox: Postbox) -> Signal { - return postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) { - let cachedData = modifier.getPeerCachedData(peerId: peerId) + return postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) { + let cachedData = transaction.getPeerCachedData(peerId: peerId) if let cachedData = cachedData as? CachedUserData { if cachedData.reportStatus != .unknown { @@ -31,9 +31,9 @@ func fetchAndUpdateSupplementalCachedPeerData(peerId: PeerId, network: Network, } if peerId.namespace == Namespaces.Peer.SecretChat { - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in let reportStatus: PeerReportStatus - if let peer = modifier.getPeer(peerId), let associatedPeerId = peer.associatedPeerId, !modifier.isPeerContact(peerId: associatedPeerId) { + if let peer = transaction.getPeer(peerId), let associatedPeerId = peer.associatedPeerId, !transaction.isPeerContact(peerId: associatedPeerId) { if let peer = peer as? TelegramSecretChat, case .creator = peer.role { reportStatus = .none } else { @@ -43,7 +43,7 @@ func fetchAndUpdateSupplementalCachedPeerData(peerId: PeerId, network: Network, reportStatus = .none } - modifier.updatePeerCachedData(peerIds: [peerId], update: { peerId, current in + transaction.updatePeerCachedData(peerIds: [peerId], update: { peerId, current in if let current = current as? CachedSecretChatData { return current.withUpdatedReportStatus(reportStatus) } else { @@ -61,8 +61,8 @@ func fetchAndUpdateSupplementalCachedPeerData(peerId: PeerId, network: Network, reportStatus = (flags & (1 << 0) != 0) ? .canReport : .none } - return postbox.modify { modifier -> Void in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + return postbox.transaction { transaction -> Void in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in switch peerId.namespace { case Namespaces.Peer.CloudUser: let previous: CachedUserData @@ -111,19 +111,19 @@ func fetchAndUpdateCachedPeerData(peerId: PeerId, network: Network, postbox: Pos return network.request(Api.functions.users.getFullUser(id: inputUser)) |> retryRequest |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in switch result { case let .userFull(_, user, _, _, _, notifySettings, _, _): let telegramUser = TelegramUser(user: user) - updatePeers(modifier: modifier, peers: [telegramUser], update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: [telegramUser], update: { _, updated -> Peer in return updated }) - modifier.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)]) + transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)]) if let presence = TelegramUserPresence(apiUser: user) { - modifier.updatePeerPresences([peer.id: presence]) + transaction.updatePeerPresences([peer.id: presence]) } } - modifier.updatePeerCachedData(peerIds: [peerId], update: { peerId, current in + transaction.updatePeerCachedData(peerIds: [peerId], update: { peerId, current in let previous: CachedUserData if let current = current as? CachedUserData { previous = current @@ -148,12 +148,12 @@ func fetchAndUpdateCachedPeerData(peerId: PeerId, network: Network, postbox: Pos return network.request(Api.functions.messages.getFullChat(chatId: peerId.id)) |> retryRequest |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in switch result { case let .chatFull(fullChat, chats, users): switch fullChat { case let .chatFull(_, _, _, notifySettings, _, _): - modifier.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)]) + transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)]) case .channelFull: break } @@ -187,13 +187,13 @@ func fetchAndUpdateCachedPeerData(peerId: PeerId, network: Network, postbox: Pos } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) - modifier.updatePeerCachedData(peerIds: [peerId], update: { _, current in + transaction.updatePeerCachedData(peerIds: [peerId], update: { _, current in let previous: CachedGroupData if let current = current as? CachedGroupData { previous = current @@ -213,12 +213,12 @@ func fetchAndUpdateCachedPeerData(peerId: PeerId, network: Network, postbox: Pos return network.request(Api.functions.channels.getFullChannel(channel: inputChannel)) |> retryRequest |> mapToSignal { result -> Signal in - return postbox.modify { modifier -> Void in + return postbox.transaction { transaction -> Void in switch result { case let .chatFull(fullChat, chats, users): switch fullChat { case let .channelFull(_, _, _, _, _, _, _, _, _, _, _, notifySettings, _, _, _, _, _, _, _): - modifier.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)]) + transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)]) case .chatFull: break } @@ -282,11 +282,11 @@ func fetchAndUpdateCachedPeerData(peerId: PeerId, network: Network, postbox: Pos } } - updatePeers(modifier: modifier, peers: peers, update: { _, updated -> Peer in + updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) - modifier.updatePeerPresences(peerPresences) + transaction.updatePeerPresences(peerPresences) let stickerPack: StickerPackCollectionInfo? = stickerSet.flatMap { apiSet -> StickerPackCollectionInfo in let namespace: ItemCollectionId.Namespace @@ -303,7 +303,7 @@ func fetchAndUpdateCachedPeerData(peerId: PeerId, network: Network, postbox: Pos } var minAvailableMessageIdUpdated = false - modifier.updatePeerCachedData(peerIds: [peerId], update: { _, current in + transaction.updatePeerCachedData(peerIds: [peerId], update: { _, current in let previous: CachedChannelData if let current = current as? CachedChannelData { previous = current @@ -325,7 +325,7 @@ func fetchAndUpdateCachedPeerData(peerId: PeerId, network: Network, postbox: Pos }) if let minAvailableMessageId = minAvailableMessageId, minAvailableMessageIdUpdated { - modifier.deleteMessagesInRange(peerId: peerId, namespace: minAvailableMessageId.namespace, minId: 1, maxId: minAvailableMessageId.id) + transaction.deleteMessagesInRange(peerId: peerId, namespace: minAvailableMessageId.namespace, minId: 1, maxId: minAvailableMessageId.id) } case .chatFull: break diff --git a/TelegramCore/UpdateContactName.swift b/TelegramCore/UpdateContactName.swift index e2afa85b24..01f64c1327 100644 --- a/TelegramCore/UpdateContactName.swift +++ b/TelegramCore/UpdateContactName.swift @@ -14,19 +14,19 @@ public enum UpdateContactNameError { } public func updateContactName(account: Account, peerId: PeerId, firstName: String, lastName: String) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) as? TelegramUser, let phone = peer.phone, !phone.isEmpty { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) as? TelegramUser, let phone = peer.phone, !phone.isEmpty { return account.network.request(Api.functions.contacts.importContacts(contacts: [Api.InputContact.inputPhoneContact(clientId: 1, phone: phone, firstName: firstName, lastName: lastName)])) |> mapError { _ -> UpdateContactNameError in return .generic } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in switch result { case let .importedContacts(_, _, _, users): if let first = users.first { let user = TelegramUser(user: first) - updatePeers(modifier: modifier, peers: [user], update: { _, updated in + updatePeers(transaction: transaction, peers: [user], update: { _, updated in return updated }) } diff --git a/TelegramCore/UpdateGroupSpecificStickerset.swift b/TelegramCore/UpdateGroupSpecificStickerset.swift index 3bb1b0a95c..b994307662 100644 --- a/TelegramCore/UpdateGroupSpecificStickerset.swift +++ b/TelegramCore/UpdateGroupSpecificStickerset.swift @@ -21,8 +21,8 @@ public func updateGroupSpecificStickerset(postbox: Postbox, network: Network, pe return network.request(api) |> mapError {_ in return} |> mapToSignal { value in switch value { case .boolTrue: - return postbox.modify { modifier -> Void in - return modifier.updatePeerCachedData(peerIds: [peerId], update: { _, current -> CachedPeerData? in + return postbox.transaction { transaction -> Void in + return transaction.updatePeerCachedData(peerIds: [peerId], update: { _, current -> CachedPeerData? in return (current as? CachedChannelData)?.withUpdatedStickerPack(info) }) } diff --git a/TelegramCore/UpdatePeerChatInterfaceState.swift b/TelegramCore/UpdatePeerChatInterfaceState.swift index 7e2529b128..21cbfda09f 100644 --- a/TelegramCore/UpdatePeerChatInterfaceState.swift +++ b/TelegramCore/UpdatePeerChatInterfaceState.swift @@ -8,16 +8,16 @@ import Foundation #endif public func updatePeerChatInterfaceState(account: Account, peerId: PeerId, state: SynchronizeableChatInterfaceState) -> Signal { - return account.postbox.modify { modifier -> Void in - let currentInputState = (modifier.getPeerChatInterfaceState(peerId) as? SynchronizeableChatInterfaceState)?.synchronizeableInputState + return account.postbox.transaction { transaction -> Void in + let currentInputState = (transaction.getPeerChatInterfaceState(peerId) as? SynchronizeableChatInterfaceState)?.synchronizeableInputState let updatedInputState = state.synchronizeableInputState if currentInputState != updatedInputState { if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudChannel || peerId.namespace == Namespaces.Peer.CloudGroup { - addSynchronizeChatInputStateOperation(modifier: modifier, peerId: peerId) + addSynchronizeChatInputStateOperation(transaction: transaction, peerId: peerId) } } - modifier.updatePeerChatInterfaceState(peerId, update: { _ in + transaction.updatePeerChatInterfaceState(peerId, update: { _ in return state }) } diff --git a/TelegramCore/UpdatePeerInfo.swift b/TelegramCore/UpdatePeerInfo.swift index 1e4ed97f86..f2e218a632 100644 --- a/TelegramCore/UpdatePeerInfo.swift +++ b/TelegramCore/UpdatePeerInfo.swift @@ -14,8 +14,8 @@ public enum UpdatePeerTitleError { } public func updatePeerTitle(account: Account, peerId: PeerId, title: String) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) { if let peer = peer as? TelegramChannel, let inputChannel = apiInputChannel(peer) { return account.network.request(Api.functions.channels.editTitle(channel: inputChannel, title: title)) |> mapError { _ -> UpdatePeerTitleError in @@ -24,9 +24,9 @@ public func updatePeerTitle(account: Account, peerId: PeerId, title: String) -> |> mapToSignal { result -> Signal in account.stateManager.addUpdates(result) - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if let apiChat = apiUpdatesGroups(result).first, let updatedPeer = parseTelegramGroupOrChannel(chat: apiChat) { - updatePeers(modifier: modifier, peers: [updatedPeer], update: { _, updated in + updatePeers(transaction: transaction, peers: [updatedPeer], update: { _, updated in return updated }) } @@ -40,9 +40,9 @@ public func updatePeerTitle(account: Account, peerId: PeerId, title: String) -> |> mapToSignal { result -> Signal in account.stateManager.addUpdates(result) - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if let apiChat = apiUpdatesGroups(result).first, let updatedPeer = parseTelegramGroupOrChannel(chat: apiChat) { - updatePeers(modifier: modifier, peers: [updatedPeer], update: { _, updated in + updatePeers(transaction: transaction, peers: [updatedPeer], update: { _, updated in return updated }) } @@ -62,17 +62,17 @@ public enum UpdatePeerDescriptionError { } public func updatePeerDescription(account: Account, peerId: PeerId, description: String?) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let peer = modifier.getPeer(peerId) { + return account.postbox.transaction { transaction -> Signal in + if let peer = transaction.getPeer(peerId) { if let peer = peer as? TelegramChannel, let inputChannel = apiInputChannel(peer) { return account.network.request(Api.functions.channels.editAbout(channel: inputChannel, about: description ?? "")) |> mapError { _ -> UpdatePeerDescriptionError in return .generic } |> mapToSignal { result -> Signal in - return account.postbox.modify { modifier -> Void in + return account.postbox.transaction { transaction -> Void in if case .boolTrue = result { - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedChannelData { return current.withUpdatedAbout(description) } else { diff --git a/TelegramCore/UpdatePeers.swift b/TelegramCore/UpdatePeers.swift index 799255ac8f..4f45641832 100644 --- a/TelegramCore/UpdatePeers.swift +++ b/TelegramCore/UpdatePeers.swift @@ -5,8 +5,8 @@ import Foundation import Postbox #endif -func updatePeerChatInclusionWithMinTimestamp(modifier: Modifier, id: PeerId, minTimestamp: Int32) { - let currentInclusion = modifier.getPeerChatListInclusion(id) +func updatePeerChatInclusionWithMinTimestamp(transaction: Transaction, id: PeerId, minTimestamp: Int32) { + let currentInclusion = transaction.getPeerChatListInclusion(id) var updatedInclusion: PeerChatListInclusion? switch currentInclusion { case .ifHasMessages, .ifHasMessagesOrOneOf: @@ -15,12 +15,12 @@ func updatePeerChatInclusionWithMinTimestamp(modifier: Modifier, id: PeerId, min break } if let updatedInclusion = updatedInclusion { - modifier.updatePeerChatListInclusion(id, inclusion: updatedInclusion) + transaction.updatePeerChatListInclusion(id, inclusion: updatedInclusion) } } -func updatePeerChatInclousionWithNewMessages(modifier: Modifier, id: PeerId) { - let currentInclusion = modifier.getPeerChatListInclusion(id) +func updatePeerChatInclousionWithNewMessages(transaction: Transaction, id: PeerId) { + let currentInclusion = transaction.getPeerChatListInclusion(id) var updatedInclusion: PeerChatListInclusion? switch currentInclusion { case .notSpecified: @@ -29,15 +29,15 @@ func updatePeerChatInclousionWithNewMessages(modifier: Modifier, id: PeerId) { break } if let updatedInclusion = updatedInclusion { - modifier.updatePeerChatListInclusion(id, inclusion: updatedInclusion) + transaction.updatePeerChatListInclusion(id, inclusion: updatedInclusion) } } -public func updatePeers(modifier: Modifier, peers: [Peer], update: (Peer?, Peer) -> Peer?) { - modifier.updatePeersInternal(peers, update: { previous, updated in +public func updatePeers(transaction: Transaction, peers: [Peer], update: (Peer?, Peer) -> Peer?) { + transaction.updatePeersInternal(peers, update: { previous, updated in let peerId = updated.id - let currentInclusion = modifier.getPeerChatListInclusion(peerId) + let currentInclusion = transaction.getPeerChatListInclusion(peerId) var updatedInclusion: PeerChatListInclusion? switch peerId.namespace { case Namespaces.Peer.CloudUser: @@ -101,12 +101,12 @@ public func updatePeers(modifier: Modifier, peers: [Peer], update: (Peer?, Peer) break } if let updatedInclusion = updatedInclusion { - modifier.updatePeerChatListInclusion(peerId, inclusion: updatedInclusion) + transaction.updatePeerChatListInclusion(peerId, inclusion: updatedInclusion) } if let channel = updated as? TelegramChannel { let previousGroupId = (previous as? TelegramChannel)?.peerGroupId if previousGroupId != channel.peerGroupId { - modifier.updatePeerGroupId(peerId, groupId: channel.peerGroupId) + transaction.updatePeerGroupId(peerId, groupId: channel.peerGroupId) } } return update(previous, updated) diff --git a/TelegramCore/UpdatePinnedMessage.swift b/TelegramCore/UpdatePinnedMessage.swift index 9062ce8c84..d37b686e0b 100644 --- a/TelegramCore/UpdatePinnedMessage.swift +++ b/TelegramCore/UpdatePinnedMessage.swift @@ -19,8 +19,8 @@ public enum PinnedMessageUpdate { } public func requestUpdatePinnedMessage(account: Account, peerId: PeerId, update: PinnedMessageUpdate) -> Signal { - return account.postbox.modify { modifier -> Peer? in - return modifier.getPeer(peerId) + return account.postbox.transaction { transaction -> Peer? in + return transaction.getPeer(peerId) } |> mapError { _ -> UpdatePinnedMessageError in return .generic } |> mapToSignal { peer -> Signal in @@ -53,8 +53,8 @@ public func requestUpdatePinnedMessage(account: Account, peerId: PeerId, update: } |> mapToSignal { updates -> Signal in account.stateManager.addUpdates(updates) - return account.postbox.modify { modifier in - modifier.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in + return account.postbox.transaction { transaction in + transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current in if let current = current as? CachedChannelData { let pinnedMessageId: MessageId? switch update { diff --git a/TelegramCore/UpdateSecretChat.swift b/TelegramCore/UpdateSecretChat.swift index ca50a5182c..f1b2085bfa 100644 --- a/TelegramCore/UpdateSecretChat.swift +++ b/TelegramCore/UpdateSecretChat.swift @@ -15,9 +15,9 @@ struct SecretChatRequestData { let a: MemoryBuffer } -func updateSecretChat(accountPeerId: PeerId, modifier: Modifier, chat: Api.EncryptedChat, requestData: SecretChatRequestData?) { - let currentPeer = modifier.getPeer(chat.peerId) as? TelegramSecretChat - let currentState = modifier.getPeerChatState(chat.peerId) as? SecretChatState +func updateSecretChat(accountPeerId: PeerId, transaction: Transaction, chat: Api.EncryptedChat, requestData: SecretChatRequestData?) { + let currentPeer = transaction.getPeer(chat.peerId) as? TelegramSecretChat + let currentState = transaction.getPeerChatState(chat.peerId) as? SecretChatState assert((currentPeer == nil) == (currentState == nil)) switch chat { case let .encryptedChat(_, _, _, adminId, _, gAOrB, remoteKeyFingerprint): @@ -45,10 +45,10 @@ func updateSecretChat(accountPeerId: PeerId, modifier: Modifier, chat: Api.Encry var updatedState = currentState.withUpdatedKeychain(SecretChatKeychain(keys: [SecretChatKey(fingerprint: keyFingerprint, key: MemoryBuffer(data: key), validity: .indefinite, useCount: 0)])).withUpdatedEmbeddedState(.basicLayer).withUpdatedKeyFingerprint(SecretChatKeyFingerprint(sha1: SecretChatKeySha1Fingerprint(digest: sha1Digest(key)), sha256: SecretChatKeySha256Fingerprint(digest: sha256Digest(key)))) - updatedState = secretChatAddReportCurrentLayerSupportOperationAndUpdateRequestedLayer(modifier: modifier, peerId: currentPeer.id, state: updatedState) + updatedState = secretChatAddReportCurrentLayerSupportOperationAndUpdateRequestedLayer(transaction: transaction, peerId: currentPeer.id, state: updatedState) - modifier.setPeerChatState(currentPeer.id, state: updatedState) - updatePeers(modifier: modifier, peers: [currentPeer.withUpdatedEmbeddedState(updatedState.embeddedState.peerState)], update: { _, updated in + transaction.setPeerChatState(currentPeer.id, state: updatedState) + updatePeers(transaction: transaction, peers: [currentPeer.withUpdatedEmbeddedState(updatedState.embeddedState.peerState)], update: { _, updated in return updated }) } else { @@ -61,9 +61,9 @@ func updateSecretChat(accountPeerId: PeerId, modifier: Modifier, chat: Api.Encry if let currentPeer = currentPeer, let currentState = currentState { let state = currentState.withUpdatedEmbeddedState(.terminated) let peer = currentPeer.withUpdatedEmbeddedState(state.embeddedState.peerState) - updatePeers(modifier: modifier, peers: [peer], update: { _, updated in return updated }) - modifier.setPeerChatState(peer.id, state: state) - modifier.operationLogRemoveAllEntries(peerId: peer.id, tag: OperationLogTags.SecretOutgoing) + updatePeers(transaction: transaction, peers: [peer], update: { _, updated in return updated }) + transaction.setPeerChatState(peer.id, state: state) + transaction.operationLogRemoveAllEntries(peerId: peer.id, tag: OperationLogTags.SecretOutgoing) } else { Logger.shared.log("State", "got encryptedChatDiscarded, but peer doesn't exist") } @@ -77,12 +77,12 @@ func updateSecretChat(accountPeerId: PeerId, modifier: Modifier, chat: Api.Encry let randomStatus = SecRandomCopyBytes(nil, 256, bBytes.assumingMemoryBound(to: UInt8.self)) let b = MemoryBuffer(memory: bBytes, capacity: 256, length: 256, freeWhenDone: true) if randomStatus == 0 { - let updatedState = addSecretChatOutgoingOperation(modifier: modifier, peerId: chat.peerId, operation: .initialHandshakeAccept(gA: MemoryBuffer(gA), accessHash: accessHash, b: b), state: state) - modifier.setPeerChatState(chat.peerId, state: updatedState) + let updatedState = addSecretChatOutgoingOperation(transaction: transaction, peerId: chat.peerId, operation: .initialHandshakeAccept(gA: MemoryBuffer(gA), accessHash: accessHash, b: b), state: state) + transaction.setPeerChatState(chat.peerId, state: updatedState) let peer = TelegramSecretChat(id: chat.peerId, creationDate: date, regularPeerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: adminId), accessHash: accessHash, role: updatedState.role, embeddedState: updatedState.embeddedState.peerState, messageAutoremoveTimeout: nil) - updatePeers(modifier: modifier, peers: [peer], update: { _, updated in return updated }) - modifier.resetIncomingReadStates([peer.id: [ + updatePeers(transaction: transaction, peers: [peer], update: { _, updated in return updated }) + transaction.resetIncomingReadStates([peer.id: [ Namespaces.Message.SecretIncoming: .indexBased(maxIncomingReadIndex: MessageIndex.lowerBound(peerId: peer.id), maxOutgoingReadIndex: MessageIndex.lowerBound(peerId: peer.id), count: 0, markedUnread: false), Namespaces.Message.Local: .indexBased(maxIncomingReadIndex: MessageIndex.lowerBound(peerId: peer.id), maxOutgoingReadIndex: MessageIndex.lowerBound(peerId: peer.id), count: 0, markedUnread: false) ] @@ -97,9 +97,9 @@ func updateSecretChat(accountPeerId: PeerId, modifier: Modifier, chat: Api.Encry if let requestData = requestData, currentPeer == nil && adminId == accountPeerId.id { let state = SecretChatState(role: .creator, embeddedState: .handshake(.requested(g: requestData.g, p: requestData.p, a: requestData.a)), keychain: SecretChatKeychain(keys: []), keyFingerprint: nil, messageAutoremoveTimeout: nil) let peer = TelegramSecretChat(id: chat.peerId, creationDate: date, regularPeerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: participantId), accessHash: accessHash, role: state.role, embeddedState: state.embeddedState.peerState, messageAutoremoveTimeout: nil) - updatePeers(modifier: modifier, peers: [peer], update: { _, updated in return updated }) - modifier.setPeerChatState(peer.id, state: state) - modifier.resetIncomingReadStates([peer.id: [ + updatePeers(transaction: transaction, peers: [peer], update: { _, updated in return updated }) + transaction.setPeerChatState(peer.id, state: state) + transaction.resetIncomingReadStates([peer.id: [ Namespaces.Message.SecretIncoming: .indexBased(maxIncomingReadIndex: MessageIndex.lowerBound(peerId: peer.id), maxOutgoingReadIndex: MessageIndex.lowerBound(peerId: peer.id), count: 0, markedUnread: false), Namespaces.Message.Local: .indexBased(maxIncomingReadIndex: MessageIndex.lowerBound(peerId: peer.id), maxOutgoingReadIndex: MessageIndex.lowerBound(peerId: peer.id), count: 0, markedUnread: false) ] diff --git a/TelegramCore/UpdatedAccountPrivacySettings.swift b/TelegramCore/UpdatedAccountPrivacySettings.swift index 87601d1225..be9863ce69 100644 --- a/TelegramCore/UpdatedAccountPrivacySettings.swift +++ b/TelegramCore/UpdatedAccountPrivacySettings.swift @@ -47,8 +47,8 @@ public func requestAccountPrivacySettings(account: Account) -> Signal AccountPrivacySettings in - updatePeers(modifier: modifier, peers: peers, update: { _, updated in + return account.postbox.transaction { transaction -> AccountPrivacySettings in + updatePeers(transaction: transaction, peers: peers, update: { _, updated in return updated }) @@ -82,10 +82,10 @@ public enum UpdateSelectiveAccountPrivacySettingsType { } } -private func apiInputUsers(modifier: Modifier, peerIds: [PeerId]) -> [Api.InputUser] { +private func apiInputUsers(transaction: Transaction, peerIds: [PeerId]) -> [Api.InputUser] { var result: [Api.InputUser] = [] for peerId in peerIds { - if let peer = modifier.getPeer(peerId), let inputUser = apiInputUser(peer) { + if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) { result.append(inputUser) } } @@ -93,25 +93,25 @@ private func apiInputUsers(modifier: Modifier, peerIds: [PeerId]) -> [Api.InputU } public func updateSelectiveAccountPrivacySettings(account: Account, type: UpdateSelectiveAccountPrivacySettingsType, settings: SelectivePrivacySettings) -> Signal { - return account.postbox.modify { modifier -> Signal in + return account.postbox.transaction { transaction -> Signal in var rules: [Api.InputPrivacyRule] = [] switch settings { case let .disableEveryone(enableFor): if !enableFor.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(users: apiInputUsers(modifier: modifier, peerIds: Array(enableFor)))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(users: apiInputUsers(transaction: transaction, peerIds: Array(enableFor)))) } rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowAll) case let .enableContacts(enableFor, disableFor): if !enableFor.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(users: apiInputUsers(modifier: modifier, peerIds: Array(enableFor)))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(users: apiInputUsers(transaction: transaction, peerIds: Array(enableFor)))) } if !disableFor.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(users: apiInputUsers(modifier: modifier, peerIds: Array(disableFor)))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(users: apiInputUsers(transaction: transaction, peerIds: Array(disableFor)))) } rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowContacts) case let.enableEveryone(disableFor): if !disableFor.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(users: apiInputUsers(modifier: modifier, peerIds: Array(disableFor)))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(users: apiInputUsers(transaction: transaction, peerIds: Array(disableFor)))) } rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowAll) } diff --git a/TelegramCore/Wallpapers.swift b/TelegramCore/Wallpapers.swift index 120104faa4..712b363f44 100644 --- a/TelegramCore/Wallpapers.swift +++ b/TelegramCore/Wallpapers.swift @@ -36,8 +36,8 @@ public enum TelegramWallpaper: OrderedItemListEntryContents, Equatable { } public func telegramWallpapers(account: Account) -> Signal<[TelegramWallpaper], NoError> { - return account.postbox.modify { modifier -> [TelegramWallpaper] in - let items = modifier.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudWallpapers) + return account.postbox.transaction { transaction -> [TelegramWallpaper] in + let items = transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudWallpapers) if items.count == 0 { return [.color(0x000000), .builtin] } else { @@ -63,14 +63,14 @@ public func telegramWallpapers(account: Account) -> Signal<[TelegramWallpaper], if items == list { return .complete() } else { - return account.postbox.modify { modifier -> [TelegramWallpaper] in + return account.postbox.transaction { transaction -> [TelegramWallpaper] in var entries: [OrderedItemListEntry] = [] for item in items { var intValue = Int32(entries.count) let id = MemoryBuffer(data: Data(bytes: &intValue, count: 4)) entries.append(OrderedItemListEntry(id: id, contents: item)) } - modifier.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.CloudWallpapers, items: entries) + transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.CloudWallpapers, items: entries) return items } diff --git a/TelegramCore/WebpagePreview.swift b/TelegramCore/WebpagePreview.swift index ae5d306e6e..2255fe72ba 100644 --- a/TelegramCore/WebpagePreview.swift +++ b/TelegramCore/WebpagePreview.swift @@ -10,8 +10,8 @@ import Foundation #endif public func webpagePreview(account: Account, url: String, webpageId: MediaId? = nil) -> Signal { - return account.postbox.modify { modifier -> Signal in - if let webpageId = webpageId, let webpage = modifier.getMedia(webpageId) as? TelegramMediaWebpage { + return account.postbox.transaction { transaction -> Signal in + if let webpageId = webpageId, let webpage = transaction.getMedia(webpageId) as? TelegramMediaWebpage { return .single(webpage) } else { return account.network.request(Api.functions.messages.getWebPagePreview(flags: 0, message: url, entities: nil)) @@ -46,8 +46,8 @@ public func actualizedWebpage(postbox: Postbox, network: Network, webpage: Teleg } |> mapToSignal { result -> Signal in if let updatedWebpage = telegramMediaWebpageFromApiWebpage(result, url: nil), case .Loaded = updatedWebpage.content, updatedWebpage.webpageId == webpage.webpageId { - return postbox.modify { modifier -> TelegramMediaWebpage in - modifier.updateMedia(webpage.webpageId, update: updatedWebpage) + return postbox.transaction { transaction -> TelegramMediaWebpage in + transaction.updateMedia(webpage.webpageId, update: updatedWebpage) return updatedWebpage } } else {