From 4dae31e3401fa23a78c1eaecdae625b566379e5e Mon Sep 17 00:00:00 2001 From: Ali <> Date: Wed, 24 Mar 2021 19:35:52 +0400 Subject: [PATCH] Initial peer id refactoring --- Telegram/SiriIntents/IntentContacts.swift | 2 +- Telegram/SiriIntents/IntentMessages.swift | 2 +- .../Sources/AccountContext.swift | 2 +- .../Sources/DeviceContactData.swift | 2 +- .../Sources/FetchMediaUtils.swift | 2 +- .../AvatarNode/Sources/AvatarNode.swift | 12 +- .../ChatListUI/Sources/ChatContextMenus.swift | 2 +- .../Sources/ChatListController.swift | 2 +- .../Sources/ChatListControllerNode.swift | 2 +- .../Sources/ChatListSearchListPaneNode.swift | 2 +- .../Sources/Node/ChatListItem.swift | 2 +- .../Sources/Node/ChatListNodeEntries.swift | 2 +- .../InviteContactsControllerNode.swift | 2 +- .../Sources/InstantPageControllerNode.swift | 2 +- .../Sources/InviteLinkViewController.swift | 2 +- .../Sources/ItemListAvatarAndNameItem.swift | 2 +- .../JoinLinkPreviewPeerContentNode.swift | 2 +- .../Sources/LegacyMediaPickers.swift | 2 +- .../Sources/LegacySuggestionContext.swift | 2 +- ...egacyPeerAvatarPlaceholderDataSource.swift | 10 +- .../Sources/PeerAvatarImageGalleryItem.swift | 2 +- .../Sources/PeerInfoAvatarListNode.swift | 4 +- .../Sources/DeviceContactInfoController.swift | 2 +- .../Postbox/Sources/ChatListIndexTable.swift | 5 +- submodules/Postbox/Sources/ContactTable.swift | 6 +- .../Sources/GlobalMessageIdsTable.swift | 2 +- submodules/Postbox/Sources/Message.swift | 13 +-- .../Postbox/Sources/MessageHistoryTable.swift | 2 +- submodules/Postbox/Sources/Peer.swift | 103 ++++++++++++---- .../Sources/PostboxUpgrade_15to16.swift | 6 +- .../Sources/PostboxUpgrade_16to17.swift | 6 +- .../Sources/PostboxUpgrade_19to20.swift | 2 +- .../Sources/PostboxUpgrade_20to21.swift | 2 +- .../BubbleSettingsController.swift | 2 +- .../ForwardPrivacyChatPreviewItem.swift | 2 +- .../TextSizeSelectionController.swift | 18 +-- .../ThemeAccentColorControllerNode.swift | 12 +- .../Themes/ThemePreviewControllerNode.swift | 18 +-- .../Themes/ThemeSettingsChatPreviewItem.swift | 4 +- .../Sources/Themes/WallpaperGalleryItem.swift | 2 +- submodules/SyncCore/Sources/Namespaces.swift | 10 +- .../SyncCore/Sources/PeerReference.swift | 6 +- .../StandaloneAccountTransaction.swift | 2 +- .../SynchronizePinnedChatsOperation.swift | 6 +- .../Sources/CallRatingController.swift | 2 +- .../Sources/PresentationCallManager.swift | 2 +- .../Sources/AccountIntermediateState.swift | 2 +- .../Sources/AccountViewTracker.swift | 2 +- .../TelegramCore/Sources/AddPeerMember.swift | 2 +- .../Sources/ApiUtils/ApiGroupOrChannel.swift | 12 +- .../Sources/ApiUtils/ApiUtils.swift | 24 ++-- .../ApiUtils/TelegramMediaAction.swift | 12 +- .../Sources/ApiUtils/TelegramMediaPoll.swift | 2 +- .../Sources/ApiUtils/TelegramUser.swift | 4 +- .../TelegramCore/Sources/AuthTransfer.swift | 4 +- .../TelegramCore/Sources/BotPaymentForm.swift | 4 +- .../Sources/CachedChannelParticipants.swift | 10 +- .../Sources/CachedGroupParticipants.swift | 6 +- .../Sources/CallSessionManager.swift | 2 +- .../Sources/ChannelAdminEventLogs.swift | 4 +- .../TelegramCore/Sources/ChannelAdmins.swift | 4 +- .../Sources/ChatListFiltering.swift | 32 ++--- .../Sources/ContactManagement.swift | 2 +- .../Sources/ContactSyncManager.swift | 4 +- .../Sources/ConvertGroupToSupergroup.swift | 2 +- .../Sources/ExportedInvitation.swift | 2 +- .../TelegramCore/Sources/FetchChatList.swift | 6 +- .../Sources/GrantSecureIdAccess.swift | 2 +- .../TelegramCore/Sources/GroupCalls.swift | 50 +------- .../Sources/GroupReturnAndLeft.swift | 4 +- .../TelegramCore/Sources/GroupsInCommon.swift | 2 +- .../Sources/HistoryViewStateValidation.swift | 4 +- submodules/TelegramCore/Sources/Holes.swift | 8 +- .../Sources/InvitationLinks.swift | 8 +- .../TelegramCore/Sources/MessageUtils.swift | 10 +- .../Sources/NotificationExceptionsList.swift | 6 +- .../TelegramCore/Sources/PeerAdmins.swift | 6 +- .../Sources/PeerPhotoUpdater.swift | 4 +- .../TelegramCore/Sources/PeerStatistics.swift | 6 +- .../TelegramCore/Sources/PeerUtils.swift | 6 +- submodules/TelegramCore/Sources/Polls.swift | 6 +- .../Sources/PrivacySettings.swift | 8 +- ...ecretChatIncomingDecryptedOperations.swift | 6 +- .../Sources/RecentWebSessions.swift | 2 +- .../Sources/RegisterNotificationToken.swift | 8 +- .../Sources/RemovePeerMember.swift | 2 +- .../TelegramCore/Sources/ReportPeer.swift | 2 +- .../Sources/RequestSecureIdForm.swift | 2 +- .../TelegramCore/Sources/SearchPeers.swift | 20 +--- ...SecretChatIncomingEncryptedOperation.swift | 4 +- .../SecretChats/UpdateSecretChat.swift | 10 +- .../Sources/StandaloneUploadedMedia.swift | 4 +- .../State/AccountStateManagementUtils.swift | 110 ++++++++---------- .../Sources/State/ChannelState.swift | 4 +- ...gedCloudChatRemoveMessagesOperations.swift | 6 +- .../State/ManagedLocalInputActivities.swift | 2 +- .../ManagedSecretChatOutgoingOperations.swift | 8 +- ...agedSynchronizePinnedChatsOperations.swift | 12 +- .../Sources/State/UpdatesApiUtils.swift | 70 +++++------ .../Sources/StoreMessage_Telegram.swift | 42 +++---- .../SynchronizeAppLogEventsOperation.swift | 4 +- .../SynchronizeGroupedPeersOperation.swift | 2 +- ...ronizeInstalledStickerPacksOperation.swift | 12 +- ...chronizeLocalizationUpdatesOperation.swift | 2 +- ...nchronizeRecentlyUsedMediaOperations.swift | 2 +- .../SynchronizeSavedGifsOperation.swift | 2 +- .../SynchronizeSavedStickersOperation.swift | 2 +- .../Sources/UpdateCachedPeerData.swift | 12 +- .../Sources/UpdateMessageService.swift | 2 +- .../TelegramCore/Sources/UpdatePeerInfo.swift | 4 +- .../UpdatedAccountPrivacySettings.swift | 8 +- .../TelegramUI/Sources/AppDelegate.swift | 22 ++-- .../Sources/ChatMediaInputNode.swift | 2 +- .../Sources/ChatMessageBubbleItemNode.swift | 8 +- .../TelegramUI/Sources/ChatMessageItem.swift | 2 +- .../ChatRecentActionsHistoryTransition.swift | 2 +- .../Sources/CreateChannelController.swift | 2 +- .../Sources/CreateGroupController.swift | 2 +- submodules/TelegramUI/Sources/OpenUrl.swift | 6 +- .../Sources/PeerInfo/PeerInfoHeaderNode.swift | 8 +- .../Sources/PollResultsController.swift | 2 +- .../TelegramUI/Sources/PrefetchManager.swift | 2 +- .../Sources/SharedNotificationManager.swift | 20 ++-- .../ChannelMemberCategoryListContext.swift | 2 +- .../UrlHandling/Sources/UrlHandling.swift | 6 +- .../WatchBridge/Sources/WatchBridge.swift | 12 +- .../Sources/WatchCommunicationManager.swift | 2 +- 127 files changed, 505 insertions(+), 532 deletions(-) diff --git a/Telegram/SiriIntents/IntentContacts.swift b/Telegram/SiriIntents/IntentContacts.swift index 836fc29984..cb0fca310e 100644 --- a/Telegram/SiriIntents/IntentContacts.swift +++ b/Telegram/SiriIntents/IntentContacts.swift @@ -35,7 +35,7 @@ private func parseAppSpecificContactReference(_ value: String) -> PeerId? { } let idString = String(value[value.index(value.startIndex, offsetBy: phonebookUsernamePrefix.count)...]) if let id = Int32(idString) { - return PeerId(namespace: Namespaces.Peer.CloudUser, id: id) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id)) } return nil } diff --git a/Telegram/SiriIntents/IntentMessages.swift b/Telegram/SiriIntents/IntentMessages.swift index 9661264889..1fddc10935 100644 --- a/Telegram/SiriIntents/IntentMessages.swift +++ b/Telegram/SiriIntents/IntentMessages.swift @@ -166,7 +166,7 @@ private func callWithTelegramMessage(_ telegramMessage: Message, account: Accoun @available(iOSApplicationExtension 10.0, iOS 10.0, *) private func messageWithTelegramMessage(_ telegramMessage: Message) -> INMessage? { - guard let author = telegramMessage.author, let user = telegramMessage.peers[author.id] as? TelegramUser, user.id.id != 777000 else { + guard let author = telegramMessage.author, let user = telegramMessage.peers[author.id] as? TelegramUser, user.id.id._internalGetInt32Value() != 777000 else { return nil } diff --git a/submodules/AccountContext/Sources/AccountContext.swift b/submodules/AccountContext/Sources/AccountContext.swift index c9696217bf..bfc8bcf819 100644 --- a/submodules/AccountContext/Sources/AccountContext.swift +++ b/submodules/AccountContext/Sources/AccountContext.swift @@ -513,7 +513,7 @@ public enum ChatListSearchFilter: Equatable { case .voice: return 5 case let .peer(peerId, _, _, _): - return peerId.id + return peerId.id._internalGetInt32Value() case let .date(_, date, _): return date } diff --git a/submodules/AccountContext/Sources/DeviceContactData.swift b/submodules/AccountContext/Sources/DeviceContactData.swift index 674b035809..3111c3bd5a 100644 --- a/submodules/AccountContext/Sources/DeviceContactData.swift +++ b/submodules/AccountContext/Sources/DeviceContactData.swift @@ -202,7 +202,7 @@ public func parseAppSpecificContactReference(_ value: String) -> PeerId? { } let idString = String(value[value.index(value.startIndex, offsetBy: phonebookUsernamePrefix.count)...]) if let id = Int32(idString) { - return PeerId(namespace: Namespaces.Peer.CloudUser, id: id) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id)) } return nil } diff --git a/submodules/AccountContext/Sources/FetchMediaUtils.swift b/submodules/AccountContext/Sources/FetchMediaUtils.swift index 52b7487363..f3dc6c4eee 100644 --- a/submodules/AccountContext/Sources/FetchMediaUtils.swift +++ b/submodules/AccountContext/Sources/FetchMediaUtils.swift @@ -13,7 +13,7 @@ public func freeMediaFileInteractiveFetched(account: Account, fileReference: Fil public func freeMediaFileInteractiveFetched(fetchManager: FetchManager, fileReference: FileMediaReference, priority: FetchManagerPriority) -> Signal { let file = fileReference.media let mediaReference = AnyMediaReference.standalone(media: fileReference.media) - return fetchManager.interactivelyFetched(category: fetchCategoryForFile(file), location: .chat(PeerId(namespace: 0, id: 0)), locationKey: .free, mediaReference: mediaReference, resourceReference: mediaReference.resourceReference(file.resource), ranges: IndexSet(integersIn: 0 ..< Int(Int32.max) as Range), statsCategory: statsCategoryForFileWithAttributes(file.attributes), elevatedPriority: false, userInitiated: false, priority: priority, storeToDownloadsPeerType: nil) + return fetchManager.interactivelyFetched(category: fetchCategoryForFile(file), location: .chat(PeerId(0)), locationKey: .free, mediaReference: mediaReference, resourceReference: mediaReference.resourceReference(file.resource), ranges: IndexSet(integersIn: 0 ..< Int(Int32.max) as Range), statsCategory: statsCategoryForFileWithAttributes(file.attributes), elevatedPriority: false, userInitiated: false, priority: priority, storeToDownloadsPeerType: nil) } public func freeMediaFileResourceInteractiveFetched(account: Account, fileReference: FileMediaReference, resource: MediaResource) -> Signal { diff --git a/submodules/AvatarNode/Sources/AvatarNode.swift b/submodules/AvatarNode/Sources/AvatarNode.swift index c874fa9ea9..3278d2713a 100644 --- a/submodules/AvatarNode/Sources/AvatarNode.swift +++ b/submodules/AvatarNode/Sources/AvatarNode.swift @@ -337,7 +337,7 @@ public final class AvatarNode: ASDisplayNode { } else if peer?.restrictionText(platform: "ios", contentSettings: context.currentContentSettings.with { $0 }) == nil { representation = peer?.smallProfileImage } - let updatedState: AvatarNodeState = .peerAvatar(peer?.id ?? PeerId(namespace: 0, id: 0), peer?.displayLetters ?? [], representation) + let updatedState: AvatarNodeState = .peerAvatar(peer?.id ?? PeerId(0), peer?.displayLetters ?? [], representation) if updatedState != self.state || overrideImage != self.overrideImage || theme !== self.theme { self.state = updatedState self.overrideImage = overrideImage @@ -381,7 +381,7 @@ public final class AvatarNode: ASDisplayNode { } self.editOverlayNode?.isHidden = true - parameters = AvatarNodeParameters(theme: theme, accountPeerId: context.account.peerId, peerId: peer?.id ?? PeerId(namespace: 0, id: 0), letters: peer?.displayLetters ?? [], font: self.font, icon: icon, explicitColorIndex: nil, hasImage: false, clipStyle: clipStyle) + parameters = AvatarNodeParameters(theme: theme, accountPeerId: context.account.peerId, peerId: peer?.id ?? PeerId(0), letters: peer?.displayLetters ?? [], font: self.font, icon: icon, explicitColorIndex: nil, hasImage: false, clipStyle: clipStyle) } if self.parameters == nil || self.parameters != parameters { self.parameters = parameters @@ -453,10 +453,10 @@ public final class AvatarNode: ASDisplayNode { colorIndex = explicitColorIndex } else { if let peerId = parameters.peerId { - if peerId.namespace == -1 { + if peerId.namespace == .max { colorIndex = -1 } else { - colorIndex = abs(Int(clamping: peerId.id)) + colorIndex = abs(Int(clamping: peerId.id._internalGetInt32Value())) } } else { colorIndex = -1 @@ -630,10 +630,10 @@ public func drawPeerAvatarLetters(context: CGContext, size: CGSize, font: UIFont context.clip() let colorIndex: Int - if peerId.namespace == -1 { + if peerId.namespace == .max { colorIndex = -1 } else { - colorIndex = Int(abs(peerId.id)) + colorIndex = Int(abs(peerId.id._internalGetInt32Value())) } let colorsArray: NSArray diff --git a/submodules/ChatListUI/Sources/ChatContextMenus.swift b/submodules/ChatListUI/Sources/ChatContextMenus.swift index f2c4bee0a4..18de9475be 100644 --- a/submodules/ChatListUI/Sources/ChatContextMenus.swift +++ b/submodules/ChatListUI/Sources/ChatContextMenus.swift @@ -260,7 +260,7 @@ func chatContextMenuItems(context: AccountContext, peerId: PeerId, promoInfo: Ch let groupAndIndex = transaction.getPeerChatListIndex(peerId) - let archiveEnabled = !isSavedMessages && peerId != PeerId(namespace: Namespaces.Peer.CloudUser, id: 777000) && peerId == context.account.peerId + let archiveEnabled = !isSavedMessages && peerId != PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(777000)) && peerId == context.account.peerId if let (group, index) = groupAndIndex { if archiveEnabled { let isArchived = group == Namespaces.PeerGroup.archive diff --git a/submodules/ChatListUI/Sources/ChatListController.swift b/submodules/ChatListUI/Sources/ChatListController.swift index 8332b4dc0d..d25743fd3a 100644 --- a/submodules/ChatListUI/Sources/ChatListController.swift +++ b/submodules/ChatListUI/Sources/ChatListController.swift @@ -938,7 +938,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController } if archiveEnabled { for peerId in peerIds { - if peerId == PeerId(namespace: Namespaces.Peer.CloudUser, id: 777000) { + if peerId == PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(777000)) { archiveEnabled = false break } else if peerId == strongSelf.context.account.peerId { diff --git a/submodules/ChatListUI/Sources/ChatListControllerNode.swift b/submodules/ChatListUI/Sources/ChatListControllerNode.swift index e12e902723..da0b82118f 100644 --- a/submodules/ChatListUI/Sources/ChatListControllerNode.swift +++ b/submodules/ChatListUI/Sources/ChatListControllerNode.swift @@ -179,7 +179,7 @@ private final class ChatListShimmerNode: ASDisplayNode { let chatListPresentationData = ChatListPresentationData(theme: presentationData.theme, fontSize: presentationData.chatFontSize, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameSortOrder: presentationData.nameSortOrder, nameDisplayOrder: presentationData.nameDisplayOrder, disableAnimations: true) - let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 1), accessHash: nil, firstName: "FirstName", lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(0)), accessHash: nil, firstName: "FirstName", lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) let timestamp1: Int32 = 100000 let peers = SimpleDictionary() let interaction = ChatListNodeInteraction(activateSearch: {}, peerSelected: { _, _ in }, disabledPeerSelected: { _ in }, togglePeerSelected: { _ in }, additionalCategorySelected: { _ in diff --git a/submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift b/submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift index a8aea23e9a..bac3b759d9 100644 --- a/submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift +++ b/submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift @@ -2327,7 +2327,7 @@ private final class ChatListSearchShimmerNode: ASDisplayNode { let chatListPresentationData = ChatListPresentationData(theme: presentationData.theme, fontSize: presentationData.chatFontSize, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameSortOrder: presentationData.nameSortOrder, nameDisplayOrder: presentationData.nameDisplayOrder, disableAnimations: true) - let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 1), accessHash: nil, firstName: "FirstName", lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(0)), accessHash: nil, firstName: "FirstName", lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) let timestamp1: Int32 = 100000 var peers = SimpleDictionary() peers[peer1.id] = peer1 diff --git a/submodules/ChatListUI/Sources/Node/ChatListItem.swift b/submodules/ChatListUI/Sources/Node/ChatListItem.swift index 9f429feaec..4c48f32239 100644 --- a/submodules/ChatListUI/Sources/Node/ChatListItem.swift +++ b/submodules/ChatListUI/Sources/Node/ChatListItem.swift @@ -196,7 +196,7 @@ private enum RevealOptionKey: Int32 { } private func canArchivePeer(id: PeerId, accountPeerId: PeerId) -> Bool { - if id.namespace == Namespaces.Peer.CloudUser && id.id == 777000 { + if id.namespace == Namespaces.Peer.CloudUser && id.id._internalGetInt32Value() == 777000 { return false } if id == accountPeerId { diff --git a/submodules/ChatListUI/Sources/Node/ChatListNodeEntries.swift b/submodules/ChatListUI/Sources/Node/ChatListNodeEntries.swift index 7004665711..1862609e7b 100644 --- a/submodules/ChatListUI/Sources/Node/ChatListNodeEntries.swift +++ b/submodules/ChatListUI/Sources/Node/ChatListNodeEntries.swift @@ -360,7 +360,7 @@ func chatListNodeEntriesForView(_ view: ChatListView, state: ChatListNodeState, if view.laterIndex == nil, case .chatList = mode { for groupReference in view.groupEntries { - let messageIndex = MessageIndex(id: MessageId(peerId: PeerId(namespace: 0, id: 0), namespace: 0, id: 0), timestamp: 1) + let messageIndex = MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: 0), timestamp: 1) result.append(.GroupReferenceEntry(index: ChatListIndex(pinningIndex: pinningIndex, messageIndex: messageIndex), presentationData: state.presentationData, groupId: groupReference.groupId, peers: groupReference.renderedPeers, message: groupReference.message, editing: state.editing, unreadState: groupReference.unreadState, revealed: state.archiveShouldBeTemporaryRevealed, hiddenByDefault: hideArchivedFolderByDefault)) if pinningIndex != 0 { pinningIndex -= 1 diff --git a/submodules/ContactListUI/Sources/InviteContactsControllerNode.swift b/submodules/ContactListUI/Sources/InviteContactsControllerNode.swift index 0523dd25e8..a991208559 100644 --- a/submodules/ContactListUI/Sources/InviteContactsControllerNode.swift +++ b/submodules/ContactListUI/Sources/InviteContactsControllerNode.swift @@ -58,7 +58,7 @@ private enum InviteContactsEntry: Comparable, Identifiable { } else { status = .none } - let peer = TelegramUser(id: PeerId(namespace: -1, id: 0), accessHash: nil, firstName: contact.firstName, lastName: contact.lastName, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer = TelegramUser(id: PeerId(namespace: .max, id: PeerId.Id._internalFromInt32Value(0)), accessHash: nil, firstName: contact.firstName, lastName: contact.lastName, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) return ContactsPeerItem(presentationData: ItemListPresentationData(presentationData), sortOrder: nameSortOrder, displayOrder: nameDisplayOrder, context: context, peerMode: .peer, peer: .peer(peer: peer, chatPeer: peer), status: status, enabled: true, selection: selection, editing: ContactsPeerItemEditing(editable: false, editing: false, revealed: false), index: nil, header: ChatListSearchItemHeader(type: .contacts, theme: theme, strings: strings, actionTitle: nil, action: nil), action: { _ in interaction.toggleContact(id) }) diff --git a/submodules/InstantPageUI/Sources/InstantPageControllerNode.swift b/submodules/InstantPageUI/Sources/InstantPageControllerNode.swift index 27fe27c82a..423e567a5f 100644 --- a/submodules/InstantPageUI/Sources/InstantPageControllerNode.swift +++ b/submodules/InstantPageUI/Sources/InstantPageControllerNode.swift @@ -1250,7 +1250,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { }, openUrl: { _ in }, openPeer: { _ in }, showAll: false) - let peer = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 1), accessHash: nil, firstName: "", lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(0)), accessHash: nil, firstName: "", lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: 0, id: 0), globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, threadId: nil, timestamp: 0, flags: [], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: peer, text: "", attributes: [], media: [map], peers: SimpleDictionary(), associatedMessages: SimpleDictionary(), associatedMessageIds: []) let controller = LocationViewController(context: self.context, subject: message, params: controllerParams) diff --git a/submodules/InviteLinksUI/Sources/InviteLinkViewController.swift b/submodules/InviteLinksUI/Sources/InviteLinkViewController.swift index a6483cda91..b15cecdda8 100644 --- a/submodules/InviteLinksUI/Sources/InviteLinkViewController.swift +++ b/submodules/InviteLinksUI/Sources/InviteLinkViewController.swift @@ -598,7 +598,7 @@ public final class InviteLinkViewController: ViewController { if state.importers.isEmpty && state.isLoadingMore { count = min(4, state.count) loading = true - let fakeUser = TelegramUser(id: PeerId(namespace: -1, id: 0), accessHash: nil, firstName: "", lastName: "", username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let fakeUser = TelegramUser(id: PeerId(namespace: .max, id: PeerId.Id._internalFromInt32Value(0)), accessHash: nil, firstName: "", lastName: "", username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) for i in 0 ..< count { entries.append(.importer(Int32(i), presentationData.theme, presentationData.dateTimeFormat, fakeUser, 0, true)) } diff --git a/submodules/ItemListAvatarAndNameInfoItem/Sources/ItemListAvatarAndNameItem.swift b/submodules/ItemListAvatarAndNameInfoItem/Sources/ItemListAvatarAndNameItem.swift index 5393572d5c..f924c08da9 100644 --- a/submodules/ItemListAvatarAndNameInfoItem/Sources/ItemListAvatarAndNameItem.swift +++ b/submodules/ItemListAvatarAndNameInfoItem/Sources/ItemListAvatarAndNameItem.swift @@ -531,7 +531,7 @@ public class ItemListAvatarAndNameInfoItemNode: ListViewItemNode, ItemListItemNo } var updateAvatarOverlayImage: UIImage? - if item.updatingImage != nil && item.peer?.id.namespace != -1 && currentOverlayImage == nil { + if item.updatingImage != nil && item.peer?.id.namespace != .max && currentOverlayImage == nil { updateAvatarOverlayImage = updatingAvatarOverlayImage } diff --git a/submodules/JoinLinkPreviewUI/Sources/JoinLinkPreviewPeerContentNode.swift b/submodules/JoinLinkPreviewUI/Sources/JoinLinkPreviewPeerContentNode.swift index 3937a380fd..0d95a46cb5 100644 --- a/submodules/JoinLinkPreviewUI/Sources/JoinLinkPreviewPeerContentNode.swift +++ b/submodules/JoinLinkPreviewUI/Sources/JoinLinkPreviewPeerContentNode.swift @@ -63,7 +63,7 @@ final class JoinLinkPreviewPeerContentNode: ASDisplayNode, ShareContentContainer super.init() - let peer = TelegramGroup(id: PeerId(namespace: 0, id: 0), title: title, photo: image.flatMap { [$0] } ?? [], participantCount: Int(memberCount), role: .member, membership: .Left, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) + let peer = TelegramGroup(id: PeerId(0), title: title, photo: image.flatMap { [$0] } ?? [], participantCount: Int(memberCount), role: .member, membership: .Left, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) self.addSubnode(self.avatarNode) self.avatarNode.setPeer(context: context, theme: theme, peer: peer, emptyColor: theme.list.mediaPlaceholderColor) diff --git a/submodules/LegacyMediaPickerUI/Sources/LegacyMediaPickers.swift b/submodules/LegacyMediaPickerUI/Sources/LegacyMediaPickers.swift index 68fd2ba850..56a36a4265 100644 --- a/submodules/LegacyMediaPickerUI/Sources/LegacyMediaPickers.swift +++ b/submodules/LegacyMediaPickerUI/Sources/LegacyMediaPickers.swift @@ -67,7 +67,7 @@ public func configureLegacyAssetPicker(_ controller: TGMediaAssetsController, co } public func legacyAssetPicker(context: AccountContext, presentationData: PresentationData, editingMedia: Bool, fileMode: Bool, peer: Peer?, saveEditedPhotos: Bool, allowGrouping: Bool, selectionLimit: Int) -> Signal<(LegacyComponentsContext) -> TGMediaAssetsController, Void> { - let isSecretChat = (peer?.id.namespace ?? 0) == Namespaces.Peer.SecretChat + let isSecretChat = (peer?.id.namespace._internalGetInt32Value() ?? 0) == Namespaces.Peer.SecretChat._internalGetInt32Value() return Signal { subscriber in let intent = fileMode ? TGMediaAssetsControllerSendFileIntent : TGMediaAssetsControllerSendMediaIntent diff --git a/submodules/LegacyMediaPickerUI/Sources/LegacySuggestionContext.swift b/submodules/LegacyMediaPickerUI/Sources/LegacySuggestionContext.swift index 53258c65b3..2af3181ce3 100644 --- a/submodules/LegacyMediaPickerUI/Sources/LegacySuggestionContext.swift +++ b/submodules/LegacyMediaPickerUI/Sources/LegacySuggestionContext.swift @@ -19,7 +19,7 @@ public func legacySuggestionContext(context: AccountContext, peerId: PeerId, cha for peer in peers { if let peer = peer as? TelegramUser { let user = TGUser() - user.uid = peer.id.id + user.uid = peer.id.id._internalGetInt32Value() user.firstName = peer.firstName user.lastName = peer.lastName user.userName = peer.addressName diff --git a/submodules/LegacyUI/Sources/LegacyPeerAvatarPlaceholderDataSource.swift b/submodules/LegacyUI/Sources/LegacyPeerAvatarPlaceholderDataSource.swift index 54fb835456..cce9f64a41 100644 --- a/submodules/LegacyUI/Sources/LegacyPeerAvatarPlaceholderDataSource.swift +++ b/submodules/LegacyUI/Sources/LegacyPeerAvatarPlaceholderDataSource.swift @@ -61,12 +61,12 @@ final class LegacyPeerAvatarPlaceholderDataSource: TGImageDataSource { return EmptyDisposable } - var peerId = PeerId(namespace: 0, id: 0) + var peerId = PeerId(0) if let uid = args["uid"] as? String, let nUid = Int32(uid) { - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: nUid) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(nUid)) } else if let cid = args["cid"] as? String, let nCid = Int32(cid) { - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: nCid) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(nCid)) } let image = generateImage(CGSize(width: CGFloat(width), height: CGFloat(height)), rotatedContext: { size, context in @@ -77,10 +77,10 @@ final class LegacyPeerAvatarPlaceholderDataSource: TGImageDataSource { context.clip() let colorIndex: Int - if peerId.id == 0 { + if peerId.id._internalGetInt32Value() == 0 { colorIndex = -1 } else { - colorIndex = abs(Int(account.peerId.id + peerId.id)) + colorIndex = abs(Int(account.peerId.id._internalGetInt32Value() &+ peerId.id._internalGetInt32Value())) } let colorsArray: NSArray diff --git a/submodules/PeerAvatarGalleryUI/Sources/PeerAvatarImageGalleryItem.swift b/submodules/PeerAvatarGalleryUI/Sources/PeerAvatarImageGalleryItem.swift index 2345f79d4d..7a9a47e931 100644 --- a/submodules/PeerAvatarGalleryUI/Sources/PeerAvatarImageGalleryItem.swift +++ b/submodules/PeerAvatarGalleryUI/Sources/PeerAvatarImageGalleryItem.swift @@ -257,7 +257,7 @@ final class PeerAvatarImageGalleryItemNode: ZoomableContentGalleryItemNode { id = image.0.id category = image.9 } else { - id = Int64(entry.peer?.id.id ?? 0) + id = Int64(entry.peer?.id.id._internalGetInt32Value() ?? 0) if let resource = entry.videoRepresentations.first?.representation.resource as? CloudPhotoSizeMediaResource { id = id &+ resource.photoId } diff --git a/submodules/PeerInfoAvatarListNode/Sources/PeerInfoAvatarListNode.swift b/submodules/PeerInfoAvatarListNode/Sources/PeerInfoAvatarListNode.swift index 1fe2f1cc0a..b3f4ab146f 100644 --- a/submodules/PeerInfoAvatarListNode/Sources/PeerInfoAvatarListNode.swift +++ b/submodules/PeerInfoAvatarListNode/Sources/PeerInfoAvatarListNode.swift @@ -322,7 +322,7 @@ public final class PeerInfoAvatarListItemNode: ASDisplayNode { representations = topRepresentations videoRepresentations = videoRepresentationsValue immediateThumbnailData = immediateThumbnail - id = Int64(self.peer.id.id) + id = Int64(self.peer.id.id._internalGetInt32Value()) if let resource = videoRepresentations.first?.representation.resource as? CloudPhotoSizeMediaResource { id = id &+ resource.photoId } @@ -333,7 +333,7 @@ public final class PeerInfoAvatarListItemNode: ASDisplayNode { if case let .cloud(imageId, _, _) = reference { id = imageId } else { - id = Int64(self.peer.id.id) + id = Int64(self.peer.id.id._internalGetInt32Value()) } } self.imageNode.setSignal(chatAvatarGalleryPhoto(account: self.context.account, representations: representations, immediateThumbnailData: immediateThumbnailData, autoFetchFullSize: true, attemptSynchronously: synchronous), attemptSynchronously: synchronous, dispatchOnDisplayLink: false) diff --git a/submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift b/submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift index 422c4175c1..64d3203a2b 100644 --- a/submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift +++ b/submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift @@ -648,7 +648,7 @@ private func deviceContactInfoEntries(account: Account, presentationData: Presen let isOrganization = personName.0.isEmpty && personName.1.isEmpty && !contactData.organization.isEmpty - entries.append(.info(entries.count, presentationData.theme, presentationData.strings, presentationData.dateTimeFormat, peer: peer ?? TelegramUser(id: PeerId(namespace: -1, id: 0), accessHash: nil, firstName: isOrganization ? contactData.organization : personName.0, lastName: isOrganization ? nil : personName.1, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []), state: ItemListAvatarAndNameInfoItemState(editingName: editingName, updatingName: nil), job: isOrganization ? nil : jobSummary, isPlain: !isShare)) + entries.append(.info(entries.count, presentationData.theme, presentationData.strings, presentationData.dateTimeFormat, peer: peer ?? TelegramUser(id: PeerId(namespace: .max, id: PeerId.Id._internalFromInt32Value(0)), accessHash: nil, firstName: isOrganization ? contactData.organization : personName.0, lastName: isOrganization ? nil : personName.1, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []), state: ItemListAvatarAndNameInfoItemState(editingName: editingName, updatingName: nil), job: isOrganization ? nil : jobSummary, isPlain: !isShare)) if !selecting { if let _ = peer { diff --git a/submodules/Postbox/Sources/ChatListIndexTable.swift b/submodules/Postbox/Sources/ChatListIndexTable.swift index c6c17af690..f44ade7157 100644 --- a/submodules/Postbox/Sources/ChatListIndexTable.swift +++ b/submodules/Postbox/Sources/ChatListIndexTable.swift @@ -62,8 +62,7 @@ final class ChatListIndexTable: Table { } private func key(_ peerId: PeerId) -> ValueBoxKey { - self.sharedKey.setInt32(0, value: peerId.namespace) - self.sharedKey.setInt32(4, value: peerId.id) + self.sharedKey.setInt64(0, value: peerId.toInt64()) assert(self.sharedKey.getInt64(0) == peerId.toInt64()) return self.sharedKey } @@ -648,7 +647,7 @@ final class ChatListIndexTable: Table { var summary = PeerGroupUnreadCountersCombinedSummary(namespaces: [:]) postbox.chatListTable.forEachPeer(groupId: groupId, { peerId in - if peerId.namespace == Int32.max { + if peerId.namespace == .max { return } guard let combinedState = postbox.readStateTable.getCombinedState(peerId) else { diff --git a/submodules/Postbox/Sources/ContactTable.swift b/submodules/Postbox/Sources/ContactTable.swift index 8be82c6de4..e236a3879a 100644 --- a/submodules/Postbox/Sources/ContactTable.swift +++ b/submodules/Postbox/Sources/ContactTable.swift @@ -22,11 +22,11 @@ final class ContactTable: Table { } private func lowerBound() -> ValueBoxKey { - return self.key(PeerId(namespace: 0, id: 0)) + return self.key(PeerId(0)) } private func upperBound() -> ValueBoxKey { - return self.key(PeerId(namespace: Int32.max, id: Int32.max)) + return self.key(PeerId.max) } func isContact(peerId: PeerId) -> Bool { @@ -81,7 +81,7 @@ final class ContactTable: Table { let removedPeerIds = peerIdsBeforeModification.subtracting(peerIds) let addedPeerIds = peerIds.subtracting(peerIdsBeforeModification) - let sharedKey = self.key(PeerId(namespace: 0, id: 0)) + let sharedKey = self.key(PeerId(0)) for peerId in removedPeerIds { self.valueBox.remove(self.table, key: self.key(peerId, sharedKey: sharedKey), secure: false) diff --git a/submodules/Postbox/Sources/GlobalMessageIdsTable.swift b/submodules/Postbox/Sources/GlobalMessageIdsTable.swift index a5665f3e16..800ddf9ffa 100644 --- a/submodules/Postbox/Sources/GlobalMessageIdsTable.swift +++ b/submodules/Postbox/Sources/GlobalMessageIdsTable.swift @@ -23,7 +23,7 @@ final class GlobalMessageIdsTable: Table { func set(_ globalId: Int32, id: MessageId) { assert(id.namespace == 0) - assert(id.peerId.namespace == 0 || id.peerId.namespace == 1) + assert(id.peerId.namespace._internalGetInt32Value() == 0 || id.peerId.namespace._internalGetInt32Value() == 1) assert(self.seedConfiguration.globalMessageIdsPeerIdNamespaces.contains(GlobalMessageIdsNamespace(peerIdNamespace: id.peerId.namespace, messageIdNamespace: id.namespace))) self.sharedBuffer.reset() diff --git a/submodules/Postbox/Sources/Message.swift b/submodules/Postbox/Sources/Message.swift index 540b072f43..d3bac69065 100644 --- a/submodules/Postbox/Sources/Message.swift +++ b/submodules/Postbox/Sources/Message.swift @@ -21,11 +21,10 @@ public struct MessageId: Hashable, Comparable, CustomStringConvertible, PostboxC } public init(_ buffer: ReadBuffer) { - var peerIdNamespaceValue: Int32 = 0 - memcpy(&peerIdNamespaceValue, buffer.memory + buffer.offset, 4) - var peerIdIdValue: Int32 = 0 - memcpy(&peerIdIdValue, buffer.memory + (buffer.offset + 4), 4) - self.peerId = PeerId(namespace: peerIdNamespaceValue, id: peerIdIdValue) + var peerIdInt64Value: Int64 = 0 + memcpy(&peerIdInt64Value, buffer.memory + buffer.offset, 8) + + self.peerId = PeerId(peerIdInt64Value) var namespaceValue: Int32 = 0 memcpy(&namespaceValue, buffer.memory + (buffer.offset + 8), 4) @@ -120,11 +119,11 @@ public struct MessageIndex: Comparable, Hashable { } public static func absoluteUpperBound() -> MessageIndex { - return MessageIndex(id: MessageId(peerId: PeerId(namespace: Int32(Int8.max), id: Int32.max), namespace: Int32(Int8.max), id: Int32.max), timestamp: Int32.max) + return MessageIndex(id: MessageId(peerId: PeerId.max, namespace: Int32(Int8.max), id: Int32.max), timestamp: Int32.max) } public static func absoluteLowerBound() -> MessageIndex { - return MessageIndex(id: MessageId(peerId: PeerId(namespace: 0, id: 0), namespace: 0, id: 0), timestamp: 0) + return MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: 0), timestamp: 0) } public static func lowerBound(peerId: PeerId) -> MessageIndex { diff --git a/submodules/Postbox/Sources/MessageHistoryTable.swift b/submodules/Postbox/Sources/MessageHistoryTable.swift index 203849fc24..35f7affa81 100644 --- a/submodules/Postbox/Sources/MessageHistoryTable.swift +++ b/submodules/Postbox/Sources/MessageHistoryTable.swift @@ -223,7 +223,7 @@ final class MessageHistoryTable: Table { } private func processIndexOperations(_ peerId: PeerId, operations: [MessageHistoryIndexOperation], processedOperationsByPeerId: inout [PeerId: [MessageHistoryOperation]], updatedMedia: inout [MediaId: Media?], unsentMessageOperations: inout [IntermediateMessageHistoryUnsentOperation], updatedPeerReadStateOperations: inout [PeerId: PeerReadStateSynchronizationOperation?], globalTagsOperations: inout [GlobalMessageHistoryTagsOperation], pendingActionsOperations: inout [PendingMessageActionsOperation], updatedMessageActionsSummaries: inout [PendingMessageActionsSummaryKey: Int32], updatedMessageTagSummaries: inout [MessageHistoryTagsSummaryKey: MessageHistoryTagNamespaceSummary], invalidateMessageTagSummaries: inout [InvalidatedMessageHistoryTagsSummaryEntryOperation], localTagsOperations: inout [IntermediateMessageHistoryLocalTagsOperation], timestampBasedMessageAttributesOperations: inout [TimestampBasedMessageAttributesOperation]) { - let sharedKey = self.key(MessageIndex(id: MessageId(peerId: PeerId(namespace: 0, id: 0), namespace: 0, id: 0), timestamp: 0)) + let sharedKey = self.key(MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: 0), timestamp: 0)) let sharedBuffer = WriteBuffer() let sharedEncoder = PostboxEncoder() diff --git a/submodules/Postbox/Sources/Peer.swift b/submodules/Postbox/Sources/Peer.swift index 2f6dc2f3ca..472b0d885c 100644 --- a/submodules/Postbox/Sources/Peer.swift +++ b/submodules/Postbox/Sources/Peer.swift @@ -1,8 +1,57 @@ import Foundation public struct PeerId: Hashable, CustomStringConvertible, Comparable, Codable { - public typealias Namespace = Int32 - public typealias Id = Int32 + public struct Namespace: Comparable, Hashable, Codable { + public static var max: Namespace { + return Namespace(rawValue: 0x7) + } + + fileprivate var rawValue: UInt32 + + public init(rawValue: UInt32) { + precondition((rawValue | 0x7) == 0x7) + + self.rawValue = rawValue + } + + public static func _internalFromInt32Value(_ value: Int32) -> Namespace { + return Namespace(rawValue: UInt32(bitPattern: value)) + } + + public func _internalGetInt32Value() -> Int32 { + return Int32(bitPattern: self.rawValue) + } + + public static func <(lhs: Namespace, rhs: Namespace) -> Bool { + return lhs.rawValue < rhs.rawValue + } + } + + public struct Id: Comparable, Hashable, Codable { + fileprivate var rawValue: UInt64 + + public init(rawValue: UInt64) { + precondition((rawValue | 0xFFFFFFFFFFFFF) == 0xFFFFFFFFFFFFF) + + self.rawValue = rawValue + } + + public static func _internalFromInt32Value(_ value: Int32) -> Id { + return Id(rawValue: UInt64(UInt32(bitPattern: value))) + } + + public func _internalGetInt32Value() -> Int32 { + return Int32(clamping: self.rawValue) + } + + public static func <(lhs: Id, rhs: Id) -> Bool { + return lhs.rawValue < rhs.rawValue + } + } + + public static var max: PeerId { + return PeerId(Int64(bitPattern: UInt64.max)) + } public let namespace: Namespace public let id: Id @@ -13,12 +62,29 @@ public struct PeerId: Hashable, CustomStringConvertible, Comparable, Codable { } public init(_ n: Int64) { - self.namespace = Int32((n >> 32) & 0x7fffffff) - self.id = Int32(bitPattern: UInt32(n & 0xffffffff)) + let data = UInt64(bitPattern: n) + + let namespaceBits = ((data >> 32) & 0x7) + self.namespace = Namespace(rawValue: UInt32(namespaceBits)) + + let idLowBits = data & 0xffffffff + let idHighBits = (data >> (32 + 3)) & 0xffffffff + assert(idHighBits == 0) + + self.id = Id(rawValue: idLowBits) } public func toInt64() -> Int64 { - return (Int64(self.namespace) << 32) | Int64(bitPattern: UInt64(UInt32(bitPattern: self.id))) + var data: UInt64 = 0 + data |= UInt64(self.namespace.rawValue) << 32 + + let idLowBits = self.id.rawValue & 0xffffffff + let idHighBits = (self.id.rawValue >> 32) & 0x3FFFFFFF + assert(idHighBits == 0) + + data |= idLowBits + + return Int64(bitPattern: data) } public static func encodeArrayToBuffer(_ array: [PeerId], buffer: WriteBuffer) { @@ -46,32 +112,23 @@ public struct PeerId: Hashable, CustomStringConvertible, Comparable, Codable { return array } - public var hashValue: Int { - get { - return Int(self.id) - } - } - public var description: String { get { return "\(namespace):\(id)" } } - public init(_ buffer: ReadBuffer) { - var namespace: Int32 = 0 - var id: Int32 = 0 - memcpy(&namespace, buffer.memory, 4) - self.namespace = namespace - memcpy(&id, buffer.memory + 4, 4) - self.id = id - } + /*public init(_ buffer: ReadBuffer) { + var value: Int64 = 0 + memcpy(&value, buffer.memory, 8) + buffer.offset += 8 + + self.init(value) + }*/ public func encodeToBuffer(_ buffer: WriteBuffer) { - var namespace = self.namespace - var id = self.id - buffer.write(&namespace, offset: 0, length: 4); - buffer.write(&id, offset: 0, length: 4); + var value = self.toInt64() + buffer.write(&value, offset: 0, length: 8); } public static func <(lhs: PeerId, rhs: PeerId) -> Bool { diff --git a/submodules/Postbox/Sources/PostboxUpgrade_15to16.swift b/submodules/Postbox/Sources/PostboxUpgrade_15to16.swift index 62a4714b43..e8d8d9334f 100644 --- a/submodules/Postbox/Sources/PostboxUpgrade_15to16.swift +++ b/submodules/Postbox/Sources/PostboxUpgrade_15to16.swift @@ -211,10 +211,8 @@ func postboxUpgrade_15to16(metadataTable: MetadataTable, valueBox: ValueBox, pro valueBox.scanInt64(chatListIndexTable, values: { key, value in let peerId = PeerId(key) - if peerId.namespace != Int32.max { - if parseInclusionIndex(peerId: peerId, value: value) { - includedPeerIds.append(peerId) - } + if parseInclusionIndex(peerId: peerId, value: value) { + includedPeerIds.append(peerId) } return true }) diff --git a/submodules/Postbox/Sources/PostboxUpgrade_16to17.swift b/submodules/Postbox/Sources/PostboxUpgrade_16to17.swift index 3bdbfea670..030c1fce46 100644 --- a/submodules/Postbox/Sources/PostboxUpgrade_16to17.swift +++ b/submodules/Postbox/Sources/PostboxUpgrade_16to17.swift @@ -215,10 +215,8 @@ func postboxUpgrade_16to17(metadataTable: MetadataTable, valueBox: ValueBox, pro valueBox.scanInt64(chatListIndexTable, values: { key, value in let peerId = PeerId(key) - if peerId.namespace != Int32.max { - if parseInclusionIndex(peerId: peerId, value: value) { - includedPeerIds.append(peerId) - } + if parseInclusionIndex(peerId: peerId, value: value) { + includedPeerIds.append(peerId) } return true }) diff --git a/submodules/Postbox/Sources/PostboxUpgrade_19to20.swift b/submodules/Postbox/Sources/PostboxUpgrade_19to20.swift index 2faa64bec9..074275cd5b 100644 --- a/submodules/Postbox/Sources/PostboxUpgrade_19to20.swift +++ b/submodules/Postbox/Sources/PostboxUpgrade_19to20.swift @@ -424,7 +424,7 @@ func postboxUpgrade_19to20(metadataTable: MetadataTable, valueBox: ValueBox, pro var removeChatListKeys: [ValueBoxKey] = [] valueBox.scan(chatListTable, keys: { key in let (_, _, index, type) = extractChatListKey(key) - if index.id.peerId.namespace != 3 { // Secret Chat + if index.id.peerId.namespace._internalGetInt32Value() != 3 { // Secret Chat sharedChatListIndexKey.setInt64(0, value: index.id.peerId.toInt64()) valueBox.remove(chatListIndexTable, key: sharedChatListIndexKey, secure: false) diff --git a/submodules/Postbox/Sources/PostboxUpgrade_20to21.swift b/submodules/Postbox/Sources/PostboxUpgrade_20to21.swift index f33b8459a2..00fd244141 100644 --- a/submodules/Postbox/Sources/PostboxUpgrade_20to21.swift +++ b/submodules/Postbox/Sources/PostboxUpgrade_20to21.swift @@ -426,7 +426,7 @@ func postboxUpgrade_20to21(metadataTable: MetadataTable, valueBox: ValueBox, pro var removeChatListKeys: [ValueBoxKey] = [] valueBox.scan(chatListTable, keys: { key in let (_, _, index, type) = extractChatListKey(key) - if index.id.peerId.namespace != 3 { // Secret Chat + if index.id.peerId.namespace._internalGetInt32Value() != 3 { // Secret Chat sharedChatListIndexKey.setInt64(0, value: index.id.peerId.toInt64()) valueBox.remove(chatListIndexTable, key: sharedChatListIndexKey, secure: false) diff --git a/submodules/SettingsUI/Sources/BubbleSettings/BubbleSettingsController.swift b/submodules/SettingsUI/Sources/BubbleSettings/BubbleSettingsController.swift index 94145bbdb7..a507b15de0 100644 --- a/submodules/SettingsUI/Sources/BubbleSettings/BubbleSettingsController.swift +++ b/submodules/SettingsUI/Sources/BubbleSettings/BubbleSettingsController.swift @@ -162,7 +162,7 @@ private final class BubbleSettingsControllerNode: ASDisplayNode, UIScrollViewDel let headerItem = self.context.sharedContext.makeChatMessageDateHeaderItem(context: self.context, timestamp: self.referenceTimestamp, theme: self.presentationData.theme, strings: self.presentationData.strings, wallpaper: self.presentationData.chatWallpaper, fontSize: self.presentationData.chatFontSize, chatBubbleCorners: self.presentationData.chatBubbleCorners, dateTimeFormat: self.presentationData.dateTimeFormat, nameOrder: self.presentationData.nameDisplayOrder) var items: [ListViewItem] = [] - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 1) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)) let otherPeerId = self.context.account.peerId var peers = SimpleDictionary() var messages = SimpleDictionary() diff --git a/submodules/SettingsUI/Sources/Privacy and Security/ForwardPrivacyChatPreviewItem.swift b/submodules/SettingsUI/Sources/Privacy and Security/ForwardPrivacyChatPreviewItem.swift index 3ac27c2c04..79e551b85f 100644 --- a/submodules/SettingsUI/Sources/Privacy and Security/ForwardPrivacyChatPreviewItem.swift +++ b/submodules/SettingsUI/Sources/Privacy and Security/ForwardPrivacyChatPreviewItem.swift @@ -150,7 +150,7 @@ class ForwardPrivacyChatPreviewItemNode: ListViewItemNode { let insets: UIEdgeInsets let separatorHeight = UIScreenPixel - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 1) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)) var peers = SimpleDictionary() let messages = SimpleDictionary() diff --git a/submodules/SettingsUI/Sources/Text Size/TextSizeSelectionController.swift b/submodules/SettingsUI/Sources/Text Size/TextSizeSelectionController.swift index e98633d1cc..4f67af1d58 100644 --- a/submodules/SettingsUI/Sources/Text Size/TextSizeSelectionController.swift +++ b/submodules/SettingsUI/Sources/Text Size/TextSizeSelectionController.swift @@ -223,14 +223,14 @@ private final class TextSizeSelectionControllerNode: ASDisplayNode, UIScrollView let peers = SimpleDictionary() let messages = SimpleDictionary() let selfPeer = TelegramUser(id: self.context.account.peerId, accessHash: nil, firstName: nil, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 1), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_1_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer2 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 2), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_2_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer3 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: 3), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .group(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) - let peer3Author = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 4), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_AuthorName, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer4 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 4), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_4_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer5 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: 5), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_5_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .broadcast(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) - let peer6 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.SecretChat, id: 5), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_6_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer7 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 6), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_7_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_1_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer2 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(2)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_2_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer3 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(3)), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .group(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) + let peer3Author = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(4)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_AuthorName, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer4 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(4)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_4_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer5 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(5)), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_5_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .broadcast(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) + let peer6 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(5)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_6_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer7 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(6)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_7_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) let timestamp = self.referenceTimestamp @@ -308,7 +308,7 @@ private final class TextSizeSelectionControllerNode: ASDisplayNode, UIScrollView let headerItem = self.context.sharedContext.makeChatMessageDateHeaderItem(context: self.context, timestamp: self.referenceTimestamp, theme: self.presentationData.theme, strings: self.presentationData.strings, wallpaper: self.presentationData.chatWallpaper, fontSize: self.presentationData.chatFontSize, chatBubbleCorners: self.presentationData.chatBubbleCorners, dateTimeFormat: self.presentationData.dateTimeFormat, nameOrder: self.presentationData.nameDisplayOrder) var items: [ListViewItem] = [] - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 1) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)) let otherPeerId = self.context.account.peerId var peers = SimpleDictionary() var messages = SimpleDictionary() diff --git a/submodules/SettingsUI/Sources/Themes/ThemeAccentColorControllerNode.swift b/submodules/SettingsUI/Sources/Themes/ThemeAccentColorControllerNode.swift index 8cd04d4ec1..6cec21d302 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemeAccentColorControllerNode.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemeAccentColorControllerNode.swift @@ -777,11 +777,11 @@ final class ThemeAccentColorControllerNode: ASDisplayNode, UIScrollViewDelegate let peers = SimpleDictionary() let messages = SimpleDictionary() let selfPeer = TelegramUser(id: self.context.account.peerId, accessHash: nil, firstName: nil, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 1), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_1_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer2 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 2), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_2_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer3 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: 3), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .group(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) - let peer3Author = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 4), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_AuthorName, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer4 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.SecretChat, id: 4), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_4_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_1_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer2 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(2)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_2_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer3 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(3)), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .group(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) + let peer3Author = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(4)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_AuthorName, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer4 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(4)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_4_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) let timestamp = self.referenceTimestamp @@ -843,7 +843,7 @@ final class ThemeAccentColorControllerNode: ASDisplayNode, UIScrollViewDelegate let headerItem = self.context.sharedContext.makeChatMessageDateHeaderItem(context: self.context, timestamp: self.referenceTimestamp, theme: self.theme, strings: self.presentationData.strings, wallpaper: self.wallpaper, fontSize: self.presentationData.chatFontSize, chatBubbleCorners: self.presentationData.chatBubbleCorners, dateTimeFormat: self.presentationData.dateTimeFormat, nameOrder: self.presentationData.nameDisplayOrder) var items: [ListViewItem] = [] - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 1) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)) let otherPeerId = self.context.account.peerId var peers = SimpleDictionary() var messages = SimpleDictionary() diff --git a/submodules/SettingsUI/Sources/Themes/ThemePreviewControllerNode.swift b/submodules/SettingsUI/Sources/Themes/ThemePreviewControllerNode.swift index 13125e369d..ec0bfc8a78 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemePreviewControllerNode.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemePreviewControllerNode.swift @@ -361,14 +361,14 @@ final class ThemePreviewControllerNode: ASDisplayNode, UIScrollViewDelegate { let peers = SimpleDictionary() let messages = SimpleDictionary() let selfPeer = TelegramUser(id: self.context.account.peerId, accessHash: nil, firstName: nil, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 1), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_1_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer2 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 2), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_2_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer3 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: 3), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .group(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) - let peer3Author = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 4), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_AuthorName, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer4 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 4), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_4_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer5 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: 5), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_5_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .broadcast(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) - let peer6 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.SecretChat, id: 5), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_6_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) - let peer7 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 6), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_7_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer1 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_1_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer2 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(2)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_2_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer3 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(3)), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .group(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) + let peer3Author = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(4)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_3_AuthorName, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer4 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(4)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_4_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer5 = TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(5)), accessHash: nil, title: self.presentationData.strings.Appearance_ThemePreview_ChatList_5_Name, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .member, info: .broadcast(.init(flags: [])), flags: [], restrictionInfo: nil, adminRights: nil, bannedRights: nil, defaultBannedRights: nil) + let peer6 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(5)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_6_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let peer7 = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(6)), accessHash: nil, firstName: self.presentationData.strings.Appearance_ThemePreview_ChatList_7_Name, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) let timestamp = self.referenceTimestamp @@ -448,7 +448,7 @@ final class ThemePreviewControllerNode: ASDisplayNode, UIScrollViewDelegate { let headerItem = self.context.sharedContext.makeChatMessageDateHeaderItem(context: self.context, timestamp: self.referenceTimestamp, theme: self.previewTheme, strings: self.presentationData.strings, wallpaper: self.presentationData.chatWallpaper, fontSize: self.presentationData.chatFontSize, chatBubbleCorners: self.presentationData.chatBubbleCorners, dateTimeFormat: self.presentationData.dateTimeFormat, nameOrder: self.presentationData.nameDisplayOrder) var items: [ListViewItem] = [] - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 1) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)) let otherPeerId = self.context.account.peerId var peers = SimpleDictionary() var messages = SimpleDictionary() diff --git a/submodules/SettingsUI/Sources/Themes/ThemeSettingsChatPreviewItem.swift b/submodules/SettingsUI/Sources/Themes/ThemeSettingsChatPreviewItem.swift index 2a24f6b579..e4d0877f1f 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemeSettingsChatPreviewItem.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemeSettingsChatPreviewItem.swift @@ -151,8 +151,8 @@ class ThemeSettingsChatPreviewItemNode: ListViewItemNode { let insets: UIEdgeInsets let separatorHeight = UIScreenPixel - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 1) - let otherPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 2) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)) + let otherPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(2)) var items: [ListViewItem] = [] for messageItem in item.messageItems.reversed() { var peers = SimpleDictionary() diff --git a/submodules/SettingsUI/Sources/Themes/WallpaperGalleryItem.swift b/submodules/SettingsUI/Sources/Themes/WallpaperGalleryItem.swift index 6a26f32ea8..c9b506636b 100644 --- a/submodules/SettingsUI/Sources/Themes/WallpaperGalleryItem.swift +++ b/submodules/SettingsUI/Sources/Themes/WallpaperGalleryItem.swift @@ -800,7 +800,7 @@ final class WallpaperGalleryItemNode: GalleryItemNode { } var items: [ListViewItem] = [] - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 1) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(1)) let otherPeerId = self.context.account.peerId var peers = SimpleDictionary() let messages = SimpleDictionary() diff --git a/submodules/SyncCore/Sources/Namespaces.swift b/submodules/SyncCore/Sources/Namespaces.swift index 4ac063b319..d7bf972845 100644 --- a/submodules/SyncCore/Sources/Namespaces.swift +++ b/submodules/SyncCore/Sources/Namespaces.swift @@ -31,11 +31,11 @@ public struct Namespaces { } public struct Peer { - public static let CloudUser: Int32 = 0 - public static let CloudGroup: Int32 = 1 - public static let CloudChannel: Int32 = 2 - public static let SecretChat: Int32 = 3 - public static let Empty: Int32 = Int32.max + public static let CloudUser = PeerId.Namespace._internalFromInt32Value(0) + public static let CloudGroup = PeerId.Namespace._internalFromInt32Value(1) + public static let CloudChannel = PeerId.Namespace._internalFromInt32Value(2) + public static let SecretChat = PeerId.Namespace._internalFromInt32Value(3) + public static let Empty = PeerId.Namespace.max } public struct ItemCollection { diff --git a/submodules/SyncCore/Sources/PeerReference.swift b/submodules/SyncCore/Sources/PeerReference.swift index dc50bea070..9b93b4f6e6 100644 --- a/submodules/SyncCore/Sources/PeerReference.swift +++ b/submodules/SyncCore/Sources/PeerReference.swift @@ -39,15 +39,15 @@ public enum PeerReference: PostboxCoding, Hashable, Equatable { switch peer { case let user as TelegramUser: if let accessHash = user.accessHash { - self = .user(id: user.id.id, accessHash: accessHash.value) + self = .user(id: user.id.id._internalGetInt32Value(), accessHash: accessHash.value) } else { return nil } case let group as TelegramGroup: - self = .group(id: group.id.id) + self = .group(id: group.id.id._internalGetInt32Value()) case let channel as TelegramChannel: if let accessHash = channel.accessHash { - self = .channel(id: channel.id.id, accessHash: accessHash.value) + self = .channel(id: channel.id.id._internalGetInt32Value(), accessHash: accessHash.value) } else { return nil } diff --git a/submodules/SyncCore/Sources/StandaloneAccountTransaction.swift b/submodules/SyncCore/Sources/StandaloneAccountTransaction.swift index 843c08ddea..d9b8c07eb7 100644 --- a/submodules/SyncCore/Sources/StandaloneAccountTransaction.swift +++ b/submodules/SyncCore/Sources/StandaloneAccountTransaction.swift @@ -38,7 +38,7 @@ public let telegramPostboxSeedConfiguration: SeedConfiguration = { globalMessageIdsPeerIdNamespaces.insert(GlobalMessageIdsNamespace(peerIdNamespace: peerIdNamespace, messageIdNamespace: Namespaces.Message.Cloud)) } - return SeedConfiguration(globalMessageIdsPeerIdNamespaces: globalMessageIdsPeerIdNamespaces, initializeChatListWithHole: (topLevel: ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.Empty, id: 0), namespace: Namespaces.Message.Cloud, id: 1), timestamp: Int32.max - 1)), groups: ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.Empty, id: 0), namespace: Namespaces.Message.Cloud, id: 1), timestamp: Int32.max - 1))), messageHoles: messageHoles, upgradedMessageHoles: upgradedMessageHoles, messageThreadHoles: messageThreadHoles, existingMessageTags: MessageTags.all, messageTagsWithSummary: [.unseenPersonalMessage, .pinned], existingGlobalMessageTags: GlobalMessageTags.all, peerNamespacesRequiringMessageTextIndex: [Namespaces.Peer.SecretChat], peerSummaryCounterTags: { peer, isContact in + return SeedConfiguration(globalMessageIdsPeerIdNamespaces: globalMessageIdsPeerIdNamespaces, initializeChatListWithHole: (topLevel: ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.Empty, id: PeerId.Id._internalFromInt32Value(0)), namespace: Namespaces.Message.Cloud, id: 1), timestamp: Int32.max - 1)), groups: ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.Empty, id: PeerId.Id._internalFromInt32Value(0)), namespace: Namespaces.Message.Cloud, id: 1), timestamp: Int32.max - 1))), messageHoles: messageHoles, upgradedMessageHoles: upgradedMessageHoles, messageThreadHoles: messageThreadHoles, existingMessageTags: MessageTags.all, messageTagsWithSummary: [.unseenPersonalMessage, .pinned], existingGlobalMessageTags: GlobalMessageTags.all, peerNamespacesRequiringMessageTextIndex: [Namespaces.Peer.SecretChat], peerSummaryCounterTags: { peer, isContact in if let peer = peer as? TelegramUser { if peer.botInfo != nil { return .bot diff --git a/submodules/SyncCore/Sources/SynchronizePinnedChatsOperation.swift b/submodules/SyncCore/Sources/SynchronizePinnedChatsOperation.swift index 4f9fd6b5ff..02b21573c2 100644 --- a/submodules/SyncCore/Sources/SynchronizePinnedChatsOperation.swift +++ b/submodules/SyncCore/Sources/SynchronizePinnedChatsOperation.swift @@ -48,7 +48,7 @@ public func addSynchronizePinnedChatsOperation(transaction: Transaction, groupId var previousItemIds = transaction.getPinnedItemIds(groupId: groupId) var updateLocalIndex: Int32? - transaction.operationLogEnumerateEntries(peerId: PeerId(namespace: 0, id: rawId), tag: OperationLogTags.SynchronizePinnedChats, { entry in + transaction.operationLogEnumerateEntries(peerId: PeerId(namespace: PeerId.Namespace._internalFromInt32Value(0), id: PeerId.Id._internalFromInt32Value(rawId)), tag: OperationLogTags.SynchronizePinnedChats, { entry in updateLocalIndex = entry.tagLocalIndex if let contents = entry.contents as? SynchronizePinnedChatsOperation { previousItemIds = contents.previousItemIds @@ -57,7 +57,7 @@ public func addSynchronizePinnedChatsOperation(transaction: Transaction, groupId }) let operationContents = SynchronizePinnedChatsOperation(previousItemIds: previousItemIds) if let updateLocalIndex = updateLocalIndex { - let _ = transaction.operationLogRemoveEntry(peerId: PeerId(namespace: 0, id: rawId), tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: updateLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: PeerId(namespace: PeerId.Namespace._internalFromInt32Value(0), id: PeerId.Id._internalFromInt32Value(rawId)), tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: updateLocalIndex) } - transaction.operationLogAddEntry(peerId: PeerId(namespace: 0, id: rawId), tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) + transaction.operationLogAddEntry(peerId: PeerId(namespace: PeerId.Namespace._internalFromInt32Value(0), id: PeerId.Id._internalFromInt32Value(rawId)), tag: OperationLogTags.SynchronizePinnedChats, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) } diff --git a/submodules/TelegramCallsUI/Sources/CallRatingController.swift b/submodules/TelegramCallsUI/Sources/CallRatingController.swift index 63103d7e8b..ebf86e48f1 100644 --- a/submodules/TelegramCallsUI/Sources/CallRatingController.swift +++ b/submodules/TelegramCallsUI/Sources/CallRatingController.swift @@ -241,7 +241,7 @@ private final class CallRatingAlertContentNode: AlertContentNode { } func rateCallAndSendLogs(account: Account, callId: CallId, starsCount: Int, comment: String, userInitiated: Bool, includeLogs: Bool) -> Signal { - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 4244000) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(4244000)) let rate = rateCall(account: account, callId: callId, starsCount: Int32(starsCount), comment: comment, userInitiated: userInitiated) if includeLogs { diff --git a/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift b/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift index 6ffd1d3607..08b27f546f 100644 --- a/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift +++ b/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift @@ -206,7 +206,7 @@ public final class PresentationCallManagerImpl: PresentationCallManager { startCallImpl = { [weak self] account, uuid, handle, isVideo in if let strongSelf = self, let userId = Int32(handle) { - return strongSelf.startCall(account: account, peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), isVideo: isVideo, internalId: uuid) + return strongSelf.startCall(account: account, peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), isVideo: isVideo, internalId: uuid) |> take(1) |> map { result -> Bool in return result diff --git a/submodules/TelegramCore/Sources/AccountIntermediateState.swift b/submodules/TelegramCore/Sources/AccountIntermediateState.swift index c468b1f85c..dcce140d9e 100644 --- a/submodules/TelegramCore/Sources/AccountIntermediateState.swift +++ b/submodules/TelegramCore/Sources/AccountIntermediateState.swift @@ -417,7 +417,7 @@ struct AccountMutableState { switch user { case let .user(_, id, _, _, _, _, _, _, status, _, _, _, _): if let status = status { - presences[PeerId(namespace: Namespaces.Peer.CloudUser, id: id)] = status + presences[PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id))] = status } break case .userEmpty: diff --git a/submodules/TelegramCore/Sources/AccountViewTracker.swift b/submodules/TelegramCore/Sources/AccountViewTracker.swift index 859a4b532c..9a91e1f4bd 100644 --- a/submodules/TelegramCore/Sources/AccountViewTracker.swift +++ b/submodules/TelegramCore/Sources/AccountViewTracker.swift @@ -717,7 +717,7 @@ public final class AccountViewTracker { switch replies { case let .messageReplies(_, repliesCountValue, _, recentRepliers, channelId, maxId, readMaxId): if let channelId = channelId { - commentsChannelId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + commentsChannelId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) } repliesCount = repliesCountValue if let recentRepliers = recentRepliers { diff --git a/submodules/TelegramCore/Sources/AddPeerMember.swift b/submodules/TelegramCore/Sources/AddPeerMember.swift index cd8654b78a..f58bdc6e24 100644 --- a/submodules/TelegramCore/Sources/AddPeerMember.swift +++ b/submodules/TelegramCore/Sources/AddPeerMember.swift @@ -18,7 +18,7 @@ public func addGroupMember(account: Account, peerId: PeerId, memberId: PeerId) - 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)) + return account.network.request(Api.functions.messages.addChatUser(chatId: group.id.id._internalGetInt32Value(), userId: inputUser, fwdLimit: 100)) |> mapError { error -> AddGroupMemberError in switch error.errorDescription { case "USERS_TOO_MUCH": diff --git a/submodules/TelegramCore/Sources/ApiUtils/ApiGroupOrChannel.swift b/submodules/TelegramCore/Sources/ApiUtils/ApiGroupOrChannel.swift index 46c548fae7..8f9edce1a6 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/ApiGroupOrChannel.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/ApiGroupOrChannel.swift @@ -34,7 +34,7 @@ func parseTelegramGroupOrChannel(chat: Api.Chat) -> Peer? { if let migratedTo = migratedTo { switch migratedTo { case let .inputChannel(channelId, accessHash): - migrationReference = TelegramGroupToChannelMigrationReference(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), accessHash: accessHash) + migrationReference = TelegramGroupToChannelMigrationReference(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)), accessHash: accessHash) case .inputChannelEmpty: break case .inputChannelFromMessage: @@ -57,11 +57,11 @@ func parseTelegramGroupOrChannel(chat: Api.Chat) -> Peer? { if (flags & Int32(1 << 24)) != 0 { groupFlags.insert(.hasActiveVoiceChat) } - return TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: id), title: title, photo: imageRepresentationsForApiChatPhoto(photo), participantCount: Int(participantsCount), role: role, membership: left ? .Left : .Member, flags: groupFlags, defaultBannedRights: defaultBannedRights.flatMap(TelegramChatBannedRights.init(apiBannedRights:)), migrationReference: migrationReference, creationDate: date, version: Int(version)) + return TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(id)), title: title, photo: imageRepresentationsForApiChatPhoto(photo), participantCount: Int(participantsCount), role: role, membership: left ? .Left : .Member, flags: groupFlags, defaultBannedRights: defaultBannedRights.flatMap(TelegramChatBannedRights.init(apiBannedRights:)), migrationReference: migrationReference, creationDate: date, version: Int(version)) case let .chatEmpty(id): - return TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: id), title: "", photo: [], participantCount: 0, role: .member, membership: .Removed, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) + return TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(id)), title: "", photo: [], participantCount: 0, role: .member, membership: .Removed, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) case let .chatForbidden(id, title): - return TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: id), title: title, photo: [], participantCount: 0, role: .member, membership: .Removed, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) + return TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(id)), title: title, photo: [], participantCount: 0, role: .member, membership: .Removed, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) case let .channel(flags, id, accessHash, title, username, photo, date, version, restrictionReason, adminRights, bannedRights, defaultBannedRights, _): let isMin = (flags & (1 << 12)) != 0 @@ -133,7 +133,7 @@ func parseTelegramGroupOrChannel(chat: Api.Chat) -> Peer? { } } - return TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: id), accessHash: accessHashValue, title: title, username: username, photo: imageRepresentationsForApiChatPhoto(photo), creationDate: date, version: version, participationStatus: participationStatus, info: info, flags: channelFlags, restrictionInfo: restrictionInfo, adminRights: adminRights.flatMap(TelegramChatAdminRights.init), bannedRights: bannedRights.flatMap(TelegramChatBannedRights.init), defaultBannedRights: defaultBannedRights.flatMap(TelegramChatBannedRights.init)) + return TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(id)), accessHash: accessHashValue, title: title, username: username, photo: imageRepresentationsForApiChatPhoto(photo), creationDate: date, version: version, participationStatus: participationStatus, info: info, flags: channelFlags, restrictionInfo: restrictionInfo, adminRights: adminRights.flatMap(TelegramChatAdminRights.init), bannedRights: bannedRights.flatMap(TelegramChatBannedRights.init), defaultBannedRights: defaultBannedRights.flatMap(TelegramChatBannedRights.init)) case let .channelForbidden(flags, id, accessHash, title, untilDate): let info: TelegramChannelInfo if (flags & Int32(1 << 8)) != 0 { @@ -142,7 +142,7 @@ func parseTelegramGroupOrChannel(chat: Api.Chat) -> Peer? { info = .broadcast(TelegramChannelBroadcastInfo(flags: [])) } - return TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: id), accessHash: .personal(accessHash), title: title, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .kicked, info: info, flags: TelegramChannelFlags(), restrictionInfo: nil, adminRights: nil, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: untilDate ?? Int32.max), defaultBannedRights: nil) + return TelegramChannel(id: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(id)), accessHash: .personal(accessHash), title: title, username: nil, photo: [], creationDate: 0, version: 0, participationStatus: .kicked, info: info, flags: TelegramChannelFlags(), restrictionInfo: nil, adminRights: nil, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: untilDate ?? Int32.max), defaultBannedRights: nil) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/ApiUtils.swift b/submodules/TelegramCore/Sources/ApiUtils/ApiUtils.swift index f7beff73f4..9f9ffc38f9 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/ApiUtils.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/ApiUtils.swift @@ -8,11 +8,11 @@ public extension PeerReference { var id: PeerId { switch self { case let .user(id, _): - return PeerId(namespace: Namespaces.Peer.CloudUser, id: id) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id)) case let .group(id): - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: id) + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(id)) case let .channel(id, _): - return PeerId(namespace: Namespaces.Peer.CloudChannel, id: id) + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(id)) } } } @@ -49,12 +49,12 @@ extension PeerReference { func forceApiInputPeer(_ peer: Peer) -> Api.InputPeer? { switch peer { case let user as TelegramUser: - return Api.InputPeer.inputPeerUser(userId: user.id.id, accessHash: user.accessHash?.value ?? 0) + return Api.InputPeer.inputPeerUser(userId: user.id.id._internalGetInt32Value(), accessHash: user.accessHash?.value ?? 0) case let group as TelegramGroup: - return Api.InputPeer.inputPeerChat(chatId: group.id.id) + return Api.InputPeer.inputPeerChat(chatId: group.id.id._internalGetInt32Value()) case let channel as TelegramChannel: if let accessHash = channel.accessHash { - return Api.InputPeer.inputPeerChannel(channelId: channel.id.id, accessHash: accessHash.value) + return Api.InputPeer.inputPeerChannel(channelId: channel.id.id._internalGetInt32Value(), accessHash: accessHash.value) } else { return nil } @@ -66,12 +66,12 @@ func forceApiInputPeer(_ peer: Peer) -> Api.InputPeer? { func apiInputPeer(_ peer: Peer) -> Api.InputPeer? { switch peer { case let user as TelegramUser where user.accessHash != nil: - return Api.InputPeer.inputPeerUser(userId: user.id.id, accessHash: user.accessHash!.value) + return Api.InputPeer.inputPeerUser(userId: user.id.id._internalGetInt32Value(), accessHash: user.accessHash!.value) case let group as TelegramGroup: - return Api.InputPeer.inputPeerChat(chatId: group.id.id) + return Api.InputPeer.inputPeerChat(chatId: group.id.id._internalGetInt32Value()) case let channel as TelegramChannel: if let accessHash = channel.accessHash { - return Api.InputPeer.inputPeerChannel(channelId: channel.id.id, accessHash: accessHash.value) + return Api.InputPeer.inputPeerChannel(channelId: channel.id.id._internalGetInt32Value(), accessHash: accessHash.value) } else { return nil } @@ -82,7 +82,7 @@ func apiInputPeer(_ peer: Peer) -> Api.InputPeer? { func apiInputChannel(_ peer: Peer) -> Api.InputChannel? { if let channel = peer as? TelegramChannel, let accessHash = channel.accessHash { - return Api.InputChannel.inputChannel(channelId: channel.id.id, accessHash: accessHash.value) + return Api.InputChannel.inputChannel(channelId: channel.id.id._internalGetInt32Value(), accessHash: accessHash.value) } else { return nil } @@ -90,7 +90,7 @@ func apiInputChannel(_ peer: Peer) -> Api.InputChannel? { func apiInputUser(_ peer: Peer) -> Api.InputUser? { if let user = peer as? TelegramUser, let accessHash = user.accessHash { - return Api.InputUser.inputUser(userId: user.id.id, accessHash: accessHash.value) + return Api.InputUser.inputUser(userId: user.id.id._internalGetInt32Value(), accessHash: accessHash.value) } else { return nil } @@ -98,7 +98,7 @@ func apiInputUser(_ peer: Peer) -> Api.InputUser? { func apiInputSecretChat(_ peer: Peer) -> Api.InputEncryptedChat? { if let chat = peer as? TelegramSecretChat { - return Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id, accessHash: chat.accessHash) + return Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id._internalGetInt32Value(), accessHash: chat.accessHash) } else { return nil } diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaAction.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaAction.swift index 8e93f430ac..eca4f06da6 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaAction.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaAction.swift @@ -9,23 +9,23 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe case let .messageActionChannelCreate(title): return TelegramMediaAction(action: .groupCreated(title: title)) case let .messageActionChannelMigrateFrom(title, chatId): - return TelegramMediaAction(action: .channelMigratedFromGroup(title: title, groupId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId))) + return TelegramMediaAction(action: .channelMigratedFromGroup(title: title, groupId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)))) case let .messageActionChatAddUser(users): - return TelegramMediaAction(action: .addedMembers(peerIds: users.map({ PeerId(namespace: Namespaces.Peer.CloudUser, id: $0) }))) + return TelegramMediaAction(action: .addedMembers(peerIds: users.map({ PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value($0)) }))) case let .messageActionChatCreate(title, _): return TelegramMediaAction(action: .groupCreated(title: title)) case .messageActionChatDeletePhoto: return TelegramMediaAction(action: .photoUpdated(image: nil)) case let .messageActionChatDeleteUser(userId): - return TelegramMediaAction(action: .removedMembers(peerIds: [PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)])) + return TelegramMediaAction(action: .removedMembers(peerIds: [PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))])) case let .messageActionChatEditPhoto(photo): return TelegramMediaAction(action: .photoUpdated(image: telegramMediaImageFromApiPhoto(photo))) case let .messageActionChatEditTitle(title): return TelegramMediaAction(action: .titleUpdated(title: title)) case let .messageActionChatJoinedByLink(inviterId): - return TelegramMediaAction(action: .joinedByLink(inviter: PeerId(namespace: Namespaces.Peer.CloudUser, id: inviterId))) + return TelegramMediaAction(action: .joinedByLink(inviter: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(inviterId)))) case let .messageActionChatMigrateTo(channelId): - return TelegramMediaAction(action: .groupMigratedToChannel(channelId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId))) + return TelegramMediaAction(action: .groupMigratedToChannel(channelId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)))) case .messageActionHistoryClear: return TelegramMediaAction(action: .historyCleared) case .messageActionPinMessage: @@ -68,7 +68,7 @@ func telegramMediaActionFromApiAction(_ action: Api.MessageAction) -> TelegramMe switch call { case let .inputGroupCall(id, accessHash): return TelegramMediaAction(action: .inviteToGroupPhoneCall(callId: id, accessHash: accessHash, peerIds: userIds.map { userId in - PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) })) } case let .messageActionSetMessagesTTL(period): diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaPoll.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaPoll.swift index 34c84ec378..2d45433129 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaPoll.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramMediaPoll.swift @@ -36,7 +36,7 @@ extension TelegramMediaPollResults { } self.init(voters: results.flatMap({ $0.map(TelegramMediaPollOptionVoters.init(apiVoters:)) }), totalVoters: totalVoters, recentVoters: recentVoters.flatMap { recentVoters in - return recentVoters.map { PeerId(namespace: Namespaces.Peer.CloudUser, id: $0) } + return recentVoters.map { PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value($0)) } } ?? [], solution: parsedSolution) } } diff --git a/submodules/TelegramCore/Sources/ApiUtils/TelegramUser.swift b/submodules/TelegramCore/Sources/ApiUtils/TelegramUser.swift index c4225bb235..673f3a0049 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/TelegramUser.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/TelegramUser.swift @@ -74,9 +74,9 @@ extension TelegramUser { let restrictionInfo: PeerAccessRestrictionInfo? = restrictionReason.flatMap(PeerAccessRestrictionInfo.init(apiReasons:)) - self.init(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: id), accessHash: accessHashValue, firstName: firstName, lastName: lastName, username: username, phone: phone, photo: representations, botInfo: botInfo, restrictionInfo: restrictionInfo, flags: userFlags) + self.init(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id)), accessHash: accessHashValue, firstName: firstName, lastName: lastName, username: username, phone: phone, photo: representations, botInfo: botInfo, restrictionInfo: restrictionInfo, flags: userFlags) case let .userEmpty(id): - self.init(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: id), accessHash: nil, firstName: nil, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + self.init(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id)), accessHash: nil, firstName: nil, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) } } diff --git a/submodules/TelegramCore/Sources/AuthTransfer.swift b/submodules/TelegramCore/Sources/AuthTransfer.swift index e661aa715d..89068b6b9e 100644 --- a/submodules/TelegramCore/Sources/AuthTransfer.swift +++ b/submodules/TelegramCore/Sources/AuthTransfer.swift @@ -21,8 +21,8 @@ public enum ExportAuthTransferTokenResult { case passwordRequested(UnauthorizedAccount) } -public func exportAuthTransferToken(accountManager: AccountManager, account: UnauthorizedAccount, otherAccountUserIds: [Int32], syncContacts: Bool) -> Signal { - return account.network.request(Api.functions.auth.exportLoginToken(apiId: account.networkArguments.apiId, apiHash: account.networkArguments.apiHash, exceptIds: otherAccountUserIds)) +public func exportAuthTransferToken(accountManager: AccountManager, account: UnauthorizedAccount, otherAccountUserIds: [PeerId.Id], syncContacts: Bool) -> Signal { + return account.network.request(Api.functions.auth.exportLoginToken(apiId: account.networkArguments.apiId, apiHash: account.networkArguments.apiHash, exceptIds: otherAccountUserIds.map({ $0._internalGetInt32Value() }))) |> map(Optional.init) |> `catch` { error -> Signal in if error.errorDescription == "SESSION_PASSWORD_NEEDED" { diff --git a/submodules/TelegramCore/Sources/BotPaymentForm.swift b/submodules/TelegramCore/Sources/BotPaymentForm.swift index cdb8a9ce8a..f7f3facc63 100644 --- a/submodules/TelegramCore/Sources/BotPaymentForm.swift +++ b/submodules/TelegramCore/Sources/BotPaymentForm.swift @@ -188,9 +188,9 @@ public func fetchBotPaymentForm(postbox: Postbox, network: Network, messageId: M parsedSavedCredentials = .card(id: id, title: title) } } - return BotPaymentForm(canSaveCredentials: (flags & (1 << 2)) != 0, passwordMissing: (flags & (1 << 3)) != 0, invoice: parsedInvoice, providerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: providerId), url: url, nativeProvider: parsedNativeProvider, savedInfo: parsedSavedInfo, savedCredentials: parsedSavedCredentials) + return BotPaymentForm(canSaveCredentials: (flags & (1 << 2)) != 0, passwordMissing: (flags & (1 << 3)) != 0, invoice: parsedInvoice, providerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(providerId)), url: url, nativeProvider: parsedNativeProvider, savedInfo: parsedSavedInfo, savedCredentials: parsedSavedCredentials) } - } |> mapError { _ -> BotPaymentFormRequestError in return .generic } + } |> mapError { _ -> BotPaymentFormRequestError in } } } diff --git a/submodules/TelegramCore/Sources/CachedChannelParticipants.swift b/submodules/TelegramCore/Sources/CachedChannelParticipants.swift index 316e401263..8964880bd0 100644 --- a/submodules/TelegramCore/Sources/CachedChannelParticipants.swift +++ b/submodules/TelegramCore/Sources/CachedChannelParticipants.swift @@ -199,17 +199,17 @@ extension ChannelParticipant { init(apiParticipant: Api.ChannelParticipant) { switch apiParticipant { case let .channelParticipant(userId, date): - self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), invitedAt: date, adminInfo: nil, banInfo: nil, rank: nil) + self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), invitedAt: date, adminInfo: nil, banInfo: nil, rank: nil) case let .channelParticipantCreator(_, userId, adminRights, rank): - self = .creator(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(apiAdminRights: adminRights) ?? TelegramChatAdminRights(rights: []), promotedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), canBeEditedByAccountPeer: true), rank: rank) + self = .creator(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(apiAdminRights: adminRights) ?? TelegramChatAdminRights(rights: []), promotedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), canBeEditedByAccountPeer: true), rank: rank) case let .channelParticipantBanned(flags, userId, restrictedBy, date, bannedRights): let hasLeft = (flags & (1 << 0)) != 0 - let banInfo = ChannelParticipantBannedInfo(rights: TelegramChatBannedRights(apiBannedRights: bannedRights), restrictedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: restrictedBy), timestamp: date, isMember: !hasLeft) + let banInfo = ChannelParticipantBannedInfo(rights: TelegramChatBannedRights(apiBannedRights: bannedRights), restrictedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(restrictedBy)), timestamp: date, isMember: !hasLeft) self = .member(id: userId.peerId, invitedAt: date, adminInfo: nil, banInfo: banInfo, rank: nil) case let .channelParticipantAdmin(flags, userId, _, promotedBy, date, adminRights, rank: rank): - self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), invitedAt: date, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(apiAdminRights: adminRights) ?? TelegramChatAdminRights(rights: []), promotedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: promotedBy), canBeEditedByAccountPeer: (flags & (1 << 0)) != 0), banInfo: nil, rank: rank) + self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), invitedAt: date, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(apiAdminRights: adminRights) ?? TelegramChatAdminRights(rights: []), promotedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(promotedBy)), canBeEditedByAccountPeer: (flags & (1 << 0)) != 0), banInfo: nil, rank: rank) case let .channelParticipantSelf(userId, _, date): - self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), invitedAt: date, adminInfo: nil, banInfo: nil, rank: nil) + self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), invitedAt: date, adminInfo: nil, banInfo: nil, rank: nil) case let .channelParticipantLeft(userId): self = .member(id: userId.peerId, invitedAt: 0, adminInfo: nil, banInfo: nil, rank: nil) } diff --git a/submodules/TelegramCore/Sources/CachedGroupParticipants.swift b/submodules/TelegramCore/Sources/CachedGroupParticipants.swift index ceb0b1839c..c536963ca3 100644 --- a/submodules/TelegramCore/Sources/CachedGroupParticipants.swift +++ b/submodules/TelegramCore/Sources/CachedGroupParticipants.swift @@ -8,11 +8,11 @@ extension GroupParticipant { init(apiParticipant: Api.ChatParticipant) { switch apiParticipant { case let .chatParticipantCreator(userId): - self = .creator(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)) + self = .creator(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))) case let .chatParticipantAdmin(userId, inviterId, date): - self = .admin(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), invitedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: inviterId), invitedAt: date) + self = .admin(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), invitedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(inviterId)), invitedAt: date) case let .chatParticipant(userId, inviterId, date): - self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), invitedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: inviterId), invitedAt: date) + self = .member(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), invitedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(inviterId)), invitedAt: date) } } } diff --git a/submodules/TelegramCore/Sources/CallSessionManager.swift b/submodules/TelegramCore/Sources/CallSessionManager.swift index 69401d05cb..e4d8ff16a0 100644 --- a/submodules/TelegramCore/Sources/CallSessionManager.swift +++ b/submodules/TelegramCore/Sources/CallSessionManager.swift @@ -815,7 +815,7 @@ private final class CallSessionManagerContext { versions = libraryVersions } if self.contextIdByStableId[id] == nil { - let internalId = self.addIncoming(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: adminId), stableId: id, accessHash: accessHash, timestamp: date, gAHash: gAHash.makeData(), versions: versions, isVideo: isVideo) + let internalId = self.addIncoming(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(adminId)), stableId: id, accessHash: accessHash, timestamp: date, gAHash: gAHash.makeData(), versions: versions, isVideo: isVideo) if let internalId = internalId { var resultRingingStateValue: CallSessionRingingState? for ringingState in self.ringingStatesValue() { diff --git a/submodules/TelegramCore/Sources/ChannelAdminEventLogs.swift b/submodules/TelegramCore/Sources/ChannelAdminEventLogs.swift index 3a38204a5d..acafdd8af0 100644 --- a/submodules/TelegramCore/Sources/ChannelAdminEventLogs.swift +++ b/submodules/TelegramCore/Sources/ChannelAdminEventLogs.swift @@ -220,7 +220,7 @@ public func channelAdminLogEvents(postbox: Postbox, network: Network, peerId: Pe action = .pollStopped(rendered) } case let .channelAdminLogEventActionChangeLinkedChat(prevValue, newValue): - action = .linkedPeerUpdated(previous: prevValue == 0 ? nil : peers[PeerId(namespace: Namespaces.Peer.CloudChannel, id: prevValue)], updated: newValue == 0 ? nil : peers[PeerId(namespace: Namespaces.Peer.CloudChannel, id: newValue)]) + action = .linkedPeerUpdated(previous: prevValue == 0 ? nil : peers[PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(prevValue))], updated: newValue == 0 ? nil : peers[PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(newValue))]) case let .channelAdminLogEventActionChangeLocation(prevValue, newValue): action = .changeGeoLocation(previous: PeerGeoLocation(apiLocation: prevValue), updated: PeerGeoLocation(apiLocation: newValue)) case let .channelAdminLogEventActionToggleSlowMode(prevValue, newValue): @@ -251,7 +251,7 @@ public func channelAdminLogEvents(postbox: Postbox, network: Network, peerId: Pe case let .channelAdminLogEventActionChangeHistoryTTL(prevValue, newValue): action = .changeHistoryTTL(previousValue: prevValue, updatedValue: newValue) } - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) if let action = action { events.append(AdminLogEvent(id: id, peerId: peerId, date: date, action: action)) } diff --git a/submodules/TelegramCore/Sources/ChannelAdmins.swift b/submodules/TelegramCore/Sources/ChannelAdmins.swift index 740af0a8f6..105e7070a8 100644 --- a/submodules/TelegramCore/Sources/ChannelAdmins.swift +++ b/submodules/TelegramCore/Sources/ChannelAdmins.swift @@ -63,9 +63,9 @@ public func channelAdminIds(postbox: Postbox, network: Network, peerId: PeerId, return participants.contains(where: { participant in switch participant { case let .channelParticipantAdmin(_, userId, _, _, _, _, _): - return user.peerId.id == userId + return user.peerId.id._internalGetInt32Value() == userId case let .channelParticipantCreator(_, userId, _, _): - return user.peerId.id == userId + return user.peerId.id._internalGetInt32Value() == userId default: return false } diff --git a/submodules/TelegramCore/Sources/ChatListFiltering.swift b/submodules/TelegramCore/Sources/ChatListFiltering.swift index 363bf5e38b..c2061ac38b 100644 --- a/submodules/TelegramCore/Sources/ChatListFiltering.swift +++ b/submodules/TelegramCore/Sources/ChatListFiltering.swift @@ -298,22 +298,22 @@ extension ChatListFilter { includePeers: ChatListFilterIncludePeers(rawPeers: includePeers.compactMap { peer -> PeerId? in switch peer { case let .inputPeerUser(userId, _): - return PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) case let .inputPeerChat(chatId): - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) case let .inputPeerChannel(channelId, _): - return PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) default: return nil } }, rawPinnedPeers: pinnedPeers.compactMap { peer -> PeerId? in switch peer { case let .inputPeerUser(userId, _): - return PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) case let .inputPeerChat(chatId): - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) case let .inputPeerChannel(channelId, _): - return PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) default: return nil } @@ -321,11 +321,11 @@ extension ChatListFilter { excludePeers: excludePeers.compactMap { peer -> PeerId? in switch peer { case let .inputPeerUser(userId, _): - return PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) case let .inputPeerChat(chatId): - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) case let .inputPeerChannel(channelId, _): - return PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) default: return nil } @@ -426,11 +426,11 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net var peerId: PeerId? switch peer { case let .inputPeerUser(userId, _): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) case let .inputPeerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) case let .inputPeerChannel(channelId, _): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) default: break } @@ -446,11 +446,11 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net var peerId: PeerId? switch peer { case let .inputPeerUser(userId, _): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) case let .inputPeerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) case let .inputPeerChannel(channelId, _): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) default: break } @@ -1092,7 +1092,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOpera func requestChatListFiltersSync(transaction: Transaction) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeChatListFilters - let peerId = PeerId(namespace: 0, id: 0) + let peerId = PeerId(0) var topOperation: (SynchronizeChatListFiltersOperation, Int32)? transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in diff --git a/submodules/TelegramCore/Sources/ContactManagement.swift b/submodules/TelegramCore/Sources/ContactManagement.swift index f2bb32ffc9..944e33db9e 100644 --- a/submodules/TelegramCore/Sources/ContactManagement.swift +++ b/submodules/TelegramCore/Sources/ContactManagement.swift @@ -56,7 +56,7 @@ func syncContactsOnce(network: Network, postbox: Postbox, accountPeerId: PeerId) let contactPeerIds = transaction.getContactPeerIds() let totalCount = transaction.getRemoteContactCount() let peerIds = Set(contactPeerIds.filter({ $0.namespace == Namespaces.Peer.CloudUser })) - return hashForCountAndIds(count: totalCount, ids: peerIds.map({ $0.id }).sorted()) + return hashForCountAndIds(count: totalCount, ids: peerIds.map({ $0.id._internalGetInt32Value() }).sorted()) } let updatedPeers = initialContactPeerIdsHash diff --git a/submodules/TelegramCore/Sources/ContactSyncManager.swift b/submodules/TelegramCore/Sources/ContactSyncManager.swift index 83b1d3db2a..b5b4aca039 100644 --- a/submodules/TelegramCore/Sources/ContactSyncManager.swift +++ b/submodules/TelegramCore/Sources/ContactSyncManager.swift @@ -345,7 +345,7 @@ private func pushDeviceContactData(postbox: Postbox, network: Network, contacts: for item in imported { switch item { case let .importedContact(userId, _): - addedContactPeerIds.insert(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)) + addedContactPeerIds.insert(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))) } } for item in retryContacts { @@ -399,7 +399,7 @@ private func updateContactPresences(postbox: Postbox, network: Network, accountP for status in statuses { switch status { case let .contactStatus(userId, status): - peerPresences[PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)] = TelegramUserPresence(apiStatus: status) + peerPresences[PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))] = TelegramUserPresence(apiStatus: status) } } updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: peerPresences) diff --git a/submodules/TelegramCore/Sources/ConvertGroupToSupergroup.swift b/submodules/TelegramCore/Sources/ConvertGroupToSupergroup.swift index a91862c0d2..cce0ed0147 100644 --- a/submodules/TelegramCore/Sources/ConvertGroupToSupergroup.swift +++ b/submodules/TelegramCore/Sources/ConvertGroupToSupergroup.swift @@ -10,7 +10,7 @@ public enum ConvertGroupToSupergroupError { } public func convertGroupToSupergroup(account: Account, peerId: PeerId) -> Signal { - return account.network.request(Api.functions.messages.migrateChat(chatId: peerId.id)) + return account.network.request(Api.functions.messages.migrateChat(chatId: peerId.id._internalGetInt32Value())) |> mapError { error -> ConvertGroupToSupergroupError in if error.errorDescription == "CHANNELS_TOO_MUCH" { return .tooManyChannels diff --git a/submodules/TelegramCore/Sources/ExportedInvitation.swift b/submodules/TelegramCore/Sources/ExportedInvitation.swift index cd4fb5b3fb..48b008b36c 100644 --- a/submodules/TelegramCore/Sources/ExportedInvitation.swift +++ b/submodules/TelegramCore/Sources/ExportedInvitation.swift @@ -8,7 +8,7 @@ extension ExportedInvitation { init(apiExportedInvite: Api.ExportedChatInvite) { switch apiExportedInvite { case let .chatInviteExported(flags, link, adminId, date, startDate, expireDate, usageLimit, usage): - self = ExportedInvitation(link: link, isPermanent: (flags & (1 << 5)) != 0, isRevoked: (flags & (1 << 0)) != 0, adminId: PeerId(namespace: Namespaces.Peer.CloudUser, id: adminId), date: date, startDate: startDate, expireDate: expireDate, usageLimit: usageLimit, count: usage) + self = ExportedInvitation(link: link, isPermanent: (flags & (1 << 5)) != 0, isRevoked: (flags & (1 << 0)) != 0, adminId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(adminId)), date: date, startDate: startDate, expireDate: expireDate, usageLimit: usageLimit, count: usage) } } } diff --git a/submodules/TelegramCore/Sources/FetchChatList.swift b/submodules/TelegramCore/Sources/FetchChatList.swift index 9da9b60c2c..1fdf736c59 100644 --- a/submodules/TelegramCore/Sources/FetchChatList.swift +++ b/submodules/TelegramCore/Sources/FetchChatList.swift @@ -113,11 +113,11 @@ private func parseDialogs(apiDialogs: [Api.Dialog], apiMessages: [Api.Message], let peerId: PeerId switch apiPeer { case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) } if readStates[peerId] == nil { diff --git a/submodules/TelegramCore/Sources/GrantSecureIdAccess.swift b/submodules/TelegramCore/Sources/GrantSecureIdAccess.swift index ef93a7ac0f..c191a5b09b 100644 --- a/submodules/TelegramCore/Sources/GrantSecureIdAccess.swift +++ b/submodules/TelegramCore/Sources/GrantSecureIdAccess.swift @@ -333,7 +333,7 @@ public func grantSecureIdAccess(network: Network, peerId: PeerId, publicKey: Str valueHashes.append(.secureValueHash(type: apiSecureValueType(value: value.value), hash: Buffer(data: value.opaqueHash))) } - return network.request(Api.functions.account.acceptAuthorization(botId: peerId.id, scope: scope, publicKey: publicKey, valueHashes: valueHashes, credentials: .secureCredentialsEncrypted(data: Buffer(data: encryptedCredentialsData), hash: Buffer(data: decryptedCredentialsHash), secret: Buffer(data: encryptedSecretData)))) + return network.request(Api.functions.account.acceptAuthorization(botId: peerId.id._internalGetInt32Value(), scope: scope, publicKey: publicKey, valueHashes: valueHashes, credentials: .secureCredentialsEncrypted(data: Buffer(data: encryptedCredentialsData), hash: Buffer(data: decryptedCredentialsHash), secret: Buffer(data: encryptedSecretData)))) |> mapError { error -> GrantSecureIdAccessError in return .generic } diff --git a/submodules/TelegramCore/Sources/GroupCalls.swift b/submodules/TelegramCore/Sources/GroupCalls.swift index 7954809f98..3832a443f0 100644 --- a/submodules/TelegramCore/Sources/GroupCalls.swift +++ b/submodules/TelegramCore/Sources/GroupCalls.swift @@ -111,15 +111,7 @@ public func getCurrentGroupCall(account: Account, callId: Int64, accessHash: Int loop: for participant in participants { switch participant { case let .groupCallParticipant(flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, params): - let peerId: PeerId - switch apiPeerId { - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - } + let peerId: PeerId = apiPeerId.peerId let ssrc = UInt32(bitPattern: source) guard let peer = transaction.getPeer(peerId) else { @@ -298,15 +290,7 @@ public func getGroupCallParticipants(account: Account, callId: Int64, accessHash loop: for participant in participants { switch participant { case let .groupCallParticipant(flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, params): - let peerId: PeerId - switch apiPeerId { - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - } + let peerId: PeerId = apiPeerId.peerId let ssrc = UInt32(bitPattern: source) guard let peer = transaction.getPeer(peerId) else { continue loop @@ -526,15 +510,7 @@ public func joinGroupCall(account: Account, peerId: PeerId, joinAs: PeerId?, cal loop: for participant in participants { switch participant { case let .groupCallParticipant(flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, params): - let peerId: PeerId - switch apiPeerId { - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - } + let peerId: PeerId = apiPeerId.peerId let ssrc = UInt32(bitPattern: source) guard let peer = transaction.getPeer(peerId) else { continue loop @@ -1732,15 +1708,7 @@ extension GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate { init(_ apiParticipant: Api.GroupCallParticipant) { switch apiParticipant { case let .groupCallParticipant(flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, params): - let peerId: PeerId - switch apiPeerId { - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - } + let peerId: PeerId = apiPeerId.peerId let ssrc = UInt32(bitPattern: source) let muted = (flags & (1 << 0)) != 0 let mutedByYou = (flags & (1 << 9)) != 0 @@ -1795,15 +1763,7 @@ extension GroupCallParticipantsContext.Update.StateUpdate { for participant in participants { switch participant { case let .groupCallParticipant(flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, params): - let peerId: PeerId - switch apiPeerId { - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - } + let peerId: PeerId = apiPeerId.peerId let ssrc = UInt32(bitPattern: source) let muted = (flags & (1 << 0)) != 0 let mutedByYou = (flags & (1 << 9)) != 0 diff --git a/submodules/TelegramCore/Sources/GroupReturnAndLeft.swift b/submodules/TelegramCore/Sources/GroupReturnAndLeft.swift index 16360909ab..5073e42342 100644 --- a/submodules/TelegramCore/Sources/GroupReturnAndLeft.swift +++ b/submodules/TelegramCore/Sources/GroupReturnAndLeft.swift @@ -9,7 +9,7 @@ public func returnGroup(account: Account, peerId: PeerId) -> Signal take(1) |> mapToSignal { peer -> Signal in if let inputUser = apiInputUser(peer) { - return account.network.request(Api.functions.messages.addChatUser(chatId: peerId.id, userId: inputUser, fwdLimit: 50)) + return account.network.request(Api.functions.messages.addChatUser(chatId: peerId.id._internalGetInt32Value(), userId: inputUser, fwdLimit: 50)) |> retryRequest |> mapToSignal { updates -> Signal in account.stateManager.addUpdates(updates) @@ -26,7 +26,7 @@ public func leftGroup(account: Account, peerId: PeerId) -> Signal |> take(1) |> mapToSignal { peer -> Signal in if let inputUser = apiInputUser(peer) { - return account.network.request(Api.functions.messages.deleteChatUser(flags: 0, chatId: peerId.id, userId: inputUser)) + return account.network.request(Api.functions.messages.deleteChatUser(flags: 0, chatId: peerId.id._internalGetInt32Value(), userId: inputUser)) |> retryRequest |> mapToSignal { updates -> Signal in account.stateManager.addUpdates(updates) diff --git a/submodules/TelegramCore/Sources/GroupsInCommon.swift b/submodules/TelegramCore/Sources/GroupsInCommon.swift index 85e72c3aac..53a5450cad 100644 --- a/submodules/TelegramCore/Sources/GroupsInCommon.swift +++ b/submodules/TelegramCore/Sources/GroupsInCommon.swift @@ -58,7 +58,7 @@ private final class GroupsInCommonContextImpl { guard let inputUser = inputUser else { return .single(([], 0)) } - return network.request(Api.functions.messages.getCommonChats(userId: inputUser, maxId: maxId ?? 0, limit: limit)) + return network.request(Api.functions.messages.getCommonChats(userId: inputUser, maxId: maxId?._internalGetInt32Value() ?? 0, limit: limit)) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) diff --git a/submodules/TelegramCore/Sources/HistoryViewStateValidation.swift b/submodules/TelegramCore/Sources/HistoryViewStateValidation.swift index f66c02d007..b5988b23ae 100644 --- a/submodules/TelegramCore/Sources/HistoryViewStateValidation.swift +++ b/submodules/TelegramCore/Sources/HistoryViewStateValidation.swift @@ -410,7 +410,7 @@ private func hashForMessages(_ messages: [Message], withChannelIds: Bool) -> Int for message in sorted { if withChannelIds { - acc = (acc &* 20261) &+ UInt32(message.id.peerId.id) + acc = (acc &* 20261) &+ UInt32(message.id.peerId.id._internalGetInt32Value()) } acc = (acc &* 20261) &+ UInt32(message.id.id) @@ -435,7 +435,7 @@ private func hashForMessages(_ messages: [StoreMessage], withChannelIds: Bool) - for message in messages { if case let .Id(id) = message.id { if withChannelIds { - acc = (acc &* 20261) &+ UInt32(id.peerId.id) + acc = (acc &* 20261) &+ UInt32(id.peerId.id._internalGetInt32Value()) } acc = (acc &* 20261) &+ UInt32(id.id) var timestamp = message.timestamp diff --git a/submodules/TelegramCore/Sources/Holes.swift b/submodules/TelegramCore/Sources/Holes.swift index fc66edb831..61e04b1d14 100644 --- a/submodules/TelegramCore/Sources/Holes.swift +++ b/submodules/TelegramCore/Sources/Holes.swift @@ -573,13 +573,13 @@ func fetchMessageHistoryHole(accountPeerId: PeerId, source: FetchMessageHistoryH func groupBoundaryPeer(_ peerId: PeerId, accountPeerId: PeerId) -> Api.Peer { switch peerId.namespace { case Namespaces.Peer.CloudUser: - return Api.Peer.peerUser(userId: peerId.id) + return Api.Peer.peerUser(userId: peerId.id._internalGetInt32Value()) case Namespaces.Peer.CloudGroup: - return Api.Peer.peerChat(chatId: peerId.id) + return Api.Peer.peerChat(chatId: peerId.id._internalGetInt32Value()) case Namespaces.Peer.CloudChannel: - return Api.Peer.peerChannel(channelId: peerId.id) + return Api.Peer.peerChannel(channelId: peerId.id._internalGetInt32Value()) default: - return Api.Peer.peerUser(userId: accountPeerId.id) + return Api.Peer.peerUser(userId: accountPeerId.id._internalGetInt32Value()) } } diff --git a/submodules/TelegramCore/Sources/InvitationLinks.swift b/submodules/TelegramCore/Sources/InvitationLinks.swift index d5d048ddaf..32e6a8cbf4 100644 --- a/submodules/TelegramCore/Sources/InvitationLinks.swift +++ b/submodules/TelegramCore/Sources/InvitationLinks.swift @@ -658,7 +658,7 @@ final class CachedPeerInvitationImporters: PostboxCoding { for index in stride(from: 0, to: datesArray.endIndex, by: 2) { let userId = datesArray[index] let date = datesArray[index + 1] - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) dates[peerId] = date } self.dates = dates @@ -671,7 +671,7 @@ final class CachedPeerInvitationImporters: PostboxCoding { var dates: [Int32] = [] for (peerId, date) in self.dates { - dates.append(peerId.id) + dates.append(peerId.id._internalGetInt32Value()) dates.append(date) } encoder.encodeInt32Array(dates, forKey: "dates") @@ -791,7 +791,7 @@ private final class PeerInvitationImportersContextImpl { let date: Int32 switch importer { case let .chatInviteImporter(userId, dateValue): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) date = dateValue } if let peer = transaction.getPeer(peerId) { @@ -911,7 +911,7 @@ public func peerExportedInvitationsCreators(account: Account, peerId: PeerId) -> for admin in admins { switch admin { case let .chatAdminWithInvites(adminId, invitesCount, revokedInvitesCount): - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: adminId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(adminId)) if let peer = peersMap[peerId], peerId != account.peerId { creators.append(ExportedInvitationCreator(peer: RenderedPeer(peer: peer), count: invitesCount, revokedCount: revokedInvitesCount)) } diff --git a/submodules/TelegramCore/Sources/MessageUtils.swift b/submodules/TelegramCore/Sources/MessageUtils.swift index b771a11815..ee98a74694 100644 --- a/submodules/TelegramCore/Sources/MessageUtils.swift +++ b/submodules/TelegramCore/Sources/MessageUtils.swift @@ -184,10 +184,12 @@ func locallyRenderedMessage(message: StoreMessage, peers: [PeerId: Peer]) -> Mes messagePeers[source.id] = source } } - - var hash: Int32 = id.id - hash = hash &* 31 &+ id.peerId.id - let stableId = UInt32(clamping: hash) + + var hasher = Hasher() + hasher.combine(id.id) + hasher.combine(id.peerId) + + let stableId = UInt32(clamping: hasher.finalize()) return Message(stableId: stableId, stableVersion: 0, id: id, globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, threadId: message.threadId, timestamp: message.timestamp, flags: MessageFlags(message.flags), tags: message.tags, globalTags: message.globalTags, localTags: message.localTags, forwardInfo: forwardInfo, author: author, text: message.text, attributes: message.attributes, media: message.media, peers: messagePeers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) } diff --git a/submodules/TelegramCore/Sources/NotificationExceptionsList.swift b/submodules/TelegramCore/Sources/NotificationExceptionsList.swift index e5fb3f8934..1210a78445 100644 --- a/submodules/TelegramCore/Sources/NotificationExceptionsList.swift +++ b/submodules/TelegramCore/Sources/NotificationExceptionsList.swift @@ -49,11 +49,11 @@ public func notificationExceptionsList(postbox: Postbox, network: Network) -> Si let peerId: PeerId switch notifyPeer { case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) } settings[peerId] = TelegramPeerNotificationSettings(apiSettings: notifySettings) default: diff --git a/submodules/TelegramCore/Sources/PeerAdmins.swift b/submodules/TelegramCore/Sources/PeerAdmins.swift index 786ca32d19..5f9c1f3f3f 100644 --- a/submodules/TelegramCore/Sources/PeerAdmins.swift +++ b/submodules/TelegramCore/Sources/PeerAdmins.swift @@ -14,7 +14,7 @@ public func removeGroupAdmin(account: Account, peerId: PeerId, adminId: PeerId) return account.postbox.transaction { transaction -> Signal in if let peer = transaction.getPeer(peerId), let adminPeer = transaction.getPeer(adminId), let inputUser = apiInputUser(adminPeer) { if let group = peer as? TelegramGroup { - return account.network.request(Api.functions.messages.editChatAdmin(chatId: group.id.id, userId: inputUser, isAdmin: .boolFalse)) + return account.network.request(Api.functions.messages.editChatAdmin(chatId: group.id.id._internalGetInt32Value(), userId: inputUser, isAdmin: .boolFalse)) |> mapError { _ -> RemoveGroupAdminError in return .generic } |> mapToSignal { result -> Signal in return account.postbox.transaction { transaction -> Void in @@ -62,7 +62,7 @@ public func addGroupAdmin(account: Account, peerId: PeerId, adminId: PeerId) -> return account.postbox.transaction { transaction -> Signal in if let peer = transaction.getPeer(peerId), let adminPeer = transaction.getPeer(adminId), let inputUser = apiInputUser(adminPeer) { if let group = peer as? TelegramGroup { - return account.network.request(Api.functions.messages.editChatAdmin(chatId: group.id.id, userId: inputUser, isAdmin: .boolTrue)) + return account.network.request(Api.functions.messages.editChatAdmin(chatId: group.id.id._internalGetInt32Value(), userId: inputUser, isAdmin: .boolTrue)) |> `catch` { error -> Signal in if error.errorDescription == "USER_NOT_PARTICIPANT" { return addGroupMember(account: account, peerId: peerId, memberId: adminId) @@ -73,7 +73,7 @@ public func addGroupAdmin(account: Account, peerId: PeerId, adminId: PeerId) -> return .complete() } |> then( - account.network.request(Api.functions.messages.editChatAdmin(chatId: group.id.id, userId: inputUser, isAdmin: .boolTrue)) + account.network.request(Api.functions.messages.editChatAdmin(chatId: group.id.id._internalGetInt32Value(), userId: inputUser, isAdmin: .boolTrue)) |> mapError { error -> AddGroupAdminError in return .generic } diff --git a/submodules/TelegramCore/Sources/PeerPhotoUpdater.swift b/submodules/TelegramCore/Sources/PeerPhotoUpdater.swift index 32325fe91c..14105775e3 100644 --- a/submodules/TelegramCore/Sources/PeerPhotoUpdater.swift +++ b/submodules/TelegramCore/Sources/PeerPhotoUpdater.swift @@ -223,7 +223,7 @@ public func updatePeerPhotoInternal(postbox: Postbox, network: Network, stateMan let request: Signal if let peer = peer as? TelegramGroup { - request = network.request(Api.functions.messages.editChatPhoto(chatId: peer.id.id, photo: .inputChatUploadedPhoto(flags: flags, file: file, video: videoFile, videoStartTs: videoStartTimestamp))) + request = network.request(Api.functions.messages.editChatPhoto(chatId: peer.id.id._internalGetInt32Value(), photo: .inputChatUploadedPhoto(flags: flags, file: file, video: videoFile, videoStartTs: videoStartTimestamp))) } else if let peer = peer as? TelegramChannel, let inputChannel = apiInputChannel(peer) { request = network.request(Api.functions.channels.editPhoto(channel: inputChannel, photo: .inputChatUploadedPhoto(flags: flags, file: file, video: videoFile, videoStartTs: videoStartTimestamp))) } else { @@ -311,7 +311,7 @@ public func updatePeerPhotoInternal(postbox: Postbox, network: Network, stateMan } else { let request: Signal if let peer = peer as? TelegramGroup { - request = network.request(Api.functions.messages.editChatPhoto(chatId: peer.id.id, photo: .inputChatPhotoEmpty)) + request = network.request(Api.functions.messages.editChatPhoto(chatId: peer.id.id._internalGetInt32Value(), photo: .inputChatPhotoEmpty)) } else if let peer = peer as? TelegramChannel, let inputChannel = apiInputChannel(peer) { request = network.request(Api.functions.channels.editPhoto(channel: inputChannel, photo: .inputChatPhotoEmpty)) } else { diff --git a/submodules/TelegramCore/Sources/PeerStatistics.swift b/submodules/TelegramCore/Sources/PeerStatistics.swift index 83f9383e9a..21726144ca 100644 --- a/submodules/TelegramCore/Sources/PeerStatistics.swift +++ b/submodules/TelegramCore/Sources/PeerStatistics.swift @@ -1065,7 +1065,7 @@ extension GroupStatsTopPoster { init(apiStatsGroupTopPoster: Api.StatsGroupTopPoster) { switch apiStatsGroupTopPoster { case let .statsGroupTopPoster(userId, messages, avgChars): - self = GroupStatsTopPoster(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), messageCount: messages, averageChars: avgChars) + self = GroupStatsTopPoster(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), messageCount: messages, averageChars: avgChars) } } } @@ -1074,7 +1074,7 @@ extension GroupStatsTopAdmin { init(apiStatsGroupTopAdmin: Api.StatsGroupTopAdmin) { switch apiStatsGroupTopAdmin { case let .statsGroupTopAdmin(userId, deleted, kicked, banned): - self = GroupStatsTopAdmin(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), deletedCount: deleted, kickedCount: kicked, bannedCount: banned) + self = GroupStatsTopAdmin(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), deletedCount: deleted, kickedCount: kicked, bannedCount: banned) } } } @@ -1083,7 +1083,7 @@ extension GroupStatsTopInviter { init(apiStatsGroupTopInviter: Api.StatsGroupTopInviter) { switch apiStatsGroupTopInviter { case let .statsGroupTopInviter(userId, invitations): - self = GroupStatsTopInviter(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), inviteCount: invitations) + self = GroupStatsTopInviter(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), inviteCount: invitations) } } } diff --git a/submodules/TelegramCore/Sources/PeerUtils.swift b/submodules/TelegramCore/Sources/PeerUtils.swift index 9bee3aa061..c39e549776 100644 --- a/submodules/TelegramCore/Sources/PeerUtils.swift +++ b/submodules/TelegramCore/Sources/PeerUtils.swift @@ -241,7 +241,7 @@ public func isServicePeer(_ peer: Peer) -> Bool { if peer.id.isReplies { return true } - return (peer.id.namespace == Namespaces.Peer.CloudUser && (peer.id.id == 777000 || peer.id.id == 333000)) + return (peer.id.namespace == Namespaces.Peer.CloudUser && (peer.id.id._internalGetInt32Value() == 777000 || peer.id.id._internalGetInt32Value() == 333000)) } return false } @@ -249,7 +249,7 @@ public func isServicePeer(_ peer: Peer) -> Bool { public extension PeerId { var isReplies: Bool { if self.namespace == Namespaces.Peer.CloudUser { - if self.id == 708513 || self.id == 1271266957 { + if self.id._internalGetInt32Value() == 708513 || self.id._internalGetInt32Value() == 1271266957 { return true } } @@ -268,7 +268,7 @@ public extension PeerId { var isImport: Bool { if self.namespace == Namespaces.Peer.CloudUser { - if self.id == 225079 { + if self.id._internalGetInt32Value() == 225079 { return true } } diff --git a/submodules/TelegramCore/Sources/Polls.swift b/submodules/TelegramCore/Sources/Polls.swift index 9c20e6b9c7..b8228f08e5 100644 --- a/submodules/TelegramCore/Sources/Polls.swift +++ b/submodules/TelegramCore/Sources/Polls.swift @@ -286,11 +286,11 @@ private final class PollResultsOptionContext { let peerId: PeerId switch vote { case let .messageUserVote(userId, _, _): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) case let .messageUserVoteInputOption(userId, _): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) case let .messageUserVoteMultiple(userId, _, _): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) } if let peer = transaction.getPeer(peerId) { resultPeers.append(RenderedPeer(peer: peer)) diff --git a/submodules/TelegramCore/Sources/PrivacySettings.swift b/submodules/TelegramCore/Sources/PrivacySettings.swift index 0ad2eade68..3f44df44b3 100644 --- a/submodules/TelegramCore/Sources/PrivacySettings.swift +++ b/submodules/TelegramCore/Sources/PrivacySettings.swift @@ -162,7 +162,7 @@ extension SelectivePrivacySettings { current = .enableContacts(enableFor: [:], disableFor: [:]) case let .privacyValueAllowUsers(users): for id in users { - if let peer = peers[PeerId(namespace: Namespaces.Peer.CloudUser, id: id)] { + if let peer = peers[PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id))] { enableFor[peer.peer.id] = peer } } @@ -172,13 +172,13 @@ extension SelectivePrivacySettings { break case let .privacyValueDisallowUsers(users): for id in users { - if let peer = peers[PeerId(namespace: Namespaces.Peer.CloudUser, id: id)] { + if let peer = peers[PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id))] { disableFor[peer.peer.id] = peer } } case let .privacyValueAllowChatParticipants(chats): for id in chats { - for possibleId in [PeerId(namespace: Namespaces.Peer.CloudGroup, id: id), PeerId(namespace: Namespaces.Peer.CloudChannel, id: id)] { + for possibleId in [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(id)), PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(id))] { if let peer = peers[possibleId] { enableFor[peer.peer.id] = peer } @@ -186,7 +186,7 @@ extension SelectivePrivacySettings { } case let .privacyValueDisallowChatParticipants(chats): for id in chats { - for possibleId in [PeerId(namespace: Namespaces.Peer.CloudGroup, id: id), PeerId(namespace: Namespaces.Peer.CloudChannel, id: id)] { + for possibleId in [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(id)), PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(id))] { if let peer = peers[possibleId] { disableFor[peer.peer.id] = peer } diff --git a/submodules/TelegramCore/Sources/ProcessSecretChatIncomingDecryptedOperations.swift b/submodules/TelegramCore/Sources/ProcessSecretChatIncomingDecryptedOperations.swift index ee7c56aaf5..7c1230bbbc 100644 --- a/submodules/TelegramCore/Sources/ProcessSecretChatIncomingDecryptedOperations.swift +++ b/submodules/TelegramCore/Sources/ProcessSecretChatIncomingDecryptedOperations.swift @@ -796,7 +796,7 @@ private func parseMessage(peerId: PeerId, authorId: PeerId, tagLocalIndex: Int32 case let .decryptedMessageMediaGeoPoint(lat, long): parsedMedia.append(TelegramMediaMap(latitude: lat, longitude: long, heading: nil, accuracyRadius: nil, geoPlace: nil, venue: nil, liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil)) case let .decryptedMessageMediaContact(phoneNumber, firstName, lastName, userId): - parsedMedia.append(TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), vCardData: nil)) + parsedMedia.append(TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), vCardData: nil)) case let .decryptedMessageMediaVenue(lat, long, title, address, provider, venueId): parsedMedia.append(TelegramMediaMap(latitude: lat, longitude: long, heading: nil, accuracyRadius: nil, geoPlace: nil, venue: MapVenue(title: title, address: address, provider: provider, id: venueId, type: nil), liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil)) case .decryptedMessageMediaEmpty: @@ -1015,7 +1015,7 @@ private func parseMessage(peerId: PeerId, authorId: PeerId, tagLocalIndex: Int32 case let .decryptedMessageMediaGeoPoint(lat, long): parsedMedia.append(TelegramMediaMap(latitude: lat, longitude: long, heading: nil, accuracyRadius: nil, geoPlace: nil, venue: nil, liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil)) case let .decryptedMessageMediaContact(phoneNumber, firstName, lastName, userId): - parsedMedia.append(TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), vCardData: nil)) + parsedMedia.append(TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), vCardData: nil)) case let .decryptedMessageMediaVenue(lat, long, title, address, provider, venueId): parsedMedia.append(TelegramMediaMap(latitude: lat, longitude: long, heading: nil, accuracyRadius: nil, geoPlace: nil, venue: MapVenue(title: title, address: address, provider: provider, id: venueId, type: nil), liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil)) case .decryptedMessageMediaEmpty: @@ -1253,7 +1253,7 @@ private func parseMessage(peerId: PeerId, authorId: PeerId, tagLocalIndex: Int32 case let .decryptedMessageMediaGeoPoint(lat, long): parsedMedia.append(TelegramMediaMap(latitude: lat, longitude: long, heading: nil, accuracyRadius: nil, geoPlace: nil, venue: nil, liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil)) case let .decryptedMessageMediaContact(phoneNumber, firstName, lastName, userId): - parsedMedia.append(TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), vCardData: nil)) + parsedMedia.append(TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), vCardData: nil)) case let .decryptedMessageMediaVenue(lat, long, title, address, provider, venueId): parsedMedia.append(TelegramMediaMap(latitude: lat, longitude: long, heading: nil, accuracyRadius: nil, geoPlace: nil, venue: MapVenue(title: title, address: address, provider: provider, id: venueId, type: nil), liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil)) case .decryptedMessageMediaEmpty: diff --git a/submodules/TelegramCore/Sources/RecentWebSessions.swift b/submodules/TelegramCore/Sources/RecentWebSessions.swift index 5c8d25baa9..e881ca75d1 100644 --- a/submodules/TelegramCore/Sources/RecentWebSessions.swift +++ b/submodules/TelegramCore/Sources/RecentWebSessions.swift @@ -32,7 +32,7 @@ public func webSessions(network: Network) -> Signal<([WebAuthorization], [PeerId for authorization in authorizations { switch authorization { case let .webAuthorization(hash, botId, domain, browser, platform, dateCreated, dateActive, ip, region): - sessions.append(WebAuthorization(hash: hash, botId: PeerId(namespace: Namespaces.Peer.CloudUser, id: botId), domain: domain, browser: browser, platform: platform, dateCreated: dateCreated, dateActive: dateActive, ip: ip, region: region)) + sessions.append(WebAuthorization(hash: hash, botId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(botId)), domain: domain, browser: browser, platform: platform, dateCreated: dateCreated, dateActive: dateActive, ip: ip, region: region)) } } diff --git a/submodules/TelegramCore/Sources/RegisterNotificationToken.swift b/submodules/TelegramCore/Sources/RegisterNotificationToken.swift index d57cb98c9b..5d6ee65829 100644 --- a/submodules/TelegramCore/Sources/RegisterNotificationToken.swift +++ b/submodules/TelegramCore/Sources/RegisterNotificationToken.swift @@ -10,7 +10,7 @@ public enum NotificationTokenType { case voip } -public func unregisterNotificationToken(account: Account, token: Data, type: NotificationTokenType, otherAccountUserIds: [Int32]) -> Signal { +public func unregisterNotificationToken(account: Account, token: Data, type: NotificationTokenType, otherAccountUserIds: [PeerId.Id]) -> Signal { let mappedType: Int32 switch type { case .aps: @@ -18,12 +18,12 @@ public func unregisterNotificationToken(account: Account, token: Data, type: Not case .voip: mappedType = 9 } - return account.network.request(Api.functions.account.unregisterDevice(tokenType: mappedType, token: hexString(token), otherUids: otherAccountUserIds)) + return account.network.request(Api.functions.account.unregisterDevice(tokenType: mappedType, token: hexString(token), otherUids: otherAccountUserIds.map({ $0._internalGetInt32Value() }))) |> retryRequest |> ignoreValues } -public func registerNotificationToken(account: Account, token: Data, type: NotificationTokenType, sandbox: Bool, otherAccountUserIds: [Int32], excludeMutedChats: Bool) -> Signal { +public func registerNotificationToken(account: Account, token: Data, type: NotificationTokenType, sandbox: Bool, otherAccountUserIds: [PeerId.Id], excludeMutedChats: Bool) -> Signal { return masterNotificationsKey(account: account, ignoreDisabled: false) |> mapToSignal { masterKey -> Signal in let mappedType: Int32 @@ -42,7 +42,7 @@ public func registerNotificationToken(account: Account, token: Data, type: Notif if excludeMutedChats { flags |= 1 << 0 } - return account.network.request(Api.functions.account.registerDevice(flags: flags, tokenType: mappedType, token: hexString(token), appSandbox: sandbox ? .boolTrue : .boolFalse, secret: Buffer(data: keyData), otherUids: otherAccountUserIds)) + return account.network.request(Api.functions.account.registerDevice(flags: flags, tokenType: mappedType, token: hexString(token), appSandbox: sandbox ? .boolTrue : .boolFalse, secret: Buffer(data: keyData), otherUids: otherAccountUserIds.map({ $0._internalGetInt32Value() }))) |> retryRequest |> ignoreValues } diff --git a/submodules/TelegramCore/Sources/RemovePeerMember.swift b/submodules/TelegramCore/Sources/RemovePeerMember.swift index f07ba2ccaf..1e052b1659 100644 --- a/submodules/TelegramCore/Sources/RemovePeerMember.swift +++ b/submodules/TelegramCore/Sources/RemovePeerMember.swift @@ -17,7 +17,7 @@ public func removePeerMember(account: Account, peerId: PeerId, memberId: PeerId) 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(flags: 0, chatId: group.id.id, userId: inputUser)) + return account.network.request(Api.functions.messages.deleteChatUser(flags: 0, chatId: group.id.id._internalGetInt32Value(), userId: inputUser)) |> mapError { error -> Void in return Void() } diff --git a/submodules/TelegramCore/Sources/ReportPeer.swift b/submodules/TelegramCore/Sources/ReportPeer.swift index 2438920e0d..34cb965184 100644 --- a/submodules/TelegramCore/Sources/ReportPeer.swift +++ b/submodules/TelegramCore/Sources/ReportPeer.swift @@ -10,7 +10,7 @@ public func reportPeer(account: Account, peerId: PeerId) -> Signal 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))) + return account.network.request(Api.functions.messages.reportEncryptedSpam(peer: Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id._internalGetInt32Value(), accessHash: peer.accessHash))) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) diff --git a/submodules/TelegramCore/Sources/RequestSecureIdForm.swift b/submodules/TelegramCore/Sources/RequestSecureIdForm.swift index 6a79f35ff1..e7d82f7a20 100644 --- a/submodules/TelegramCore/Sources/RequestSecureIdForm.swift +++ b/submodules/TelegramCore/Sources/RequestSecureIdForm.swift @@ -251,7 +251,7 @@ public func requestSecureIdForm(postbox: Postbox, network: Network, peerId: Peer if publicKey.isEmpty { return .fail(.serverError("PUBLIC_KEY_REQUIRED")) } - return network.request(Api.functions.account.getAuthorizationForm(botId: peerId.id, scope: scope, publicKey: publicKey)) + return network.request(Api.functions.account.getAuthorizationForm(botId: peerId.id._internalGetInt32Value(), scope: scope, publicKey: publicKey)) |> mapError { error -> RequestSecureIdFormError in switch error.errorDescription { case "APP_VERSION_OUTDATED": diff --git a/submodules/TelegramCore/Sources/SearchPeers.swift b/submodules/TelegramCore/Sources/SearchPeers.swift index ab6b93a3e7..5276cffa85 100644 --- a/submodules/TelegramCore/Sources/SearchPeers.swift +++ b/submodules/TelegramCore/Sources/SearchPeers.swift @@ -61,15 +61,7 @@ public func searchPeers(account: Account, query: String) -> Signal<([FoundPeer], var renderedMyPeers: [FoundPeer] = [] for result in myResults { - let peerId: PeerId - switch result { - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - } + let peerId: PeerId = result.peerId if let peer = peers[peerId] { if let group = peer as? TelegramGroup, group.migrationReference != nil { continue @@ -80,15 +72,7 @@ public func searchPeers(account: Account, query: String) -> Signal<([FoundPeer], var renderedPeers: [FoundPeer] = [] for result in results { - let peerId: PeerId - switch result { - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - } + let peerId: PeerId = result.peerId if let peer = peers[peerId] { if let group = peer as? TelegramGroup, group.migrationReference != nil { continue diff --git a/submodules/TelegramCore/Sources/SecretChats/SecretChatIncomingEncryptedOperation.swift b/submodules/TelegramCore/Sources/SecretChats/SecretChatIncomingEncryptedOperation.swift index ac842093b8..6977f48dad 100644 --- a/submodules/TelegramCore/Sources/SecretChats/SecretChatIncomingEncryptedOperation.swift +++ b/submodules/TelegramCore/Sources/SecretChats/SecretChatIncomingEncryptedOperation.swift @@ -17,9 +17,9 @@ extension SecretChatIncomingEncryptedOperation { convenience init(message: Api.EncryptedMessage) { switch message { case let .encryptedMessage(randomId, chatId, date, bytes, file): - self.init(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: chatId), globallyUniqueId: randomId, timestamp: date, type: .message, keyFingerprint: keyFingerprintFromBytes(bytes), contents: MemoryBuffer(bytes), mediaFileReference: SecretChatFileReference(file)) + self.init(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(chatId)), globallyUniqueId: randomId, timestamp: date, type: .message, keyFingerprint: keyFingerprintFromBytes(bytes), contents: MemoryBuffer(bytes), mediaFileReference: SecretChatFileReference(file)) case let .encryptedMessageService(randomId, chatId, date, bytes): - self.init(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: chatId), globallyUniqueId: randomId, timestamp: date, type: .service, keyFingerprint: keyFingerprintFromBytes(bytes), contents: MemoryBuffer(bytes), mediaFileReference: nil) + self.init(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(chatId)), globallyUniqueId: randomId, timestamp: date, type: .service, keyFingerprint: keyFingerprintFromBytes(bytes), contents: MemoryBuffer(bytes), mediaFileReference: nil) } } } diff --git a/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift b/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift index 1ddf64698a..7157b2735a 100644 --- a/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift +++ b/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift @@ -19,7 +19,7 @@ func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: Pee assert((currentPeer == nil) == (currentState == nil)) switch chat { case let .encryptedChat(_, _, _, adminId, _, gAOrB, remoteKeyFingerprint): - if let currentPeer = currentPeer, let currentState = currentState, adminId == accountPeerId.id { + if let currentPeer = currentPeer, let currentState = currentState, adminId == accountPeerId.id._internalGetInt32Value() { if case let .handshake(handshakeState) = currentState.embeddedState, case let .requested(_, p, a) = handshakeState { let pData = p.makeData() let aData = a.makeData() @@ -88,7 +88,7 @@ func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: Pee case .encryptedChatEmpty(_): break case let .encryptedChatRequested(_, folderId, _, accessHash, date, adminId, participantId, gA): - if currentPeer == nil && participantId == accountPeerId.id { + if currentPeer == nil && participantId == accountPeerId.id._internalGetInt32Value() { if settings.acceptOnThisDevice { let state = SecretChatState(role: .participant, embeddedState: .handshake(.accepting), keychain: SecretChatKeychain(keys: []), keyFingerprint: nil, messageAutoremoveTimeout: nil) @@ -99,7 +99,7 @@ func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: Pee 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) + let peer = TelegramSecretChat(id: chat.peerId, creationDate: date, regularPeerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(adminId)), accessHash: accessHash, role: updatedState.role, embeddedState: updatedState.embeddedState.peerState, messageAutoremoveTimeout: nil) updatePeers(transaction: transaction, peers: [peer], update: { _, updated in return updated }) if folderId != nil { transaction.updatePeerChatListInclusion(peer.id, inclusion: .ifHasMessagesOrOneOf(groupId: Namespaces.PeerGroup.archive, pinningIndex: nil, minTimestamp: date)) @@ -122,9 +122,9 @@ func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: Pee Logger.shared.log("State", "got encryptedChatRequested, but peer already exists or this account is creator") } case let .encryptedChatWaiting(_, accessHash, date, adminId, participantId): - if let requestData = requestData, currentPeer == nil && adminId == accountPeerId.id { + if let requestData = requestData, currentPeer == nil && adminId == accountPeerId.id._internalGetInt32Value() { 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) + let peer = TelegramSecretChat(id: chat.peerId, creationDate: date, regularPeerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(participantId)), accessHash: accessHash, role: state.role, embeddedState: state.embeddedState.peerState, messageAutoremoveTimeout: nil) updatePeers(transaction: transaction, peers: [peer], update: { _, updated in return updated }) transaction.setPeerChatState(peer.id, state: state) transaction.resetIncomingReadStates([peer.id: [ diff --git a/submodules/TelegramCore/Sources/StandaloneUploadedMedia.swift b/submodules/TelegramCore/Sources/StandaloneUploadedMedia.swift index a704f06335..9ff622d556 100644 --- a/submodules/TelegramCore/Sources/StandaloneUploadedMedia.swift +++ b/submodules/TelegramCore/Sources/StandaloneUploadedMedia.swift @@ -87,7 +87,7 @@ public func standaloneUploadedImage(account: Account, peerId: PeerId, text: Stri case let .inputSecretFile(file, _, key): return account.postbox.transaction { transaction -> Api.InputEncryptedChat? in if let peer = transaction.getPeer(peerId) as? TelegramSecretChat { - return Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id, accessHash: peer.accessHash) + return Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id._internalGetInt32Value(), accessHash: peer.accessHash) } return nil } @@ -181,7 +181,7 @@ public func standaloneUploadedFile(account: Account, peerId: PeerId, text: Strin case let .inputSecretFile(file, _, key): return account.postbox.transaction { transaction -> Api.InputEncryptedChat? in if let peer = transaction.getPeer(peerId) as? TelegramSecretChat { - return Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id, accessHash: peer.accessHash) + return Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id._internalGetInt32Value(), accessHash: peer.accessHash) } return nil } diff --git a/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift b/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift index 2232c30a19..b7cf8a95d8 100644 --- a/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift +++ b/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift @@ -23,7 +23,7 @@ private func peerIdsFromUpdateGroups(_ groups: [UpdateGroup]) -> Set { } switch group { case let .updateChannelPts(channelId, _, _): - peerIds.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)) + peerIds.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))) default: break } @@ -77,7 +77,7 @@ private func peerIdsRequiringLocalChatStateFromUpdates(_ updates: [Api.Update]) } switch update { case let .updateChannelTooLong(_, channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) peerIds.insert(peerId) case let .updateFolderPeers(folderPeers, _, _): for peer in folderPeers { @@ -87,7 +87,7 @@ private func peerIdsRequiringLocalChatStateFromUpdates(_ updates: [Api.Update]) } } case let .updateReadChannelInbox(_, _, channelId, _, _, _): - peerIds.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)) + peerIds.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))) case let .updateReadHistoryInbox(_, _, peer, _, _, _, _): peerIds.insert(peer.peerId) case let .updateDraftMessage(peer, draft): @@ -114,7 +114,7 @@ private func peerIdsRequiringLocalChatStateFromUpdateGroups(_ groups: [UpdateGro for update in group.updates { switch update { case let .updateChannel(channelId): - channelUpdates.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)) + channelUpdates.insert(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))) default: break } @@ -147,7 +147,7 @@ private func locallyGeneratedMessageTimestampsFromUpdateGroups(_ groups: [Update switch update { case let .updateServiceNotification(_, date, _, _, _, _): if let date = date { - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 777000) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(777000)) if messageTimestamps[peerId] == nil { messageTimestamps[peerId] = [(Namespaces.Message.Local, date)] } else { @@ -303,7 +303,7 @@ private func peerIdsRequiringLocalChatStateFromDifference(_ difference: Api.upda } switch update { case let .updateChannelTooLong(_, channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) peerIds.insert(peerId) default: break @@ -325,7 +325,7 @@ private func peerIdsRequiringLocalChatStateFromDifference(_ difference: Api.upda } switch update { case let .updateChannelTooLong(_, channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) peerIds.insert(peerId) default: break @@ -358,7 +358,7 @@ private func locallyGeneratedMessageTimestampsFromDifference(_ difference: Api.u switch update { case let .updateServiceNotification(_, date, _, _, _, _): if let date = date { - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 777000) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(777000)) if messageTimestamps[peerId] == nil { messageTimestamps[peerId] = [(Namespaces.Message.Local, date)] } else { @@ -684,21 +684,21 @@ private func sortedUpdates(_ updates: [Api.Update]) -> [Api.Update] { for update in updates { switch update { case let .updateChannelTooLong(_, channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { updatesByChannel[peerId]!.append(update) } case let .updateDeleteChannelMessages(channelId, _, _, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { updatesByChannel[peerId]!.append(update) } case let .updatePinnedChannelMessages(_, channelId, _, _, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { @@ -725,14 +725,14 @@ private func sortedUpdates(_ updates: [Api.Update]) -> [Api.Update] { otherUpdates.append(update) } case let .updateChannelWebPage(channelId, _, _, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { updatesByChannel[peerId]!.append(update) } case let .updateChannelAvailableMessages(channelId, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) if updatesByChannel[peerId] == nil { updatesByChannel[peerId] = [update] } else { @@ -817,7 +817,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo for update in sortedUpdates(updates) { switch update { case let .updateChannelTooLong(_, channelId, channelPts): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) if !channelsToPoll.contains(peerId) { if let channelPts = channelPts, let channelState = state.channelStates[peerId], channelState.pts >= channelPts { Logger.shared.log("State", "channel \(peerId) (\((updatedState.peers[peerId] as? TelegramChannel)?.title ?? "nil")) skip updateChannelTooLong by pts") @@ -826,7 +826,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo } } case let .updateDeleteChannelMessages(channelId, messages, pts: pts, ptsCount): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) if let previousState = updatedState.channelStates[peerId] { if previousState.pts >= pts { Logger.shared.log("State", "channel \(peerId) (\((updatedState.peers[peerId] as? TelegramChannel)?.title ?? "nil")) skip old delete update") @@ -877,7 +877,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo Logger.shared.log("State", "Invalid updateEditChannelMessage") } case let .updateChannelWebPage(channelId, apiWebpage, pts, ptsCount): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) if let previousState = updatedState.channelStates[peerId] { if previousState.pts >= pts { } else if previousState.pts + ptsCount == pts { @@ -903,7 +903,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo } } case let .updateChannelAvailableMessages(channelId, minId): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) updatedState.updateMinAvailableMessage(MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: minId)) case let .updateDeleteMessages(messages, _, _): updatedState.deleteMessagesWithGlobalIds(messages) @@ -980,7 +980,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo if popup { updatedState.addDisplayAlert(text, isDropAuth: type.hasPrefix("AUTH_KEY_DROP_")) } else if let date = date { - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 777000) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(777000)) if updatedState.peers[peerId] == nil { updatedState.updatePeer(peerId, { peer in @@ -1029,13 +1029,13 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo } } case let .updateReadChannelInbox(_, folderId, channelId, maxId, stillUnreadCount, pts): - updatedState.resetIncomingReadState(groupId: PeerGroupId(rawValue: folderId ?? 0), peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), namespace: Namespaces.Message.Cloud, maxIncomingReadId: maxId, count: stillUnreadCount, pts: pts) + updatedState.resetIncomingReadState(groupId: PeerGroupId(rawValue: folderId ?? 0), peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)), namespace: Namespaces.Message.Cloud, maxIncomingReadId: maxId, count: stillUnreadCount, pts: pts) case let .updateReadChannelOutbox(channelId, maxId): - updatedState.readOutbox(MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), namespace: Namespaces.Message.Cloud, id: maxId), timestamp: nil) + updatedState.readOutbox(MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)), namespace: Namespaces.Message.Cloud, id: maxId), timestamp: nil) case let .updateChannel(channelId): - updatedState.addExternallyUpdatedPeerId(PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)) + updatedState.addExternallyUpdatedPeerId(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))) case let .updateChat(chatId): - updatedState.addExternallyUpdatedPeerId(PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId)) + updatedState.addExternallyUpdatedPeerId(PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId))) case let .updateReadHistoryInbox(_, folderId, peer, maxId, stillUnreadCount, pts, _): updatedState.resetIncomingReadState(groupId: PeerGroupId(rawValue: folderId ?? 0), peerId: peer.peerId, namespace: Namespaces.Message.Cloud, maxIncomingReadId: maxId, count: stillUnreadCount, pts: pts) case let .updateReadHistoryOutbox(peer, maxId, _, _): @@ -1043,11 +1043,11 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo case let .updateReadChannelDiscussionInbox(_, channelId, topMsgId, readMaxId, mainChannelId, mainChannelPost): var mainChannelMessage: MessageId? if let mainChannelId = mainChannelId, let mainChannelPost = mainChannelPost { - mainChannelMessage = MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: mainChannelId), namespace: Namespaces.Message.Cloud, id: mainChannelPost) + mainChannelMessage = MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(mainChannelId)), namespace: Namespaces.Message.Cloud, id: mainChannelPost) } - updatedState.readThread(threadMessageId: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), namespace: Namespaces.Message.Cloud, id: topMsgId), readMaxId: readMaxId, isIncoming: true, mainChannelMessage: mainChannelMessage) + updatedState.readThread(threadMessageId: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)), namespace: Namespaces.Message.Cloud, id: topMsgId), readMaxId: readMaxId, isIncoming: true, mainChannelMessage: mainChannelMessage) case let .updateReadChannelDiscussionOutbox(channelId, topMsgId, readMaxId): - updatedState.readThread(threadMessageId: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), namespace: Namespaces.Message.Cloud, id: topMsgId), readMaxId: readMaxId, isIncoming: false, mainChannelMessage: nil) + updatedState.readThread(threadMessageId: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)), namespace: Namespaces.Message.Cloud, id: topMsgId), readMaxId: readMaxId, isIncoming: false, mainChannelMessage: nil) case let .updateDialogUnreadMark(flags, peer): switch peer { case let .dialogPeer(peer): @@ -1081,9 +1081,9 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo let groupPeerId: PeerId switch participants { case let .chatParticipants(chatId, _, _): - groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) case let .chatParticipantsForbidden(_, chatId, _): - groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) } updatedState.updateCachedPeerData(groupPeerId, { current in let previous: CachedGroupData @@ -1095,9 +1095,9 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo return previous.withUpdatedParticipants(CachedGroupParticipants(apiParticipants: participants)) }) case let .updateChatParticipantAdd(chatId, userId, inviterId, date, _): - let groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - let userPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - let inviterPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: inviterId) + let groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) + let userPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) + let inviterPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(inviterId)) updatedState.updateCachedPeerData(groupPeerId, { current in if let current = current as? CachedGroupData, let participants = current.participants { var updatedParticipants = participants.participants @@ -1110,8 +1110,8 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo } }) case let .updateChatParticipantDelete(chatId, userId, _): - let groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - let userPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + let groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) + let userPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) updatedState.updateCachedPeerData(groupPeerId, { current in if let current = current as? CachedGroupData, let participants = current.participants { var updatedParticipants = participants.participants @@ -1124,8 +1124,8 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo } }) case let .updateChatParticipantAdmin(chatId, userId, isAdmin, _): - let groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - let userPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + let groupPeerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) + let userPeerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) updatedState.updateCachedPeerData(groupPeerId, { current in if let current = current as? CachedGroupData, let participants = current.participants { var updatedParticipants = participants.participants @@ -1156,12 +1156,12 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo } }) case let .updatePinnedChannelMessages(flags, channelId, messages, pts, ptsCount): - let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) if let previousState = updatedState.channelStates[peerId] { if previousState.pts >= pts { Logger.shared.log("State", "channel \(peerId) (\((updatedState.peers[peerId] as? TelegramChannel)?.title ?? "nil")) skip old pinned messages update") } else if previousState.pts + ptsCount == pts { - let channelPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let channelPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) updatedState.updateMessagesPinned(ids: messages.map { id in MessageId(peerId: channelPeerId, namespace: Namespaces.Message.Cloud, id: id) }, pinned: (flags & (1 << 0)) != 0) @@ -1190,10 +1190,10 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo return previous.withUpdatedIsBlocked(blocked == .boolTrue) }) case let .updateUserStatus(userId, status): - updatedState.mergePeerPresences([PeerId(namespace: Namespaces.Peer.CloudUser, id: userId): status], explicit: true) + updatedState.mergePeerPresences([PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)): status], explicit: true) case let .updateUserName(userId, firstName, lastName, username): //TODO add contact checking for apply first and last name - updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), { peer in + updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), { peer in if let user = peer as? TelegramUser { return user.withUpdatedUsername(username) } else { @@ -1201,7 +1201,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo } }) case let .updateUserPhoto(userId, _, photo, _): - updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), { peer in + updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), { peer in if let user = peer as? TelegramUser { return user.withUpdatedPhoto(parsedTelegramProfilePhoto(photo)) } else { @@ -1209,7 +1209,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo } }) case let .updateUserPhone(userId, phone): - updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), { peer in + updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), { peer in if let user = peer as? TelegramUser { return user.withUpdatedPhone(phone.isEmpty ? nil : phone) } else { @@ -1252,7 +1252,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo case let .updateNewEncryptedMessage(message, _): updatedState.addSecretMessages([message]) case let .updateEncryptedMessagesRead(chatId, maxDate, date): - updatedState.readSecretOutbox(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: chatId), timestamp: maxDate, actionTimestamp: date) + updatedState.readSecretOutbox(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(chatId)), timestamp: maxDate, actionTimestamp: date) case let .updateUserTyping(userId, type): if let date = updatesDate, date + 60 > serverTime { let activity = PeerInputActivity(apiType: type, timestamp: date) @@ -1261,7 +1261,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo category = .voiceChat } - updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), category: category), peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), activity: activity) + updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), category: category), peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), activity: activity) } case let .updateChatUserTyping(chatId, userId, type): if let date = updatesDate, date + 60 > serverTime { @@ -1271,11 +1271,11 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo category = .voiceChat } - updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId), category: category), peerId: userId.peerId, activity: activity) + updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)), category: category), peerId: userId.peerId, activity: activity) } case let .updateChannelUserTyping(_, channelId, topMsgId, userId, type): if let date = updatesDate, date + 60 > serverTime { - let channelPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let channelPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) let threadId = topMsgId.flatMap { makeMessageThreadId(MessageId(peerId: channelPeerId, namespace: Namespaces.Message.Cloud, id: $0)) } let activity = PeerInputActivity(apiType: type, timestamp: date) @@ -1290,7 +1290,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo } case let .updateEncryptedChatTyping(chatId): if let date = updatesDate, date + 60 > serverTime { - updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: chatId), category: .global), peerId: nil, activity: .typingText) + updatedState.addPeerInputActivity(chatPeerId: PeerActivitySpace(peerId: PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(chatId)), category: .global), peerId: nil, activity: .typingText) } case let .updateDialogPinned(flags, folderId, peer): let groupId: PeerGroupId = folderId.flatMap(PeerGroupId.init(rawValue:)) ?? .root @@ -1325,9 +1325,9 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo case let .updateReadMessagesContents(messages, _, _): updatedState.addReadMessagesContents((nil, messages)) case let .updateChannelReadMessagesContents(channelId, messages): - updatedState.addReadMessagesContents((PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), messages)) + updatedState.addReadMessagesContents((PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)), messages)) case let .updateChannelMessageViews(channelId, id, views): - updatedState.addUpdateMessageImpressionCount(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), namespace: Namespaces.Message.Cloud, id: id), count: views) + updatedState.addUpdateMessageImpressionCount(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)), namespace: Namespaces.Message.Cloud, id: id), count: views) /*case let .updateChannelMessageForwards(channelId, id, forwards): updatedState.addUpdateMessageForwardsCount(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), namespace: Namespaces.Message.Cloud, id: id), count: forwards)*/ case let .updateNewStickerSet(stickerset): @@ -1367,8 +1367,8 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo updatedState.updateGroupCallParticipants(id: id, accessHash: accessHash, participants: participants, version: version) } case let .updateGroupCall(channelId, call): - updatedState.updateGroupCall(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), call: call) - updatedState.updateGroupCall(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: channelId), call: call) + updatedState.updateGroupCall(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)), call: call) + updatedState.updateGroupCall(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(channelId)), call: call) case let .updatePeerHistoryTTL(_, peer, ttl): updatedState.updateAutoremoveTimeout(peer: peer, value: CachedPeerAutoremoveTimeout.Value(ttl)) case let .updateLangPackTooLong(langCode): @@ -1791,15 +1791,7 @@ private func resetChannels(network: Network, peers: [Peer], state: AccountMutabl continue loop } - let peerId: PeerId - switch apiPeer { - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - } + let peerId: PeerId = apiPeer.peerId if readStates[peerId] == nil { readStates[peerId] = [:] @@ -1967,7 +1959,7 @@ private func pollChannel(network: Network, peer: Peer, state: AccountMutableStat Logger.shared.log("State", "Invalid updateEditChannelMessage") } case let .updatePinnedChannelMessages(flags, channelId, messages, _, _): - let channelPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + let channelPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) updatedState.updateMessagesPinned(ids: messages.map { id in MessageId(peerId: channelPeerId, namespace: Namespaces.Message.Cloud, id: id) }, pinned: (flags & (1 << 0)) != 0) diff --git a/submodules/TelegramCore/Sources/State/ChannelState.swift b/submodules/TelegramCore/Sources/State/ChannelState.swift index 504cd68f65..effa4e6c62 100644 --- a/submodules/TelegramCore/Sources/State/ChannelState.swift +++ b/submodules/TelegramCore/Sources/State/ChannelState.swift @@ -18,11 +18,11 @@ func channelUpdatesByPeerId(updates: [ChannelUpdate]) -> [PeerId: [ChannelUpdate case let .updateNewChannelMessage(message, _, _): peerId = apiMessagePeerId(message) case let .updateDeleteChannelMessages(channelId, _, _, _): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) case let .updateEditChannelMessage(message, _, _): peerId = apiMessagePeerId(message) case let .updateChannelWebPage(channelId, _, _, _): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) default: break } diff --git a/submodules/TelegramCore/Sources/State/ManagedCloudChatRemoveMessagesOperations.swift b/submodules/TelegramCore/Sources/State/ManagedCloudChatRemoveMessagesOperations.swift index 6e769af8a3..ab4e02c849 100644 --- a/submodules/TelegramCore/Sources/State/ManagedCloudChatRemoveMessagesOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedCloudChatRemoveMessagesOperations.swift @@ -177,7 +177,7 @@ private func removeMessages(postbox: Postbox, network: Network, stateManager: Ac if let result = result { switch result { case let .affectedMessages(pts, ptsCount): - stateManager.addUpdateGroups([.updateChannelPts(channelId: peer.id.id, pts: pts, ptsCount: ptsCount)]) + stateManager.addUpdateGroups([.updateChannelPts(channelId: peer.id.id._internalGetInt32Value(), pts: pts, ptsCount: ptsCount)]) } } return .complete() @@ -267,7 +267,7 @@ private func removeChat(transaction: Transaction, postbox: Postbox, network: Net } else if peer.id.namespace == Namespaces.Peer.CloudGroup { let deleteUser: Signal if operation.deleteGloballyIfPossible { - deleteUser = network.request(Api.functions.messages.deleteChat(chatId: peer.id.id)) + deleteUser = network.request(Api.functions.messages.deleteChat(chatId: peer.id.id._internalGetInt32Value())) |> `catch` { _ in return .single(.boolFalse) } @@ -275,7 +275,7 @@ private func removeChat(transaction: Transaction, postbox: Postbox, network: Net return .complete() } } else { - deleteUser = network.request(Api.functions.messages.deleteChatUser(flags: 0, chatId: peer.id.id, userId: Api.InputUser.inputUserSelf)) + deleteUser = network.request(Api.functions.messages.deleteChatUser(flags: 0, chatId: peer.id.id._internalGetInt32Value(), userId: Api.InputUser.inputUserSelf)) |> map { result -> Api.Updates? in return result } diff --git a/submodules/TelegramCore/Sources/State/ManagedLocalInputActivities.swift b/submodules/TelegramCore/Sources/State/ManagedLocalInputActivities.swift index 95b5eea8cf..0dff9dc0bc 100644 --- a/submodules/TelegramCore/Sources/State/ManagedLocalInputActivities.swift +++ b/submodules/TelegramCore/Sources/State/ManagedLocalInputActivities.swift @@ -177,7 +177,7 @@ private func requestActivity(postbox: Postbox, network: Network, accountPeerId: return .complete() } } else if let peer = peer as? TelegramSecretChat, activity == .typingText { - return network.request(Api.functions.messages.setEncryptedTyping(peer: .inputEncryptedChat(chatId: peer.id.id, accessHash: peer.accessHash), typing: .boolTrue)) + return network.request(Api.functions.messages.setEncryptedTyping(peer: .inputEncryptedChat(chatId: peer.id.id._internalGetInt32Value(), accessHash: peer.accessHash), typing: .boolTrue)) |> `catch` { _ -> Signal in return .single(.boolFalse) } diff --git a/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift index e8cedadb60..43907d36b0 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift @@ -227,7 +227,7 @@ private func initialHandshakeAccept(postbox: Postbox, network: Network, peerId: memcpy(&keyFingerprint, bytes.advanced(by: keyHash.count - 8), 8) } - let result = network.request(Api.functions.messages.acceptEncryption(peer: .inputEncryptedChat(chatId: peerId.id, accessHash: accessHash), gB: Buffer(data: gb), keyFingerprint: keyFingerprint)) + let result = network.request(Api.functions.messages.acceptEncryption(peer: .inputEncryptedChat(chatId: peerId.id._internalGetInt32Value(), accessHash: accessHash), gB: Buffer(data: gb), keyFingerprint: keyFingerprint)) let response = result |> map { result -> Api.EncryptedChat? in @@ -1636,7 +1636,7 @@ private func sendBoxedDecryptedMessage(postbox: Postbox, network: Network, peer: decryptedMessage.serialize(payload, role: state.role, sequenceInfo: sequenceInfo) let encryptedPayload = encryptedMessageContents(parameters: parameters, data: MemoryBuffer(payload)) let sendMessage: Signal - let inputPeer = Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id, accessHash: peer.accessHash) + let inputPeer = Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id._internalGetInt32Value(), accessHash: peer.accessHash) var flags: Int32 = 0 if silent { @@ -1676,7 +1676,7 @@ private func requestTerminateSecretChat(postbox: Postbox, network: Network, peer if requestRemoteHistoryRemoval { flags |= 1 << 0 } - return network.request(Api.functions.messages.discardEncryption(flags: flags, chatId: peerId.id)) + return network.request(Api.functions.messages.discardEncryption(flags: flags, chatId: peerId.id._internalGetInt32Value())) |> map(Optional.init) |> `catch` { _ in return .single(nil) @@ -1692,7 +1692,7 @@ private func requestTerminateSecretChat(postbox: Postbox, network: Network, peer } |> mapToSignal { peer -> Signal in if let peer = peer { - return network.request(Api.functions.messages.reportEncryptedSpam(peer: Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id, accessHash: peer.accessHash))) + return network.request(Api.functions.messages.reportEncryptedSpam(peer: Api.InputEncryptedChat.inputEncryptedChat(chatId: peer.id.id._internalGetInt32Value(), accessHash: peer.accessHash))) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift index b5ff3b474e..90280571f0 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift @@ -83,7 +83,7 @@ func managedSynchronizePinnedChatsOperations(postbox: Postbox, network: Network, 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(transaction: transaction, postbox: postbox, network: network, accountPeerId: accountPeerId, stateManager: stateManager, groupId: PeerGroupId(rawValue: entry.peerId.id), operation: operation) + return synchronizePinnedChats(transaction: transaction, postbox: postbox, network: network, accountPeerId: accountPeerId, stateManager: stateManager, groupId: PeerGroupId(rawValue: entry.peerId.id._internalGetInt32Value()), operation: operation) } else { assertionFailure() } @@ -182,15 +182,7 @@ private func synchronizePinnedChats(transaction: Transaction, postbox: Postbox, continue loop } - let peerId: PeerId - switch apiPeer { - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - } + let peerId: PeerId = apiPeer.peerId remoteItemIds.append(.peer(peerId)) diff --git a/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift b/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift index b9f6ae6935..e52fe1912b 100644 --- a/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift +++ b/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift @@ -152,15 +152,15 @@ extension Api.Chat { var peerId: PeerId { switch self { case let .chat(chat): - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: chat.id) + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chat.id)) case let .chatEmpty(id): - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: id) + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(id)) case let .chatForbidden(id, _): - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: id) + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(id)) case let .channel(channel): - return PeerId(namespace: Namespaces.Peer.CloudChannel, id: channel.id) + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channel.id)) case let .channelForbidden(_, id, _, _, _): - return PeerId(namespace: Namespaces.Peer.CloudChannel, id: id) + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(id)) } } } @@ -169,9 +169,9 @@ extension Api.User { var peerId: PeerId { switch self { case .user(_, let id, _, _, _, _, _, _, _, _, _, _, _): - return PeerId(namespace: Namespaces.Peer.CloudUser, id: id) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id)) case let .userEmpty(id): - return PeerId(namespace: Namespaces.Peer.CloudUser, id: id) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id)) } } } @@ -180,11 +180,11 @@ extension Api.Peer { var peerId: PeerId { switch self { case let .peerChannel(channelId): - return PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) case let .peerChat(chatId): - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) case let .peerUser(userId): - return PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) } } } @@ -254,40 +254,40 @@ extension Api.Update { var peerIds: [PeerId] { switch self { case let .updateChannel(channelId): - return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)] + return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))] case let .updateChat(chatId): - return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId)] + return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId))] case let .updateChannelTooLong(_, channelId, _): - return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)] + return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))] case let .updateChatParticipantAdd(chatId, userId, inviterId, _, _): - return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId), PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), PeerId(namespace: Namespaces.Peer.CloudUser, id: inviterId)] + return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)), PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(inviterId))] case let .updateChatParticipantAdmin(chatId, userId, _, _): - return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId), PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)] + return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)), PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))] case let .updateChatParticipantDelete(chatId, userId, _): - return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId), PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)] + return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)), PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))] case let .updateChatParticipants(participants): switch participants { case let .chatParticipants(chatId, _, _): - return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId)] + return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId))] case let .chatParticipantsForbidden(_, chatId, _): - return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId)] + return [PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId))] } case let .updateDeleteChannelMessages(channelId, _, _, _): - return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)] + return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))] case let .updatePinnedChannelMessages(_, channelId, _, _, _): - return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)] + return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))] case let .updateNewChannelMessage(message, _, _): return apiMessagePeerIds(message) case let .updateEditChannelMessage(message, _, _): return apiMessagePeerIds(message) case let .updateChannelWebPage(channelId, _, _, _): - return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)] + return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))] case let .updateNewMessage(message, _, _): return apiMessagePeerIds(message) case let .updateEditMessage(message, _, _): return apiMessagePeerIds(message) case let .updateReadChannelInbox(_, _, channelId, _, _, _): - return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)] + return [PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))] case let .updateNotifySettings(peer, _): switch peer { case let .notifyPeer(peer): @@ -296,14 +296,14 @@ extension Api.Update { return [] } case let .updateUserName(userId, _, _, _): - return [PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)] + return [PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))] case let .updateUserPhone(userId, _): - return [PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)] + return [PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))] case let .updateUserPhoto(userId, _, _, _): - return [PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)] + return [PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))] case let .updateServiceNotification(_, inboxDate, _, _, _, _): if let _ = inboxDate { - return [PeerId(namespace: Namespaces.Peer.CloudUser, id: 777000)] + return [PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(777000))] } else { return [] } @@ -424,9 +424,9 @@ extension Api.Updates { case .updatesTooLong: return [] case let .updateShortMessage(_, id, userId, _, _, _, _, _, _, _, _, _): - return [MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), namespace: Namespaces.Message.Cloud, id: id)] + return [MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), namespace: Namespaces.Message.Cloud, id: id)] case let .updateShortChatMessage(_, id, _, chatId, _, _, _, _, _, _, _, _, _): - return [MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId), namespace: Namespaces.Message.Cloud, id: id)] + return [MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)), namespace: Namespaces.Message.Cloud, id: id)] } } @@ -555,15 +555,15 @@ extension Api.EncryptedChat { var peerId: PeerId { switch self { case let .encryptedChat(id, _, _, _, _, _, _): - return PeerId(namespace: Namespaces.Peer.SecretChat, id: id) + return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(id)) case let .encryptedChatDiscarded(_, id): - return PeerId(namespace: Namespaces.Peer.SecretChat, id: id) + return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(id)) case let .encryptedChatEmpty(id): - return PeerId(namespace: Namespaces.Peer.SecretChat, id: id) + return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(id)) case let .encryptedChatRequested(_, _, id, _, _, _, _, _): - return PeerId(namespace: Namespaces.Peer.SecretChat, id: id) + return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(id)) case let .encryptedChatWaiting(id, _, _, _, _): - return PeerId(namespace: Namespaces.Peer.SecretChat, id: id) + return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(id)) } } } @@ -572,9 +572,9 @@ extension Api.EncryptedMessage { var peerId: PeerId { switch self { case let .encryptedMessage(_, chatId, _, _, _): - return PeerId(namespace: Namespaces.Peer.SecretChat, id: chatId) + return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(chatId)) case let .encryptedMessageService(_, chatId, _, _): - return PeerId(namespace: Namespaces.Peer.SecretChat, id: chatId) + return PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(chatId)) } } } diff --git a/submodules/TelegramCore/Sources/StoreMessage_Telegram.swift b/submodules/TelegramCore/Sources/StoreMessage_Telegram.swift index bb7bea2dc2..b090bf615d 100644 --- a/submodules/TelegramCore/Sources/StoreMessage_Telegram.swift +++ b/submodules/TelegramCore/Sources/StoreMessage_Telegram.swift @@ -157,14 +157,14 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { } if let viaBotId = viaBotId { - result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: viaBotId)) + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(viaBotId))) } if let media = media { switch media { case let .messageMediaContact(_, _, _, _, userId): if userId != 0 { - result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)) + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))) } default: break @@ -175,7 +175,7 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { for entity in entities { switch entity { case let .messageEntityMentionName(_, _, userId): - result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)) + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))) default: break } @@ -199,27 +199,27 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { case .messageActionChannelCreate, .messageActionChatDeletePhoto, .messageActionChatEditPhoto, .messageActionChatEditTitle, .messageActionEmpty, .messageActionPinMessage, .messageActionHistoryClear, .messageActionGameScore, .messageActionPaymentSent, .messageActionPaymentSentMe, .messageActionPhoneCall, .messageActionScreenshotTaken, .messageActionCustomAction, .messageActionBotAllowed, .messageActionSecureValuesSent, .messageActionSecureValuesSentMe, .messageActionContactSignUp, .messageActionGroupCall, .messageActionSetMessagesTTL: break case let .messageActionChannelMigrateFrom(_, chatId): - result.append(PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId)) + result.append(PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId))) case let .messageActionChatAddUser(users): for id in users { - result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: id)) + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id))) } case let .messageActionChatCreate(_, users): for id in users { - result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: id)) + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id))) } case let .messageActionChatDeleteUser(userId): - result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)) + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))) case let .messageActionChatJoinedByLink(inviterId): - result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: inviterId)) + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(inviterId))) case let .messageActionChatMigrateTo(channelId): - result.append(PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)) + result.append(PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId))) case let .messageActionGeoProximityReached(fromId, toId, _): result.append(fromId.peerId) result.append(toId.peerId) case let .messageActionInviteToGroupCall(_, userIds): for id in userIds { - result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: id)) + result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(id))) } } @@ -263,7 +263,7 @@ func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerI return (TelegramMediaExpiredContent(data: .image), nil) } case let .messageMediaContact(phoneNumber, firstName, lastName, vcard, userId): - let contactPeerId: PeerId? = userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + let contactPeerId: PeerId? = userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) let mediaContact = TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: contactPeerId, vCardData: vcard.isEmpty ? nil : vcard) return (mediaContact, nil) case let .messageMediaGeo(geo): @@ -354,7 +354,7 @@ func messageTextEntitiesFromApiEntities(_ entities: [Api.MessageEntity]) -> [Mes case let .messageEntityTextUrl(offset, length, url): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .TextUrl(url: url))) case let .messageEntityMentionName(offset, length, userId): - result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .TextMention(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)))) + result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .TextMention(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId))))) case let .messageEntityPhone(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .PhoneNumber)) case let .messageEntityCashtag(offset, length): @@ -385,10 +385,10 @@ extension StoreMessage { peerId = chatPeerId.peerId authorId = resolvedFromId case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(chatId)) authorId = resolvedFromId case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)) authorId = resolvedFromId } @@ -444,15 +444,7 @@ extension StoreMessage { } if let savedFromPeer = savedFromPeer, let savedFromMsgId = savedFromMsgId { - let peerId: PeerId - switch savedFromPeer { - case let .peerChannel(channelId): - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) - case let .peerChat(chatId): - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) - case let .peerUser(userId): - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) - } + let peerId: PeerId = savedFromPeer.peerId let messageId: MessageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: savedFromMsgId) attributes.append(SourceReferenceMessageAttribute(messageId: messageId)) } @@ -510,7 +502,7 @@ extension StoreMessage { } if let viaBotId = viaBotId { - attributes.append(InlineBotMessageAttribute(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: viaBotId), title: nil)) + attributes.append(InlineBotMessageAttribute(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(viaBotId)), title: nil)) } if namespace != Namespaces.Message.ScheduledCloud { @@ -569,7 +561,7 @@ extension StoreMessage { recentRepliersPeerIds = nil } - let commentsPeerId = channelId.flatMap { PeerId(namespace: Namespaces.Peer.CloudChannel, id: $0) } + let commentsPeerId = channelId.flatMap { PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value($0)) } attributes.append(ReplyThreadMessageAttribute(count: repliesCount, latestUsers: recentRepliersPeerIds ?? [], commentsPeerId: commentsPeerId, maxMessageId: maxId, maxReadMessageId: readMaxId)) } diff --git a/submodules/TelegramCore/Sources/SynchronizeAppLogEventsOperation.swift b/submodules/TelegramCore/Sources/SynchronizeAppLogEventsOperation.swift index 541fb91a73..7ab8ac4b8f 100644 --- a/submodules/TelegramCore/Sources/SynchronizeAppLogEventsOperation.swift +++ b/submodules/TelegramCore/Sources/SynchronizeAppLogEventsOperation.swift @@ -7,7 +7,7 @@ import SyncCore public func addAppLogEvent(postbox: Postbox, time: Double = Date().timeIntervalSince1970, type: String, peerId: PeerId? = nil, data: JSON = .dictionary([:])) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeAppLogEvents - let peerId = PeerId(namespace: 0, id: 0) + let peerId = PeerId(0) let _ = (postbox.transaction { transaction in transaction.operationLogAddEntry(peerId: peerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeAppLogEventsOperation(content: .add(time: time, type: type, peerId: peerId, data: data))) }).start() @@ -15,7 +15,7 @@ public func addAppLogEvent(postbox: Postbox, time: Double = Date().timeIntervalS public func invokeAppLogEventsSynchronization(postbox: Postbox) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeAppLogEvents - let peerId = PeerId(namespace: 0, id: 0) + let peerId = PeerId(0) let _ = (postbox.transaction { transaction in var topOperation: (SynchronizeSavedStickersOperation, Int32)? diff --git a/submodules/TelegramCore/Sources/SynchronizeGroupedPeersOperation.swift b/submodules/TelegramCore/Sources/SynchronizeGroupedPeersOperation.swift index ccc308a736..ee66d432f9 100644 --- a/submodules/TelegramCore/Sources/SynchronizeGroupedPeersOperation.swift +++ b/submodules/TelegramCore/Sources/SynchronizeGroupedPeersOperation.swift @@ -36,7 +36,7 @@ public func updatePeerGroupIdInteractively(transaction: Transaction, peerId: Pee private func addSynchronizeGroupedPeersOperation(transaction: Transaction, peerId: PeerId, groupId: PeerGroupId) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeGroupedPeers - let logPeerId = PeerId(namespace: 0, id: 0) + let logPeerId = PeerId(0) transaction.operationLogAddEntry(peerId: logPeerId, tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: SynchronizeGroupedPeersOperation(peerId: peerId, groupId: groupId)) } diff --git a/submodules/TelegramCore/Sources/SynchronizeInstalledStickerPacksOperation.swift b/submodules/TelegramCore/Sources/SynchronizeInstalledStickerPacksOperation.swift index f550172e03..0cb242c17f 100644 --- a/submodules/TelegramCore/Sources/SynchronizeInstalledStickerPacksOperation.swift +++ b/submodules/TelegramCore/Sources/SynchronizeInstalledStickerPacksOperation.swift @@ -35,7 +35,7 @@ func addSynchronizeInstalledStickerPacksOperation(transaction: Transaction, name } var previousStickerPackIds: [ItemCollectionId]? var archivedPacks: [ItemCollectionId] = [] - transaction.operationLogEnumerateEntries(peerId: PeerId(namespace: 0, id: 0), tag: tag, { entry in + transaction.operationLogEnumerateEntries(peerId: PeerId(0), tag: tag, { entry in updateLocalIndex = entry.tagLocalIndex if let operation = entry.contents as? SynchronizeInstalledStickerPacksOperation { previousStickerPackIds = operation.previousPacks @@ -64,16 +64,16 @@ func addSynchronizeInstalledStickerPacksOperation(transaction: Transaction, name } let operationContents = SynchronizeInstalledStickerPacksOperation(previousPacks: previousPacks, archivedPacks: archivedPacks, noDelay: noDelay) if let updateLocalIndex = updateLocalIndex { - let _ = transaction.operationLogRemoveEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: updateLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: PeerId(0), tag: tag, tagLocalIndex: updateLocalIndex) } - transaction.operationLogAddEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) + transaction.operationLogAddEntry(peerId: PeerId(0), tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) } func addSynchronizeMarkFeaturedStickerPacksAsSeenOperation(transaction: Transaction, ids: [ItemCollectionId]) { var updateLocalIndex: Int32? let tag: PeerOperationLogTag = OperationLogTags.SynchronizeMarkFeaturedStickerPacksAsSeen var previousIds = Set() - transaction.operationLogEnumerateEntries(peerId: PeerId(namespace: 0, id: 0), tag: tag, { entry in + transaction.operationLogEnumerateEntries(peerId: PeerId(0), tag: tag, { entry in updateLocalIndex = entry.tagLocalIndex if let operation = entry.contents as? SynchronizeMarkFeaturedStickerPacksAsSeenOperation { previousIds = Set(operation.ids) @@ -84,7 +84,7 @@ func addSynchronizeMarkFeaturedStickerPacksAsSeenOperation(transaction: Transact }) let operationContents = SynchronizeMarkFeaturedStickerPacksAsSeenOperation(ids: Array(previousIds.union(Set(ids)))) if let updateLocalIndex = updateLocalIndex { - let _ = transaction.operationLogRemoveEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: updateLocalIndex) + let _ = transaction.operationLogRemoveEntry(peerId: PeerId(0), tag: tag, tagLocalIndex: updateLocalIndex) } - transaction.operationLogAddEntry(peerId: PeerId(namespace: 0, id: 0), tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) + transaction.operationLogAddEntry(peerId: PeerId(0), tag: tag, tagLocalIndex: .automatic, tagMergedIndex: .automatic, contents: operationContents) } diff --git a/submodules/TelegramCore/Sources/SynchronizeLocalizationUpdatesOperation.swift b/submodules/TelegramCore/Sources/SynchronizeLocalizationUpdatesOperation.swift index f471030761..b2e72b4a2a 100644 --- a/submodules/TelegramCore/Sources/SynchronizeLocalizationUpdatesOperation.swift +++ b/submodules/TelegramCore/Sources/SynchronizeLocalizationUpdatesOperation.swift @@ -6,7 +6,7 @@ import SyncCore func addSynchronizeLocalizationUpdatesOperation(transaction: Transaction) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeLocalizationUpdates - let peerId = PeerId(namespace: 0, id: 0) + let peerId = PeerId(0) var topLocalIndex: Int32? transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in diff --git a/submodules/TelegramCore/Sources/SynchronizeRecentlyUsedMediaOperations.swift b/submodules/TelegramCore/Sources/SynchronizeRecentlyUsedMediaOperations.swift index c8104c39fd..ab5ca09fab 100644 --- a/submodules/TelegramCore/Sources/SynchronizeRecentlyUsedMediaOperations.swift +++ b/submodules/TelegramCore/Sources/SynchronizeRecentlyUsedMediaOperations.swift @@ -14,7 +14,7 @@ func addSynchronizeRecentlyUsedMediaOperation(transaction: Transaction, category case .stickers: tag = OperationLogTags.SynchronizeRecentlyUsedStickers } - let peerId = PeerId(namespace: 0, id: 0) + let peerId = PeerId(0) var topOperation: (SynchronizeRecentlyUsedMediaOperation, Int32)? transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in diff --git a/submodules/TelegramCore/Sources/SynchronizeSavedGifsOperation.swift b/submodules/TelegramCore/Sources/SynchronizeSavedGifsOperation.swift index e130f8c64e..2b4c00961a 100644 --- a/submodules/TelegramCore/Sources/SynchronizeSavedGifsOperation.swift +++ b/submodules/TelegramCore/Sources/SynchronizeSavedGifsOperation.swift @@ -6,7 +6,7 @@ import SyncCore func addSynchronizeSavedGifsOperation(transaction: Transaction, operation: SynchronizeSavedGifsOperationContent) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeSavedGifs - let peerId = PeerId(namespace: 0, id: 0) + let peerId = PeerId(0) var topOperation: (SynchronizeSavedGifsOperation, Int32)? transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in diff --git a/submodules/TelegramCore/Sources/SynchronizeSavedStickersOperation.swift b/submodules/TelegramCore/Sources/SynchronizeSavedStickersOperation.swift index bd53548f3e..5eb5ea9075 100644 --- a/submodules/TelegramCore/Sources/SynchronizeSavedStickersOperation.swift +++ b/submodules/TelegramCore/Sources/SynchronizeSavedStickersOperation.swift @@ -7,7 +7,7 @@ import SyncCore func addSynchronizeSavedStickersOperation(transaction: Transaction, operation: SynchronizeSavedStickersOperationContent) { let tag: PeerOperationLogTag = OperationLogTags.SynchronizeSavedStickers - let peerId = PeerId(namespace: 0, id: 0) + let peerId = PeerId(0) var topOperation: (SynchronizeSavedStickersOperation, Int32)? transaction.operationLogEnumerateEntries(peerId: peerId, tag: tag, { entry in diff --git a/submodules/TelegramCore/Sources/UpdateCachedPeerData.swift b/submodules/TelegramCore/Sources/UpdateCachedPeerData.swift index fab05e44a0..7c8cc0db67 100644 --- a/submodules/TelegramCore/Sources/UpdateCachedPeerData.swift +++ b/submodules/TelegramCore/Sources/UpdateCachedPeerData.swift @@ -217,7 +217,7 @@ func fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPeerId: PeerI } } } else if peerId.namespace == Namespaces.Peer.CloudGroup { - return network.request(Api.functions.messages.getFullChat(chatId: peerId.id)) + return network.request(Api.functions.messages.getFullChat(chatId: peerId.id._internalGetInt32Value())) |> retryRequest |> mapToSignal { result -> Signal in return postbox.transaction { transaction -> Bool in @@ -236,7 +236,7 @@ func fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPeerId: PeerI for botInfo in chatFull.botInfo ?? [] { switch botInfo { case let .botInfo(userId, _, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) let parsedBotInfo = BotInfo(apiBotInfo: botInfo) botInfos.append(CachedPeerBotInfo(peerId: peerId, botInfo: parsedBotInfo)) } @@ -381,7 +381,7 @@ func fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPeerId: PeerI let linkedDiscussionPeerId: PeerId? if let linkedChatId = linkedChatId, linkedChatId != 0 { - linkedDiscussionPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: linkedChatId) + linkedDiscussionPeerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(linkedChatId)) } else { linkedDiscussionPeerId = nil } @@ -399,7 +399,7 @@ func fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPeerId: PeerI for botInfo in apiBotInfos { switch botInfo { case let .botInfo(userId, _, _): - let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) + let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)) let parsedBotInfo = BotInfo(apiBotInfo: botInfo) botInfos.append(CachedPeerBotInfo(peerId: peerId, botInfo: parsedBotInfo)) } @@ -421,7 +421,7 @@ func fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPeerId: PeerI var migrationReference: ChannelMigrationReference? if let migratedFromChatId = migratedFromChatId, let migratedFromMaxId = migratedFromMaxId { - migrationReference = ChannelMigrationReference(maxMessageId: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: migratedFromChatId), namespace: Namespaces.Message.Cloud, id: migratedFromMaxId)) + migrationReference = ChannelMigrationReference(maxMessageId: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(migratedFromChatId)), namespace: Namespaces.Message.Cloud, id: migratedFromMaxId)) } var peers: [Peer] = [] @@ -490,7 +490,7 @@ func fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPeerId: PeerI case let.channelParticipant(participant, _, _): switch participant { case let .channelParticipantSelf(_, inviterId, _): - invitedBy = PeerId(namespace: Namespaces.Peer.CloudUser, id: inviterId) + invitedBy = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(inviterId)) default: break } diff --git a/submodules/TelegramCore/Sources/UpdateMessageService.swift b/submodules/TelegramCore/Sources/UpdateMessageService.swift index aa4b178dd1..fc375938cc 100644 --- a/submodules/TelegramCore/Sources/UpdateMessageService.swift +++ b/submodules/TelegramCore/Sources/UpdateMessageService.swift @@ -67,7 +67,7 @@ class UpdateMessageService: NSObject, MTMessageService { case let .updateShortMessage(flags, id, userId, message, pts, ptsCount, date, fwdFrom, viaBotId, replyHeader, entities, ttlPeriod): let generatedFromId: Api.Peer if (Int(flags) & 1 << 1) != 0 { - generatedFromId = Api.Peer.peerUser(userId: self.peerId.id) + generatedFromId = Api.Peer.peerUser(userId: self.peerId.id._internalGetInt32Value()) } else { generatedFromId = Api.Peer.peerUser(userId: userId) } diff --git a/submodules/TelegramCore/Sources/UpdatePeerInfo.swift b/submodules/TelegramCore/Sources/UpdatePeerInfo.swift index d70ded671a..db1115c585 100644 --- a/submodules/TelegramCore/Sources/UpdatePeerInfo.swift +++ b/submodules/TelegramCore/Sources/UpdatePeerInfo.swift @@ -27,10 +27,10 @@ public func updatePeerTitle(account: Account, peerId: PeerId, title: String) -> return updated }) } - } |> mapError { _ -> UpdatePeerTitleError in return .generic } + } |> mapError { _ -> UpdatePeerTitleError in } } } else if let peer = peer as? TelegramGroup { - return account.network.request(Api.functions.messages.editChatTitle(chatId: peer.id.id, title: title)) + return account.network.request(Api.functions.messages.editChatTitle(chatId: peer.id.id._internalGetInt32Value(), title: title)) |> mapError { _ -> UpdatePeerTitleError in return .generic } diff --git a/submodules/TelegramCore/Sources/UpdatedAccountPrivacySettings.swift b/submodules/TelegramCore/Sources/UpdatedAccountPrivacySettings.swift index 0f8c5b47a6..ca6a3a84f5 100644 --- a/submodules/TelegramCore/Sources/UpdatedAccountPrivacySettings.swift +++ b/submodules/TelegramCore/Sources/UpdatedAccountPrivacySettings.swift @@ -234,7 +234,7 @@ public func updateSelectiveAccountPrivacySettings(account: Account, type: Update rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(users: apiInputUsers(transaction: transaction, peerIds: enablePeers.users))) } if !enablePeers.groups.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(chats: enablePeers.groups.map({ $0.id }))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(chats: enablePeers.groups.map({ $0.id._internalGetInt32Value() }))) } rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowAll) @@ -246,14 +246,14 @@ public func updateSelectiveAccountPrivacySettings(account: Account, type: Update rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowUsers(users: apiInputUsers(transaction: transaction, peerIds: enablePeers.users))) } if !enablePeers.groups.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(chats: enablePeers.groups.map({ $0.id }))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowChatParticipants(chats: enablePeers.groups.map({ $0.id._internalGetInt32Value() }))) } if !disablePeers.users.isEmpty { rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(users: apiInputUsers(transaction: transaction, peerIds: disablePeers.users))) } if !disablePeers.groups.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(chats: disablePeers.groups.map({ $0.id }))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(chats: disablePeers.groups.map({ $0.id._internalGetInt32Value() }))) } rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowContacts) @@ -264,7 +264,7 @@ public func updateSelectiveAccountPrivacySettings(account: Account, type: Update rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowUsers(users: apiInputUsers(transaction: transaction, peerIds: disablePeers.users))) } if !disablePeers.groups.isEmpty { - rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(chats: disablePeers.groups.map({ $0.id }))) + rules.append(Api.InputPrivacyRule.inputPrivacyValueDisallowChatParticipants(chats: disablePeers.groups.map({ $0.id._internalGetInt32Value() }))) } rules.append(Api.InputPrivacyRule.inputPrivacyValueAllowAll) diff --git a/submodules/TelegramUI/Sources/AppDelegate.swift b/submodules/TelegramUI/Sources/AppDelegate.swift index 400d70d963..ff4ac28e74 100644 --- a/submodules/TelegramUI/Sources/AppDelegate.swift +++ b/submodules/TelegramUI/Sources/AppDelegate.swift @@ -277,13 +277,13 @@ final class SharedApplicationContext { var peerId: PeerId? if let fromId = payload["from_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["chat_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["channel_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } if let msgId = payload["msg_id"] { @@ -1682,7 +1682,7 @@ final class SharedApplicationContext { if let startCallContacts = startCallContacts { let startCall: (Int32) -> Void = { userId in - self.startCallWhenReady(accountId: nil, peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), isVideo: startCallIsVideo) + self.startCallWhenReady(accountId: nil, peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), isVideo: startCallIsVideo) } func cleanPhoneNumber(_ text: String) -> String { @@ -1744,7 +1744,7 @@ final class SharedApplicationContext { return result } |> deliverOnMainQueue).start(next: { peerId in if let peerId = peerId { - startCall(peerId.id) + startCall(peerId.id._internalGetInt32Value()) } }) processed = true @@ -1759,7 +1759,7 @@ final class SharedApplicationContext { if let contact = sendMessageIntent.recipients?.first, let handle = contact.customIdentifier, handle.hasPrefix("tg") { let string = handle.suffix(from: handle.index(handle.startIndex, offsetBy: 2)) if let userId = Int32(string) { - self.openChatWhenReady(accountId: nil, peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), activateInput: true) + self.openChatWhenReady(accountId: nil, peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(userId)), activateInput: true) } } } @@ -2303,7 +2303,7 @@ private func accountIdFromNotification(_ notification: UNNotification, sharedCon |> take(1) |> map { _, accounts, _ -> AccountRecordId? in for (_, account, _) in accounts { - if Int(account.peerId.id) == userId { + if Int(account.peerId.id._internalGetInt32Value()) == userId { return account.id } } @@ -2325,16 +2325,16 @@ private func peerIdFromNotification(_ notification: UNNotification) -> PeerId? { var peerId: PeerId? if let fromId = payload["from_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["chat_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["channel_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["encryption_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.SecretChat, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } return peerId } diff --git a/submodules/TelegramUI/Sources/ChatMediaInputNode.swift b/submodules/TelegramUI/Sources/ChatMediaInputNode.swift index 96404e4872..ac93046ed5 100644 --- a/submodules/TelegramUI/Sources/ChatMediaInputNode.swift +++ b/submodules/TelegramUI/Sources/ChatMediaInputNode.swift @@ -1008,7 +1008,7 @@ final class ChatMediaInputNode: ChatInputNode { return } - let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: PeerId(namespace: 0, id: 0), namespace: Namespaces.Message.Local, id: 0), globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, threadId: nil, timestamp: 0, flags: [], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: nil, text: "", attributes: [], media: [file.file.media], peers: SimpleDictionary(), associatedMessages: SimpleDictionary(), associatedMessageIds: []) + let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: PeerId(0), namespace: Namespaces.Message.Local, id: 0), globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, threadId: nil, timestamp: 0, flags: [], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: nil, text: "", attributes: [], media: [file.file.media], peers: SimpleDictionary(), associatedMessages: SimpleDictionary(), associatedMessageIds: []) let gallery = GalleryController(context: strongSelf.context, source: .standaloneMessage(message), streamSingleVideo: true, replaceRootController: { _, _ in }, baseNavigationController: nil) diff --git a/submodules/TelegramUI/Sources/ChatMessageBubbleItemNode.swift b/submodules/TelegramUI/Sources/ChatMessageBubbleItemNode.swift index 820fecee5a..664d8726f6 100644 --- a/submodules/TelegramUI/Sources/ChatMessageBubbleItemNode.swift +++ b/submodules/TelegramUI/Sources/ChatMessageBubbleItemNode.swift @@ -1041,7 +1041,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewItemNode ignoreForward = true effectiveAuthor = forwardInfo.author if effectiveAuthor == nil, let authorSignature = forwardInfo.authorSignature { - effectiveAuthor = TelegramUser(id: PeerId(namespace: Namespaces.Peer.Empty, id: Int32(clamping: authorSignature.persistentHashValue)), accessHash: nil, firstName: authorSignature, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: UserInfoFlags()) + effectiveAuthor = TelegramUser(id: PeerId(namespace: Namespaces.Peer.Empty, id: PeerId.Id._internalFromInt32Value(Int32(clamping: authorSignature.persistentHashValue))), accessHash: nil, firstName: authorSignature, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: UserInfoFlags()) } } displayAuthorInfo = !mergedTop.merged && incoming && effectiveAuthor != nil @@ -1057,7 +1057,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewItemNode displayAuthorInfo = !mergedTop.merged && incoming } else if let forwardInfo = item.content.firstMessage.forwardInfo, forwardInfo.flags.contains(.isImported), let authorSignature = forwardInfo.authorSignature { ignoreForward = true - effectiveAuthor = TelegramUser(id: PeerId(namespace: Namespaces.Peer.Empty, id: Int32(clamping: authorSignature.persistentHashValue)), accessHash: nil, firstName: authorSignature, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: UserInfoFlags()) + effectiveAuthor = TelegramUser(id: PeerId(namespace: Namespaces.Peer.Empty, id: PeerId.Id._internalFromInt32Value(Int32(clamping: authorSignature.persistentHashValue))), accessHash: nil, firstName: authorSignature, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: UserInfoFlags()) displayAuthorInfo = !mergedTop.merged && incoming } else { effectiveAuthor = firstMessage.author @@ -1437,12 +1437,12 @@ class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewItemNode if initialDisplayHeader && displayAuthorInfo { if let peer = firstMessage.peers[firstMessage.id.peerId] as? TelegramChannel, case .broadcast = peer.info { authorNameString = peer.displayTitle(strings: item.presentationData.strings, displayOrder: item.presentationData.nameDisplayOrder) - authorNameColor = chatMessagePeerIdColors[Int(peer.id.id % 7)] + authorNameColor = chatMessagePeerIdColors[Int(peer.id.id._internalGetInt32Value() % 7)] } else if let effectiveAuthor = effectiveAuthor { authorNameString = effectiveAuthor.displayTitle(strings: item.presentationData.strings, displayOrder: item.presentationData.nameDisplayOrder) if incoming { - authorNameColor = chatMessagePeerIdColors[Int(effectiveAuthor.id.id % 7)] + authorNameColor = chatMessagePeerIdColors[Int(effectiveAuthor.id.id._internalGetInt32Value() % 7)] } else { authorNameColor = item.presentationData.theme.theme.chat.message.outgoing.accentTextColor } diff --git a/submodules/TelegramUI/Sources/ChatMessageItem.swift b/submodules/TelegramUI/Sources/ChatMessageItem.swift index d699fd11a9..3392533409 100644 --- a/submodules/TelegramUI/Sources/ChatMessageItem.swift +++ b/submodules/TelegramUI/Sources/ChatMessageItem.swift @@ -302,7 +302,7 @@ public final class ChatMessageItem: ListViewItem, CustomStringConvertible { if let forwardInfo = content.firstMessage.forwardInfo { effectiveAuthor = forwardInfo.author if effectiveAuthor == nil, let authorSignature = forwardInfo.authorSignature { - effectiveAuthor = TelegramUser(id: PeerId(namespace: Namespaces.Peer.Empty, id: Int32(clamping: authorSignature.persistentHashValue)), accessHash: nil, firstName: authorSignature, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: UserInfoFlags()) + effectiveAuthor = TelegramUser(id: PeerId(namespace: Namespaces.Peer.Empty, id: PeerId.Id._internalFromInt32Value(Int32(clamping: authorSignature.persistentHashValue))), accessHash: nil, firstName: authorSignature, lastName: nil, username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: UserInfoFlags()) } } displayAuthorInfo = incoming && effectiveAuthor != nil diff --git a/submodules/TelegramUI/Sources/ChatRecentActionsHistoryTransition.swift b/submodules/TelegramUI/Sources/ChatRecentActionsHistoryTransition.swift index 1197ebff43..5cc933f1a5 100644 --- a/submodules/TelegramUI/Sources/ChatRecentActionsHistoryTransition.swift +++ b/submodules/TelegramUI/Sources/ChatRecentActionsHistoryTransition.swift @@ -286,7 +286,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { case .header: var peers = SimpleDictionary() var author: Peer? - if self.entry.event.peerId == PeerId(namespace: Namespaces.Peer.CloudUser, id: 136817688) { + if self.entry.event.peerId == PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(136817688)) { author = message?.effectiveAuthor } else if let peer = self.entry.peers[self.entry.event.peerId] { author = peer diff --git a/submodules/TelegramUI/Sources/CreateChannelController.swift b/submodules/TelegramUI/Sources/CreateChannelController.swift index 2e57f10698..903b3c83b9 100644 --- a/submodules/TelegramUI/Sources/CreateChannelController.swift +++ b/submodules/TelegramUI/Sources/CreateChannelController.swift @@ -197,7 +197,7 @@ private func CreateChannelEntries(presentationData: PresentationData, state: Cre let groupInfoState = ItemListAvatarAndNameInfoItemState(editingName: state.editingName, updatingName: nil) - let peer = TelegramGroup(id: PeerId(namespace: -1, id: 0), title: state.editingName.composedTitle, photo: [], participantCount: 0, role: .creator(rank: nil), membership: .Member, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) + let peer = TelegramGroup(id: PeerId(namespace: .max, id: PeerId.Id._internalFromInt32Value(0)), title: state.editingName.composedTitle, photo: [], participantCount: 0, role: .creator(rank: nil), membership: .Member, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) entries.append(.channelInfo(presentationData.theme, presentationData.strings, presentationData.dateTimeFormat, peer, groupInfoState, state.avatar)) diff --git a/submodules/TelegramUI/Sources/CreateGroupController.swift b/submodules/TelegramUI/Sources/CreateGroupController.swift index 3fe9f78ff9..91e3620fa6 100644 --- a/submodules/TelegramUI/Sources/CreateGroupController.swift +++ b/submodules/TelegramUI/Sources/CreateGroupController.swift @@ -298,7 +298,7 @@ private func createGroupEntries(presentationData: PresentationData, state: Creat let groupInfoState = ItemListAvatarAndNameInfoItemState(editingName: state.editingName, updatingName: nil) - let peer = TelegramGroup(id: PeerId(namespace: -1, id: 0), title: state.editingName.composedTitle, photo: [], participantCount: 0, role: .creator(rank: nil), membership: .Member, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) + let peer = TelegramGroup(id: PeerId(namespace: .max, id: PeerId.Id._internalFromInt32Value(0)), title: state.editingName.composedTitle, photo: [], participantCount: 0, role: .creator(rank: nil), membership: .Member, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) entries.append(.groupInfo(presentationData.theme, presentationData.strings, presentationData.dateTimeFormat, peer, groupInfoState, state.avatar)) diff --git a/submodules/TelegramUI/Sources/OpenUrl.swift b/submodules/TelegramUI/Sources/OpenUrl.swift index 8f0a468096..218059f25c 100644 --- a/submodules/TelegramUI/Sources/OpenUrl.swift +++ b/submodules/TelegramUI/Sources/OpenUrl.swift @@ -96,7 +96,7 @@ public func parseSecureIdUrl(_ url: URL) -> ParsedSecureIdUrl? { return nil } - return ParsedSecureIdUrl(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: botId), scope: scope, publicKey: publicKey, callbackUrl: callbackUrl, opaquePayload: opaquePayload, opaqueNonce: opaqueNonce) + return ParsedSecureIdUrl(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(botId)), scope: scope, publicKey: publicKey, callbackUrl: callbackUrl, opaquePayload: opaquePayload, opaqueNonce: opaqueNonce) } } } @@ -451,7 +451,7 @@ func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, ur if case .chat = urlContext { return } - let controller = SecureIdAuthController(context: context, mode: .form(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: botId), scope: scope, publicKey: publicKey, callbackUrl: callbackUrl, opaquePayload: opaquePayload, opaqueNonce: opaqueNonce)) + let controller = SecureIdAuthController(context: context, mode: .form(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(botId)), scope: scope, publicKey: publicKey, callbackUrl: callbackUrl, opaquePayload: opaquePayload, opaqueNonce: opaqueNonce)) if let navigationController = navigationController { context.sharedContext.applicationBindings.dismissNativeController() @@ -478,7 +478,7 @@ func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, ur if let id = id, !id.isEmpty, let idValue = Int32(id), idValue > 0 { let _ = (context.account.postbox.transaction { transaction -> Peer? in - return transaction.getPeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: idValue)) + return transaction.getPeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(idValue))) } |> deliverOnMainQueue).start(next: { peer in if let peer = peer, let controller = context.sharedContext.makePeerInfoController(context: context, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false) { diff --git a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoHeaderNode.swift b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoHeaderNode.swift index 6c82e85d08..681491def6 100644 --- a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoHeaderNode.swift +++ b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoHeaderNode.swift @@ -331,7 +331,7 @@ final class PeerInfoAvatarTransformContainerNode: ASDisplayNode { representations = topRepresentations videoRepresentations = videoRepresentationsValue immediateThumbnailData = immediateThumbnail - id = Int64(peer.id.id) + id = Int64(peer.id.id._internalGetInt32Value()) if let resource = videoRepresentations.first?.representation.resource as? CloudPhotoSizeMediaResource { id = id &+ resource.photoId } @@ -342,7 +342,7 @@ final class PeerInfoAvatarTransformContainerNode: ASDisplayNode { if case let .cloud(imageId, _, _) = reference { id = imageId } else { - id = Int64(peer.id.id) + id = Int64(peer.id.id._internalGetInt32Value()) } } @@ -621,7 +621,7 @@ final class PeerInfoEditingAvatarNode: ASDisplayNode { representations = topRepresentations videoRepresentations = videoRepresentationsValue immediateThumbnailData = immediateThumbnail - id = Int64(peer.id.id) + id = Int64(peer.id.id._internalGetInt32Value()) if let resource = videoRepresentations.first?.representation.resource as? CloudPhotoSizeMediaResource { id = id &+ resource.photoId } @@ -632,7 +632,7 @@ final class PeerInfoEditingAvatarNode: ASDisplayNode { if case let .cloud(imageId, _, _) = reference { id = imageId } else { - id = Int64(peer.id.id) + id = Int64(peer.id.id._internalGetInt32Value()) } } diff --git a/submodules/TelegramUI/Sources/PollResultsController.swift b/submodules/TelegramUI/Sources/PollResultsController.swift index a3c23ca54a..1efa4db7d6 100644 --- a/submodules/TelegramUI/Sources/PollResultsController.swift +++ b/submodules/TelegramUI/Sources/PollResultsController.swift @@ -252,7 +252,7 @@ private func pollResultsControllerEntries(presentationData: PresentationData, po displayCount = Int(voterCount) } for peerIndex in 0 ..< displayCount { - let fakeUser = TelegramUser(id: PeerId(namespace: -1, id: 0), accessHash: nil, firstName: "", lastName: "", username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) + let fakeUser = TelegramUser(id: PeerId(namespace: .max, id: PeerId.Id._internalFromInt32Value(0)), accessHash: nil, firstName: "", lastName: "", username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) let peer = RenderedPeer(peer: fakeUser) entries.append(.optionPeer(optionId: i, index: peerIndex, peer: peer, optionText: optionTextHeader, optionAdditionalText: optionAdditionalTextHeader, optionCount: voterCount, optionExpanded: false, opaqueIdentifier: option.opaqueIdentifier, shimmeringAlternation: peerIndex % 2, isFirstInOption: peerIndex == 0)) } diff --git a/submodules/TelegramUI/Sources/PrefetchManager.swift b/submodules/TelegramUI/Sources/PrefetchManager.swift index a3746e8397..c91153056f 100644 --- a/submodules/TelegramUI/Sources/PrefetchManager.swift +++ b/submodules/TelegramUI/Sources/PrefetchManager.swift @@ -203,7 +203,7 @@ private final class PrefetchManagerImpl { context = PrefetchMediaContext() self.contexts[id] = context - let priority: FetchManagerPriority = .backgroundPrefetch(locationOrder: HistoryPreloadIndex(index: nil, hasUnread: false, isMuted: false, isPriority: true), localOrder: MessageIndex(id: MessageId(peerId: PeerId(namespace: 0, id: 0), namespace: 0, id: order), timestamp: 0)) + let priority: FetchManagerPriority = .backgroundPrefetch(locationOrder: HistoryPreloadIndex(index: nil, hasUnread: false, isMuted: false, isPriority: true), localOrder: MessageIndex(id: MessageId(peerId: PeerId(0), namespace: 0, id: order), timestamp: 0)) if case .full = automaticDownload { let fetchSignal = freeMediaFileInteractiveFetched(fetchManager: self.fetchManager, fileReference: .standalone(media: media), priority: priority) diff --git a/submodules/TelegramUI/Sources/SharedNotificationManager.swift b/submodules/TelegramUI/Sources/SharedNotificationManager.swift index 2c6796bd7b..77d8ea8fa5 100644 --- a/submodules/TelegramUI/Sources/SharedNotificationManager.swift +++ b/submodules/TelegramUI/Sources/SharedNotificationManager.swift @@ -250,13 +250,13 @@ public final class SharedNotificationManager { var peerId: PeerId? if let fromId = payload["from_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["chat_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["channel_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } if let peerId = peerId { if let messageIds = payload["messages"] as? String { @@ -314,13 +314,13 @@ public final class SharedNotificationManager { if let fromId = payload["from_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["chat_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["channel_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } if let msgId = payload["msg_id"] { @@ -332,7 +332,7 @@ public final class SharedNotificationManager { let randomIdValue = randomId as! NSString var peerId: PeerId? if let encryptionIdString = payload["encryption_id"] as? String, let encryptionId = Int32(encryptionIdString) { - peerId = PeerId(namespace: Namespaces.Peer.SecretChat, id: encryptionId) + peerId = PeerId(namespace: Namespaces.Peer.SecretChat, id: PeerId.Id._internalFromInt32Value(encryptionId)) } notificationRequestId = .globallyUniqueId(randomIdValue.longLongValue, peerId) } else { @@ -344,13 +344,13 @@ public final class SharedNotificationManager { if let fromId = payload["from_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["chat_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } else if let fromId = payload["channel_id"] { let fromIdValue = fromId as! NSString - peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: Int32(fromIdValue.intValue)) + peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(Int32(fromIdValue.intValue))) } if let peerId = peerId { diff --git a/submodules/TemporaryCachedPeerDataManager/Sources/ChannelMemberCategoryListContext.swift b/submodules/TemporaryCachedPeerDataManager/Sources/ChannelMemberCategoryListContext.swift index 0b20956993..9c86d77e5a 100644 --- a/submodules/TemporaryCachedPeerDataManager/Sources/ChannelMemberCategoryListContext.swift +++ b/submodules/TemporaryCachedPeerDataManager/Sources/ChannelMemberCategoryListContext.swift @@ -315,7 +315,7 @@ private final class ChannelMemberSingleCategoryListContext: ChannelMemberCategor for i in 0 ..< min(strongSelf.listStateValue.list.count, Int(initialBatchSize)) { let peerId = strongSelf.listStateValue.list[i].peer.id - hash = (hash &* 20261) &+ UInt32(peerId.id) + hash = (hash &* 20261) &+ UInt32(bitPattern: peerId.id._internalGetInt32Value()) } hash = hash % 0x7FFFFFFF strongSelf.headUpdateDisposable.set((strongSelf.loadSignal(offset: 0, count: initialBatchSize, hash: Int32(bitPattern: hash)) diff --git a/submodules/UrlHandling/Sources/UrlHandling.swift b/submodules/UrlHandling/Sources/UrlHandling.swift index 07b8c01734..55c1ce387d 100644 --- a/submodules/UrlHandling/Sources/UrlHandling.swift +++ b/submodules/UrlHandling/Sources/UrlHandling.swift @@ -146,7 +146,7 @@ public func parseInternalUrl(query: String) -> ParsedInternalUrl? { } } } else if pathComponents[0].hasPrefix(phonebookUsernamePathPrefix), let idValue = Int32(String(pathComponents[0][pathComponents[0].index(pathComponents[0].startIndex, offsetBy: phonebookUsernamePathPrefix.count)...])) { - return .peerId(PeerId(namespace: Namespaces.Peer.CloudUser, id: idValue)) + return .peerId(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(idValue))) } else if pathComponents[0].hasPrefix("+") || pathComponents[0].hasPrefix("%20") { return .join(String(pathComponents[0].dropFirst())) } @@ -261,7 +261,7 @@ public func parseInternalUrl(query: String) -> ParsedInternalUrl? { } } } - return .privateMessage(messageId: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId), namespace: Namespaces.Message.Cloud, id: messageId), threadId: threadId) + return .privateMessage(messageId: MessageId(peerId: PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(channelId)), namespace: Namespaces.Message.Cloud, id: messageId), threadId: threadId) } else { return nil } @@ -374,7 +374,7 @@ private func resolveInternalUrl(account: Account, url: ParsedInternalUrl) -> Sig if let peer = peer { foundPeer = .single(peer) } else { - foundPeer = TelegramEngine(account: account).peerNames.findChannelById(channelId: messageId.peerId.id) + foundPeer = TelegramEngine(account: account).peerNames.findChannelById(channelId: messageId.peerId.id._internalGetInt32Value()) } return foundPeer |> mapToSignal { foundPeer -> Signal in diff --git a/submodules/WatchBridge/Sources/WatchBridge.swift b/submodules/WatchBridge/Sources/WatchBridge.swift index e01c5941be..08a9ccc38c 100644 --- a/submodules/WatchBridge/Sources/WatchBridge.swift +++ b/submodules/WatchBridge/Sources/WatchBridge.swift @@ -9,11 +9,11 @@ import PhoneNumberFormat func makePeerIdFromBridgeIdentifier(_ identifier: Int64) -> PeerId? { if identifier < 0 && identifier > Int32.min { - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: Int32(clamping: -identifier)) + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt32Value(Int32(clamping: -identifier))) } else if identifier < Int64(Int32.min) * 2 && identifier > Int64(Int32.min) * 3 { - return PeerId(namespace: Namespaces.Peer.CloudChannel, id: Int32(clamping: Int64(Int32.min) &* 2 &- identifier)) + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt32Value(Int32(clamping: Int64(Int32.min) &* 2 &- identifier))) } else if identifier > 0 && identifier < Int32.max { - return PeerId(namespace: Namespaces.Peer.CloudUser, id: Int32(clamping: identifier)) + return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt32Value(Int32(clamping: identifier))) } else { return nil } @@ -22,11 +22,11 @@ func makePeerIdFromBridgeIdentifier(_ identifier: Int64) -> PeerId? { func makeBridgeIdentifier(_ peerId: PeerId) -> Int64 { switch peerId.namespace { case Namespaces.Peer.CloudGroup: - return -Int64(peerId.id) + return -Int64(peerId.id._internalGetInt32Value()) case Namespaces.Peer.CloudChannel: - return Int64(Int32.min) * 2 - Int64(peerId.id) + return Int64(Int32.min) * 2 - Int64(peerId.id._internalGetInt32Value()) default: - return Int64(peerId.id) + return Int64(peerId.id._internalGetInt32Value()) } } diff --git a/submodules/WatchBridge/Sources/WatchCommunicationManager.swift b/submodules/WatchBridge/Sources/WatchCommunicationManager.swift index 18b3f617ad..629b456a41 100644 --- a/submodules/WatchBridge/Sources/WatchCommunicationManager.swift +++ b/submodules/WatchBridge/Sources/WatchCommunicationManager.swift @@ -89,7 +89,7 @@ public final class WatchCommunicationManager { } if let context = appContext { strongSelf.accountContext.set(.single(context.context)) - strongSelf.server.setAuthorized(true, userId: context.context.account.peerId.id) + strongSelf.server.setAuthorized(true, userId: context.context.account.peerId.id._internalGetInt32Value()) strongSelf.server.setMicAccessAllowed(false) strongSelf.server.pushContext() strongSelf.server.setMicAccessAllowed(true)