diff --git a/TelegramUI/AvatarNode.swift b/TelegramUI/AvatarNode.swift index 5d9bd42bcd..74747ba4cd 100644 --- a/TelegramUI/AvatarNode.swift +++ b/TelegramUI/AvatarNode.swift @@ -200,7 +200,7 @@ public final class AvatarNode: ASDisplayNode { } } - public func setPeer(account: Account, theme: PresentationTheme? = nil, peer: Peer, authorOfMessage: MessageReference? = nil, overrideImage: AvatarNodeImageOverride? = nil, emptyColor: UIColor? = nil, synchronousLoad: Bool = false) { + public func setPeer(account: Account, theme: PresentationTheme, peer: Peer, authorOfMessage: MessageReference? = nil, overrideImage: AvatarNodeImageOverride? = nil, emptyColor: UIColor? = nil, synchronousLoad: Bool = false) { var synchronousLoad = synchronousLoad var representation: TelegramMediaImageRepresentation? var icon = AvatarNodeIcon.none @@ -247,8 +247,6 @@ public final class AvatarNode: ASDisplayNode { self.editOverlayNode?.isHidden = true } - let theme = theme ?? account.telegramApplicationContext.currentPresentationData.with { $0 }.theme - parameters = AvatarNodeParameters(theme: theme, accountPeerId: account.peerId, peerId: peer.id, letters: peer.displayLetters, font: self.font, icon: icon, explicitColorIndex: nil, hasImage: true) } else { self.imageReady.set(.single(true)) diff --git a/TelegramUI/BotCheckoutControllerNode.swift b/TelegramUI/BotCheckoutControllerNode.swift index 2b3a63d48e..44f70c8421 100644 --- a/TelegramUI/BotCheckoutControllerNode.swift +++ b/TelegramUI/BotCheckoutControllerNode.swift @@ -403,7 +403,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, openShippingMethodImpl?() }) - let signal: Signal<(PresentationTheme, (ItemListNodeState, BotCheckoutEntry.ItemGenerationArguments)), NoError> = combineLatest(context.presentationData, self.state.get(), paymentFormAndInfo.get(), account.postbox.loadedPeerWithId(messageId.peerId)) + let signal: Signal<(PresentationTheme, (ItemListNodeState, BotCheckoutEntry.ItemGenerationArguments)), NoError> = combineLatest(context.presentationData, self.state.get(), paymentFormAndInfo.get(), context.account.postbox.loadedPeerWithId(messageId.peerId)) |> map { presentationData, state, paymentFormAndInfo, botPeer -> (PresentationTheme, (ItemListNodeState, BotCheckoutEntry.ItemGenerationArguments)) in let nodeState = ItemListNodeState(entries: botCheckoutControllerEntries(presentationData: presentationData, state: state, invoice: invoice, paymentForm: paymentFormAndInfo?.0, formInfo: paymentFormAndInfo?.1, validatedFormInfo: paymentFormAndInfo?.2, currentShippingOptionId: paymentFormAndInfo?.3, currentPaymentMethod: paymentFormAndInfo?.4, botPeer: botPeer), style: .plain, focusItemTag: nil, emptyStateItem: nil, animateChanges: false) diff --git a/TelegramUI/BotReceiptControllerNode.swift b/TelegramUI/BotReceiptControllerNode.swift index ebaef04ba3..9c9aeaf7b1 100644 --- a/TelegramUI/BotReceiptControllerNode.swift +++ b/TelegramUI/BotReceiptControllerNode.swift @@ -260,14 +260,14 @@ final class BotReceiptControllerNode: ItemListControllerNode { private let actionButton: BotCheckoutActionButton init(navigationBar: NavigationBar, updateNavigationOffset: @escaping (CGFloat) -> Void, context: AccountContext, invoice: TelegramMediaInvoice, messageId: MessageId, dismissAnimated: @escaping () -> Void) { - self.account = account + self.context = context self.dismissAnimated = dismissAnimated self.presentationData = context.currentPresentationData.with { $0 } - let arguments = BotReceiptControllerArguments(account: account) + let arguments = BotReceiptControllerArguments(account: context.account) - let signal: Signal<(PresentationTheme, (ItemListNodeState, BotReceiptEntry.ItemGenerationArguments)), NoError> = combineLatest(context.presentationData, receiptData.get(), account.postbox.loadedPeerWithId(messageId.peerId)) + let signal: Signal<(PresentationTheme, (ItemListNodeState, BotReceiptEntry.ItemGenerationArguments)), NoError> = combineLatest(context.presentationData, receiptData.get(), context.account.postbox.loadedPeerWithId(messageId.peerId)) |> map { presentationData, receiptData, botPeer -> (PresentationTheme, (ItemListNodeState, BotReceiptEntry.ItemGenerationArguments)) in let nodeState = ItemListNodeState(entries: botReceiptControllerEntries(presentationData: presentationData, invoice: invoice, formInvoice: receiptData?.0, formInfo: receiptData?.1, shippingOption: receiptData?.2, paymentMethodTitle: receiptData?.3, botPeer: botPeer), style: .plain, focusItemTag: nil, emptyStateItem: nil, animateChanges: false) diff --git a/TelegramUI/CallListCallItem.swift b/TelegramUI/CallListCallItem.swift index a479c16ff7..d7e9334a72 100644 --- a/TelegramUI/CallListCallItem.swift +++ b/TelegramUI/CallListCallItem.swift @@ -428,7 +428,7 @@ class CallListCallItemNode: ItemListRevealOptionsItemNode { return (nodeLayout, { [weak self] in if let strongSelf = self { if let peer = item.topMessage.peers[item.topMessage.id.peerId] { - strongSelf.avatarNode.setPeer(account: item.account, peer: peer, emptyColor: item.theme.list.mediaPlaceholderColor) + strongSelf.avatarNode.setPeer(account: item.account, theme: item.theme, peer: peer, emptyColor: item.theme.list.mediaPlaceholderColor) } return (strongSelf.avatarNode.ready, { [weak strongSelf] animated in diff --git a/TelegramUI/ChannelMembersController.swift b/TelegramUI/ChannelMembersController.swift index 40465d3760..0a6434d342 100644 --- a/TelegramUI/ChannelMembersController.swift +++ b/TelegramUI/ChannelMembersController.swift @@ -245,7 +245,7 @@ private struct ChannelMembersControllerState: Equatable { } } -private func ChannelMembersControllerEntries(context: Account, presentationData: PresentationData, view: PeerView, state: ChannelMembersControllerState, participants: [RenderedChannelParticipant]?) -> [ChannelMembersEntry] { +private func ChannelMembersControllerEntries(context: AccountContext, presentationData: PresentationData, view: PeerView, state: ChannelMembersControllerState, participants: [RenderedChannelParticipant]?) -> [ChannelMembersEntry] { if participants == nil || participants?.count == nil { return [] } @@ -291,7 +291,7 @@ private func ChannelMembersControllerEntries(context: Account, presentationData: canEditMembers = peer.hasPermission(.banMembers) } - if participant.peer.id == account.peerId { + if participant.peer.id == context.account.peerId { editable = false } else { switch participant.participant { @@ -404,7 +404,7 @@ public func channelMembersController(context: AccountContext, peerId: PeerId) -> let peerView = context.account.viewTracker.peerView(peerId) - let (disposable, loadMoreControl) = context.peerChannelMemberCategoriesContextsManager.recent(postbox: contextaccount.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, updated: { state in + let (disposable, loadMoreControl) = context.peerChannelMemberCategoriesContextsManager.recent(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, updated: { state in peersPromise.set(.single(state.list)) }) actionsDisposable.add(disposable) @@ -465,7 +465,7 @@ public func channelMembersController(context: AccountContext, peerId: PeerId) -> previousPeers = peers let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.Channel_Subscribers_Title), leftNavigationButton: nil, rightNavigationButton: rightNavigationButton, secondaryRightNavigationButton: secondaryRightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: true) - let listState = ItemListNodeState(entries: ChannelMembersControllerEntries(account: context.account, presentationData: presentationData, view: view, state: state, participants: peers), style: .blocks, emptyStateItem: emptyStateItem, searchItem: searchItem, animateChanges: previous != nil && peers != nil && previous!.count >= peers!.count) + let listState = ItemListNodeState(entries: ChannelMembersControllerEntries(context: context, presentationData: presentationData, view: view, state: state, participants: peers), style: .blocks, emptyStateItem: emptyStateItem, searchItem: searchItem, animateChanges: previous != nil && peers != nil && previous!.count >= peers!.count) return (controllerState, (listState, arguments)) } |> afterDisposed { diff --git a/TelegramUI/ChannelVisibilityController.swift b/TelegramUI/ChannelVisibilityController.swift index 50dfa4e946..5f8dac4fb3 100644 --- a/TelegramUI/ChannelVisibilityController.swift +++ b/TelegramUI/ChannelVisibilityController.swift @@ -908,7 +908,7 @@ public func channelVisibilityController(context: AccountContext, peerId: PeerId, ]) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, sharePrivateLink: { - let _ = (account.postbox.transaction { transaction -> String? in + let _ = (context.account.postbox.transaction { transaction -> String? in if let cachedData = transaction.getPeerCachedData(peerId: peerId) { if let cachedData = cachedData as? CachedChannelData { return cachedData.exportedInvitation?.link @@ -1190,7 +1190,7 @@ public func channelVisibilityController(context: AccountContext, peerId: PeerId, navigateToChatController(navigationController: navigationController, chatController: nil, context: context, chatLocation: .peer(peerId), keepStack: .never, animated: true) } else { selectionController.displayProgress = true - let _ = (addChannelMembers(account: account, peerId: peerId, memberIds: filteredPeerIds) + let _ = (addChannelMembers(account: context.account, peerId: peerId, memberIds: filteredPeerIds) |> deliverOnMainQueue).start(completed: { [weak selectionController] in guard let selectionController = selectionController, let navigationController = selectionController.navigationController as? NavigationController else { return diff --git a/TelegramUI/ChatController.swift b/TelegramUI/ChatController.swift index b4c8dae9ee..632734e836 100644 --- a/TelegramUI/ChatController.swift +++ b/TelegramUI/ChatController.swift @@ -1223,7 +1223,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let strongSelf = self { if let peer = peerViewMainPeer(peerView) { strongSelf.chatTitleView?.titleContent = .peer(peerView: peerView, onlineMemberCount: onlineMemberCount) - (strongSelf.chatInfoNavigationButton?.buttonItem.customDisplayNode as? ChatAvatarNavigationNode)?.avatarNode.setPeer(account: strongSelf.context.account, peer: peer) + (strongSelf.chatInfoNavigationButton?.buttonItem.customDisplayNode as? ChatAvatarNavigationNode)?.avatarNode.setPeer(account: strongSelf.context.account, theme: strongSelf.presentationData.theme, peer: peer) } if strongSelf.peerView === peerView { return @@ -1345,7 +1345,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal |> deliverOnMainQueue).start(next: { [weak self] topPeersView in if let strongSelf = self { strongSelf.chatTitleView?.titleContent = .group(topPeersView.peers) - (strongSelf.chatInfoNavigationButton?.buttonItem.customDisplayNode as? ChatMultipleAvatarsNavigationNode)?.setPeers(account: strongSelf.context.account, peers: topPeersView.peers, animated: strongSelf.didSetChatLocationInfoReady) + (strongSelf.chatInfoNavigationButton?.buttonItem.customDisplayNode as? ChatMultipleAvatarsNavigationNode)?.setPeers(account: strongSelf.context.account, theme: strongSelf.presentationData.theme, peers: topPeersView.peers, animated: strongSelf.didSetChatLocationInfoReady) if !strongSelf.didSetChatLocationInfoReady { strongSelf.didSetChatLocationInfoReady = true @@ -2499,7 +2499,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard let strongSelf = self, strongSelf.beginMediaRecordingRequestId == requestId else { return } - guard checkAvailableDiskSpace(account: strongSelf.context.account, present: { [weak self] c, a in + guard checkAvailableDiskSpace(context: strongSelf.context, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a) }) else { return @@ -3874,7 +3874,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal legacyController.bind(controller: navigationController) legacyController.enableSizeClassSignal = true - let controller = legacyAttachmentMenu(account: strongSelf.context.account, peer: peer, editMediaOptions: editMediaOptions, saveEditedPhotos: settings.storeEditedPhotos, allowGrouping: true, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, parentController: legacyController, recentlyUsedInlineBots: strongSelf.recentlyUsedInlineBotsValue, openGallery: { + let controller = legacyAttachmentMenu(context: strongSelf.context, peer: peer, editMediaOptions: editMediaOptions, saveEditedPhotos: settings.storeEditedPhotos, allowGrouping: true, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, parentController: legacyController, recentlyUsedInlineBots: strongSelf.recentlyUsedInlineBotsValue, openGallery: { self?.presentMediaPicker(fileMode: false, editingMedia: editMediaOptions != nil, completion: { signals in if editMediaOptions != nil { self?.editMessageMediaWithLegacySignals(signals) @@ -4322,7 +4322,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal |> deliverOnMainQueue).start(next: { [weak self] settings in if let strongSelf = self, let peer = strongSelf.presentationInterfaceState.renderedPeer?.peer { strongSelf.chatDisplayNode.dismissInput() - let _ = presentLegacyPasteMenu(account: strongSelf.context.account, peer: peer, saveEditedPhotos: settings.storeEditedPhotos, allowGrouping: true, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, images: images, sendMessagesWithSignals: { signals in + let _ = presentLegacyPasteMenu(context: strongSelf.context, peer: peer, saveEditedPhotos: settings.storeEditedPhotos, allowGrouping: true, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, images: images, sendMessagesWithSignals: { signals in self?.enqueueMediaMessages(signals: signals) }, present: { [weak self] controller, arguments in if let strongSelf = self { @@ -5466,7 +5466,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } if let selectedTransitionNode = selectedTransitionNode { - if let previewData = chatMessagePreviewControllerData(account: self.context.account, message: message, standalone: false, reverseMessageGalleryOrder: false, navigationController: self.navigationController as? NavigationController) { + if let previewData = chatMessagePreviewControllerData(context: self.context, message: message, standalone: false, reverseMessageGalleryOrder: false, navigationController: self.navigationController as? NavigationController) { switch previewData { case let .gallery(gallery): gallery.setHintWillBePresentedInPreviewingContext(true) diff --git a/TelegramUI/ChatHistorySearchContainerNode.swift b/TelegramUI/ChatHistorySearchContainerNode.swift index 510e38e02b..e8f6e03ba7 100644 --- a/TelegramUI/ChatHistorySearchContainerNode.swift +++ b/TelegramUI/ChatHistorySearchContainerNode.swift @@ -75,10 +75,10 @@ private enum ChatHistorySearchEntry: Comparable, Identifiable { } } - func item(account: Account, peerId: PeerId, interaction: ChatControllerInteraction) -> ListViewItem { + func item(context: AccountContext, peerId: PeerId, interaction: ChatControllerInteraction) -> ListViewItem { switch self { case let .message(message, theme, strings, dateTimeFormat): - return ListMessageItem(theme: theme, strings: strings, dateTimeFormat: dateTimeFormat, account: account, chatLocation: .peer(peerId), controllerInteraction: interaction, message: message, selection: .none, displayHeader: true) + return ListMessageItem(theme: theme, strings: strings, dateTimeFormat: dateTimeFormat, context: context, chatLocation: .peer(peerId), controllerInteraction: interaction, message: message, selection: .none, displayHeader: true) } } } @@ -91,12 +91,12 @@ private struct ChatHistorySearchContainerTransition { let displayingResults: Bool } -private func chatHistorySearchContainerPreparedTransition(from fromEntries: [ChatHistorySearchEntry], to toEntries: [ChatHistorySearchEntry], query: String, displayingResults: Bool, account: Account, peerId: PeerId, interaction: ChatControllerInteraction) -> ChatHistorySearchContainerTransition { +private func chatHistorySearchContainerPreparedTransition(from fromEntries: [ChatHistorySearchEntry], to toEntries: [ChatHistorySearchEntry], query: String, displayingResults: Bool, context: AccountContext, peerId: PeerId, interaction: ChatControllerInteraction) -> ChatHistorySearchContainerTransition { let (deleteIndices, indicesAndItems, updateIndices) = mergeListsStableWithUpdates(leftList: fromEntries, rightList: toEntries) let deletions = deleteIndices.map { ListViewDeleteItem(index: $0, directionHint: nil) } - let insertions = indicesAndItems.map { ListViewInsertItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(account: account, peerId: peerId, interaction: interaction), directionHint: nil) } - let updates = updateIndices.map { ListViewUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(account: account, peerId: peerId, interaction: interaction), directionHint: nil) } + let insertions = indicesAndItems.map { ListViewInsertItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, peerId: peerId, interaction: interaction), directionHint: nil) } + let updates = updateIndices.map { ListViewUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, peerId: peerId, interaction: interaction), directionHint: nil) } return ChatHistorySearchContainerTransition(deletions: deletions, insertions: insertions, updates: updates, query: query, displayingResults: displayingResults) } @@ -175,7 +175,7 @@ final class ChatHistorySearchContainerNode: SearchDisplayControllerContentNode { if let strongSelf = self { let signal: Signal<([ChatHistorySearchEntry], [MessageId: Message])?, NoError> if let query = query, !query.isEmpty { - let foundRemoteMessages: Signal<[Message], NoError> = searchMessages(account: account, location: .peer(peerId: peerId, fromId: nil, tags: tagMask), query: query, state: nil) + let foundRemoteMessages: Signal<[Message], NoError> = searchMessages(account: context.account, location: .peer(peerId: peerId, fromId: nil, tags: tagMask), query: query, state: nil) |> map { $0.0.messages } |> delay(0.2, queue: Queue.concurrentDefaultQueue()) @@ -202,7 +202,7 @@ final class ChatHistorySearchContainerNode: SearchDisplayControllerContentNode { let previousEntries = previousEntriesValue.swap(entriesAndMessages?.0) let firstTime = previousEntries == nil - let transition = chatHistorySearchContainerPreparedTransition(from: previousEntries ?? [], to: entriesAndMessages?.0 ?? [], query: query ?? "", displayingResults: entriesAndMessages?.0 != nil, account: account, peerId: peerId, interaction: interfaceInteraction) + let transition = chatHistorySearchContainerPreparedTransition(from: previousEntries ?? [], to: entriesAndMessages?.0 ?? [], query: query ?? "", displayingResults: entriesAndMessages?.0 != nil, context: context, peerId: peerId, interaction: interfaceInteraction) strongSelf.currentEntries = entriesAndMessages?.0 strongSelf.currentMessages = entriesAndMessages?.1 strongSelf.enqueueTransition(transition, firstTime: firstTime) @@ -216,7 +216,7 @@ final class ChatHistorySearchContainerNode: SearchDisplayControllerContentNode { self?.dismissInput?() } - self.presentationDataDisposable = account.telegramApplicationContext.presentationData.start(next: { [weak self] presentationData in + self.presentationDataDisposable = context.presentationData.start(next: { [weak self] presentationData in if let strongSelf = self { strongSelf.themeAndStringsPromise.set(.single((presentationData.theme, presentationData.strings, presentationData.dateTimeFormat))) diff --git a/TelegramUI/ChatInterfaceInputContextPanels.swift b/TelegramUI/ChatInterfaceInputContextPanels.swift index e9e77e5d53..d5000dd9d3 100644 --- a/TelegramUI/ChatInterfaceInputContextPanels.swift +++ b/TelegramUI/ChatInterfaceInputContextPanels.swift @@ -65,7 +65,7 @@ func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfa if let currentPanel = currentPanel as? DisabledContextResultsChatInputContextPanelNode { return currentPanel } else { - let panel = DisabledContextResultsChatInputContextPanelNode(account: account, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panel = DisabledContextResultsChatInputContextPanelNode(context: context, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panel.interfaceInteraction = interfaceInteraction return panel } @@ -81,7 +81,7 @@ func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfa currentPanel.updateResults(results.map({ $0.file })) return currentPanel } else { - let panel = HorizontalStickersChatContextPanelNode(account: account, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panel = HorizontalStickersChatContextPanelNode(context: context, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panel.controllerInteraction = controllerInteraction panel.interfaceInteraction = interfaceInteraction panel.updateResults(results.map({ $0.file })) @@ -94,7 +94,7 @@ func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfa currentPanel.updateResults(results) return currentPanel } else { - let panel = HashtagChatInputContextPanelNode(account: account, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panel = HashtagChatInputContextPanelNode(context: context, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panel.interfaceInteraction = interfaceInteraction panel.updateResults(results) return panel @@ -106,7 +106,7 @@ func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfa currentPanel.updateResults(results) return currentPanel } else { - let panel = EmojisChatInputContextPanelNode(account: account, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panel = EmojisChatInputContextPanelNode(context: context, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panel.interfaceInteraction = interfaceInteraction panel.updateResults(results) return panel @@ -118,7 +118,7 @@ func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfa currentPanel.updateResults(peers) return currentPanel } else { - let panel = MentionChatInputContextPanelNode(account: account, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, mode: .input) + let panel = MentionChatInputContextPanelNode(context: context, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, mode: .input) panel.interfaceInteraction = interfaceInteraction panel.updateResults(peers) return panel @@ -132,7 +132,7 @@ func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfa currentPanel.updateResults(commands) return currentPanel } else { - let panel = CommandChatInputContextPanelNode(account: account, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panel = CommandChatInputContextPanelNode(context: context, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panel.interfaceInteraction = interfaceInteraction panel.updateResults(commands) return panel @@ -148,7 +148,7 @@ func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfa currentPanel.updateResults(results) return currentPanel } else { - let panel = VerticalListContextResultsChatInputContextPanelNode(account: account, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panel = VerticalListContextResultsChatInputContextPanelNode(context: context, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panel.interfaceInteraction = interfaceInteraction panel.updateResults(results) return panel @@ -158,7 +158,7 @@ func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfa currentPanel.updateResults(results) return currentPanel } else { - let panel = HorizontalListContextResultsChatInputContextPanelNode(account: account, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panel = HorizontalListContextResultsChatInputContextPanelNode(context: context, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panel.interfaceInteraction = interfaceInteraction panel.updateResults(results) return panel @@ -184,7 +184,7 @@ func chatOverlayContextPanelForChatPresentationIntefaceState(_ chatPresentationI currentPanel.updateResults(peers) return currentPanel } else { - let panel = MentionChatInputContextPanelNode(account: account, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, mode: .search) + let panel = MentionChatInputContextPanelNode(context: context, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, mode: .search) panel.interfaceInteraction = interfaceInteraction panel.updateResults(peers) return panel diff --git a/TelegramUI/ChatInterfaceInputNodes.swift b/TelegramUI/ChatInterfaceInputNodes.swift index 80f8b540e7..2dad572ed8 100644 --- a/TelegramUI/ChatInterfaceInputNodes.swift +++ b/TelegramUI/ChatInterfaceInputNodes.swift @@ -18,7 +18,7 @@ func inputNodeForChatPresentationIntefaceState(_ chatPresentationInterfaceState: if case let .peer(id) = chatPresentationInterfaceState.chatLocation { peerId = id } - let inputNode = ChatMediaInputNode(account: account, peerId: peerId, controllerInteraction: controllerInteraction, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, gifPaneIsActiveUpdated: { [weak interfaceInteraction] value in + let inputNode = ChatMediaInputNode(context: context, peerId: peerId, controllerInteraction: controllerInteraction, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, gifPaneIsActiveUpdated: { [weak interfaceInteraction] value in if let interfaceInteraction = interfaceInteraction { interfaceInteraction.updateInputModeAndDismissedButtonKeyboardMessageId { state in if case let .media(_, expanded) = state.inputMode { @@ -40,7 +40,7 @@ func inputNodeForChatPresentationIntefaceState(_ chatPresentationInterfaceState: if let currentNode = currentNode as? ChatButtonKeyboardInputNode { return currentNode } else { - let inputNode = ChatButtonKeyboardInputNode(account: account, controllerInteraction: controllerInteraction) + let inputNode = ChatButtonKeyboardInputNode(context: context, controllerInteraction: controllerInteraction) inputNode.interfaceInteraction = interfaceInteraction return inputNode } diff --git a/TelegramUI/ChatInterfaceStateContextMenus.swift b/TelegramUI/ChatInterfaceStateContextMenus.swift index 493ba0e296..b803557411 100644 --- a/TelegramUI/ChatInterfaceStateContextMenus.swift +++ b/TelegramUI/ChatInterfaceStateContextMenus.swift @@ -195,7 +195,7 @@ func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: } else if message.peers[message.id.peerId] is TelegramSecretChat { canDeleteMessage = true } else { - canDeleteMessage = account.peerId == message.author?.id + canDeleteMessage = context.account.peerId == message.author?.id } if messages[0].flags.intersection([.Failed, .Unsent]).isEmpty { @@ -233,7 +233,7 @@ func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: var loadStickerSaveStatusSignal: Signal = .single(nil) if loadStickerSaveStatus != nil { - loadStickerSaveStatusSignal = account.postbox.transaction { transaction -> Bool? in + loadStickerSaveStatusSignal = context.account.postbox.transaction { transaction -> Bool? in var starStatus: Bool? if let loadStickerSaveStatus = loadStickerSaveStatus { if getIsStickerSaved(transaction: transaction, fileId: loadStickerSaveStatus) { @@ -249,16 +249,16 @@ func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: var loadResourceStatusSignal: Signal = .single(nil) if let loadCopyMediaResource = loadCopyMediaResource { - loadResourceStatusSignal = account.postbox.mediaBox.resourceStatus(loadCopyMediaResource) + loadResourceStatusSignal = context.account.postbox.mediaBox.resourceStatus(loadCopyMediaResource) |> take(1) |> map(Optional.init) } - let loadLimits = account.postbox.transaction { transaction -> LimitsConfiguration in + let loadLimits = context.account.postbox.transaction { transaction -> LimitsConfiguration in return transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration ?? LimitsConfiguration.defaultValue } - dataSignal = combineLatest(loadLimits, loadStickerSaveStatusSignal, loadResourceStatusSignal, chatAvailableMessageActions(postbox: account.postbox, accountPeerId: account.peerId, messageIds: Set(messages.map { $0.id }))) + dataSignal = combineLatest(loadLimits, loadStickerSaveStatusSignal, loadResourceStatusSignal, chatAvailableMessageActions(postbox: context.account.postbox, accountPeerId: context.account.peerId, messageIds: Set(messages.map { $0.id }))) |> map { limitsConfiguration, stickerSaveStatus, resourceStatus, messageActions -> MessageContextMenuData in var canEdit = false if messages[0].id.namespace == Namespaces.Message.Cloud && !isAction { @@ -267,7 +267,7 @@ func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: var hasEditRights = false if message.id.peerId.namespace == Namespaces.Peer.SecretChat { hasEditRights = false - } else if let author = message.author, author.id == account.peerId { + } else if let author = message.author, author.id == context.account.peerId { hasEditRights = true } else if message.author?.id == message.id.peerId, let peer = message.peers[message.id.peerId] { if let peer = peer as? TelegramChannel, case .broadcast = peer.info { @@ -318,7 +318,7 @@ func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: } if !hasUneditableAttributes { - if canPerformEditingActions(limits: limitsConfiguration, accountPeerId: account.peerId, message: message) { + if canPerformEditingActions(limits: limitsConfiguration, accountPeerId: context.account.peerId, message: message) { canEdit = true } } @@ -362,27 +362,27 @@ func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: if resourceAvailable { for media in message.media { if let image = media as? TelegramMediaImage, let largest = largestImageRepresentation(image.representations) { - let _ = (account.postbox.mediaBox.resourceData(largest.resource, option: .incremental(waitUntilFetchStatus: false)) - |> take(1) - |> deliverOnMainQueue).start(next: { data in - if data.complete, let imageData = try? Data(contentsOf: URL(fileURLWithPath: data.path)) { - if let image = UIImage(data: imageData) { - if !message.text.isEmpty { - UIPasteboard.general.string = message.text - /*UIPasteboard.general.items = [ - [kUTTypeUTF8PlainText as String: message.text], - [kUTTypePNG as String: image] - ]*/ - } else { - UIPasteboard.general.image = image - } - } else { + let _ = (context.account.postbox.mediaBox.resourceData(largest.resource, option: .incremental(waitUntilFetchStatus: false)) + |> take(1) + |> deliverOnMainQueue).start(next: { data in + if data.complete, let imageData = try? Data(contentsOf: URL(fileURLWithPath: data.path)) { + if let image = UIImage(data: imageData) { + if !message.text.isEmpty { UIPasteboard.general.string = message.text + /*UIPasteboard.general.items = [ + [kUTTypeUTF8PlainText as String: message.text], + [kUTTypePNG as String: image] + ]*/ + } else { + UIPasteboard.general.image = image } } else { UIPasteboard.general.string = message.text } - }) + } else { + UIPasteboard.general.string = message.text + } + }) } } } else { @@ -433,7 +433,7 @@ func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: if messages[0].id.namespace == Namespaces.Message.Cloud { if message.id.peerId.namespace == Namespaces.Peer.SecretChat { hasEditRights = false - } else if let author = message.author, author.id == account.peerId { + } else if let author = message.author, author.id == context.account.peerId { hasEditRights = true } else if message.author?.id == message.id.peerId, let peer = message.peers[message.id.peerId] { if let peer = peer as? TelegramChannel, case .broadcast = peer.info { @@ -479,7 +479,7 @@ func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: if file.isVideo { if file.isAnimated { actions.append(.sheet(ChatMessageContextMenuSheetAction(color: .accent, title: chatPresentationInterfaceState.strings.Conversation_LinkDialogSave, action: { - let _ = addSavedGif(postbox: account.postbox, fileReference: .message(message: MessageReference(message), media: file)).start() + let _ = addSavedGif(postbox: context.account.postbox, fileReference: .message(message: MessageReference(message), media: file)).start() }))) } break @@ -510,7 +510,7 @@ func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: for media in message.media { if let action = media as? TelegramMediaAction, case let .phoneCall(id, discardReason, _) = action.action { if discardReason != .busy && discardReason != .missed { - if let logName = callLogNameForId(id: id, account: account) { + if let logName = callLogNameForId(id: id, account: context.account) { let start = logName.index(logName.startIndex, offsetBy: "\(id)".count + 1) let end = logName.index(logName.endIndex, offsetBy: -4) let accessHash = logName[start.. Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError> { +private func updatedContextQueryResultStateForQuery(context: AccountContext, peer: Peer, inputQuery: ChatPresentationInputQuery, previousQuery: ChatPresentationInputQuery?) -> Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError> { switch inputQuery { case let .emoji(query): var signal: Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError> = .complete() @@ -68,7 +68,7 @@ private func updatedContextQueryResultStateForQuery(account: Account, peer: Peer } else { signal = .single({ _ in return .stickers([]) }) } - let stickers: Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError> = account.postbox.transaction { transaction -> StickerSettings in + let stickers: Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError> = context.account.postbox.transaction { transaction -> StickerSettings in let stickerSettings: StickerSettings = (transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.stickerSettings) as? StickerSettings) ?? .defaultSettings return stickerSettings } @@ -82,7 +82,7 @@ private func updatedContextQueryResultStateForQuery(account: Account, peer: Peer case .installed: scope = [.installed] } - return searchStickers(account: account, query: query.firstEmoji, scope: scope) + return searchStickers(account: context.account, query: query.firstEmoji, scope: scope) } |> map { stickers -> (ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult? in return { _ in @@ -103,7 +103,7 @@ private func updatedContextQueryResultStateForQuery(account: Account, peer: Peer signal = .single({ _ in return .hashtags([]) }) } - let hashtags: Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError> = recentlyUsedHashtags(postbox: account.postbox) |> map { hashtags -> (ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult? in + let hashtags: Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError> = recentlyUsedHashtags(postbox: context.account.postbox) |> map { hashtags -> (ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult? in let normalizedQuery = query.lowercased() var result: [String] = [] for hashtag in hashtags { @@ -130,8 +130,8 @@ private func updatedContextQueryResultStateForQuery(account: Account, peer: Peer signal = .single({ _ in return .mentions([]) }) } - let inlineBots: Signal<[(Peer, Double)], NoError> = types.contains(.contextBots) ? recentlyUsedInlineBots(postbox: account.postbox) : .single([]) - let participants = combineLatest(inlineBots, searchPeerMembers(account: account, peerId: peer.id, query: query)) + let inlineBots: Signal<[(Peer, Double)], NoError> = types.contains(.contextBots) ? recentlyUsedInlineBots(postbox: context.account.postbox) : .single([]) + let participants = combineLatest(inlineBots, searchPeerMembers(context: context, peerId: peer.id, query: query)) |> map { inlineBots, peers -> (ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult? in let filteredInlineBots = inlineBots.sorted(by: { $0.1 > $1.1 }).filter { peer, rating in if rating < 0.14 { @@ -152,7 +152,7 @@ private func updatedContextQueryResultStateForQuery(account: Account, peer: Peer if inlineBotPeerIds.contains(peer.id) { return false } - if !types.contains(.accountPeer) && peer.id == account.peerId { + if !types.contains(.accountPeer) && peer.id == context.account.peerId { return false } return true @@ -184,7 +184,7 @@ private func updatedContextQueryResultStateForQuery(account: Account, peer: Peer signal = .single({ _ in return .commands([]) }) } - let participants = peerCommands(account: account, id: peer.id) + let participants = peerCommands(account: context.account, id: peer.id) |> map { commands -> (ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult? in let filteredCommands = commands.commands.filter { command in if command.command.text.hasPrefix(normalizedQuery) { @@ -215,21 +215,21 @@ private func updatedContextQueryResultStateForQuery(account: Account, peer: Peer } let chatPeer = peer - let contextBot = resolvePeerByName(account: account, name: addressName) + let contextBot = resolvePeerByName(account: context.account, name: addressName) |> mapToSignal { peerId -> Signal in if let peerId = peerId { - return account.postbox.loadedPeerWithId(peerId) - |> map { peer -> Peer? in - return peer - } - |> take(1) + return context.account.postbox.loadedPeerWithId(peerId) + |> map { peer -> Peer? in + return peer + } + |> take(1) } else { return .single(nil) } } |> mapToSignal { peer -> Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError> in if let user = peer as? TelegramUser, let botInfo = user.botInfo, let _ = botInfo.inlinePlaceholder { - let contextResults = requestChatContextResults(account: account, botId: user.id, peerId: chatPeer.id, query: query, offset: "") + let contextResults = requestChatContextResults(account: context.account, botId: user.id, peerId: chatPeer.id, query: query, offset: "") |> map { results -> (ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult? in return { _ in return .contextRequestResult(user, results) @@ -311,7 +311,7 @@ func searchQuerySuggestionResultStateForChatInterfacePresentationState(_ chatPre } } - let participants = searchPeerMembers(account: account, peerId: peer.id, query: query) + let participants = searchPeerMembers(context: context, peerId: peer.id, query: query) |> map { peers -> (ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult? in let filteredPeers = peers var sortedPeers: [Peer] = [] @@ -358,7 +358,7 @@ func urlPreviewStateForInputText(_ inputText: String?, context: AccountContext, if detectedUrl != currentQuery { if let detectedUrl = detectedUrl { - return (detectedUrl, webpagePreview(account: account, url: detectedUrl) |> map { value in + return (detectedUrl, webpagePreview(account: context.account, url: detectedUrl) |> map { value in return { _ in return value } }) } else { diff --git a/TelegramUI/ChatInterfaceTitlePanelNodes.swift b/TelegramUI/ChatInterfaceTitlePanelNodes.swift index c87f6ddef6..eb8c8c9684 100644 --- a/TelegramUI/ChatInterfaceTitlePanelNodes.swift +++ b/TelegramUI/ChatInterfaceTitlePanelNodes.swift @@ -43,7 +43,7 @@ func titlePanelForChatPresentationInterfaceState(_ chatPresentationInterfaceStat if let currentPanel = currentPanel as? ChatPinnedMessageTitlePanelNode { return currentPanel } else { - let panel = ChatPinnedMessageTitlePanelNode(account: account) + let panel = ChatPinnedMessageTitlePanelNode(context: context) panel.interfaceInteraction = interfaceInteraction return panel } diff --git a/TelegramUI/ChatItemGalleryFooterContentNode.swift b/TelegramUI/ChatItemGalleryFooterContentNode.swift index 21edf6cce1..e23597ecb2 100644 --- a/TelegramUI/ChatItemGalleryFooterContentNode.swift +++ b/TelegramUI/ChatItemGalleryFooterContentNode.swift @@ -551,7 +551,7 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { if messages.count == 1 { strongSelf.commitDeleteMessages(messages, ask: true) } else { - let presentationData = strongSelf.context.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } var generalMessageContentKind: MessageContentKind? for message in messages { let currentKind = messageContentKind(message, strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: strongSelf.context.account.peerId) diff --git a/TelegramUI/ChatListItem.swift b/TelegramUI/ChatListItem.swift index 215d45ca21..6b7371af83 100644 --- a/TelegramUI/ChatListItem.swift +++ b/TelegramUI/ChatListItem.swift @@ -515,7 +515,7 @@ class ChatListItemNode: ItemListRevealOptionsItemNode { summaryInfo = ChatListMessageTagSummaryInfo() inputActivities = nil isPeerGroup = true - multipleAvatarsApply = multipleAvatarsLayout(item.account, topPeersValue, CGSize(width: 60.0, height: 60.0)) + multipleAvatarsApply = multipleAvatarsLayout(item.account, item.presentationData.theme, topPeersValue, CGSize(width: 60.0, height: 60.0)) if counters.unreadCount > 0 { let count = counters.unreadCount + counters.unreadMutedCount unreadCount = (count, count > 0, false) diff --git a/TelegramUI/ChatMediaInputTrendingPane.swift b/TelegramUI/ChatMediaInputTrendingPane.swift index 04c2186e3d..4a67fe42b7 100644 --- a/TelegramUI/ChatMediaInputTrendingPane.swift +++ b/TelegramUI/ChatMediaInputTrendingPane.swift @@ -149,7 +149,7 @@ final class ChatMediaInputTrendingPane: ChatMediaInputPane { let interaction = TrendingPaneInteraction(installPack: { [weak self] info in if let strongSelf = self, let info = info as? StickerPackCollectionInfo { - let _ = (loadedStickerPack(postbox: strongSelf.context.account.postbox, network: strongSelf.account.network, reference: .id(id: info.id.id, accessHash: info.accessHash), forceActualized: false) + let _ = (loadedStickerPack(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, reference: .id(id: info.id.id, accessHash: info.accessHash), forceActualized: false) |> mapToSignal { result -> Signal in switch result { case let .result(info, items, installed): @@ -199,7 +199,7 @@ final class ChatMediaInputTrendingPane: ChatMediaInputPane { let entries = trendingPaneEntries(trendingEntries: trendingEntries, installedPacks: installedPacks, theme: presentationData.theme, strings: presentationData.strings) let previous = previousEntries.swap(entries) - return preparedTransition(from: previous ?? [], to: entries, account: account, interaction: interaction, initial: previous == nil) + return preparedTransition(from: previous ?? [], to: entries, account: context.account, interaction: interaction, initial: previous == nil) } |> deliverOnMainQueue).start(next: { [weak self] transition in guard let strongSelf = self else { diff --git a/TelegramUI/ChatMessageActionItemNode.swift b/TelegramUI/ChatMessageActionItemNode.swift index 16b4f4a9fe..3d4f09de01 100644 --- a/TelegramUI/ChatMessageActionItemNode.swift +++ b/TelegramUI/ChatMessageActionItemNode.swift @@ -585,8 +585,8 @@ class ChatMessageActionBubbleContentNode: ChatMessageBubbleContentNode { apply() } - strongSelf.fetchDisposable.set(chatMessagePhotoInteractiveFetched(account: item.account, photoReference: .message(message: MessageReference(item.message), media: image), storeToDownloadsPeerType: nil).start()) - let updateImageSignal = chatMessagePhoto(postbox: item.account.postbox, photoReference: .message(message: MessageReference(item.message), media: image)) + strongSelf.fetchDisposable.set(chatMessagePhotoInteractiveFetched(context: item.context, photoReference: .message(message: MessageReference(item.message), media: image), storeToDownloadsPeerType: nil).start()) + let updateImageSignal = chatMessagePhoto(postbox: item.context.account.postbox, photoReference: .message(message: MessageReference(item.message), media: image)) imageNode.setSignal(updateImageSignal) diff --git a/TelegramUI/ChatMessageInteractiveFileNode.swift b/TelegramUI/ChatMessageInteractiveFileNode.swift index 3422402377..7c61ef1736 100644 --- a/TelegramUI/ChatMessageInteractiveFileNode.swift +++ b/TelegramUI/ChatMessageInteractiveFileNode.swift @@ -204,16 +204,16 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { updatedFetchControls = FetchControls(fetch: { [weak self] in if let strongSelf = self { - strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: file, userInitiated: true).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(context: context, message: message, file: file, userInitiated: true).start()) } }, cancel: { - messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: file) + messageMediaFileCancelInteractiveFetch(context: context, messageId: message.id, file: file) }) } if statusUpdated { - updatedStatusSignal = messageFileMediaResourceStatus(account: context.account, file: file, message: message, isRecentActions: isRecentActions) - updatedPlaybackStatusSignal = messageFileMediaPlaybackStatus(account: context.account, file: file, message: message, isRecentActions: isRecentActions) + updatedStatusSignal = messageFileMediaResourceStatus(context: context, file: file, message: message, isRecentActions: isRecentActions) + updatedPlaybackStatusSignal = messageFileMediaPlaybackStatus(context: context, file: file, message: message, isRecentActions: isRecentActions) } var statusSize: CGSize? diff --git a/TelegramUI/ChatMessageInteractiveInstantVideoNode.swift b/TelegramUI/ChatMessageInteractiveInstantVideoNode.swift index 6c92f801ce..2d442a2923 100644 --- a/TelegramUI/ChatMessageInteractiveInstantVideoNode.swift +++ b/TelegramUI/ChatMessageInteractiveInstantVideoNode.swift @@ -181,7 +181,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { var updatedPlaybackStatus: Signal? if let updatedFile = updatedFile, updatedMedia { - updatedPlaybackStatus = combineLatest(messageFileMediaResourceStatus(account: item.context.account, file: updatedFile, message: item.message, isRecentActions: item.associatedData.isRecentActions), item.context.account.pendingMessageManager.pendingMessageStatus(item.message.id)) + updatedPlaybackStatus = combineLatest(messageFileMediaResourceStatus(context: item.context, file: updatedFile, message: item.message, isRecentActions: item.associatedData.isRecentActions), item.context.account.pendingMessageManager.pendingMessageStatus(item.message.id)) |> map { resourceStatus, pendingStatus -> FileMediaResourceStatus in if let pendingStatus = pendingStatus { var progress = pendingStatus.progress @@ -364,7 +364,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { if let strongSelf = self { if let item = strongSelf.item { if strongSelf.infoBackgroundNode.alpha.isZero { - item.context.account.telegramApplicationContext.mediaManager?.playlistControl(.playback(.togglePlayPause), type: .voice) + item.context.mediaManager.playlistControl(.playback(.togglePlayPause), type: .voice) } else { //let _ = item.controllerInteraction.openMessage(item.message) } @@ -407,7 +407,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { strongSelf.updateStatus() if let telegramFile = updatedFile, previousAutomaticDownload != automaticDownload, automaticDownload { - strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: item.context.account, message: item.message, file: telegramFile, userInitiated: false).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(context: item.context, message: item.message, file: telegramFile, userInitiated: false).start()) } } }) @@ -545,7 +545,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { } playbackStatusNode.frame = videoFrame.insetBy(dx: 1.5, dy: 1.5) - let status = messageFileMediaPlaybackStatus(account: item.context.account, file: file, message: item.message, isRecentActions: item.associatedData.isRecentActions) + let status = messageFileMediaPlaybackStatus(context: item.context, file: file, message: item.message, isRecentActions: item.associatedData.isRecentActions) playbackStatusNode.status = status self.durationNode?.status = status |> map(Optional.init) @@ -637,7 +637,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { deleteMessages(transaction: transaction, mediaBox: item.context.account.postbox.mediaBox, ids: [messageId]) }).start() } else { - messageMediaFileCancelInteractiveFetch(account: item.context.account, messageId: item.message.id, file: file) + messageMediaFileCancelInteractiveFetch(context: item.context, messageId: item.message.id, file: file) } case .Remote: self.videoNode?.fetchControl(.fetch) diff --git a/TelegramUI/ChatMessageInteractiveMediaNode.swift b/TelegramUI/ChatMessageInteractiveMediaNode.swift index 5d4cbfb5c9..d66cff8455 100644 --- a/TelegramUI/ChatMessageInteractiveMediaNode.swift +++ b/TelegramUI/ChatMessageInteractiveMediaNode.swift @@ -105,9 +105,9 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { }).start() } else if let media = media, let context = self.context, let message = message { if let media = media as? TelegramMediaFile { - messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: media) + messageMediaFileCancelInteractiveFetch(context: context, messageId: message.id, file: media) } else if let media = media as? TelegramMediaImage, let resource = largestImageRepresentation(media.representations)?.resource { - messageMediaImageCancelInteractiveFetch(account: context.account, messageId: message.id, image: media, resource: resource) + messageMediaImageCancelInteractiveFetch(context: context, messageId: message.id, image: media, resource: resource) } } if let cancel = self.fetchControls.with({ return $0?.cancel }) { @@ -296,15 +296,15 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { updatedFetchControls = FetchControls(fetch: { manual in if let strongSelf = self { if !manual { - strongSelf.fetchDisposable.set(chatMessagePhotoInteractiveFetched(account: context.account, photoReference: .message(message: MessageReference(message), media: image), storeToDownloadsPeerType: storeToDownloadsPeerType).start()) + strongSelf.fetchDisposable.set(chatMessagePhotoInteractiveFetched(context: context, photoReference: .message(message: MessageReference(message), media: image), storeToDownloadsPeerType: storeToDownloadsPeerType).start()) } else if let resource = largestRepresentationForPhoto(image)?.resource { - strongSelf.fetchDisposable.set(messageMediaImageInteractiveFetched(account: context.account, message: message, image: image, resource: resource, storeToDownloadsPeerType: storeToDownloadsPeerType).start()) + strongSelf.fetchDisposable.set(messageMediaImageInteractiveFetched(context: context, message: message, image: image, resource: resource, storeToDownloadsPeerType: storeToDownloadsPeerType).start()) } } }, cancel: { chatMessagePhotoCancelInteractiveFetch(account: context.account, photoReference: .message(message: MessageReference(message), media: image)) if let resource = largestRepresentationForPhoto(image)?.resource { - messageMediaImageCancelInteractiveFetch(account: context.account, messageId: message.id, image: image, resource: resource) + messageMediaImageCancelInteractiveFetch(context: context, messageId: message.id, image: image, resource: resource) } }) } else if let image = media as? TelegramMediaWebFile { @@ -359,14 +359,14 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { if file.isAnimated { strongSelf.fetchDisposable.set(fetchedMediaResource(postbox: context.account.postbox, reference: AnyMediaReference.message(message: MessageReference(message), media: file).resourceReference(file.resource), statsCategory: statsCategoryForFileWithAttributes(file.attributes)).start()) } else { - strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: file, userInitiated: manual).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(context: context, message: message, file: file, userInitiated: manual).start()) } } }, cancel: { if file.isAnimated { context.account.postbox.mediaBox.cancelInteractiveResourceFetch(file.resource) } else { - messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: file) + messageMediaFileCancelInteractiveFetch(context: context, messageId: message.id, file: file) } }) } @@ -375,7 +375,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { if statusUpdated { if let image = media as? TelegramMediaImage { if message.flags.isSending { - updatedStatusSignal = combineLatest(chatMessagePhotoStatus(account: context.account, messageId: message.id, photoReference: .message(message: MessageReference(message), media: image)), context.account.pendingMessageManager.pendingMessageStatus(message.id)) + updatedStatusSignal = combineLatest(chatMessagePhotoStatus(context: context, messageId: message.id, photoReference: .message(message: MessageReference(message), media: image)), context.account.pendingMessageManager.pendingMessageStatus(message.id)) |> map { resourceStatus, pendingStatus -> MediaResourceStatus in if let pendingStatus = pendingStatus { let adjustedProgress = max(pendingStatus.progress, 0.027) @@ -385,10 +385,10 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { } } } else { - updatedStatusSignal = chatMessagePhotoStatus(account: context.account, messageId: message.id, photoReference: .message(message: MessageReference(message), media: image)) + updatedStatusSignal = chatMessagePhotoStatus(context: context, messageId: message.id, photoReference: .message(message: MessageReference(message), media: image)) } } else if let file = media as? TelegramMediaFile { - updatedStatusSignal = combineLatest(messageMediaFileStatus(account: context.account, messageId: message.id, file: file), account.pendingMessageManager.pendingMessageStatus(message.id)) + updatedStatusSignal = combineLatest(messageMediaFileStatus(context: context, messageId: message.id, file: file), context.account.pendingMessageManager.pendingMessageStatus(message.id)) |> map { resourceStatus, pendingStatus -> MediaResourceStatus in if let pendingStatus = pendingStatus { let adjustedProgress = max(pendingStatus.progress, 0.027) @@ -500,7 +500,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { strongSelf.fetchDisposable.set(chatMessageWebFileInteractiveFetched(account: context.account, image: image).start()) } else if let file = media as? TelegramMediaFile { if automaticPlayback || !file.isAnimated { - strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: file, userInitiated: false).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(context: context, message: message, file: file, userInitiated: false).start()) } } } diff --git a/TelegramUI/ChatMessageLiveLocationPositionNode.swift b/TelegramUI/ChatMessageLiveLocationPositionNode.swift index f801b92945..4d411e643f 100644 --- a/TelegramUI/ChatMessageLiveLocationPositionNode.swift +++ b/TelegramUI/ChatMessageLiveLocationPositionNode.swift @@ -94,7 +94,7 @@ final class ChatMessageLiveLocationPositionNode: ASDisplayNode { strongSelf.backgroundNode.frame = CGRect(origin: CGPoint(), size: CGSize(width: 62.0, height: 74.0)) strongSelf.avatarNode.frame = CGRect(origin: CGPoint(x: 10.0, y: 9.0), size: CGSize(width: 42.0, height: 42.0)) if let peer = peer { - strongSelf.avatarNode.setPeer(account: account, peer: peer) + strongSelf.avatarNode.setPeer(account: account, theme: theme, peer: peer) strongSelf.avatarNode.isHidden = false if let liveActive = liveActive { diff --git a/TelegramUI/ChatMessageNotificationItem.swift b/TelegramUI/ChatMessageNotificationItem.swift index d9280ce2f8..3e6d5f72f4 100644 --- a/TelegramUI/ChatMessageNotificationItem.swift +++ b/TelegramUI/ChatMessageNotificationItem.swift @@ -6,7 +6,7 @@ import TelegramCore import SwiftSignalKit public final class ChatMessageNotificationItem: NotificationItem { - let account: Account + let context: AccountContext let strings: PresentationStrings let nameDisplayOrder: PresentationPersonNameOrder let messages: [Message] @@ -17,8 +17,8 @@ public final class ChatMessageNotificationItem: NotificationItem { return messages.first?.id.peerId } - public init(account: Account, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder, messages: [Message], tapAction: @escaping () -> Bool, expandAction: @escaping (() -> (ASDisplayNode?, () -> Void)) -> Void) { - self.account = account + public init(context: AccountContext, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder, messages: [Message], tapAction: @escaping () -> Bool, expandAction: @escaping (() -> (ASDisplayNode?, () -> Void)) -> Void) { + self.context = context self.strings = strings self.nameDisplayOrder = nameDisplayOrder self.messages = messages @@ -96,11 +96,11 @@ final class ChatMessageNotificationItemNode: NotificationItemNode { if compact { self.avatarNode.font = compactAvatarFont } - let presentationData = item.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = item.context.currentPresentationData.with { $0 } var title: String? if let firstMessage = item.messages.first, let peer = messageMainPeer(firstMessage) { - self.avatarNode.setPeer(account: item.account, peer: peer, emptyColor: presentationData.theme.list.mediaPlaceholderColor) + self.avatarNode.setPeer(account: item.context.account, theme: presentationData.theme, peer: peer, emptyColor: presentationData.theme.list.mediaPlaceholderColor) if let channel = peer as? TelegramChannel, case .broadcast = channel.info { title = peer.displayTitle(strings: item.strings, displayOrder: item.nameDisplayOrder) @@ -140,7 +140,7 @@ final class ChatMessageNotificationItemNode: NotificationItemNode { if message.containsSecretMedia { imageDimensions = nil } - messageText = descriptionStringForMessage(message, strings: item.strings, nameDisplayOrder: item.nameDisplayOrder, accountPeerId: item.account.peerId).0 + messageText = descriptionStringForMessage(message, strings: item.strings, nameDisplayOrder: item.nameDisplayOrder, accountPeerId: item.context.account.peerId).0 } else if item.messages.count > 1, let peer = item.messages[0].peers[item.messages[0].id.peerId] { var displayAuthor = true if let channel = peer as? TelegramChannel { @@ -175,9 +175,9 @@ final class ChatMessageNotificationItemNode: NotificationItemNode { } } } else if item.messages[0].groupingKey != nil { - var kind = messageContentKind(item.messages[0], strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: item.account.peerId).key + var kind = messageContentKind(item.messages[0], strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: item.context.account.peerId).key for i in 1 ..< item.messages.count { - let nextKind = messageContentKind(item.messages[i], strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: item.account.peerId) + let nextKind = messageContentKind(item.messages[i], strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: item.context.account.peerId) if kind != nextKind.key { kind = .text break @@ -281,12 +281,12 @@ final class ChatMessageNotificationItemNode: NotificationItemNode { var updateImageSignal: Signal<(TransformImageArguments) -> DrawingContext?, NoError>? if let firstMessage = item.messages.first, let updatedMedia = updatedMedia, imageDimensions != nil { if let image = updatedMedia as? TelegramMediaImage { - updateImageSignal = mediaGridMessagePhoto(account: item.account, photoReference: .message(message: MessageReference(firstMessage), media: image)) + updateImageSignal = mediaGridMessagePhoto(account: item.context.account, photoReference: .message(message: MessageReference(firstMessage), media: image)) } else if let file = updatedMedia as? TelegramMediaFile { if file.isSticker { - updateImageSignal = chatMessageSticker(account: item.account, file: file, small: true, fetched: true) + updateImageSignal = chatMessageSticker(account: item.context.account, file: file, small: true, fetched: true) } else if file.isVideo { - updateImageSignal = mediaGridMessageVideo(postbox: item.account.postbox, videoReference: .message(message: MessageReference(firstMessage), media: file)) + updateImageSignal = mediaGridMessageVideo(postbox: item.context.account.postbox, videoReference: .message(message: MessageReference(firstMessage), media: file)) } } } diff --git a/TelegramUI/ChatMultipleAvatarsNavigationNode.swift b/TelegramUI/ChatMultipleAvatarsNavigationNode.swift index 6c5dd8caa3..fb37ea6fe6 100644 --- a/TelegramUI/ChatMultipleAvatarsNavigationNode.swift +++ b/TelegramUI/ChatMultipleAvatarsNavigationNode.swift @@ -8,6 +8,7 @@ final class ChatMultipleAvatarsNavigationNode: ASDisplayNode { private let multipleAvatarsNode: MultipleAvatarsNode private weak var account: Account? + private var theme: PresentationTheme? private var peers: [Peer] = [] override init() { @@ -30,9 +31,9 @@ final class ChatMultipleAvatarsNavigationNode: ASDisplayNode { super.layout() let bounds = self.bounds - if let account = self.account, !bounds.width.isZero { + if let account = self.account, let theme = self.theme, !bounds.width.isZero { let avatarsLayout = MultipleAvatarsNode.asyncLayout(self.multipleAvatarsNode) - let apply = avatarsLayout(account, self.peers, bounds.size) + let apply = avatarsLayout(account, theme, self.peers, bounds.size) let _ = apply(false) } if self.bounds.size.height.isLessThanOrEqualTo(26.0) { @@ -42,14 +43,14 @@ final class ChatMultipleAvatarsNavigationNode: ASDisplayNode { } } - func setPeers(account: Account, peers: [Peer], animated: Bool) { + func setPeers(account: Account, theme: PresentationTheme, peers: [Peer], animated: Bool) { self.account = account self.peers = peers let bounds = self.bounds if !bounds.width.isZero { let avatarsLayout = MultipleAvatarsNode.asyncLayout(self.multipleAvatarsNode) - let apply = avatarsLayout(account, peers, bounds.size) + let apply = avatarsLayout(account, theme, peers, bounds.size) let _ = apply(animated) } } diff --git a/TelegramUI/ChatRecentActionsController.swift b/TelegramUI/ChatRecentActionsController.swift index 4c5dd97486..9b0a80d4f2 100644 --- a/TelegramUI/ChatRecentActionsController.swift +++ b/TelegramUI/ChatRecentActionsController.swift @@ -176,7 +176,7 @@ final class ChatRecentActionsController: TelegramController { } private func openFilterSetup() { - self.present(channelRecentActionsFilterController(account: self.account, peer: self.peer, events: self.controllerNode.filter.events, adminPeerIds: self.controllerNode.filter.adminPeerIds, apply: { [weak self] events, adminPeerIds in + self.present(channelRecentActionsFilterController(context: self.context, peer: self.peer, events: self.controllerNode.filter.events, adminPeerIds: self.controllerNode.filter.adminPeerIds, apply: { [weak self] events, adminPeerIds in self?.controllerNode.updateFilter(events: events, adminPeerIds: adminPeerIds) self?.updateTitle() }), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) diff --git a/TelegramUI/ChatRecentActionsFilterController.swift b/TelegramUI/ChatRecentActionsFilterController.swift index f12cfe55fe..71259bec15 100644 --- a/TelegramUI/ChatRecentActionsFilterController.swift +++ b/TelegramUI/ChatRecentActionsFilterController.swift @@ -433,7 +433,7 @@ public func channelRecentActionsFilterController(context: AccountContext, peer: adminsPromise.set(.single(nil)) - let (membersDisposable, _) = context.peerChannelMemberCategoriesContextsManager.admins(postbox: context.account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peer.id) { membersState in + let (membersDisposable, _) = context.peerChannelMemberCategoriesContextsManager.admins(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peer.id) { membersState in if case .loading = membersState.loadingState, membersState.list.isEmpty { adminsPromise.set(.single(nil)) } else { diff --git a/TelegramUI/ChatTextInputPanelNode.swift b/TelegramUI/ChatTextInputPanelNode.swift index 89d543f06c..9a757c8312 100644 --- a/TelegramUI/ChatTextInputPanelNode.swift +++ b/TelegramUI/ChatTextInputPanelNode.swift @@ -257,7 +257,7 @@ class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDelegate { override var context: AccountContext? { didSet { - self.actionButtons.micButton.account = self.context.account + self.actionButtons.micButton.account = self.context?.account } } diff --git a/TelegramUI/CheckDeviceAccess.swift b/TelegramUI/CheckDeviceAccess.swift index 576c591a1f..533394fb1e 100644 --- a/TelegramUI/CheckDeviceAccess.swift +++ b/TelegramUI/CheckDeviceAccess.swift @@ -81,7 +81,7 @@ public final class DeviceAccess { return AVAudioSession.sharedInstance().recordPermission() == .granted } - public static func authorizationStatus(account: Account? = nil, subject: DeviceAccessSubject) -> Signal { + public static func authorizationStatus(context: AccountContext? = nil, subject: DeviceAccessSubject) -> Signal { switch subject { case .notifications: let status = (Signal { subscriber in @@ -124,8 +124,8 @@ public final class DeviceAccess { return .complete() } }) - if let account = account { - return account.telegramApplicationContext.applicationBindings.applicationInForeground + if let context = context { + return context.applicationBindings.applicationInForeground |> distinctUntilChanged |> mapToSignal { inForeground -> Signal in return status @@ -196,9 +196,9 @@ public final class DeviceAccess { return EmptyDisposable } case .siri: - if let account = account { + if let context = context { return Signal { subscriber in - let status = account.telegramApplicationContext.applicationBindings.siriAuthorization() + let status = context.applicationBindings.siriAuthorization() subscriber.putNext(status) subscriber.putCompletion() return EmptyDisposable @@ -219,7 +219,7 @@ public final class DeviceAccess { } } - public static func authorizeAccess(to subject: DeviceAccessSubject, account: Account? = nil, presentationData: PresentationData? = nil, present: @escaping (ViewController, Any?) -> Void = { _, _ in }, openSettings: @escaping () -> Void = { }, displayNotificationFromBackground: @escaping (String) -> Void = { _ in }, _ completion: @escaping (Bool) -> Void = { _ in }) { + public static func authorizeAccess(to subject: DeviceAccessSubject, context: AccountContext? = nil, presentationData: PresentationData? = nil, present: @escaping (ViewController, Any?) -> Void = { _, _ in }, openSettings: @escaping () -> Void = { }, displayNotificationFromBackground: @escaping (String) -> Void = { _ in }, _ completion: @escaping (Bool) -> Void = { _ in }) { switch subject { case .camera: let status = PGCamera.cameraAuthorizationStatus() @@ -404,15 +404,15 @@ public final class DeviceAccess { } }) case .notifications: - if let account = account { - account.telegramApplicationContext.applicationBindings.registerForNotifications { result in + if let context = context { + context.applicationBindings.registerForNotifications { result in self.notificationsPromise.set(.single(result)) completion(result) } } case .siri: - if let account = account { - account.telegramApplicationContext.applicationBindings.requestSiriAuthorization { result in + if let context = context { + context.applicationBindings.requestSiriAuthorization { result in self.siriPromise.set(.single(result)) completion(result) } diff --git a/TelegramUI/CheckDiskSpace.swift b/TelegramUI/CheckDiskSpace.swift index d6fe0cb922..6980f04850 100644 --- a/TelegramUI/CheckDiskSpace.swift +++ b/TelegramUI/CheckDiskSpace.swift @@ -20,14 +20,14 @@ func freeDiskSpace() -> Int64 { } } -func checkAvailableDiskSpace(account: Account, threshold: Int64 = 100 * 1024 * 1024, present: @escaping (ViewController, Any?) -> Void) -> Bool { +func checkAvailableDiskSpace(context: AccountContext, threshold: Int64 = 100 * 1024 * 1024, present: @escaping (ViewController, Any?) -> Void) -> Bool { guard freeDiskSpace() < threshold else { return true } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - let controller = textAlertController(account: account, title: nil, text: presentationData.strings.Cache_LowDiskSpaceText, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: { - let controller = storageUsageController(account: account, isModal: true) + let presentationData = context.currentPresentationData.with { $0 } + let controller = textAlertController(context: context, title: nil, text: presentationData.strings.Cache_LowDiskSpaceText, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: { + let controller = storageUsageController(context: context, isModal: true) present(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }), TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]) diff --git a/TelegramUI/ComposeController.swift b/TelegramUI/ComposeController.swift index b3eda898a2..19e7ddbb30 100644 --- a/TelegramUI/ComposeController.swift +++ b/TelegramUI/ComposeController.swift @@ -116,7 +116,7 @@ public class ComposeController: ViewController { strongSelf.createActionDisposable.set((controller.result |> deliverOnMainQueue).start(next: { [weak controller] peerIds in if let strongSelf = self, let controller = controller { - let createGroup = createGroupController(account: strongSelf.account, peerIds: peerIds.compactMap({ peerId in + let createGroup = createGroupController(context: strongSelf.context, peerIds: peerIds.compactMap({ peerId in if case let .peer(peerId) = peerId { return peerId } else { @@ -138,14 +138,14 @@ public class ComposeController: ViewController { if let strongSelf = self, let contactPeer = peer, case let .peer(peer, _) = contactPeer { controller?.dismissSearch() controller?.displayNavigationActivity = true - strongSelf.createActionDisposable.set((createSecretChat(account: strongSelf.account, peerId: peer.id) |> deliverOnMainQueue).start(next: { peerId in + strongSelf.createActionDisposable.set((createSecretChat(account: strongSelf.context.account, peerId: peer.id) |> deliverOnMainQueue).start(next: { peerId in if let strongSelf = self, let controller = controller { controller.displayNavigationActivity = false - (controller.navigationController as? NavigationController)?.replaceAllButRootController(ChatController(account: strongSelf.account, chatLocation: .peer(peerId)), animated: true) + (controller.navigationController as? NavigationController)?.replaceAllButRootController(ChatController(context: strongSelf.context, chatLocation: .peer(peerId)), animated: true) } }, error: { _ in if let strongSelf = self, let controller = controller { - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } controller.displayNavigationActivity = false controller.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.Login_UnknownError, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), in: .window(.root)) diff --git a/TelegramUI/ContactListNode.swift b/TelegramUI/ContactListNode.swift index 8925722cc8..085a918bcd 100644 --- a/TelegramUI/ContactListNode.swift +++ b/TelegramUI/ContactListNode.swift @@ -769,11 +769,11 @@ final class ContactListNode: ASDisplayNode { if value != self.enableUpdatesValue { self.enableUpdatesValue = value if value { - self.contactPeersViewPromise.set(self.context.account.postbox.contactPeersView(accountPeerId: self.account.peerId, includePresences: true) |> mapToThrottled { next -> Signal in + self.contactPeersViewPromise.set(self.context.account.postbox.contactPeersView(accountPeerId: self.context.account.peerId, includePresences: true) |> mapToThrottled { next -> Signal in return .single(next) |> then(.complete() |> delay(5.0, queue: Queue.concurrentDefaultQueue())) }) } else { - self.contactPeersViewPromise.set(self.context.account.postbox.contactPeersView(accountPeerId: self.account.peerId, includePresences: true) |> take(1)) + self.contactPeersViewPromise.set(self.context.account.postbox.contactPeersView(accountPeerId: self.context.account.peerId, includePresences: true) |> take(1)) } } } @@ -814,7 +814,7 @@ final class ContactListNode: ASDisplayNode { let contactsAuthorization = Promise() contactsAuthorization.set(.single(.allowed) - |> then(DeviceAccess.authorizationStatus(account: context.account, subject: .contacts))) + |> then(DeviceAccess.authorizationStatus(context: context, subject: .contacts))) let warningKey = PostboxViewKey.noticeEntry(ApplicationSpecificNotice.contactsPermissionWarningKey()) let preferencesKey = PostboxViewKey.preferences(keys: Set([ApplicationSpecificPreferencesKeys.contactSynchronizationSettings])) @@ -945,7 +945,7 @@ final class ContactListNode: ASDisplayNode { resultPeers.append(mainPeer) } } - return account.postbox.transaction { transaction -> ([Peer], [PeerId : PeerPresence]) in + return context.account.postbox.transaction { transaction -> ([Peer], [PeerId : PeerPresence]) in var resultPresences: [PeerId: PeerPresence] = [:] for peer in resultPeers { if let presence = transaction.getPeerPresence(peerId: peer.id) { @@ -1181,7 +1181,7 @@ final class ContactListNode: ASDisplayNode { } authorizeImpl = { - let _ = (DeviceAccess.authorizationStatus(account: context.account, subject: .contacts) + let _ = (DeviceAccess.authorizationStatus(context: context, subject: .contacts) |> take(1) |> deliverOnMainQueue).start(next: { status in switch status { diff --git a/TelegramUI/ContactMultiselectionControllerNode.swift b/TelegramUI/ContactMultiselectionControllerNode.swift index 8767ecdb8a..1d80ded30d 100644 --- a/TelegramUI/ContactMultiselectionControllerNode.swift +++ b/TelegramUI/ContactMultiselectionControllerNode.swift @@ -45,7 +45,7 @@ final class ContactMultiselectionControllerNode: ASDisplayNode { private var presentationDataDisposable: Disposable? init(context: AccountContext, mode: ContactMultiselectionControllerMode, options: [ContactListAdditionalOption], filters: [ContactListFilter]) { - self.account = account + self.context = context self.presentationData = context.currentPresentationData.with { $0 } let placeholder: String diff --git a/TelegramUI/ContactSelectionController.swift b/TelegramUI/ContactSelectionController.swift index 90d27ae0e7..9e6857ce57 100644 --- a/TelegramUI/ContactSelectionController.swift +++ b/TelegramUI/ContactSelectionController.swift @@ -88,7 +88,7 @@ class ContactSelectionController: ViewController { } } - self.presentationDataDisposable = (account.telegramApplicationContext.presentationData + self.presentationDataDisposable = (context.presentationData |> deliverOnMainQueue).start(next: { [weak self] presentationData in if let strongSelf = self { let previousTheme = strongSelf.presentationData.theme diff --git a/TelegramUI/ContactsController.swift b/TelegramUI/ContactsController.swift index d48e087de1..a2bad08e61 100644 --- a/TelegramUI/ContactsController.swift +++ b/TelegramUI/ContactsController.swift @@ -121,7 +121,7 @@ public class ContactsController: ViewController { let preferencesKey = PostboxViewKey.preferences(keys: Set([ApplicationSpecificPreferencesKeys.contactSynchronizationSettings])) if #available(iOSApplicationExtension 10.0, *) { let warningKey = PostboxViewKey.noticeEntry(ApplicationSpecificNotice.contactsPermissionWarningKey()) - self.authorizationDisposable = (combineLatest(DeviceAccess.authorizationStatus(account: context.account, subject: .contacts), context.account.postbox.combinedView(keys: [warningKey, preferencesKey]) + self.authorizationDisposable = (combineLatest(DeviceAccess.authorizationStatus(context: context, subject: .contacts), context.account.postbox.combinedView(keys: [warningKey, preferencesKey]) |> map { combined -> (Bool, ContactsSortOrder) in let settings = ((combined.views[preferencesKey] as? PreferencesView)?.values[ApplicationSpecificPreferencesKeys.contactSynchronizationSettings] as? ContactSynchronizationSettings) let synchronizeDeviceContacts: Bool = settings?.synchronizeDeviceContacts ?? true @@ -335,7 +335,7 @@ public class ContactsController: ViewController { } @objc func addPressed() { - let _ = (DeviceAccess.authorizationStatus(account: self.context.account, subject: .contacts) + let _ = (DeviceAccess.authorizationStatus(context: self.context, subject: .contacts) |> take(1) |> deliverOnMainQueue).start(next: { [weak self] status in guard let strongSelf = self else { @@ -358,11 +358,11 @@ public class ContactsController: ViewController { } })), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) case .notDetermined: - DeviceAccess.authorizeAccess(to: .contacts, account: strongSelf.context.account) + DeviceAccess.authorizeAccess(to: .contacts, context: strongSelf.context) default: let presentationData = strongSelf.presentationData strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: presentationData.strings.AccessDenied_Title, text: presentationData.strings.Contacts_AccessDeniedError, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: { - self?.account.telegramApplicationContext.applicationBindings.openSettings() + self?.context.applicationBindings.openSettings() })]), in: .window(.root)) } }) diff --git a/TelegramUI/ContactsControllerNode.swift b/TelegramUI/ContactsControllerNode.swift index 6daa4fe2ff..22a5759d24 100644 --- a/TelegramUI/ContactsControllerNode.swift +++ b/TelegramUI/ContactsControllerNode.swift @@ -69,7 +69,7 @@ final class ContactsControllerNode: ASDisplayNode { }) inviteImpl = { [weak self] in - let _ = (DeviceAccess.authorizationStatus(account: account, subject: .contacts) + let _ = (DeviceAccess.authorizationStatus(context: context, subject: .contacts) |> take(1) |> deliverOnMainQueue).start(next: { value in guard let strongSelf = self else { diff --git a/TelegramUI/ContactsSearchContainerNode.swift b/TelegramUI/ContactsSearchContainerNode.swift index ee865658a4..cf1f85c319 100644 --- a/TelegramUI/ContactsSearchContainerNode.swift +++ b/TelegramUI/ContactsSearchContainerNode.swift @@ -139,7 +139,7 @@ final class ContactsSearchContainerNode: SearchDisplayControllerContentNode { private var enqueuedTransitions: [ContactListSearchContainerTransition] = [] init(context: AccountContext, onlyWriteable: Bool, categories: ContactsSearchCategories, filters: [ContactListFilter] = [.excludeSelf], openPeer: @escaping (ContactListPeer) -> Void) { - self.account = account + self.context = context self.openPeer = openPeer self.presentationData = context.currentPresentationData.with { $0 } @@ -169,7 +169,7 @@ final class ContactsSearchContainerNode: SearchDisplayControllerContentNode { if let query = query, !query.isEmpty { let foundLocalContacts: Signal<([Peer], [PeerId: PeerPresence]), NoError> if categories.contains(.cloudContacts) { - foundLocalContacts = account.postbox.searchContacts(query: query.lowercased()) + foundLocalContacts = context.account.postbox.searchContacts(query: query.lowercased()) } else { foundLocalContacts = .single(([], [:])) } @@ -177,7 +177,7 @@ final class ContactsSearchContainerNode: SearchDisplayControllerContentNode { if categories.contains(.global) { foundRemoteContacts = .single(nil) |> then( - searchPeers(account: account, query: query) + searchPeers(account: context.account, query: query) |> map { ($0.0, $0.1) } |> delay(0.2, queue: Queue.concurrentDefaultQueue()) ) diff --git a/TelegramUI/ConvertToSupergroupController.swift b/TelegramUI/ConvertToSupergroupController.swift index b3893bea39..3ac85f5769 100644 --- a/TelegramUI/ConvertToSupergroupController.swift +++ b/TelegramUI/ConvertToSupergroupController.swift @@ -142,7 +142,7 @@ public func convertToSupergroupController(context: AccountContext, peerId: PeerI if !alreadyConverting { convertDisposable.set((convertGroupToSupergroup(account: context.account, peerId: peerId) |> deliverOnMainQueue).start(next: { createdPeerId in - replaceControllerImpl?(ChatController(account: context.account, chatLocation: .peer(createdPeerId))) + replaceControllerImpl?(ChatController(context: context, chatLocation: .peer(createdPeerId))) })) } })]), nil) diff --git a/TelegramUI/CreateChannelController.swift b/TelegramUI/CreateChannelController.swift index f09de7cb20..ee97fcc7a1 100644 --- a/TelegramUI/CreateChannelController.swift +++ b/TelegramUI/CreateChannelController.swift @@ -266,7 +266,7 @@ public func createChannelController(context: AccountContext) -> ViewController { return state.editingName.composedTitle } - let _ = (account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in + let _ = (context.account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in return (transaction.getPeer(context.account.peerId), currentSearchBotsConfiguration(transaction: transaction)) } |> deliverOnMainQueue).start(next: { peer, searchBotsConfiguration in let presentationData = context.currentPresentationData.with { $0 } @@ -287,9 +287,9 @@ public func createChannelController(context: AccountContext) -> ViewController { let completedImpl: (UIImage) -> Void = { image in if let data = UIImageJPEGRepresentation(image, 0.6) { let resource = LocalFileMediaResource(fileId: arc4random64()) - account.postbox.mediaBox.storeResourceData(resource.id, data: data) + context.account.postbox.mediaBox.storeResourceData(resource.id, data: data) let representation = TelegramMediaImageRepresentation(dimensions: CGSize(width: 640.0, height: 640.0), resource: resource) - uploadedAvatar.set(uploadedPeerPhoto(postbox: account.postbox, network: account.network, resource: resource)) + uploadedAvatar.set(uploadedPeerPhoto(postbox: context.account.postbox, network: context.account.network, resource: resource)) updateState { current in var current = current current.avatar = .image(representation, false) @@ -301,7 +301,7 @@ public func createChannelController(context: AccountContext) -> ViewController { let mixin = TGMediaAvatarMenuMixin(context: legacyController.context, parentController: emptyController, hasSearchButton: true, hasDeleteButton: stateValue.with({ $0.avatar }) != nil, hasViewButton: false, personalPhoto: false, saveEditedPhotos: false, saveCapturedMedia: false, signup: false)! let _ = currentAvatarMixin.swap(mixin) mixin.requestSearchController = { assetsController in - let controller = WebSearchController(account: account, peer: peer, configuration: searchBotsConfiguration, mode: .avatar(initialQuery: title, completion: { result in + let controller = WebSearchController(context: context, peer: peer, configuration: searchBotsConfiguration, mode: .avatar(initialQuery: title, completion: { result in assetsController?.dismiss() completedImpl(result) })) diff --git a/TelegramUI/CreateGroupController.swift b/TelegramUI/CreateGroupController.swift index bc6a87eb38..6bfae35cfe 100644 --- a/TelegramUI/CreateGroupController.swift +++ b/TelegramUI/CreateGroupController.swift @@ -272,7 +272,7 @@ public func createGroupController(context: AccountContext, peerIds: [PeerId]) -> } if let _ = updatingAvatar { let _ = updatePeerPhoto(postbox: context.account.postbox, network: context.account.network, stateManager: context.account.stateManager, accountPeerId: context.account.peerId, peerId: peerId, photo: uploadedAvatar.get(), mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) + return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations) }).start() } let controller = ChatController(context: context, chatLocation: .peer(peerId)) @@ -288,7 +288,7 @@ public func createGroupController(context: AccountContext, peerIds: [PeerId]) -> } let _ = (context.account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in - return (transaction.getPeer(account.peerId), currentSearchBotsConfiguration(transaction: transaction)) + return (transaction.getPeer(context.account.peerId), currentSearchBotsConfiguration(transaction: transaction)) } |> deliverOnMainQueue).start(next: { peer, searchBotsConfiguration in let presentationData = context.currentPresentationData.with { $0 } diff --git a/TelegramUI/CreatePasswordController.swift b/TelegramUI/CreatePasswordController.swift index c77f0c38dd..6526dd6cb4 100644 --- a/TelegramUI/CreatePasswordController.swift +++ b/TelegramUI/CreatePasswordController.swift @@ -218,7 +218,7 @@ enum CreatePasswordState: Equatable { case pendingVerification(emailPattern: String) } -func createPasswordController(context: AccountContext, context: CreatePasswordContext, state: CreatePasswordState, completion: @escaping (String, String, Bool) -> Void, updatePasswordEmailConfirmation: @escaping ((String, String)?) -> Void, processPasswordEmailConfirmation: Bool = true) -> ViewController { +func createPasswordController(context: AccountContext, createPasswordContext: CreatePasswordContext, state: CreatePasswordState, completion: @escaping (String, String, Bool) -> Void, updatePasswordEmailConfirmation: @escaping ((String, String)?) -> Void, processPasswordEmailConfirmation: Bool = true) -> ViewController { let statePromise = ValuePromise(CreatePasswordControllerState(state: state), ignoreRepeated: true) let stateValue = Atomic(value: CreatePasswordControllerState(state: state)) let updateState: ((CreatePasswordControllerState) -> CreatePasswordControllerState) -> Void = { f in @@ -398,7 +398,7 @@ func createPasswordController(context: AccountContext, context: CreatePasswordCo } let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(title), leftNavigationButton: leftNavigationButton, rightNavigationButton: rightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: false) - let listState = ItemListNodeState(entries: createPasswordControllerEntries(presentationData: presentationData, context: context, state: state), style: .blocks, focusItemTag: CreatePasswordEntryTag.password, emptyStateItem: nil, animateChanges: false) + let listState = ItemListNodeState(entries: createPasswordControllerEntries(presentationData: presentationData, context: createPasswordContext, state: state), style: .blocks, focusItemTag: CreatePasswordEntryTag.password, emptyStateItem: nil, animateChanges: false) return (controllerState, (listState, arguments)) } diff --git a/TelegramUI/CreatePollController.swift b/TelegramUI/CreatePollController.swift index e176531b3d..e6c27cdfbf 100644 --- a/TelegramUI/CreatePollController.swift +++ b/TelegramUI/CreatePollController.swift @@ -299,7 +299,7 @@ public func createPollController(context: AccountContext, peerId: PeerId, comple let previousOptionIds = Atomic<[Int]?>(value: nil) let limitsKey = PostboxViewKey.preferences(keys: Set([PreferencesKeys.limitsConfiguration])) - let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, account.postbox.combinedView(keys: [limitsKey])) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, context.account.postbox.combinedView(keys: [limitsKey])) |> map { presentationData, state, combinedView -> (ItemListControllerState, (ItemListNodeState, CreatePollEntry.ItemGenerationArguments)) in let limitsConfiguration: LimitsConfiguration = (combinedView.views[limitsKey] as? PreferencesView)?.values[PreferencesKeys.limitsConfiguration] as? LimitsConfiguration ?? LimitsConfiguration.defaultValue @@ -346,7 +346,7 @@ public func createPollController(context: AccountContext, peerId: PeerId, comple } } if hasNonEmptyOptions || !state.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.CreatePoll_CancelConfirmation, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_No, action: {}), TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Yes, action: { dismissImpl?() })]), nil) diff --git a/TelegramUI/DataPrivacySettingsController.swift b/TelegramUI/DataPrivacySettingsController.swift index bfed57fa65..f4ee1a9349 100644 --- a/TelegramUI/DataPrivacySettingsController.swift +++ b/TelegramUI/DataPrivacySettingsController.swift @@ -479,7 +479,7 @@ public func dataPrivacyController(context: AccountContext) -> ViewController { actionsDisposable.add(managedUpdatedRecentPeers(accountPeerId: context.account.peerId, postbox: context.account.postbox, network: context.account.network).start()) - let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, account.postbox.combinedView(keys: [.noticeEntry(ApplicationSpecificNotice.secretChatLinkPreviewsKey()), preferencesKey]), recentPeers(account: context.account)) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, context.account.postbox.combinedView(keys: [.noticeEntry(ApplicationSpecificNotice.secretChatLinkPreviewsKey()), preferencesKey]), recentPeers(account: context.account)) |> map { presentationData, state, combined, recentPeers -> (ItemListControllerState, (ItemListNodeState, PrivacyAndSecurityEntry.ItemGenerationArguments)) in let secretChatLinkPreviews = (combined.views[.noticeEntry(ApplicationSpecificNotice.secretChatLinkPreviewsKey())] as? NoticeEntryView)?.value.flatMap({ ApplicationSpecificNotice.getSecretChatLinkPreviews($0) }) diff --git a/TelegramUI/DebugAccountsController.swift b/TelegramUI/DebugAccountsController.swift index 09cb5330af..9a1a129b30 100644 --- a/TelegramUI/DebugAccountsController.swift +++ b/TelegramUI/DebugAccountsController.swift @@ -5,14 +5,14 @@ import Postbox import TelegramCore private final class DebugAccountsControllerArguments { - let account: Account + let context: AccountContext let presentController: (ViewController, ViewControllerPresentationArguments) -> Void let switchAccount: (AccountRecordId) -> Void let loginNewAccount: () -> Void - init(account: Account, presentController: @escaping (ViewController, ViewControllerPresentationArguments) -> Void, switchAccount: @escaping (AccountRecordId) -> Void, loginNewAccount: @escaping () -> Void) { - self.account = account + init(context: AccountContext, presentController: @escaping (ViewController, ViewControllerPresentationArguments) -> Void, switchAccount: @escaping (AccountRecordId) -> Void, loginNewAccount: @escaping () -> Void) { + self.context = context self.presentController = presentController self.switchAccount = switchAccount self.loginNewAccount = loginNewAccount diff --git a/TelegramUI/DebugController.swift b/TelegramUI/DebugController.swift index 6bfe088d99..12afcd2cb9 100644 --- a/TelegramUI/DebugController.swift +++ b/TelegramUI/DebugController.swift @@ -6,13 +6,13 @@ import TelegramCore import MtProtoKitDynamic private final class DebugControllerArguments { - let account: Account + let context: AccountContext let accountManager: AccountManager let presentController: (ViewController, ViewControllerPresentationArguments?) -> Void let pushController: (ViewController) -> Void - init(account: Account, accountManager: AccountManager, presentController: @escaping (ViewController, ViewControllerPresentationArguments?) -> Void, pushController: @escaping (ViewController) -> Void) { - self.account = account + init(context: AccountContext, accountManager: AccountManager, presentController: @escaping (ViewController, ViewControllerPresentationArguments?) -> Void, pushController: @escaping (ViewController) -> Void) { + self.context = context self.accountManager = accountManager self.presentController = presentController self.pushController = pushController @@ -111,7 +111,7 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListDisclosureItem(theme: theme, title: "Send Logs", label: "", sectionId: self.section, style: .blocks, action: { let _ = (Logger.shared.collectLogs() |> deliverOnMainQueue).start(next: { logs in - let controller = PeerSelectionController(account: arguments.account) + let controller = PeerSelectionController(context: arguments.context) controller.peerSelected = { [weak controller] peerId in if let strongController = controller { strongController.dismiss() @@ -121,7 +121,7 @@ private enum DebugControllerEntry: ItemListNodeEntry { let file = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: id), partialReference: nil, resource: LocalFileReferenceMediaResource(localFilePath: path, randomId: id), previewRepresentations: [], immediateThumbnailData: nil, mimeType: "application/text", size: nil, attributes: [.FileName(fileName: name)]) return .message(text: "", attributes: [], mediaReference: .standalone(media: file), replyToMessageId: nil, localGroupingKey: nil) } - let _ = enqueueMessages(account: arguments.account, peerId: peerId, messages: messages).start() + let _ = enqueueMessages(account: arguments.context.account, peerId: peerId, messages: messages).start() } } arguments.presentController(controller, ViewControllerPresentationArguments(presentationAnimation: ViewControllerPresentationAnimation.modalSheet)) @@ -131,7 +131,7 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListDisclosureItem(theme: theme, title: "Send Latest Log", label: "", sectionId: self.section, style: .blocks, action: { let _ = (Logger.shared.collectLogs() |> deliverOnMainQueue).start(next: { logs in - let controller = PeerSelectionController(account: arguments.account) + let controller = PeerSelectionController(context: arguments.context) controller.peerSelected = { [weak controller] peerId in if let strongController = controller { strongController.dismiss() @@ -143,7 +143,7 @@ private enum DebugControllerEntry: ItemListNodeEntry { let file = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: id), partialReference: nil, resource: LocalFileReferenceMediaResource(localFilePath: path, randomId: id), previewRepresentations: [], immediateThumbnailData: nil, mimeType: "application/text", size: nil, attributes: [.FileName(fileName: name)]) return .message(text: "", attributes: [], mediaReference: .standalone(media: file), replyToMessageId: nil, localGroupingKey: nil) } - let _ = enqueueMessages(account: arguments.account, peerId: peerId, messages: messages).start() + let _ = enqueueMessages(account: arguments.context.account, peerId: peerId, messages: messages).start() } } arguments.presentController(controller, ViewControllerPresentationArguments(presentationAnimation: ViewControllerPresentationAnimation.modalSheet)) @@ -151,15 +151,15 @@ private enum DebugControllerEntry: ItemListNodeEntry { }) case let .accounts(theme): return ItemListDisclosureItem(theme: theme, title: "Accounts", label: "", sectionId: self.section, style: .blocks, action: { - arguments.pushController(debugAccountsController(account: arguments.account, accountManager: arguments.accountManager)) + arguments.pushController(debugAccountsController(context: arguments.context, accountManager: arguments.accountManager)) }) case let .resetServerContacts(theme): return ItemListActionItem(theme: theme, title: "Reset Server Contacts", kind: .generic, alignment: .natural, sectionId: self.section, style: .blocks, action: { - let _ = resetSavedContacts(network: arguments.account.network).start() + let _ = resetSavedContacts(network: arguments.context.account.network).start() }) case let .clearPaymentData(theme): return ItemListActionItem(theme: theme, title: "Clear Payment Password", kind: .generic, alignment: .natural, sectionId: self.section, style: .blocks, action: { - let _ = cacheTwoStepPasswordToken(postbox: arguments.account.postbox, token: nil).start() + let _ = cacheTwoStepPasswordToken(postbox: arguments.context.account.postbox, token: nil).start() }) case let .logToFile(theme, value): return ItemListSwitchItem(theme: theme, title: "Log to File", value: value, sectionId: self.section, style: .blocks, updated: { value in @@ -181,13 +181,13 @@ private enum DebugControllerEntry: ItemListNodeEntry { }) case let .enableRaiseToSpeak(theme, value): return ItemListSwitchItem(theme: theme, title: "Enable Raise to Speak", value: value, sectionId: self.section, style: .blocks, updated: { value in - let _ = updateMediaInputSettingsInteractively(postbox: arguments.account.postbox, { + let _ = updateMediaInputSettingsInteractively(postbox: arguments.context.account.postbox, { $0.withUpdatedEnableRaiseToSpeak(value) }).start() }) case let .keepChatNavigationStack(theme, value): return ItemListSwitchItem(theme: theme, title: "Keep Chat Stack", value: value, sectionId: self.section, style: .blocks, updated: { value in - let _ = updateExperimentalUISettingsInteractively(postbox: arguments.account.postbox, { settings in + let _ = updateExperimentalUISettingsInteractively(postbox: arguments.context.account.postbox, { settings in var settings = settings settings.keepChatNavigationStack = value return settings @@ -195,7 +195,7 @@ private enum DebugControllerEntry: ItemListNodeEntry { }) case let .clearTips(theme): return ItemListActionItem(theme: theme, title: "Clear Tips", kind: .generic, alignment: .natural, sectionId: self.section, style: .blocks, action: { - let _ = (arguments.account.postbox.transaction { transaction -> Void in + let _ = (arguments.context.account.postbox.transaction { transaction -> Void in transaction.clearNoticeEntries() }).start() }) @@ -268,7 +268,7 @@ public func debugController(context: AccountContext, accountManager: AccountMana var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? var pushControllerImpl: ((ViewController) -> Void)? - let arguments = DebugControllerArguments(account: context.account, accountManager: accountManager, presentController: { controller, arguments in + let arguments = DebugControllerArguments(context: context, accountManager: accountManager, presentController: { controller, arguments in presentControllerImpl?(controller, arguments) }, pushController: { controller in pushControllerImpl?(controller) diff --git a/TelegramUI/DeviceContactInfoController.swift b/TelegramUI/DeviceContactInfoController.swift index 408af46ff6..9b94a8b947 100644 --- a/TelegramUI/DeviceContactInfoController.swift +++ b/TelegramUI/DeviceContactInfoController.swift @@ -755,7 +755,7 @@ public func deviceContactInfoController(context: AccountContext, subject: Device var displayCopyContextMenuImpl: ((DeviceContactInfoEntryTag, String) -> Void)? let callImpl: (String) -> Void = { number in - let _ = (account.postbox.transaction { transaction -> TelegramUser? in + let _ = (context.account.postbox.transaction { transaction -> TelegramUser? in if let peer = subject.peer { return transaction.getPeer(peer.id) as? TelegramUser } @@ -763,7 +763,7 @@ public func deviceContactInfoController(context: AccountContext, subject: Device } |> deliverOnMainQueue).start(next: { user in if let user = user, let phone = user.phone, formatPhoneNumber(phone) == formatPhoneNumber(number) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let controller = ActionSheetController(presentationTheme: presentationData.theme) let dismissAction: () -> Void = { [weak controller] in controller?.dismissAnimated() @@ -772,18 +772,18 @@ public func deviceContactInfoController(context: AccountContext, subject: Device ActionSheetItemGroup(items: [ ActionSheetButtonItem(title: presentationData.strings.UserInfo_TelegramCall, action: { dismissAction() - let callResult = account.telegramApplicationContext.callManager?.requestCall(peerId: user.id, endCurrentIfAny: false) + let callResult = context.callManager?.requestCall(peerId: user.id, endCurrentIfAny: false) if let callResult = callResult, case let .alreadyInProgress(currentPeerId) = callResult { if currentPeerId == user.id { - account.telegramApplicationContext.navigateToCurrentCall?() + context.navigateToCurrentCall?() } else { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - let _ = (account.postbox.transaction { transaction -> (Peer?, Peer?) in + let presentationData = context.currentPresentationData.with { $0 } + let _ = (context.account.postbox.transaction { transaction -> (Peer?, Peer?) in return (transaction.getPeer(user.id), transaction.getPeer(currentPeerId)) } |> deliverOnMainQueue).start(next: { peer, current in if let peer = peer, let current = current { presentControllerImpl?(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: presentationData.strings.Call_CallInProgressTitle, text: presentationData.strings.Call_CallInProgressMessage(current.compactDisplayTitle, peer.compactDisplayTitle).0, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: { - let _ = account.telegramApplicationContext.callManager?.requestCall(peerId: peer.id, endCurrentIfAny: true) + let _ = context.callManager?.requestCall(peerId: peer.id, endCurrentIfAny: true) })]), nil) } }) @@ -792,19 +792,19 @@ public func deviceContactInfoController(context: AccountContext, subject: Device }), ActionSheetButtonItem(title: presentationData.strings.UserInfo_PhoneCall, action: { dismissAction() - account.telegramApplicationContext.applicationBindings.openUrl("tel:\(formatPhoneNumber(number).replacingOccurrences(of: " ", with: ""))") + context.applicationBindings.openUrl("tel:\(formatPhoneNumber(number).replacingOccurrences(of: " ", with: ""))") }), ]), ActionSheetItemGroup(items: [ActionSheetButtonItem(title: presentationData.strings.Common_Cancel, action: { dismissAction() })]) ]) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } else { - account.telegramApplicationContext.applicationBindings.openUrl("tel:\(formatPhoneNumber(number).replacingOccurrences(of: " ", with: ""))") + context.applicationBindings.openUrl("tel:\(formatPhoneNumber(number).replacingOccurrences(of: " ", with: ""))") } }) } - let arguments = DeviceContactInfoControllerArguments(account: account, updateEditingName: { editingName in + let arguments = DeviceContactInfoControllerArguments(account: context.account, updateEditingName: { editingName in updateState { state in var state = state if let _ = state.editingState { @@ -861,7 +861,7 @@ public func deviceContactInfoController(context: AccountContext, subject: Device if subject.contactData.basicData.phoneNumbers.count == 1 { inviteAction(subject.contactData.basicData.phoneNumbers[0].value) } else { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let controller = ActionSheetController(presentationTheme: presentationData.theme) let dismissAction: () -> Void = { [weak controller] in controller?.dismissAnimated() @@ -881,7 +881,7 @@ public func deviceContactInfoController(context: AccountContext, subject: Device presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } case .createContact: - presentControllerImpl?(deviceContactInfoController(account: account, subject: .create(peer: subject.peer, contactData: subject.contactData, completion: { peer, stableId, contactData in + presentControllerImpl?(deviceContactInfoController(context: context, subject: .create(peer: subject.peer, contactData: subject.contactData, completion: { peer, stableId, contactData in dismissImpl?(false) if let peer = peer { @@ -927,7 +927,7 @@ public func deviceContactInfoController(context: AccountContext, subject: Device } let previousEditingPhoneIds = Atomic?>(value: nil) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), contactData) + let signal = combineLatest(context.presentationData, statePromise.get(), contactData) |> map { presentationData, state, peerAndContactData -> (ItemListControllerState, (ItemListNodeState, DeviceContactInfoEntry.ItemGenerationArguments)) in var leftNavigationButton: ItemListNavigationButton? switch subject { @@ -968,7 +968,7 @@ public func deviceContactInfoController(context: AccountContext, subject: Device state.savingData = true return state } - let _ = (account.telegramApplicationContext.contactDataManager.createContactWithData(composedContactData) + let _ = (context.contactDataManager.createContactWithData(composedContactData) |> deliverOnMainQueue).start(next: { contactIdAndData in updateState { state in var state = state @@ -1022,7 +1022,7 @@ public func deviceContactInfoController(context: AccountContext, subject: Device focusItemTag = DeviceContactInfoEntryTag.editingPhone(insertedPhoneId) } - let listState = ItemListNodeState(entries: deviceContactInfoEntries(account: account, presentationData: presentationData, peer: peerAndContactData.0, contactData: peerAndContactData.2, isContact: peerAndContactData.1 != nil, state: state, selecting: selecting, editingPhoneNumbers: editingPhones), style: .plain, focusItemTag: focusItemTag) + let listState = ItemListNodeState(entries: deviceContactInfoEntries(account: context.account, presentationData: presentationData, peer: peerAndContactData.0, contactData: peerAndContactData.2, isContact: peerAndContactData.1 != nil, state: state, selecting: selecting, editingPhoneNumbers: editingPhones), style: .plain, focusItemTag: focusItemTag) return (controllerState, (listState, arguments)) } @@ -1030,18 +1030,18 @@ public func deviceContactInfoController(context: AccountContext, subject: Device actionsDisposable.dispose() } - let controller = DeviceContactInfoController(account: account, state: signal) + let controller = DeviceContactInfoController(context: context, state: signal) addToExistingImpl = { [weak controller] in guard let controller = controller else { return } - addContactToExisting(account: account, parentController: controller, contactData: subject.contactData, completion: { peer, contactId, contactData in - replaceControllerImpl?(deviceContactInfoController(account: account, subject: .vcard(peer, contactId, contactData))) + addContactToExisting(context: context, parentController: controller, contactData: subject.contactData, completion: { peer, contactId, contactData in + replaceControllerImpl?(deviceContactInfoController(context: context, subject: .vcard(peer, contactId, contactData))) }) } openChatImpl = { [weak controller] peerId in if let navigationController = (controller?.navigationController as? NavigationController) { - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId)) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId)) } } replaceControllerImpl = { [weak controller] value in @@ -1059,7 +1059,7 @@ public func deviceContactInfoController(context: AccountContext, subject: Device } } inviteImpl = { [weak controller] numbers in - controller?.inviteContact(presentationData: account.telegramApplicationContext.currentPresentationData.with { $0 }, numbers: numbers) + controller?.inviteContact(presentationData: context.currentPresentationData.with { $0 }, numbers: numbers) } openAddressImpl = { [weak controller] address in guard let _ = controller else { @@ -1070,14 +1070,14 @@ public func deviceContactInfoController(context: AccountContext, subject: Device guard let controller = controller else { return } - openExternalUrl(account: account, url: url, presentationData: account.telegramApplicationContext.currentPresentationData.with { $0 }, applicationContext: account.telegramApplicationContext, navigationController: controller.navigationController as? NavigationController, dismissInput: { [weak controller] in + openExternalUrl(context: context, url: url, presentationData: context.currentPresentationData.with { $0 }, navigationController: controller.navigationController as? NavigationController, dismissInput: { [weak controller] in controller?.view.endEditing(true) }) } displayCopyContextMenuImpl = { [weak controller] tag, value in if let strongController = controller { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } var resultItemNode: ListViewItemNode? let _ = strongController.frameForItemNode({ itemNode in if let itemNode = itemNode as? ItemListTextWithLabelItemNode { @@ -1109,8 +1109,8 @@ public func deviceContactInfoController(context: AccountContext, subject: Device return controller } -private func addContactToExisting(account: Account, parentController: ViewController, contactData: DeviceContactExtendedData, completion: @escaping (Peer?, DeviceContactStableId, DeviceContactExtendedData) -> Void) { - let contactsController = ContactSelectionController(account: account, title: { $0.Contacts_Title }, displayDeviceContacts: true) +private func addContactToExisting(context: AccountContext, parentController: ViewController, contactData: DeviceContactExtendedData, completion: @escaping (Peer?, DeviceContactStableId, DeviceContactExtendedData) -> Void) { + let contactsController = ContactSelectionController(context: context, title: { $0.Contacts_Title }, displayDeviceContacts: true) parentController.present(contactsController, in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) let _ = (contactsController.result |> deliverOnMainQueue).start(next: { peer in @@ -1121,7 +1121,7 @@ private func addContactToExisting(account: Account, parentController: ViewContro guard let contact = contact as? TelegramUser, let phoneNumber = contact.phone else { return } - dataSignal = account.telegramApplicationContext.contactDataManager.basicData() + dataSignal = context.contactDataManager.basicData() |> take(1) |> mapToSignal { basicData -> Signal<(Peer?, DeviceContactStableId?), NoError> in var stableId: String? @@ -1142,17 +1142,17 @@ private func addContactToExisting(account: Account, parentController: ViewContro let _ = (dataSignal |> deliverOnMainQueue).start(next: { peer, stableId in guard let stableId = stableId else { - parentController.present(deviceContactInfoController(account: account, subject: .create(peer: peer, contactData: contactData, completion: { peer, stableId, contactData in + parentController.present(deviceContactInfoController(context: context, subject: .create(peer: peer, contactData: contactData, completion: { peer, stableId, contactData in })), in: .window(.root)) return } - let _ = (account.telegramApplicationContext.contactDataManager.appendContactData(contactData, to: stableId) + let _ = (context.contactDataManager.appendContactData(contactData, to: stableId) |> deliverOnMainQueue).start(next: { contactData in guard let contactData = contactData else { return } - let _ = (account.postbox.contactPeersView(accountPeerId: nil, includePresences: false) + let _ = (context.account.postbox.contactPeersView(accountPeerId: nil, includePresences: false) |> take(1) |> deliverOnMainQueue).start(next: { view in let phones = Set(contactData.basicData.phoneNumbers.map { @@ -1200,7 +1200,7 @@ func addContactOptionsController(context: AccountContext, peer: Peer?, contactDa guard let controller = controller else { return } - addContactToExisting(account: context.account, parentController: controller, contactData: contactData, completion: { peer, contactId, contactData in + addContactToExisting(context: context, parentController: controller, contactData: contactData, completion: { peer, contactId, contactData in }) dismissAction() diff --git a/TelegramUI/DisabledContextResultsChatInputContextPanelNode.swift b/TelegramUI/DisabledContextResultsChatInputContextPanelNode.swift index 86cf342397..37c037bed8 100644 --- a/TelegramUI/DisabledContextResultsChatInputContextPanelNode.swift +++ b/TelegramUI/DisabledContextResultsChatInputContextPanelNode.swift @@ -10,14 +10,14 @@ final class DisabledContextResultsChatInputContextPanelNode: ChatInputContextPan private var validLayout: (CGSize, CGFloat, CGFloat)? - override init(account: Account, theme: PresentationTheme, strings: PresentationStrings) { + override init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings) { self.containerNode = ASDisplayNode() self.separatorNode = ASDisplayNode() self.textNode = ImmediateTextNode() self.textNode.maximumNumberOfLines = 0 self.textNode.textAlignment = .center - super.init(account: account, theme: theme, strings: strings) + super.init(context: context, theme: theme, strings: strings) self.isOpaque = false self.clipsToBounds = true diff --git a/TelegramUI/EditSettingsController.swift b/TelegramUI/EditSettingsController.swift index 42ea62a8ff..5954324964 100644 --- a/TelegramUI/EditSettingsController.swift +++ b/TelegramUI/EditSettingsController.swift @@ -6,7 +6,7 @@ import TelegramCore import LegacyComponents private struct EditSettingsItemArguments { - let account: Account + let context: AccountContext let accountManager: AccountManager let avatarAndNameInfoContext: ItemListAvatarAndNameInfoItemContext @@ -167,7 +167,7 @@ private enum SettingsEntry: ItemListNodeEntry { func item(_ arguments: EditSettingsItemArguments) -> ListViewItem { switch self { case let .userInfo(theme, strings, dateTimeFormat, peer, cachedData, state, updatingImage): - return ItemListAvatarAndNameInfoItem(account: arguments.account, theme: theme, strings: strings, dateTimeFormat: dateTimeFormat, mode: .editSettings, peer: peer, presence: TelegramUserPresence(status: .present(until: Int32.max), lastActivity: 0), cachedData: cachedData, state: state, sectionId: ItemListSectionId(self.section), style: .blocks(withTopInset: false), editingNameUpdated: { editingName in + return ItemListAvatarAndNameInfoItem(account: arguments.context.account, theme: theme, strings: strings, dateTimeFormat: dateTimeFormat, mode: .editSettings, peer: peer, presence: TelegramUserPresence(status: .present(until: Int32.max), lastActivity: 0), cachedData: cachedData, state: state, sectionId: ItemListSectionId(self.section), style: .blocks(withTopInset: false), editingNameUpdated: { editingName in arguments.updateEditingName(editingName) }, avatarTapped: { arguments.avatarTapAction() @@ -184,11 +184,11 @@ private enum SettingsEntry: ItemListNodeEntry { return ItemListTextItem(theme: theme, text: .plain(text), sectionId: self.section) case let .phoneNumber(theme, text, number): return ItemListDisclosureItem(theme: theme, title: text, label: number, sectionId: ItemListSectionId(self.section), style: .blocks, action: { - arguments.pushController(ChangePhoneNumberIntroController(account: arguments.account, phoneNumber: number)) + arguments.pushController(ChangePhoneNumberIntroController(context: arguments.context, phoneNumber: number)) }) case let .username(theme, text, address): return ItemListDisclosureItem(theme: theme, title: text, label: address, sectionId: ItemListSectionId(self.section), style: .blocks, action: { - arguments.presentController(usernameSetupController(account: arguments.account)) + arguments.presentController(usernameSetupController(context: arguments.context)) }) case let .addAccount(theme, text): return ItemListActionItem(theme: theme, title: text, kind: .generic, alignment: .center, sectionId: ItemListSectionId(self.section), style: .blocks, action: { @@ -313,7 +313,7 @@ func editSettingsController(context: AccountContext, currentName: ItemListAvatar var updateHiddenAvatarImpl: (() -> Void)? var changeProfilePhotoImpl: (() -> Void)? - let arguments = EditSettingsItemArguments(account: context.account, accountManager: accountManager, avatarAndNameInfoContext: avatarAndNameInfoContext, avatarTapAction: { + let arguments = EditSettingsItemArguments(context: context, accountManager: accountManager, avatarAndNameInfoContext: avatarAndNameInfoContext, avatarTapAction: { var updating = false updateState { updating = $0.updatingAvatar != nil @@ -531,7 +531,7 @@ func editSettingsController(context: AccountContext, currentName: ItemListAvatar |> take(1) |> deliverOnMainQueue).start(next: { peer in if peer.smallProfileImage != nil { - let galleryController = AvatarGalleryController(account: context.account, peer: peer, replaceRootController: { controller, ready in + let galleryController = AvatarGalleryController(context: context, peer: peer, replaceRootController: { controller, ready in }) /*hiddenAvatarRepresentationDisposable.set((galleryController.hiddenMedia |> deliverOnMainQueue).start(next: { entry in avatarAndNameInfoContext.hiddenAvatarRepresentation = entry?.representations.first diff --git a/TelegramUI/FeaturedStickerPacksController.swift b/TelegramUI/FeaturedStickerPacksController.swift index f44cb1caea..b7428968cf 100644 --- a/TelegramUI/FeaturedStickerPacksController.swift +++ b/TelegramUI/FeaturedStickerPacksController.swift @@ -233,7 +233,7 @@ public func featuredStickerPacksController(context: AccountContext) -> ViewContr if !unreadIds.isEmpty { alreadyReadIds.formUnion(Set(unreadIds)) - let _ = markFeaturedStickerPacksAsSeenInteractively(postbox: account.postbox, ids: unreadIds).start() + let _ = markFeaturedStickerPacksAsSeenInteractively(postbox: context.account.postbox, ids: unreadIds).start() } } @@ -244,7 +244,7 @@ public func featuredStickerPacksController(context: AccountContext) -> ViewContr } presentStickerPackController = { [weak controller] info in - presentControllerImpl?(StickerPackPreviewController(account: account, stickerPack: .id(id: info.id.id, accessHash: info.accessHash), mode: .settings, parentNavigationController: controller?.navigationController as? NavigationController), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + presentControllerImpl?(StickerPackPreviewController(context: context, stickerPack: .id(id: info.id.id, accessHash: info.accessHash), mode: .settings, parentNavigationController: controller?.navigationController as? NavigationController), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } return controller diff --git a/TelegramUI/FetchMediaUtils.swift b/TelegramUI/FetchMediaUtils.swift index 0fc55c2b56..8ecfc97136 100644 --- a/TelegramUI/FetchMediaUtils.swift +++ b/TelegramUI/FetchMediaUtils.swift @@ -25,24 +25,24 @@ private func fetchCategoryForFile(_ file: TelegramMediaFile) -> FetchManagerCate } } -public func messageMediaFileInteractiveFetched(account: Account, message: Message, file: TelegramMediaFile, userInitiated: Bool) -> Signal { +public func messageMediaFileInteractiveFetched(context: AccountContext, message: Message, file: TelegramMediaFile, userInitiated: Bool) -> Signal { let mediaReference = AnyMediaReference.message(message: MessageReference(message), media: file) - return account.telegramApplicationContext.fetchManager.interactivelyFetched(category: fetchCategoryForFile(file), location: .chat(message.id.peerId), locationKey: .messageId(message.id), mediaReference: mediaReference, resourceReference: mediaReference.resourceReference(file.resource), statsCategory: statsCategoryForFileWithAttributes(file.attributes), elevatedPriority: false, userInitiated: userInitiated) + return context.fetchManager.interactivelyFetched(category: fetchCategoryForFile(file), location: .chat(message.id.peerId), locationKey: .messageId(message.id), mediaReference: mediaReference, resourceReference: mediaReference.resourceReference(file.resource), statsCategory: statsCategoryForFileWithAttributes(file.attributes), elevatedPriority: false, userInitiated: userInitiated) } -func messageMediaFileCancelInteractiveFetch(account: Account, messageId: MessageId, file: TelegramMediaFile) { - account.telegramApplicationContext.fetchManager.cancelInteractiveFetches(category: fetchCategoryForFile(file), location: .chat(messageId.peerId), locationKey: .messageId(messageId), resource: file.resource) +func messageMediaFileCancelInteractiveFetch(context: AccountContext, messageId: MessageId, file: TelegramMediaFile) { + context.fetchManager.cancelInteractiveFetches(category: fetchCategoryForFile(file), location: .chat(messageId.peerId), locationKey: .messageId(messageId), resource: file.resource) } -public func messageMediaImageInteractiveFetched(account: Account, message: Message, image: TelegramMediaImage, resource: MediaResource, storeToDownloadsPeerType: AutomaticMediaDownloadPeerType?) -> Signal { +public func messageMediaImageInteractiveFetched(context: AccountContext, message: Message, image: TelegramMediaImage, resource: MediaResource, storeToDownloadsPeerType: AutomaticMediaDownloadPeerType?) -> Signal { let mediaReference = AnyMediaReference.message(message: MessageReference(message), media: image) - return account.telegramApplicationContext.fetchManager.interactivelyFetched(category: .image, location: .chat(message.id.peerId), locationKey: .messageId(message.id), mediaReference: mediaReference, resourceReference: mediaReference.resourceReference(resource), statsCategory: .image, elevatedPriority: false, userInitiated: true, storeToDownloadsPeerType: storeToDownloadsPeerType) + return context.fetchManager.interactivelyFetched(category: .image, location: .chat(message.id.peerId), locationKey: .messageId(message.id), mediaReference: mediaReference, resourceReference: mediaReference.resourceReference(resource), statsCategory: .image, elevatedPriority: false, userInitiated: true, storeToDownloadsPeerType: storeToDownloadsPeerType) } -func messageMediaImageCancelInteractiveFetch(account: Account, messageId: MessageId, image: TelegramMediaImage, resource: MediaResource) { - account.telegramApplicationContext.fetchManager.cancelInteractiveFetches(category: .image, location: .chat(messageId.peerId), locationKey: .messageId(messageId), resource: resource) +func messageMediaImageCancelInteractiveFetch(context: AccountContext, messageId: MessageId, image: TelegramMediaImage, resource: MediaResource) { + context.fetchManager.cancelInteractiveFetches(category: .image, location: .chat(messageId.peerId), locationKey: .messageId(messageId), resource: resource) } -func messageMediaFileStatus(account: Account, messageId: MessageId, file: TelegramMediaFile) -> Signal { - return account.telegramApplicationContext.fetchManager.fetchStatus(category: fetchCategoryForFile(file), location: .chat(messageId.peerId), locationKey: .messageId(messageId), resource: file.resource) +func messageMediaFileStatus(context: AccountContext, messageId: MessageId, file: TelegramMediaFile) -> Signal { + return context.fetchManager.fetchStatus(category: fetchCategoryForFile(file), location: .chat(messageId.peerId), locationKey: .messageId(messageId), resource: file.resource) } diff --git a/TelegramUI/FileMediaResourceStatus.swift b/TelegramUI/FileMediaResourceStatus.swift index 21b6688883..41f01f4e03 100644 --- a/TelegramUI/FileMediaResourceStatus.swift +++ b/TelegramUI/FileMediaResourceStatus.swift @@ -18,43 +18,40 @@ enum FileMediaResourceMediaStatus { case playbackStatus(FileMediaResourcePlaybackStatus) } -private func internalMessageFileMediaPlaybackStatus(account: Account, file: TelegramMediaFile, message: Message, isRecentActions: Bool) -> Signal { +private func internalMessageFileMediaPlaybackStatus(context: AccountContext, file: TelegramMediaFile, message: Message, isRecentActions: Bool) -> Signal { guard let playerType = peerMessageMediaPlayerType(message) else { return .single(nil) } if let (playlistId, itemId) = peerMessagesMediaPlaylistAndItemId(message, isRecentActions: isRecentActions) { - if let mediaManager = account.telegramApplicationContext.mediaManager { - return mediaManager.filteredPlaylistState(playlistId: playlistId, itemId: itemId, type: playerType) - |> mapToSignal { state -> Signal in - return .single(state?.status) - } - } else { - return .single(nil) + let mediaManager = context.mediaManager + return mediaManager.filteredPlaylistState(playlistId: playlistId, itemId: itemId, type: playerType) + |> mapToSignal { state -> Signal in + return .single(state?.status) } } else { return .single(nil) } } -func messageFileMediaPlaybackStatus(account: Account, file: TelegramMediaFile, message: Message, isRecentActions: Bool) -> Signal { +func messageFileMediaPlaybackStatus(context: AccountContext, file: TelegramMediaFile, message: Message, isRecentActions: Bool) -> Signal { var duration = 0.0 if let value = file.duration { duration = Double(value) } let defaultStatus = MediaPlayerStatus(generationTimestamp: 0.0, duration: duration, dimensions: CGSize(), timestamp: 0.0, baseRate: 1.0, seekId: 0, status: .paused) - return internalMessageFileMediaPlaybackStatus(account: account, file: file, message: message, isRecentActions: isRecentActions) |> map { status in + return internalMessageFileMediaPlaybackStatus(context: context, file: file, message: message, isRecentActions: isRecentActions) |> map { status in return status ?? defaultStatus } } -func messageFileMediaResourceStatus(account: Account, file: TelegramMediaFile, message: Message, isRecentActions: Bool) -> Signal { - let playbackStatus = internalMessageFileMediaPlaybackStatus(account: account, file: file, message: message, isRecentActions: isRecentActions) |> map { status -> MediaPlayerPlaybackStatus? in +func messageFileMediaResourceStatus(context: AccountContext, file: TelegramMediaFile, message: Message, isRecentActions: Bool) -> Signal { + let playbackStatus = internalMessageFileMediaPlaybackStatus(context: context, file: file, message: message, isRecentActions: isRecentActions) |> map { status -> MediaPlayerPlaybackStatus? in return status?.status } if message.flags.isSending { - return combineLatest(messageMediaFileStatus(account: account, messageId: message.id, file: file), account.pendingMessageManager.pendingMessageStatus(message.id), playbackStatus) + return combineLatest(messageMediaFileStatus(context: context, messageId: message.id, file: file), context.account.pendingMessageManager.pendingMessageStatus(message.id), playbackStatus) |> map { resourceStatus, pendingStatus, playbackStatus -> FileMediaResourceStatus in let mediaStatus: FileMediaResourceMediaStatus if let playbackStatus = playbackStatus { @@ -78,7 +75,7 @@ func messageFileMediaResourceStatus(account: Account, file: TelegramMediaFile, m return FileMediaResourceStatus(mediaStatus: mediaStatus, fetchStatus: resourceStatus) } } else { - return combineLatest(messageMediaFileStatus(account: account, messageId: message.id, file: file), playbackStatus) + return combineLatest(messageMediaFileStatus(context: context, messageId: message.id, file: file), playbackStatus) |> map { resourceStatus, playbackStatus -> FileMediaResourceStatus in let mediaStatus: FileMediaResourceMediaStatus if let playbackStatus = playbackStatus { diff --git a/TelegramUI/GridMessageItem.swift b/TelegramUI/GridMessageItem.swift index 7d09f43e77..58b4f619db 100644 --- a/TelegramUI/GridMessageItem.swift +++ b/TelegramUI/GridMessageItem.swift @@ -255,7 +255,7 @@ final class GridMessageItemNode: GridItemNode { } self.resourceStatus = nil - self.fetchStatusDisposable.set((messageMediaFileStatus(account: context.account, messageId: messageId, file: file) |> deliverOnMainQueue).start(next: { [weak self] status in + self.fetchStatusDisposable.set((messageMediaFileStatus(context: context, messageId: messageId, file: file) |> deliverOnMainQueue).start(next: { [weak self] status in if let strongSelf = self { strongSelf.resourceStatus = status let statusState: RadialStatusNodeState @@ -421,11 +421,11 @@ final class GridMessageItemNode: GridItemNode { if let resourceStatus = self.resourceStatus { switch resourceStatus { case .Fetching: - messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: file) + messageMediaFileCancelInteractiveFetch(context: context, messageId: message.id, file: file) case .Local: let _ = controllerInteraction.openMessage(message, .default) case .Remote: - self.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: file, userInitiated: true).start()) + self.fetchDisposable.set(messageMediaFileInteractiveFetched(context: context, message: message, file: file, userInitiated: true).start()) } } } else { diff --git a/TelegramUI/GroupInfoController.swift b/TelegramUI/GroupInfoController.swift index 0308a8ebb1..630799e967 100644 --- a/TelegramUI/GroupInfoController.swift +++ b/TelegramUI/GroupInfoController.swift @@ -8,7 +8,7 @@ import LegacyComponents import SafariServices private final class GroupInfoArguments { - let account: Account + let context: AccountContext let avatarAndNameInfoContext: ItemListAvatarAndNameInfoItemContext let tapAvatarAction: () -> Void @@ -35,8 +35,8 @@ private final class GroupInfoArguments { let openStickerPackSetup: () -> Void let openGroupTypeSetup: () -> Void - init(account: Account, avatarAndNameInfoContext: ItemListAvatarAndNameInfoItemContext, tapAvatarAction: @escaping () -> Void, changeProfilePhoto: @escaping () -> Void, pushController: @escaping (ViewController) -> Void, presentController: @escaping (ViewController, ViewControllerPresentationArguments) -> Void, changeNotificationMuteSettings: @escaping () -> Void, openPreHistory: @escaping () -> Void, openSharedMedia: @escaping () -> Void, openAdministrators: @escaping () -> Void, openPermissions: @escaping () -> Void, updateEditingName: @escaping (ItemListAvatarAndNameInfoItemName) -> Void, updateEditingDescriptionText: @escaping (String) -> Void, setPeerIdWithRevealedOptions: @escaping (PeerId?, PeerId?) -> Void, addMember: @escaping () -> Void, promotePeer: @escaping (RenderedChannelParticipant) -> Void, restrictPeer: @escaping (RenderedChannelParticipant) -> Void, removePeer: @escaping (PeerId) -> Void, leave: @escaping () -> Void, displayUsernameShareMenu: @escaping (String) -> Void, displayUsernameContextMenu: @escaping (String) -> Void, displayAboutContextMenu: @escaping (String) -> Void, aboutLinkAction: @escaping (TextLinkItemActionType, TextLinkItem) -> Void, openStickerPackSetup: @escaping () -> Void, openGroupTypeSetup: @escaping () -> Void) { - self.account = account + init(context: AccountContext, avatarAndNameInfoContext: ItemListAvatarAndNameInfoItemContext, tapAvatarAction: @escaping () -> Void, changeProfilePhoto: @escaping () -> Void, pushController: @escaping (ViewController) -> Void, presentController: @escaping (ViewController, ViewControllerPresentationArguments) -> Void, changeNotificationMuteSettings: @escaping () -> Void, openPreHistory: @escaping () -> Void, openSharedMedia: @escaping () -> Void, openAdministrators: @escaping () -> Void, openPermissions: @escaping () -> Void, updateEditingName: @escaping (ItemListAvatarAndNameInfoItemName) -> Void, updateEditingDescriptionText: @escaping (String) -> Void, setPeerIdWithRevealedOptions: @escaping (PeerId?, PeerId?) -> Void, addMember: @escaping () -> Void, promotePeer: @escaping (RenderedChannelParticipant) -> Void, restrictPeer: @escaping (RenderedChannelParticipant) -> Void, removePeer: @escaping (PeerId) -> Void, leave: @escaping () -> Void, displayUsernameShareMenu: @escaping (String) -> Void, displayUsernameContextMenu: @escaping (String) -> Void, displayAboutContextMenu: @escaping (String) -> Void, aboutLinkAction: @escaping (TextLinkItemActionType, TextLinkItem) -> Void, openStickerPackSetup: @escaping () -> Void, openGroupTypeSetup: @escaping () -> Void) { + self.context = context self.avatarAndNameInfoContext = avatarAndNameInfoContext self.tapAvatarAction = tapAvatarAction self.changeProfilePhoto = changeProfilePhoto @@ -408,7 +408,7 @@ private enum GroupInfoEntry: ItemListNodeEntry { func item(_ arguments: GroupInfoArguments) -> ListViewItem { switch self { case let .info(theme, strings, dateTimeFormat, peer, cachedData, state, updatingAvatar): - return ItemListAvatarAndNameInfoItem(account: arguments.account, theme: theme, strings: strings, dateTimeFormat: dateTimeFormat, mode: .generic, peer: peer, presence: nil, cachedData: cachedData, state: state, sectionId: self.section, style: .blocks(withTopInset: false), editingNameUpdated: { editingName in + return ItemListAvatarAndNameInfoItem(account: arguments.context.account, theme: theme, strings: strings, dateTimeFormat: dateTimeFormat, mode: .generic, peer: peer, presence: nil, cachedData: cachedData, state: state, sectionId: self.section, style: .blocks(withTopInset: false), editingNameUpdated: { editingName in arguments.updateEditingName(editingName) }, avatarTapped: { arguments.tapAvatarAction() @@ -494,8 +494,8 @@ private enum GroupInfoEntry: ItemListNodeEntry { } })) } - return ItemListPeerItem(theme: theme, strings: strings, dateTimeFormat: dateTimeFormat, nameDisplayOrder: nameDisplayOrder, account: arguments.account, peer: peer, presence: presence, text: .presence, label: label == nil ? .none : .text(label!), editing: editing, revealOptions: ItemListPeerItemRevealOptions(options: options), switchValue: nil, enabled: enabled, sectionId: self.section, action: { - if let infoController = peerInfoController(account: arguments.account, peer: peer) { + return ItemListPeerItem(theme: theme, strings: strings, dateTimeFormat: dateTimeFormat, nameDisplayOrder: nameDisplayOrder, account: arguments.context.account, peer: peer, presence: presence, text: .presence, label: label == nil ? .none : .text(label!), editing: editing, revealOptions: ItemListPeerItemRevealOptions(options: options), switchValue: nil, enabled: enabled, sectionId: self.section, action: { + if let infoController = peerInfoController(context: arguments.context, peer: peer) { arguments.pushController(infoController) } }, setPeerIdWithRevealedOptions: { peerId, fromPeerId in @@ -1222,7 +1222,7 @@ public func groupInfoController(context: AccountContext, peerId originalPeerId: } peerView.set(peerViewSignal) - let arguments = GroupInfoArguments(account: context.account, avatarAndNameInfoContext: avatarAndNameInfoContext, tapAvatarAction: { + let arguments = GroupInfoArguments(context: context, avatarAndNameInfoContext: avatarAndNameInfoContext, tapAvatarAction: { let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in @@ -1365,7 +1365,7 @@ public func groupInfoController(context: AccountContext, peerId originalPeerId: } let controller = notificationMuteSettingsController(presentationData: presentationData, notificationSettings: globalSettings.effective.groupChats, soundSettings: soundSettings, openSoundSettings: { let controller = notificationSoundSelectionController(context: context, isModal: true, currentSound: peerSettings.messageSound, defaultSound: globalSettings.effective.groupChats.sound, completion: { sound in - let _ = updatePeerNotificationSoundInteractive(context: context, peerId: peerView.peerId, sound: sound).start() + let _ = updatePeerNotificationSoundInteractive(account: context.account, peerId: peerView.peerId, sound: sound).start() }) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, updateSettings: { value in @@ -1482,7 +1482,7 @@ public func groupInfoController(context: AccountContext, peerId originalPeerId: } confirmationImpl = { [weak contactsController] peerId in - return account.postbox.loadedPeerWithId(peerId) + return context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue |> mapToSignal { peer in let result = ValuePromise() @@ -1850,7 +1850,7 @@ public func groupInfoController(context: AccountContext, peerId originalPeerId: |> distinctUntilChanged |> deliverOnMainQueue).start(next: { peerId in if peerId.namespace == Namespaces.Peer.CloudChannel { - let (disposable, control) = context.peerChannelMemberCategoriesContextsManager.recent(postbox: contextaccount.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, updated: { state in + let (disposable, control) = context.peerChannelMemberCategoriesContextsManager.recent(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, updated: { state in channelMembersPromise.set(.single(state.list)) if case .loading(true) = state.loadingState { } else if !membersLoadedCalled { @@ -2191,7 +2191,7 @@ func handlePeerInfoAboutTextAction(context: AccountContext, peerId: PeerId, navi } case .info: let peerSignal: Signal - peerSignal = account.postbox.loadedPeerWithId(peerId) |> map(Optional.init) + peerSignal = context.account.postbox.loadedPeerWithId(peerId) |> map(Optional.init) navigateDisposable.set((peerSignal |> take(1) |> deliverOnMainQueue).start(next: { peer in if let controller = controller, let peer = peer { if let infoController = peerInfoController(context: context, peer: peer) { @@ -2206,7 +2206,7 @@ func handlePeerInfoAboutTextAction(context: AccountContext, peerId: PeerId, navi } let openLinkImpl: (String) -> Void = { [weak controller] url in - navigateDisposable.set((resolveUrl(context: context, url: url) |> deliverOnMainQueue).start(next: { result in + navigateDisposable.set((resolveUrl(account: context.account, url: url) |> deliverOnMainQueue).start(next: { result in if let controller = controller { switch result { case let .externalUrl(url): @@ -2220,7 +2220,7 @@ func handlePeerInfoAboutTextAction(context: AccountContext, peerId: PeerId, navi case let .stickerPack(name): controller.present(StickerPackPreviewController(context: context, stickerPack: .name(name), parentNavigationController: controller.navigationController as? NavigationController), in: .window(.root)) case let .instantView(webpage, anchor): - (controller.navigationController as? NavigationController)?.pushViewController(InstantPageController(context: account, webPage: webpage, anchor: anchor)) + (controller.navigationController as? NavigationController)?.pushViewController(InstantPageController(context: context, webPage: webpage, anchor: anchor)) case let .join(link): controller.present(JoinLinkPreviewController(context: context, link: link, navigateToPeer: { peerId in openResolvedPeerImpl(peerId, .chat(textInputState: nil, messageId: nil)) diff --git a/TelegramUI/HorizontalListContextResultsChatInputContextPanelNode.swift b/TelegramUI/HorizontalListContextResultsChatInputContextPanelNode.swift index 55ba69a730..98d4043c79 100644 --- a/TelegramUI/HorizontalListContextResultsChatInputContextPanelNode.swift +++ b/TelegramUI/HorizontalListContextResultsChatInputContextPanelNode.swift @@ -155,7 +155,7 @@ final class HorizontalListContextResultsChatInputContextPanelNode: ChatInputCont } })) } - selectedItemNodeAndContent = (itemNode, StickerPreviewPeekContent(account: item.context.account, item: .found(FoundStickerItem(file: file, stringRepresentations: [])), menu: menuItems)) + selectedItemNodeAndContent = (itemNode, StickerPreviewPeekContent(account: item.account, item: .found(FoundStickerItem(file: file, stringRepresentations: [])), menu: menuItems)) } else { var menuItems: [PeekControllerMenuItem] = [] if case let .internalReference(internalReference) = item.result, let file = internalReference.file, file.isAnimated { @@ -166,7 +166,7 @@ final class HorizontalListContextResultsChatInputContextPanelNode: ChatInputCont menuItems.append(PeekControllerMenuItem(title: strongSelf.strings.ShareMenu_Send, color: .accent, font: .bold, action: { item.resultSelected(item.result) })) - selectedItemNodeAndContent = (itemNode, ChatContextResultPeekContent(account: item.context.account, contextResult: item.result, menu: menuItems)) + selectedItemNodeAndContent = (itemNode, ChatContextResultPeekContent(account: item.account, contextResult: item.result, menu: menuItems)) } } } diff --git a/TelegramUI/HorizontalPeerItem.swift b/TelegramUI/HorizontalPeerItem.swift index dfe1f6954e..60d8b5e072 100644 --- a/TelegramUI/HorizontalPeerItem.swift +++ b/TelegramUI/HorizontalPeerItem.swift @@ -189,7 +189,7 @@ final class HorizontalPeerItemNode: ListViewItemNode { if let strongSelf = self { strongSelf.item = item strongSelf.peerNode.theme = itemTheme - strongSelf.peerNode.setup(account: item.account, strings: item.strings, peer: RenderedPeer(peer: item.peer), numberOfLines: 1, synchronousLoad: false) + strongSelf.peerNode.setup(account: item.account, theme: item.theme, strings: item.strings, peer: RenderedPeer(peer: item.peer), numberOfLines: 1, synchronousLoad: false) strongSelf.peerNode.frame = CGRect(origin: CGPoint(), size: itemLayout.size) strongSelf.peerNode.updateSelection(selected: item.isPeerSelected(item.peer.id), animated: false) diff --git a/TelegramUI/InstantPageAnchorItem.swift b/TelegramUI/InstantPageAnchorItem.swift index 2b6e2fd9f3..06219d7a85 100644 --- a/TelegramUI/InstantPageAnchorItem.swift +++ b/TelegramUI/InstantPageAnchorItem.swift @@ -23,7 +23,7 @@ final class InstantPageAnchorItem: InstantPageItem { func drawInTile(context: CGContext) { } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { return nil } diff --git a/TelegramUI/InstantPageArticleItem.swift b/TelegramUI/InstantPageArticleItem.swift index 2bf8d0ef0a..c32c9bd3dc 100644 --- a/TelegramUI/InstantPageArticleItem.swift +++ b/TelegramUI/InstantPageArticleItem.swift @@ -28,8 +28,8 @@ final class InstantPageArticleItem: InstantPageItem { self.rtl = rtl } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { - return InstantPageArticleNode(account: account, item: self, webPage: self.webPage, strings: strings, theme: theme, contentItems: self.contentItems, contentSize: self.contentSize, cover: self.cover, url: self.url, webpageId: self.webpageId, rtl: self.rtl, openUrl: openUrl) + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + return InstantPageArticleNode(context: context, item: self, webPage: self.webPage, strings: strings, theme: theme, contentItems: self.contentItems, contentSize: self.contentSize, cover: self.cover, url: self.url, webpageId: self.webpageId, rtl: self.rtl, openUrl: openUrl) } func matchesAnchor(_ anchor: String) -> Bool { diff --git a/TelegramUI/InstantPageArticleNode.swift b/TelegramUI/InstantPageArticleNode.swift index 584f09e143..9408216876 100644 --- a/TelegramUI/InstantPageArticleNode.swift +++ b/TelegramUI/InstantPageArticleNode.swift @@ -24,7 +24,7 @@ final class InstantPageArticleNode: ASDisplayNode, InstantPageNode { private var fetchedDisposable = MetaDisposable() - init(account: Account, item: InstantPageArticleItem, webPage: TelegramMediaWebpage, strings: PresentationStrings, theme: InstantPageTheme, contentItems: [InstantPageItem], contentSize: CGSize, cover: TelegramMediaImage?, url: String, webpageId: MediaId, rtl: Bool, openUrl: @escaping (InstantPageUrlItem) -> Void) { + init(context: AccountContext, item: InstantPageArticleItem, webPage: TelegramMediaWebpage, strings: PresentationStrings, theme: InstantPageTheme, contentItems: [InstantPageItem], contentSize: CGSize, cover: TelegramMediaImage?, url: String, webpageId: MediaId, rtl: Bool, openUrl: @escaping (InstantPageUrlItem) -> Void) { self.item = item self.url = url self.webpageId = webpageId @@ -53,8 +53,8 @@ final class InstantPageArticleNode: ASDisplayNode, InstantPageNode { imageNode.isUserInteractionEnabled = false let imageReference = ImageMediaReference.webPage(webPage: WebpageReference(webPage), media: image) - imageNode.setSignal(chatMessagePhoto(postbox: account.postbox, photoReference: imageReference)) - self.fetchedDisposable.set(chatMessagePhotoInteractiveFetched(account: account, photoReference: imageReference, storeToDownloadsPeerType: nil).start()) + imageNode.setSignal(chatMessagePhoto(postbox: context.account.postbox, photoReference: imageReference)) + self.fetchedDisposable.set(chatMessagePhotoInteractiveFetched(context: context, photoReference: imageReference, storeToDownloadsPeerType: nil).start()) self.imageNode = imageNode self.addSubnode(imageNode) diff --git a/TelegramUI/InstantPageAudioItem.swift b/TelegramUI/InstantPageAudioItem.swift index 6d822fa3f0..b282ddad73 100644 --- a/TelegramUI/InstantPageAudioItem.swift +++ b/TelegramUI/InstantPageAudioItem.swift @@ -19,8 +19,8 @@ final class InstantPageAudioItem: InstantPageItem { self.medias = [media] } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { - return InstantPageAudioNode(account: account, strings: strings, theme: theme, webPage: self.webpage, media: self.media, openMedia: openMedia) + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + return InstantPageAudioNode(context: context, strings: strings, theme: theme, webPage: self.webpage, media: self.media, openMedia: openMedia) } func matchesAnchor(_ anchor: String) -> Bool { diff --git a/TelegramUI/InstantPageAudioNode.swift b/TelegramUI/InstantPageAudioNode.swift index eafd276b3e..df5c1e4d53 100644 --- a/TelegramUI/InstantPageAudioNode.swift +++ b/TelegramUI/InstantPageAudioNode.swift @@ -51,7 +51,7 @@ private func titleString(media: InstantPageMedia, theme: InstantPageTheme) -> NS } final class InstantPageAudioNode: ASDisplayNode, InstantPageNode { - private let account: Account + private let context: AccountContext let media: InstantPageMedia private let openMedia: (InstantPageMedia) -> Void private var strings: PresentationStrings @@ -72,8 +72,8 @@ final class InstantPageAudioNode: ASDisplayNode, InstantPageNode { private var isPlaying: Bool = false private var playbackState: SharedMediaPlayerItemPlaybackState? - init(account: Account, strings: PresentationStrings, theme: InstantPageTheme, webPage: TelegramMediaWebpage, media: InstantPageMedia, openMedia: @escaping (InstantPageMedia) -> Void) { - self.account = account + init(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, webPage: TelegramMediaWebpage, media: InstantPageMedia, openMedia: @escaping (InstantPageMedia) -> Void) { + self.context = context self.strings = strings self.theme = theme self.media = media @@ -130,7 +130,7 @@ final class InstantPageAudioNode: ASDisplayNode, InstantPageNode { self.scrubbingNode.seek = { [weak self] timestamp in if let strongSelf = self { if let _ = strongSelf.playbackState { - strongSelf.account.telegramApplicationContext.mediaManager?.playlistControl(.seek(timestamp), type: strongSelf.playlistType) + strongSelf.context.mediaManager.playlistControl(.seek(timestamp), type: strongSelf.playlistType) } } } @@ -174,12 +174,12 @@ final class InstantPageAudioNode: ASDisplayNode, InstantPageNode { } })*/ - self.scrubbingNode.status = account.telegramApplicationContext.mediaManager!.filteredPlaylistState(playlistId: InstantPageMediaPlaylistId(webpageId: webPage.webpageId), itemId: InstantPageMediaPlaylistItemId(index: self.media.index), type: self.playlistType) + self.scrubbingNode.status = context.mediaManager.filteredPlaylistState(playlistId: InstantPageMediaPlaylistId(webpageId: webPage.webpageId), itemId: InstantPageMediaPlaylistItemId(index: self.media.index), type: self.playlistType) |> map { playbackState -> MediaPlayerStatus in return playbackState?.status ?? MediaPlayerStatus(generationTimestamp: 0.0, duration: 0.0, dimensions: CGSize(), timestamp: 0.0, baseRate: 1.0, seekId: 0, status: .paused) } - self.playerStatusDisposable = (account.telegramApplicationContext.mediaManager!.filteredPlaylistState(playlistId: InstantPageMediaPlaylistId(webpageId: webPage.webpageId), itemId: InstantPageMediaPlaylistItemId(index: self.media.index), type: playlistType) + self.playerStatusDisposable = (context.mediaManager.filteredPlaylistState(playlistId: InstantPageMediaPlaylistId(webpageId: webPage.webpageId), itemId: InstantPageMediaPlaylistItemId(index: self.media.index), type: playlistType) |> deliverOnMainQueue).start(next: { [weak self] playbackState in guard let strongSelf = self else { return @@ -249,7 +249,7 @@ final class InstantPageAudioNode: ASDisplayNode, InstantPageNode { @objc func buttonPressed() { if let _ = self.playbackState { - self.account.telegramApplicationContext.mediaManager?.playlistControl(.playback(.togglePlayPause), type: self.playlistType) + self.context.mediaManager.playlistControl(.playback(.togglePlayPause), type: self.playlistType) } else { self.openMedia(self.media) } diff --git a/TelegramUI/InstantPageContentNode.swift b/TelegramUI/InstantPageContentNode.swift index 2ab8ce4472..96d5cc52ae 100644 --- a/TelegramUI/InstantPageContentNode.swift +++ b/TelegramUI/InstantPageContentNode.swift @@ -6,7 +6,7 @@ import TelegramCore import SwiftSignalKit final class InstantPageContentNode : ASDisplayNode { - private let account: Account + private let context: AccountContext private let strings: PresentationStrings private let theme: InstantPageTheme @@ -34,8 +34,8 @@ final class InstantPageContentNode : ASDisplayNode { private var previousVisibleBounds: CGRect? - init(account: Account, strings: PresentationStrings, theme: InstantPageTheme, items: [InstantPageItem], contentSize: CGSize, inOverlayPanel: Bool = false, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void) { - self.account = account + init(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, items: [InstantPageItem], contentSize: CGSize, inOverlayPanel: Bool = false, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void) { + self.context = context self.strings = strings self.theme = theme @@ -180,7 +180,7 @@ final class InstantPageContentNode : ASDisplayNode { if itemNode == nil { let itemIndex = itemIndex let detailsIndex = detailsIndex - if let newNode = item.node(account: self.account, strings: self.strings, theme: theme, openMedia: { [weak self] media in + if let newNode = item.node(context: self.context, strings: self.strings, theme: theme, openMedia: { [weak self] media in self?.openMedia(media) }, longPressMedia: { [weak self] media in self?.longPressMedia(media) @@ -188,7 +188,7 @@ final class InstantPageContentNode : ASDisplayNode { self?.openPeer(peerId) }, openUrl: { [weak self] url in self?.openUrl(url) - }, updateWebEmbedHeight: { [weak self] height in + }, updateWebEmbedHeight: { _ in }, updateDetailsExpanded: { [weak self] expanded in self?.updateDetailsExpanded(detailsIndex, expanded) }, currentExpandedDetails: self.currentExpandedDetails) { diff --git a/TelegramUI/InstantPageController.swift b/TelegramUI/InstantPageController.swift index 0b91195d64..627f904bab 100644 --- a/TelegramUI/InstantPageController.swift +++ b/TelegramUI/InstantPageController.swift @@ -71,7 +71,7 @@ final class InstantPageController: ViewController { } override func viewWillDisappear(_ animated: Bool) { - let _ = updateInstantPageStoredStateInteractively(postbox: self.contextaccount.postbox, webPage: self.webPage, state: self.controllerNode.currentState).start() + let _ = updateInstantPageStoredStateInteractively(postbox: self.context.account.postbox, webPage: self.webPage, state: self.controllerNode.currentState).start() } override public func loadDisplayNode() { @@ -83,7 +83,7 @@ final class InstantPageController: ViewController { (self?.navigationController as? NavigationController)?.pushViewController(c) }, openPeer: { [weak self] peerId in if let strongSelf = self { - (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(account: strongSelf.account, chatLocation: .peer(peerId))) + (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(context: strongSelf.context, chatLocation: .peer(peerId))) } }, navigateBack: { [weak self] in if let strongSelf = self, let controllers = strongSelf.navigationController?.viewControllers.reversed() { diff --git a/TelegramUI/InstantPageControllerNode.swift b/TelegramUI/InstantPageControllerNode.swift index 4e67a70ae1..066fd46e24 100644 --- a/TelegramUI/InstantPageControllerNode.swift +++ b/TelegramUI/InstantPageControllerNode.swift @@ -499,7 +499,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { let itemIndex = itemIndex let embedIndex = embedIndex let detailsIndex = detailsIndex - if let newNode = item.node(account: self.context.account, strings: self.strings, theme: theme, openMedia: { [weak self] media in + if let newNode = item.node(context: self.context, strings: self.strings, theme: theme, openMedia: { [weak self] media in self?.openMedia(media) }, longPressMedia: { [weak self] media in self?.longPressMedia(media) @@ -866,12 +866,12 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { let controller = ContextMenuController(actions: [ContextMenuAction(content: .text(self.strings.Conversation_ContextMenuCopy), action: { [weak self] in if let strongSelf = self, let image = media.media as? TelegramMediaImage { let media = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: image.representations, immediateThumbnailData: image.immediateThumbnailData, reference: nil, partialReference: nil) - let _ = copyToPasteboard(context: strongSelf.context, postbox: strongSelf.account.postbox, mediaReference: .standalone(media: media)).start() + let _ = copyToPasteboard(context: strongSelf.context, postbox: strongSelf.context.account.postbox, mediaReference: .standalone(media: media)).start() } }), ContextMenuAction(content: .text(self.strings.Conversation_LinkDialogSave), action: { [weak self] in if let strongSelf = self, let image = media.media as? TelegramMediaImage { let media = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: image.representations, immediateThumbnailData: image.immediateThumbnailData, reference: nil, partialReference: nil) - let _ = saveToCameraRoll(context: strongSelf.context, postbox: strongSelf.account.postbox, mediaReference: .standalone(media: media)).start() + let _ = saveToCameraRoll(context: strongSelf.context, postbox: strongSelf.context.account.postbox, mediaReference: .standalone(media: media)).start() } }), ContextMenuAction(content: .text(self.strings.Conversation_ContextMenuShare), action: { [weak self] in if let strongSelf = self, let webPage = strongSelf.webPage, let image = media.media as? TelegramMediaImage { @@ -1131,7 +1131,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { })) } else { strongSelf.loadProgress.set(1.0) - openExternalUrl(context: strongSelf.context, url: externalUrl, presentationData: context.currentPresentationData.with { $0 }, navigationController: strongSelf.getNavigationController(), dismissInput: { + openExternalUrl(context: strongSelf.context, url: externalUrl, presentationData: strongSelf.context.currentPresentationData.with { $0 }, navigationController: strongSelf.getNavigationController(), dismissInput: { self?.view.endEditing(true) }) } diff --git a/TelegramUI/InstantPageDetailsItem.swift b/TelegramUI/InstantPageDetailsItem.swift index 6d5ea686b8..8df24df5a7 100644 --- a/TelegramUI/InstantPageDetailsItem.swift +++ b/TelegramUI/InstantPageDetailsItem.swift @@ -29,12 +29,12 @@ final class InstantPageDetailsItem: InstantPageItem { self.index = index } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { var expanded: Bool? if let expandedDetails = currentExpandedDetails, let currentlyExpanded = expandedDetails[self.index] { expanded = currentlyExpanded } - return InstantPageDetailsNode(account: account, strings: strings, theme: theme, item: self, openMedia: openMedia, longPressMedia: longPressMedia, openPeer: openPeer, openUrl: openUrl, currentlyExpanded: expanded, updateDetailsExpanded: updateDetailsExpanded) + return InstantPageDetailsNode(context: context, strings: strings, theme: theme, item: self, openMedia: openMedia, longPressMedia: longPressMedia, openPeer: openPeer, openUrl: openUrl, currentlyExpanded: expanded, updateDetailsExpanded: updateDetailsExpanded) } func matchesAnchor(_ anchor: String) -> Bool { diff --git a/TelegramUI/InstantPageDetailsNode.swift b/TelegramUI/InstantPageDetailsNode.swift index c82af30566..ec9ffb44f2 100644 --- a/TelegramUI/InstantPageDetailsNode.swift +++ b/TelegramUI/InstantPageDetailsNode.swift @@ -9,7 +9,7 @@ private let detailsInset: CGFloat = 17.0 private let titleInset: CGFloat = 22.0 final class InstantPageDetailsNode: ASDisplayNode, InstantPageNode { - private let account: Account + private let context: AccountContext private let strings: PresentationStrings private let theme: InstantPageTheme let item: InstantPageDetailsItem @@ -30,8 +30,8 @@ final class InstantPageDetailsNode: ASDisplayNode, InstantPageNode { var requestLayoutUpdate: ((Bool) -> Void)? - init(account: Account, strings: PresentationStrings, theme: InstantPageTheme, item: InstantPageDetailsItem, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, currentlyExpanded: Bool?, updateDetailsExpanded: @escaping (Bool) -> Void) { - self.account = account + init(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, item: InstantPageDetailsItem, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, currentlyExpanded: Bool?, updateDetailsExpanded: @escaping (Bool) -> Void) { + self.context = context self.strings = strings self.theme = theme self.item = item @@ -59,7 +59,7 @@ final class InstantPageDetailsNode: ASDisplayNode, InstantPageNode { self.arrowNode = InstantPageDetailsArrowNode(color: theme.controlColor, open: self.expanded) self.separatorNode = ASDisplayNode() - self.contentNode = InstantPageContentNode(account: account, strings: strings, theme: theme, items: item.items, contentSize: CGSize(width: item.frame.width, height: item.frame.height - item.titleHeight), openMedia: openMedia, longPressMedia: longPressMedia, openPeer: openPeer, openUrl: openUrl) + self.contentNode = InstantPageContentNode(context: context, strings: strings, theme: theme, items: item.items, contentSize: CGSize(width: item.frame.width, height: item.frame.height - item.titleHeight), openMedia: openMedia, longPressMedia: longPressMedia, openPeer: openPeer, openUrl: openUrl) super.init() diff --git a/TelegramUI/InstantPageFeedbackItem.swift b/TelegramUI/InstantPageFeedbackItem.swift index ddcd79869b..47782da1f8 100644 --- a/TelegramUI/InstantPageFeedbackItem.swift +++ b/TelegramUI/InstantPageFeedbackItem.swift @@ -16,8 +16,8 @@ final class InstantPageFeedbackItem: InstantPageItem { self.webPage = webPage } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { - return InstantPageFeedbackNode(account: account, strings: strings, theme: theme, webPage: self.webPage, openUrl: openUrl) + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + return InstantPageFeedbackNode(context: context, strings: strings, theme: theme, webPage: self.webPage, openUrl: openUrl) } func matchesAnchor(_ anchor: String) -> Bool { diff --git a/TelegramUI/InstantPageFeedbackNode.swift b/TelegramUI/InstantPageFeedbackNode.swift index 234f312690..b4f4c4a802 100644 --- a/TelegramUI/InstantPageFeedbackNode.swift +++ b/TelegramUI/InstantPageFeedbackNode.swift @@ -6,7 +6,7 @@ import TelegramCore import SwiftSignalKit final class InstantPageFeedbackNode: ASDisplayNode, InstantPageNode { - private let account: Account + private let context: AccountContext private let webPage: TelegramMediaWebpage private let openUrl: (InstantPageUrlItem) -> Void @@ -16,8 +16,8 @@ final class InstantPageFeedbackNode: ASDisplayNode, InstantPageNode { private let resolveDisposable = MetaDisposable() - init(account: Account, strings: PresentationStrings, theme: InstantPageTheme, webPage: TelegramMediaWebpage, openUrl: @escaping (InstantPageUrlItem) -> Void) { - self.account = account + init(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, webPage: TelegramMediaWebpage, openUrl: @escaping (InstantPageUrlItem) -> Void) { + self.context = context self.webPage = webPage self.openUrl = openUrl @@ -59,7 +59,7 @@ final class InstantPageFeedbackNode: ASDisplayNode, InstantPageNode { } @objc func buttonPressed() { - self.resolveDisposable.set((resolvePeerByName(account: self.account, name: "previews") |> deliverOnMainQueue).start(next: { [weak self] peerId in + self.resolveDisposable.set((resolvePeerByName(account: self.context.account, name: "previews") |> deliverOnMainQueue).start(next: { [weak self] peerId in if let strongSelf = self, let peerId = peerId, let webPageId = strongSelf.webPage.id?.id { strongSelf.openUrl(InstantPageUrlItem(url: "https://t.me/previews?start=webpage\(webPageId)", webpageId: nil)) } diff --git a/TelegramUI/InstantPageImageItem.swift b/TelegramUI/InstantPageImageItem.swift index 19a21cc428..5dbf633bf8 100644 --- a/TelegramUI/InstantPageImageItem.swift +++ b/TelegramUI/InstantPageImageItem.swift @@ -40,8 +40,8 @@ final class InstantPageImageItem: InstantPageItem { self.fit = fit } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { - return InstantPageImageNode(account: account, theme: theme, webPage: self.webPage, media: self.media, attributes: self.attributes, interactive: self.interactive, roundCorners: self.roundCorners, fit: self.fit, openMedia: openMedia, longPressMedia: longPressMedia) + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + return InstantPageImageNode(context: context, theme: theme, webPage: self.webPage, media: self.media, attributes: self.attributes, interactive: self.interactive, roundCorners: self.roundCorners, fit: self.fit, openMedia: openMedia, longPressMedia: longPressMedia) } func matchesAnchor(_ anchor: String) -> Bool { diff --git a/TelegramUI/InstantPageImageNode.swift b/TelegramUI/InstantPageImageNode.swift index c89841416b..b59b71749e 100644 --- a/TelegramUI/InstantPageImageNode.swift +++ b/TelegramUI/InstantPageImageNode.swift @@ -6,7 +6,7 @@ import TelegramCore import SwiftSignalKit final class InstantPageImageNode: ASDisplayNode, InstantPageNode { - private let account: Account + private let context: AccountContext private let webPage: TelegramMediaWebpage private var theme: InstantPageTheme let media: InstantPageMedia @@ -30,8 +30,8 @@ final class InstantPageImageNode: ASDisplayNode, InstantPageNode { private var themeUpdated: Bool = false - init(account: Account, theme: InstantPageTheme, webPage: TelegramMediaWebpage, media: InstantPageMedia, attributes: [InstantPageImageAttribute], interactive: Bool, roundCorners: Bool, fit: Bool, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void) { - self.account = account + init(context: AccountContext, theme: InstantPageTheme, webPage: TelegramMediaWebpage, media: InstantPageMedia, attributes: [InstantPageImageAttribute], interactive: Bool, roundCorners: Bool, fit: Bool, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void) { + self.context = context self.theme = theme self.webPage = webPage self.media = media @@ -53,11 +53,11 @@ final class InstantPageImageNode: ASDisplayNode, InstantPageNode { if let image = media.media as? TelegramMediaImage, let largest = largestImageRepresentation(image.representations) { let imageReference = ImageMediaReference.webPage(webPage: WebpageReference(webPage), media: image) - self.imageNode.setSignal(chatMessagePhoto(postbox: account.postbox, photoReference: imageReference)) - self.fetchedDisposable.set(chatMessagePhotoInteractiveFetched(account: account, photoReference: imageReference, storeToDownloadsPeerType: nil).start()) + self.imageNode.setSignal(chatMessagePhoto(postbox: context.account.postbox, photoReference: imageReference)) + self.fetchedDisposable.set(chatMessagePhotoInteractiveFetched(context: context, photoReference: imageReference, storeToDownloadsPeerType: nil).start()) if interactive { - self.statusDisposable.set((account.postbox.mediaBox.resourceStatus(largest.resource) |> deliverOnMainQueue).start(next: { [weak self] status in + self.statusDisposable.set((context.account.postbox.mediaBox.resourceStatus(largest.resource) |> deliverOnMainQueue).start(next: { [weak self] status in displayLinkDispatcher.dispatch { if let strongSelf = self { strongSelf.fetchStatus = status @@ -76,10 +76,10 @@ final class InstantPageImageNode: ASDisplayNode, InstantPageNode { } else if let file = media.media as? TelegramMediaFile { let fileReference = FileMediaReference.webPage(webPage: WebpageReference(webPage), media: file) if file.mimeType.hasPrefix("image/") { - _ = freeMediaFileInteractiveFetched(account: account, fileReference: fileReference).start() - self.imageNode.setSignal(instantPageImageFile(account: account, fileReference: fileReference, fetched: true)) + _ = freeMediaFileInteractiveFetched(account: context.account, fileReference: fileReference).start() + self.imageNode.setSignal(instantPageImageFile(account: context.account, fileReference: fileReference, fetched: true)) } else { - self.imageNode.setSignal(chatMessageVideo(postbox: account.postbox, videoReference: fileReference)) + self.imageNode.setSignal(chatMessageVideo(postbox: context.account.postbox, videoReference: fileReference)) } } else if let map = media.media as? TelegramMediaMap { self.addSubnode(self.pinNode) @@ -94,11 +94,11 @@ final class InstantPageImageNode: ASDisplayNode, InstantPageNode { } } let resource = MapSnapshotMediaResource(latitude: map.latitude, longitude: map.longitude, width: Int32(dimensions.width), height: Int32(dimensions.height)) - self.imageNode.setSignal(chatMapSnapshotImage(account: account, resource: resource)) + self.imageNode.setSignal(chatMapSnapshotImage(account: context.account, resource: resource)) } else if let webPage = media.media as? TelegramMediaWebpage, case let .Loaded(content) = webPage.content, let image = content.image { let imageReference = ImageMediaReference.webPage(webPage: WebpageReference(webPage), media: image) - self.imageNode.setSignal(chatMessagePhoto(postbox: account.postbox, photoReference: imageReference)) - self.fetchedDisposable.set(chatMessagePhotoInteractiveFetched(account: account, photoReference: imageReference, storeToDownloadsPeerType: nil).start()) + self.imageNode.setSignal(chatMessagePhoto(postbox: context.account.postbox, photoReference: imageReference)) + self.fetchedDisposable.set(chatMessagePhotoInteractiveFetched(context: context, photoReference: imageReference, storeToDownloadsPeerType: nil).start()) self.statusNode.transitionToState(.play(.white), animated: false, completion: {}) self.addSubnode(self.statusNode) } @@ -198,8 +198,8 @@ final class InstantPageImageNode: ASDisplayNode, InstantPageNode { } let makePinLayout = self.pinNode.asyncLayout() - let theme = self.account.telegramApplicationContext.currentPresentationData.with { $0 }.theme - let (pinSize, pinApply) = makePinLayout(self.account, theme, nil, false) + let theme = self.context.currentPresentationData.with { $0 }.theme + let (pinSize, pinApply) = makePinLayout(self.context.account, theme, nil, false) self.pinNode.frame = CGRect(origin: CGPoint(x: floor((size.width - pinSize.width) / 2.0), y: floor(size.height * 0.5 - 10.0 - pinSize.height / 2.0)), size: pinSize) pinApply() } else if let webPage = media.media as? TelegramMediaWebpage, case let .Loaded(content) = webPage.content, let image = content.image, let largest = largestImageRepresentation(image.representations) { diff --git a/TelegramUI/InstantPageItem.swift b/TelegramUI/InstantPageItem.swift index feb88bad24..6eff881521 100644 --- a/TelegramUI/InstantPageItem.swift +++ b/TelegramUI/InstantPageItem.swift @@ -11,7 +11,7 @@ protocol InstantPageItem { func matchesAnchor(_ anchor: String) -> Bool func drawInTile(context: CGContext) - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? func matchesNode(_ node: InstantPageNode) -> Bool func linkSelectionRects(at point: CGPoint) -> [CGRect] diff --git a/TelegramUI/InstantPagePeerReferenceItem.swift b/TelegramUI/InstantPagePeerReferenceItem.swift index 7cb3f48b9f..e4c415aa98 100644 --- a/TelegramUI/InstantPagePeerReferenceItem.swift +++ b/TelegramUI/InstantPagePeerReferenceItem.swift @@ -22,8 +22,8 @@ final class InstantPagePeerReferenceItem: InstantPageItem { self.rtl = rtl } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { - return InstantPagePeerReferenceNode(account: account, strings: strings, theme: theme, initialPeer: self.initialPeer, safeInset: self.safeInset, transparent: self.transparent, rtl: self.rtl, openPeer: openPeer) + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + return InstantPagePeerReferenceNode(context: context, strings: strings, theme: theme, initialPeer: self.initialPeer, safeInset: self.safeInset, transparent: self.transparent, rtl: self.rtl, openPeer: openPeer) } func matchesAnchor(_ anchor: String) -> Bool { diff --git a/TelegramUI/InstantPagePeerReferenceNode.swift b/TelegramUI/InstantPagePeerReferenceNode.swift index c3c0792e4a..b94ebe8069 100644 --- a/TelegramUI/InstantPagePeerReferenceNode.swift +++ b/TelegramUI/InstantPagePeerReferenceNode.swift @@ -42,7 +42,7 @@ private enum JoinState: Equatable { } final class InstantPagePeerReferenceNode: ASDisplayNode, InstantPageNode { - private let account: Account + private let context: AccountContext let safeInset: CGFloat private let transparent: Bool private let rtl: Bool @@ -63,8 +63,8 @@ final class InstantPagePeerReferenceNode: ASDisplayNode, InstantPageNode { private let joinDisposable = MetaDisposable() private var joinState: JoinState = .none - init(account: Account, strings: PresentationStrings, theme: InstantPageTheme, initialPeer: Peer, safeInset: CGFloat, transparent: Bool, rtl: Bool, openPeer: @escaping (PeerId) -> Void) { - self.account = account + init(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, initialPeer: Peer, safeInset: CGFloat, transparent: Bool, rtl: Bool, openPeer: @escaping (PeerId) -> Void) { + self.context = context self.strings = strings self.theme = theme self.peer = initialPeer @@ -137,7 +137,7 @@ final class InstantPagePeerReferenceNode: ASDisplayNode, InstantPageNode { self.buttonNode.addTarget(self, action: #selector(self.buttonPressed), forControlEvents: .touchUpInside) self.joinNode.addTarget(self, action: #selector(self.joinPressed), forControlEvents: .touchUpInside) - let account = self.account + let account = self.context.account let signal = actualizedPeer(postbox: account.postbox, network: account.network, peer: initialPeer) |> mapToSignal({ peer -> Signal in if let peer = peer as? TelegramChannel, let username = peer.username, peer.accessHash == nil { @@ -300,7 +300,7 @@ final class InstantPagePeerReferenceNode: ASDisplayNode, InstantPageNode { @objc func joinPressed() { if let peer = self.peer, case .notJoined = self.joinState { self.updateJoinState(.inProgress) - self.joinDisposable.set((joinChannel(account: self.account, peerId: peer.id) |> deliverOnMainQueue).start(error: { [weak self] _ in + self.joinDisposable.set((joinChannel(account: self.context.account, peerId: peer.id) |> deliverOnMainQueue).start(error: { [weak self] _ in if let strongSelf = self { if case .inProgress = strongSelf.joinState { strongSelf.updateJoinState(.notJoined) diff --git a/TelegramUI/InstantPagePlayableVideoItem.swift b/TelegramUI/InstantPagePlayableVideoItem.swift index 863feba41a..41cd76a05c 100644 --- a/TelegramUI/InstantPagePlayableVideoItem.swift +++ b/TelegramUI/InstantPagePlayableVideoItem.swift @@ -24,8 +24,8 @@ final class InstantPagePlayableVideoItem: InstantPageItem { self.interactive = interactive } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { - return InstantPagePlayableVideoNode(account: account, webPage: self.webPage, theme: theme, media: self.media, interactive: self.interactive, openMedia: openMedia) + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + return InstantPagePlayableVideoNode(context: context, webPage: self.webPage, theme: theme, media: self.media, interactive: self.interactive, openMedia: openMedia) } func matchesAnchor(_ anchor: String) -> Bool { diff --git a/TelegramUI/InstantPagePlayableVideoNode.swift b/TelegramUI/InstantPagePlayableVideoNode.swift index 58248b5d1f..e0017a1007 100644 --- a/TelegramUI/InstantPagePlayableVideoNode.swift +++ b/TelegramUI/InstantPagePlayableVideoNode.swift @@ -6,7 +6,7 @@ import TelegramCore import SwiftSignalKit final class InstantPagePlayableVideoNode: ASDisplayNode, InstantPageNode { - private let account: Account + private let context: AccountContext let media: InstantPageMedia private let interactive: Bool private let openMedia: (InstantPageMedia) -> Void @@ -19,8 +19,8 @@ final class InstantPagePlayableVideoNode: ASDisplayNode, InstantPageNode { private var localIsVisible = false - init(account: Account, webPage: TelegramMediaWebpage, theme: InstantPageTheme, media: InstantPageMedia, interactive: Bool, openMedia: @escaping (InstantPageMedia) -> Void) { - self.account = account + init(context: AccountContext, webPage: TelegramMediaWebpage, theme: InstantPageTheme, media: InstantPageMedia, interactive: Bool, openMedia: @escaping (InstantPageMedia) -> Void) { + self.context = context self.media = media self.interactive = interactive self.openMedia = openMedia @@ -31,7 +31,7 @@ final class InstantPagePlayableVideoNode: ASDisplayNode, InstantPageNode { imageReference = ImageMediaReference.webPage(webPage: WebpageReference(webPage), media: image) } - self.videoNode = UniversalVideoNode(postbox: account.postbox, audioSession: context.mediaManager.audioSession, manager: context.universalVideoManager, decoration: GalleryVideoDecoration(), content: NativeVideoContent(id: .instantPage(webPage.webpageId, media.media.id!), fileReference: .webPage(webPage: WebpageReference(webPage), media: media.media as! TelegramMediaFile), imageReference: imageReference, loopVideo: true, enableSound: false, fetchAutomatically: true, placeholderColor: theme.pageBackgroundColor), priority: .embedded, autoplay: true) + self.videoNode = UniversalVideoNode(postbox: context.account.postbox, audioSession: context.mediaManager.audioSession, manager: context.mediaManager.universalVideoManager, decoration: GalleryVideoDecoration(), content: NativeVideoContent(id: .instantPage(webPage.webpageId, media.media.id!), fileReference: .webPage(webPage: WebpageReference(webPage), media: media.media as! TelegramMediaFile), imageReference: imageReference, loopVideo: true, enableSound: false, fetchAutomatically: true, placeholderColor: theme.pageBackgroundColor), priority: .embedded, autoplay: true) self.videoNode.isUserInteractionEnabled = false super.init() @@ -39,7 +39,7 @@ final class InstantPagePlayableVideoNode: ASDisplayNode, InstantPageNode { self.addSubnode(self.videoNode) if let file = media.media as? TelegramMediaFile { - self.fetchedDisposable.set(fetchedMediaResource(postbox: account.postbox, reference: AnyMediaReference.webPage(webPage: WebpageReference(webPage), media: file).resourceReference(file.resource)).start()) + self.fetchedDisposable.set(fetchedMediaResource(postbox: context.account.postbox, reference: AnyMediaReference.webPage(webPage: WebpageReference(webPage), media: file).resourceReference(file.resource)).start()) } } diff --git a/TelegramUI/InstantPageReferenceControllerNode.swift b/TelegramUI/InstantPageReferenceControllerNode.swift index d2c9e13a94..58b3d157b9 100644 --- a/TelegramUI/InstantPageReferenceControllerNode.swift +++ b/TelegramUI/InstantPageReferenceControllerNode.swift @@ -33,7 +33,7 @@ class InstantPageReferenceControllerNode: ViewControllerTracingNode, UIScrollVie var close: (() -> Void)? init(context: AccountContext, theme: InstantPageTheme, webPage: TelegramMediaWebpage, item: InstantPageTextItem, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlIn: @escaping (InstantPageUrlItem) -> Void, present: @escaping (ViewController, Any?) -> Void) { - self.account = account + self.context = context self.presentationData = context.currentPresentationData.with { $0 } self.theme = theme self.webPage = webPage diff --git a/TelegramUI/InstantPageShapeItem.swift b/TelegramUI/InstantPageShapeItem.swift index de91ce4a69..71699dbb6b 100644 --- a/TelegramUI/InstantPageShapeItem.swift +++ b/TelegramUI/InstantPageShapeItem.swift @@ -57,7 +57,7 @@ final class InstantPageShapeItem: InstantPageItem { return false } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { return nil } diff --git a/TelegramUI/InstantPageSlideshowItem.swift b/TelegramUI/InstantPageSlideshowItem.swift index c619270a1e..787b3132b3 100644 --- a/TelegramUI/InstantPageSlideshowItem.swift +++ b/TelegramUI/InstantPageSlideshowItem.swift @@ -16,8 +16,8 @@ final class InstantPageSlideshowItem: InstantPageItem { self.medias = medias } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { - return InstantPageSlideshowNode(account: account, theme: theme, webPage: webPage, medias: self.medias, openMedia: openMedia, longPressMedia: longPressMedia) + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + return InstantPageSlideshowNode(context: context, theme: theme, webPage: webPage, medias: self.medias, openMedia: openMedia, longPressMedia: longPressMedia) } func matchesAnchor(_ anchor: String) -> Bool { diff --git a/TelegramUI/InstantPageSlideshowItemNode.swift b/TelegramUI/InstantPageSlideshowItemNode.swift index 2b17bfef1e..3569d9f490 100644 --- a/TelegramUI/InstantPageSlideshowItemNode.swift +++ b/TelegramUI/InstantPageSlideshowItemNode.swift @@ -59,7 +59,7 @@ private final class InstantPageSlideshowItemNode: ASDisplayNode { } private final class InstantPageSlideshowPagerNode: ASDisplayNode, UIScrollViewDelegate { - private let account: Account + private let context: AccountContext private let theme: InstantPageTheme private let webPage: TelegramMediaWebpage private let openMedia: (InstantPageMedia) -> Void @@ -93,8 +93,8 @@ private final class InstantPageSlideshowPagerNode: ASDisplayNode, UIScrollViewDe } } - init(account: Account, theme: InstantPageTheme, webPage: TelegramMediaWebpage, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, pageGap: CGFloat = 0.0) { - self.account = account + init(context: AccountContext, theme: InstantPageTheme, webPage: TelegramMediaWebpage, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, pageGap: CGFloat = 0.0) { + self.context = context self.theme = theme self.webPage = webPage self.openMedia = openMedia @@ -176,7 +176,7 @@ private final class InstantPageSlideshowPagerNode: ASDisplayNode, UIScrollViewDe let media = self.items[index] let contentNode: ASDisplayNode if let _ = media.media as? TelegramMediaImage { - contentNode = InstantPageImageNode(account: self.account, theme: self.theme, webPage: self.webPage, media: media, attributes: [], interactive: true, roundCorners: false, fit: false, openMedia: self.openMedia, longPressMedia: self.longPressMedia) + contentNode = InstantPageImageNode(context: self.context, theme: self.theme, webPage: self.webPage, media: media, attributes: [], interactive: true, roundCorners: false, fit: false, openMedia: self.openMedia, longPressMedia: self.longPressMedia) } else if let file = media.media as? TelegramMediaFile { contentNode = ASDisplayNode() } else { @@ -375,10 +375,10 @@ final class InstantPageSlideshowNode: ASDisplayNode, InstantPageNode { private let pagerNode: InstantPageSlideshowPagerNode private let pageControlNode: PageControlNode - init(account: Account, theme: InstantPageTheme, webPage: TelegramMediaWebpage, medias: [InstantPageMedia], openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void) { + init(context: AccountContext, theme: InstantPageTheme, webPage: TelegramMediaWebpage, medias: [InstantPageMedia], openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void) { self.medias = medias - self.pagerNode = InstantPageSlideshowPagerNode(account: account, theme: theme, webPage: webPage, openMedia: openMedia, longPressMedia: longPressMedia) + self.pagerNode = InstantPageSlideshowPagerNode(context: context, theme: theme, webPage: webPage, openMedia: openMedia, longPressMedia: longPressMedia) self.pagerNode.replaceItems(medias, centralItemIndex: nil) self.pageControlNode = PageControlNode(dotColor: .white) diff --git a/TelegramUI/InstantPageTableItem.swift b/TelegramUI/InstantPageTableItem.swift index dfe8d1d631..bc08ea8d41 100644 --- a/TelegramUI/InstantPageTableItem.swift +++ b/TelegramUI/InstantPageTableItem.swift @@ -194,12 +194,12 @@ final class InstantPageTableItem: InstantPageScrollableItem { return false } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { var additionalNodes: [InstantPageNode] = [] for cell in self.cells { for item in cell.additionalItems { if item.wantsNode { - if let node = item.node(account: account, strings: strings, theme: theme, openMedia: { _ in }, longPressMedia: { _ in }, openPeer: { _ in }, openUrl: { _ in}, updateWebEmbedHeight: { _ in }, updateDetailsExpanded: { _ in }, currentExpandedDetails: nil) { + if let node = item.node(context: context, strings: strings, theme: theme, openMedia: { _ in }, longPressMedia: { _ in }, openPeer: { _ in }, openUrl: { _ in}, updateWebEmbedHeight: { _ in }, updateDetailsExpanded: { _ in }, currentExpandedDetails: nil) { node.frame = item.frame.offsetBy(dx: cell.frame.minX, dy: cell.frame.minY) additionalNodes.append(node) } diff --git a/TelegramUI/InstantPageTextItem.swift b/TelegramUI/InstantPageTextItem.swift index 6f6e181483..a47d5e9989 100644 --- a/TelegramUI/InstantPageTextItem.swift +++ b/TelegramUI/InstantPageTextItem.swift @@ -312,7 +312,7 @@ final class InstantPageTextItem: InstantPageItem { return false } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { return nil } @@ -361,11 +361,11 @@ final class InstantPageScrollableTextItem: InstantPageScrollableItem { context.restoreGState() } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (ASDisplayNode & InstantPageNode)? { + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (ASDisplayNode & InstantPageNode)? { var additionalNodes: [InstantPageNode] = [] for item in additionalItems { if item.wantsNode { - if let node = item.node(account: account, strings: strings, theme: theme, openMedia: { _ in }, longPressMedia: { _ in }, openPeer: { _ in }, openUrl: { _ in}, updateWebEmbedHeight: { _ in }, updateDetailsExpanded: { _ in }, currentExpandedDetails: nil) { + if let node = item.node(context: context, strings: strings, theme: theme, openMedia: { _ in }, longPressMedia: { _ in }, openPeer: { _ in }, openUrl: { _ in}, updateWebEmbedHeight: { _ in }, updateDetailsExpanded: { _ in }, currentExpandedDetails: nil) { node.frame = item.frame additionalNodes.append(node) } diff --git a/TelegramUI/InstantPageWebEmbedItem.swift b/TelegramUI/InstantPageWebEmbedItem.swift index 7fff8cebd6..7857afa587 100644 --- a/TelegramUI/InstantPageWebEmbedItem.swift +++ b/TelegramUI/InstantPageWebEmbedItem.swift @@ -20,7 +20,7 @@ final class InstantPageWebEmbedItem: InstantPageItem { self.enableScrolling = enableScrolling } - func node(account: Account, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { + func node(context: AccountContext, strings: PresentationStrings, theme: InstantPageTheme, openMedia: @escaping (InstantPageMedia) -> Void, longPressMedia: @escaping (InstantPageMedia) -> Void, openPeer: @escaping (PeerId) -> Void, openUrl: @escaping (InstantPageUrlItem) -> Void, updateWebEmbedHeight: @escaping (CGFloat) -> Void, updateDetailsExpanded: @escaping (Bool) -> Void, currentExpandedDetails: [Int : Bool]?) -> (InstantPageNode & ASDisplayNode)? { return InstantPageWebEmbedNode(frame: self.frame, url: self.url, html: self.html, enableScrolling: self.enableScrolling, updateWebEmbedHeight: updateWebEmbedHeight) } diff --git a/TelegramUI/InviteContactsController.swift b/TelegramUI/InviteContactsController.swift index 1bc46cd38f..f17ab0298d 100644 --- a/TelegramUI/InviteContactsController.swift +++ b/TelegramUI/InviteContactsController.swift @@ -85,7 +85,7 @@ public class InviteContactsController: ViewController, MFMessageComposeViewContr } override public func loadDisplayNode() { - self.displayNode = InviteContactsControllerNode(account: self.account) + self.displayNode = InviteContactsControllerNode(context: self.context) self._ready.set(self.contactsNode.ready) self.contactsNode.navigationBar = self.navigationBar diff --git a/TelegramUI/InviteContactsControllerNode.swift b/TelegramUI/InviteContactsControllerNode.swift index f06ae300c2..0f2a6e7330 100644 --- a/TelegramUI/InviteContactsControllerNode.swift +++ b/TelegramUI/InviteContactsControllerNode.swift @@ -323,7 +323,7 @@ final class InviteContactsControllerNode: ASDisplayNode { } }) - let account = self.account + let account = self.context.account var firstTime: Int32 = 1 let selectionStateSignal = self.selectionStatePromise.get() let transition: Signal diff --git a/TelegramUI/JoinLinkPreviewControllerNode.swift b/TelegramUI/JoinLinkPreviewControllerNode.swift index 6b69dc9bdd..3de3a265e7 100644 --- a/TelegramUI/JoinLinkPreviewControllerNode.swift +++ b/TelegramUI/JoinLinkPreviewControllerNode.swift @@ -452,6 +452,6 @@ final class JoinLinkPreviewControllerNode: ViewControllerTracingNode, UIScrollVi self.actionButtonNode.setTitle(data.isGroup ? self.presentationData.strings.Invitation_JoinGroup : self.presentationData.strings.Channel_JoinChannel, with: Font.medium(20.0), with: self.presentationData.theme.actionSheet.standardActionTextColor, for: .normal) } - self.transitionToContentNode(JoinLinkPreviewPeerContentNode(account: self.context.account, image: image, title: title, memberCount: memberCount, members: members, theme: self.presentationData.theme, strings: self.presentationData.strings)) + self.transitionToContentNode(JoinLinkPreviewPeerContentNode(context: self.context, image: image, title: title, memberCount: memberCount, members: members, theme: self.presentationData.theme, strings: self.presentationData.strings)) } } diff --git a/TelegramUI/LegacyAttachmentMenu.swift b/TelegramUI/LegacyAttachmentMenu.swift index 5126fc0a03..6673329a10 100644 --- a/TelegramUI/LegacyAttachmentMenu.swift +++ b/TelegramUI/LegacyAttachmentMenu.swift @@ -6,7 +6,7 @@ import SwiftSignalKit import Postbox import TelegramCore -func legacyAttachmentMenu(account: Account, peer: Peer, editMediaOptions: MessageMediaEditingOptions?, saveEditedPhotos: Bool, allowGrouping: Bool, theme: PresentationTheme, strings: PresentationStrings, parentController: LegacyController, recentlyUsedInlineBots: [Peer], openGallery: @escaping () -> Void, openCamera: @escaping (TGAttachmentCameraView?, TGMenuSheetController?) -> Void, openFileGallery: @escaping () -> Void, openWebSearch: @escaping () -> Void, openMap: @escaping () -> Void, openContacts: @escaping () -> Void, openPoll: @escaping () -> Void, sendMessagesWithSignals: @escaping ([Any]?) -> Void, selectRecentlyUsedInlineBot: @escaping (Peer) -> Void) -> TGMenuSheetController { +func legacyAttachmentMenu(context: AccountContext, peer: Peer, editMediaOptions: MessageMediaEditingOptions?, saveEditedPhotos: Bool, allowGrouping: Bool, theme: PresentationTheme, strings: PresentationStrings, parentController: LegacyController, recentlyUsedInlineBots: [Peer], openGallery: @escaping () -> Void, openCamera: @escaping (TGAttachmentCameraView?, TGMenuSheetController?) -> Void, openFileGallery: @escaping () -> Void, openWebSearch: @escaping () -> Void, openMap: @escaping () -> Void, openContacts: @escaping () -> Void, openPoll: @escaping () -> Void, sendMessagesWithSignals: @escaping ([Any]?) -> Void, selectRecentlyUsedInlineBot: @escaping (Peer) -> Void) -> TGMenuSheetController { let isSecretChat = peer.id.namespace == Namespaces.Peer.SecretChat let controller = TGMenuSheetController(context: parentController.context, dark: false)! @@ -35,18 +35,18 @@ func legacyAttachmentMenu(account: Account, peer: Peer, editMediaOptions: Messag if canSendImageOrVideo { let carouselItem = TGAttachmentCarouselItemView(context: parentController.context, camera: PGCamera.cameraAvailable(), selfPortrait: false, forProfilePhoto: false, assetType: TGMediaAssetAnyType, saveEditedPhotos: !isSecretChat && saveEditedPhotos, allowGrouping: editMediaOptions == nil && allowGrouping, allowSelection: editMediaOptions == nil, allowEditing: true, document: false)! carouselItemView = carouselItem - carouselItem.suggestionContext = legacySuggestionContext(account: account, peerId: peer.id) + carouselItem.suggestionContext = legacySuggestionContext(account: context.account, peerId: peer.id) carouselItem.recipientName = peer.displayTitle carouselItem.cameraPressed = { [weak controller] cameraView in if let controller = controller { - DeviceAccess.authorizeAccess(to: .camera, presentationData: account.telegramApplicationContext.currentPresentationData.with { $0 }, present: account.telegramApplicationContext.presentGlobalController, openSettings: account.telegramApplicationContext.applicationBindings.openSettings, { value in + DeviceAccess.authorizeAccess(to: .camera, presentationData: context.currentPresentationData.with { $0 }, present: context.presentGlobalController, openSettings: context.applicationBindings.openSettings, { value in if value { openCamera(cameraView, controller) } }) } } - if (peer is TelegramUser) && peer.id != account.peerId { + if (peer is TelegramUser) && peer.id != context.account.peerId { carouselItem.hasTimer = true } carouselItem.sendPressed = { [weak controller, weak carouselItem] currentItem, asFiles in @@ -151,7 +151,7 @@ func legacyMenuPaletteFromTheme(_ theme: PresentationTheme) -> TGMenuSheetPallet return TGMenuSheetPallete(dark: theme.overallDarkAppearance, backgroundColor: sheetTheme.opaqueItemBackgroundColor, selectionColor: sheetTheme.opaqueItemHighlightedBackgroundColor, separatorColor: sheetTheme.opaqueItemSeparatorColor, accentColor: sheetTheme.controlAccentColor, destructiveColor: sheetTheme.destructiveActionTextColor, textColor: sheetTheme.primaryTextColor, secondaryTextColor: sheetTheme.secondaryTextColor, spinnerColor: sheetTheme.secondaryTextColor, badgeTextColor: sheetTheme.controlAccentColor, badgeImage: nil, cornersImage: generateStretchableFilledCircleImage(diameter: 11.0, color: nil, strokeColor: nil, strokeWidth: nil, backgroundColor: sheetTheme.opaqueItemBackgroundColor)) } -func presentLegacyPasteMenu(account: Account, peer: Peer, saveEditedPhotos: Bool, allowGrouping: Bool, theme: PresentationTheme, strings: PresentationStrings, images: [UIImage], sendMessagesWithSignals: @escaping ([Any]?) -> Void, present: (ViewController, Any?) -> Void, initialLayout: ContainerViewLayout? = nil) -> ViewController { +func presentLegacyPasteMenu(context: AccountContext, peer: Peer, saveEditedPhotos: Bool, allowGrouping: Bool, theme: PresentationTheme, strings: PresentationStrings, images: [UIImage], sendMessagesWithSignals: @escaping ([Any]?) -> Void, present: (ViewController, Any?) -> Void, initialLayout: ContainerViewLayout? = nil) -> ViewController { let legacyController = LegacyController(presentation: .custom, theme: theme, initialLayout: initialLayout) legacyController.statusBar.statusBarStyle = .Ignore legacyController.controllerLoaded = { [weak legacyController] in @@ -164,7 +164,7 @@ func presentLegacyPasteMenu(account: Account, peer: Peer, saveEditedPhotos: Bool legacyController.bind(controller: navigationController) var hasTimer = false - if (peer is TelegramUser) && peer.id != account.peerId { + if (peer is TelegramUser) && peer.id != context.account.peerId { hasTimer = true } let recipientName = peer.displayTitle @@ -181,7 +181,7 @@ func presentLegacyPasteMenu(account: Account, peer: Peer, saveEditedPhotos: Bool legacyController?.dismiss() } - let presentationDisposable = account.telegramApplicationContext.presentationData.start(next: { [weak legacyController] presentationData in + let presentationDisposable = context.presentationData.start(next: { [weak legacyController] presentationData in if let legacyController = legacyController, let controller = legacyController.legacyController as? TGMenuSheetController { controller.pallete = legacyMenuPaletteFromTheme(presentationData.theme) } diff --git a/TelegramUI/LegacyCamera.swift b/TelegramUI/LegacyCamera.swift index 96667125a4..84e248ab8c 100644 --- a/TelegramUI/LegacyCamera.swift +++ b/TelegramUI/LegacyCamera.swift @@ -7,7 +7,7 @@ import Postbox import SwiftSignalKit func presentedLegacyCamera(context: AccountContext, peer: Peer, cameraView: TGAttachmentCameraView?, menuController: TGMenuSheetController?, parentController: ViewController, editingMedia: Bool, saveCapturedPhotos: Bool, mediaGrouping: Bool, sendMessagesWithSignals: @escaping ([Any]?) -> Void, recognizedQRCode: @escaping (String) -> Void = { _ in }) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: .custom, theme: presentationData.theme) legacyController.supportedOrientations = ViewControllerSupportedOrientations(regularSize: .portrait, compactSize: .portrait) legacyController.statusBar.statusBarStyle = .Hide @@ -31,7 +31,7 @@ func presentedLegacyCamera(context: AccountContext, peer: Peer, cameraView: TGAt return } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let overlayLegacyController = LegacyController(presentation: .custom, theme: presentationData.theme) overlayLegacyController.supportedOrientations = ViewControllerSupportedOrientations(regularSize: .portrait, compactSize: .portrait) overlayLegacyController.statusBar.statusBarStyle = .Hide @@ -53,9 +53,9 @@ func presentedLegacyCamera(context: AccountContext, peer: Peer, cameraView: TGAt controller.allowCaptionEntities = true controller.allowGrouping = mediaGrouping controller.inhibitDocumentCaptions = false - controller.suggestionContext = legacySuggestionContext(account: account, peerId: peer.id) + controller.suggestionContext = legacySuggestionContext(account: context.account, peerId: peer.id) controller.recipientName = peer.displayTitle - if (peer is TelegramUser) && peer.id != account.peerId { + if (peer is TelegramUser) && peer.id != context.account.peerId { controller.hasTimer = true } @@ -188,14 +188,14 @@ func presentedLegacyShortcutCamera(context: AccountContext, saveCapturedMedia: B if let selectionContext = selectionContext, let editingContext = editingContext { let signals = TGCameraController.resultSignals(for: selectionContext, editingContext: editingContext, currentItem: currentItem, storeAssets: saveCapturedMedia, saveEditedPhotos: saveEditedPhotos, descriptionGenerator: legacyAssetPickerItemGenerator()) if let parentController = parentController { - parentController.present(ShareController(account: account, subject: .fromExternal({ peerIds, text in - return legacyAssetPickerEnqueueMessages(account: account, signals: signals!) + parentController.present(ShareController(context: context, subject: .fromExternal({ peerIds, text in + return legacyAssetPickerEnqueueMessages(account: context.account, signals: signals!) |> `catch` { _ -> Signal<[EnqueueMessage], NoError> in return .single([]) } |> mapToSignal { messages -> Signal in let resultSignals = peerIds.map({ peerId in - return enqueueMessages(account: account, peerId: peerId, messages: messages) + return enqueueMessages(account: context.account, peerId: peerId, messages: messages) |> mapToSignal { _ -> Signal in return .complete() } diff --git a/TelegramUI/LegacyChannelIntroController.swift b/TelegramUI/LegacyChannelIntroController.swift index 93bb6b0ab3..cc2ee52ab1 100644 --- a/TelegramUI/LegacyChannelIntroController.swift +++ b/TelegramUI/LegacyChannelIntroController.swift @@ -4,7 +4,7 @@ import Display import TelegramUIPrivateModule -func legacyChannelIntroController(account: Account, theme: PresentationTheme, strings: PresentationStrings) -> ViewController { +func legacyChannelIntroController(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings) -> ViewController { let controller = LegacyController(presentation: .custom, theme: theme) controller.bind(controller: TGChannelIntroController(context: controller.context, getLocalizedString: { string in guard let string = string else { @@ -23,7 +23,7 @@ func legacyChannelIntroController(account: Account, theme: PresentationTheme, st } }, completion: { [weak controller] in if let navigationController = controller?.navigationController as? NavigationController { - navigationController.replaceTopController(createChannelController(account: account), animated: true) + navigationController.replaceTopController(createChannelController(context: context), animated: true) } })!) return controller diff --git a/TelegramUI/LegacyEmptyController.swift b/TelegramUI/LegacyEmptyController.swift index 6dac6436ca..592102919d 100644 --- a/TelegramUI/LegacyEmptyController.swift +++ b/TelegramUI/LegacyEmptyController.swift @@ -18,8 +18,8 @@ final class LegacyEmptyController: TGViewController { override func present(context generator: ((LegacyComponentsContext?) -> UIViewController?)!) { if let context = self.context as? LegacyControllerContext, let controller = context.controller { - let account = legacyAccountGet() - let presentationData = account?.telegramApplicationContext.currentPresentationData.with { $0 } + let context = legacyContextGet() + let presentationData = context?.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: .modal(animateIn: true), theme: presentationData?.theme, initialLayout: controller.currentlyAppliedLayout) guard let presentedController = generator(legacyController.context) else { diff --git a/TelegramUI/LegacyImageDownloadActor.swift b/TelegramUI/LegacyImageDownloadActor.swift index dda05fc9a2..c4d4d6b0ff 100644 --- a/TelegramUI/LegacyImageDownloadActor.swift +++ b/TelegramUI/LegacyImageDownloadActor.swift @@ -50,7 +50,7 @@ final class LegacyImageDownloadActor: ASActor { } else if let resource = resourceFromLegacyImageUri(url) { let disposables = DisposableSet() self.disposable.set(disposables) - if let account = legacyAccountGet() { + if let account = legacyContextGet()?.account { let path = self.path disposables.add(account.postbox.mediaBox.resourceData(resource).start(next: { data in if data.complete { diff --git a/TelegramUI/LegacyInstantVideoController.swift b/TelegramUI/LegacyInstantVideoController.swift index 92b387c8a8..e974c426fb 100644 --- a/TelegramUI/LegacyInstantVideoController.swift +++ b/TelegramUI/LegacyInstantVideoController.swift @@ -101,7 +101,7 @@ func legacyInstantVideoController(theme: PresentationTheme, panelFrame: CGRect, legacyController.view.disablesInteractiveTransitionGestureRecognizer = true var uploadInterface: LegacyLiveUploadInterface? if peerId.namespace != Namespaces.Peer.SecretChat { - uploadInterface = LegacyLiveUploadInterface(account: account) + uploadInterface = LegacyLiveUploadInterface(account: context.account) } let controller = TGVideoMessageCaptureController(context: legacyController.context, assets: TGVideoMessageCaptureControllerAssets(send: PresentationResourcesChat.chatInputPanelSendButtonImage(theme)!, slideToCancel: PresentationResourcesChat.chatInputPanelMediaRecordingCancelArrowImage(theme)!, actionDelete: generateTintedImage(image: UIImage(bundleImageName: "Chat/Input/Accessory Panels/MessageSelectionThrash"), color: theme.chat.inputPanel.panelControlAccentColor))!, transitionInView: { return nil @@ -122,7 +122,7 @@ func legacyInstantVideoController(theme: PresentationTheme, panelFrame: CGRect, let thumbnailSize = finalDimensions.aspectFitted(CGSize(width: 320.0, height: 320.0)) let thumbnailImage = TGScaleImageToPixelSize(previewImage, thumbnailSize)! if let thumbnailData = UIImageJPEGRepresentation(thumbnailImage, 0.4) { - account.postbox.mediaBox.storeResourceData(resource.id, data: thumbnailData) + context.account.postbox.mediaBox.storeResourceData(resource.id, data: thumbnailData) previewRepresentations.append(TelegramMediaImageRepresentation(dimensions: thumbnailSize, resource: resource)) } } @@ -147,14 +147,14 @@ func legacyInstantVideoController(theme: PresentationTheme, panelFrame: CGRect, let resource: TelegramMediaResource if let liveUploadData = liveUploadData as? LegacyLiveUploadInterfaceResult, resourceAdjustments == nil, let data = try? Data(contentsOf: videoUrl) { resource = LocalFileMediaResource(fileId: liveUploadData.id) - account.postbox.mediaBox.storeResourceData(resource.id, data: data) + context.account.postbox.mediaBox.storeResourceData(resource.id, data: data) } else { resource = LocalFileVideoMediaResource(randomId: arc4random64(), path: videoUrl.path, adjustments: resourceAdjustments) } if let previewImage = previewImage { if let data = compressImageToJPEG(previewImage, quality: 0.7) { - account.postbox.mediaBox.storeCachedResourceRepresentation(resource, representation: CachedVideoFirstFrameRepresentation(), data: data) + context.account.postbox.mediaBox.storeCachedResourceRepresentation(resource, representation: CachedVideoFirstFrameRepresentation(), data: data) } } @@ -169,7 +169,7 @@ func legacyInstantVideoController(theme: PresentationTheme, panelFrame: CGRect, } legacyController.bindCaptureController(controller) - let presentationDisposable = account.telegramApplicationContext.presentationData.start(next: { [weak controller] presentationData in + let presentationDisposable = context.presentationData.start(next: { [weak controller] presentationData in if let controller = controller { controller.pallete = legacyInputMicPalette(from: presentationData.theme) } diff --git a/TelegramUI/LegacyLocationController.swift b/TelegramUI/LegacyLocationController.swift index 2be200210f..08e05640b1 100644 --- a/TelegramUI/LegacyLocationController.swift +++ b/TelegramUI/LegacyLocationController.swift @@ -128,7 +128,7 @@ func legacyLocationController(message: Message?, mapMedia: TelegramMediaMap, con legacyLocation.venue = TGVenueAttachment(title: venue.title, address: venue.address, provider: venue.provider, venueId: venue.id, type: venue.type) } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: isModal ? .modal(animateIn: true) : .navigation, theme: presentationData.theme, strings: presentationData.strings) let controller: TGLocationViewController @@ -138,7 +138,7 @@ func legacyLocationController(message: Message?, mapMedia: TelegramMediaMap, con let legacyAuthor: AnyObject? = message.author.flatMap(makeLegacyPeer) let updatedLocations = SSignal(generator: { subscriber in - let disposable = topPeerActiveLiveLocationMessages(viewTracker: account.viewTracker, accountPeerId: account.peerId, peerId: message.id.peerId).start(next: { (_, messages) in + let disposable = topPeerActiveLiveLocationMessages(viewTracker: context.account.viewTracker, accountPeerId: context.account.peerId, peerId: message.id.peerId).start(next: { (_, messages) in var result: [Any] = [] let currentTime = Int32(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) loop: for message in messages { @@ -224,7 +224,7 @@ func legacyLocationController(message: Message?, mapMedia: TelegramMediaMap, con legacyController?.dismiss() } - let theme = (account.telegramApplicationContext.currentPresentationData.with { $0 }).theme + let theme = (context.currentPresentationData.with { $0 }).theme controller.pallete = legacyLocationPalette(from: theme) controller.modalMode = isModal @@ -232,12 +232,12 @@ func legacyLocationController(message: Message?, mapMedia: TelegramMediaMap, con if let strongLegacyController = legacyController, let location = legacyLocation { let map = telegramMap(for: location) - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let shareAction = OpenInControllerAction(title: presentationData.strings.Conversation_ContextMenuShare, action: { - strongLegacyController.present(ShareController(account: account, subject: .mapMedia(map), externalShare: true), in: .window(.root), with: nil) + strongLegacyController.present(ShareController(context: context, subject: .mapMedia(map), externalShare: true), in: .window(.root), with: nil) }) - strongLegacyController.present(OpenInActionSheetController(account: account, item: .location(location: map, withDirections: directions), additionalAction: !directions ? shareAction : nil, openUrl: openUrl), in: .window(.root), with: nil) + strongLegacyController.present(OpenInActionSheetController(context: context, item: .location(location: map, withDirections: directions), additionalAction: !directions ? shareAction : nil, openUrl: openUrl), in: .window(.root), with: nil) } } @@ -267,7 +267,7 @@ func legacyLocationController(message: Message?, mapMedia: TelegramMediaMap, con legacyController.bind(controller: controller) } - let presentationDisposable = account.telegramApplicationContext.presentationData.start(next: { [weak controller] presentationData in + let presentationDisposable = context.presentationData.start(next: { [weak controller] presentationData in if let controller = controller { controller.pallete = legacyLocationPalette(from: presentationData.theme) } diff --git a/TelegramUI/LegacyLocationPicker.swift b/TelegramUI/LegacyLocationPicker.swift index 3e969a213f..028c21802f 100644 --- a/TelegramUI/LegacyLocationPicker.swift +++ b/TelegramUI/LegacyLocationPicker.swift @@ -41,13 +41,13 @@ func legacyLocationPickerController(context: AccountContext, selfPeer: Peer, pee } controller.nearbyPlacesSignal = { query, location in return SSignal(generator: { subscriber in - let nearbyPlacesSignal: Signal<[TGLocationVenue], NoError> = resolvePeerByName(account: account, name: "foursquare") + let nearbyPlacesSignal: Signal<[TGLocationVenue], NoError> = resolvePeerByName(account: context.account, name: "foursquare") |> take(1) |> mapToSignal { peerId -> Signal in guard let peerId = peerId else { return .single(nil) } - return requestChatContextResults(account: account, botId: peerId, peerId: selfPeer.id, query: query ?? "", location: .single((location?.coordinate.latitude ?? 0.0, location?.coordinate.longitude ?? 0.0)), offset: "") + return requestChatContextResults(account: context.account, botId: peerId, peerId: selfPeer.id, query: query ?? "", location: .single((location?.coordinate.latitude ?? 0.0, location?.coordinate.longitude ?? 0.0)), offset: "") } |> mapToSignal { contextResult -> Signal<[TGLocationVenue], NoError> in guard let contextResult = contextResult else { @@ -84,7 +84,7 @@ func legacyLocationPickerController(context: AccountContext, selfPeer: Peer, pee }) }) } - let presentationDisposable = account.telegramApplicationContext.presentationData.start(next: { [weak controller] presentationData in + let presentationDisposable = context.presentationData.start(next: { [weak controller] presentationData in if let controller = controller { controller.pallete = legacyLocationPalette(from: presentationData.theme) } diff --git a/TelegramUI/LegacyMediaPickers.swift b/TelegramUI/LegacyMediaPickers.swift index 16bdbecc44..7344dd0c8a 100644 --- a/TelegramUI/LegacyMediaPickers.swift +++ b/TelegramUI/LegacyMediaPickers.swift @@ -16,8 +16,8 @@ func guessMimeTypeByFileExtension(_ ext: String) -> String { func configureLegacyAssetPicker(_ controller: TGMediaAssetsController, context: AccountContext, peer: Peer, captionsEnabled: Bool = true, storeCreatedAssets: Bool = true, showFileTooltip: Bool = false, presentWebSearch: (() -> Void)?) { controller.captionsEnabled = captionsEnabled controller.inhibitDocumentCaptions = false - controller.suggestionContext = legacySuggestionContext(account: account, peerId: peer.id) - if (peer is TelegramUser) && peer.id != account.peerId { + controller.suggestionContext = legacySuggestionContext(account: context.account, peerId: peer.id) + if (peer is TelegramUser) && peer.id != context.account.peerId { controller.hasTimer = true } controller.dismissalBlock = { @@ -34,7 +34,7 @@ func legacyAssetPicker(context: AccountContext, presentationData: PresentationDa return Signal { subscriber in let intent = fileMode ? TGMediaAssetsControllerSendFileIntent : TGMediaAssetsControllerSendMediaIntent - DeviceAccess.authorizeAccess(to: .mediaLibrary(.send), presentationData: presentationData, present: applicationContext.presentGlobalController, openSettings: applicationContext.applicationBindings.openSettings, { value in + DeviceAccess.authorizeAccess(to: .mediaLibrary(.send), presentationData: presentationData, present: context.presentGlobalController, openSettings: context.applicationBindings.openSettings, { value in if !value { subscriber.putError(Void()) return diff --git a/TelegramUI/LegacySecureIdAttachmentMenu.swift b/TelegramUI/LegacySecureIdAttachmentMenu.swift index d9215dd4ae..c69ccacc2a 100644 --- a/TelegramUI/LegacySecureIdAttachmentMenu.swift +++ b/TelegramUI/LegacySecureIdAttachmentMenu.swift @@ -26,8 +26,8 @@ struct SecureIdRecognizedDocumentData { let expiryDate: Date? } -func presentLegacySecureIdAttachmentMenu(account: Account, present: @escaping (ViewController) -> Void, validLayout: ContainerViewLayout, type: SecureIdAttachmentMenuType, recognizeDocumentData: Bool, completion: @escaping ([TelegramMediaResource], SecureIdRecognizedDocumentData?) -> Void) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } +func presentLegacySecureIdAttachmentMenu(context: AccountContext, present: @escaping (ViewController) -> Void, validLayout: ContainerViewLayout, type: SecureIdAttachmentMenuType, recognizeDocumentData: Bool, completion: @escaping ([TelegramMediaResource], SecureIdRecognizedDocumentData?) -> Void) { + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: .custom, theme: presentationData.theme, initialLayout: validLayout) legacyController.statusBar.statusBarStyle = .Ignore @@ -53,12 +53,12 @@ func presentLegacySecureIdAttachmentMenu(account: Account, present: @escaping (V guard let attachMenu = TGPassportAttachMenu.present(with: legacyController.context, parentController: emptyController, menuController: nil, title: "", intent: mappedIntent, uploadAction: { signal, completed in if let signal = signal { - let _ = (processedLegacySecureIdAttachmentItems(postbox: account.postbox, signal: signal) + let _ = (processedLegacySecureIdAttachmentItems(postbox: context.account.postbox, signal: signal) |> mapToSignal { resources -> Signal<([TelegramMediaResource], SecureIdRecognizedDocumentData?), NoError> in switch type { case .generic, .idCard: if recognizeDocumentData { - return recognizedResources(postbox: account.postbox, resources: resources, shouldBeDriversLicense: false) + return recognizedResources(postbox: context.account.postbox, resources: resources, shouldBeDriversLicense: false) |> map { data -> ([TelegramMediaResource], SecureIdRecognizedDocumentData?) in return (resources, data) } diff --git a/TelegramUI/LegacyWallpaperEditor.swift b/TelegramUI/LegacyWallpaperEditor.swift index 13334f6520..97926f931d 100644 --- a/TelegramUI/LegacyWallpaperEditor.swift +++ b/TelegramUI/LegacyWallpaperEditor.swift @@ -48,11 +48,11 @@ func legacyWallpaperEditor(theme: PresentationTheme, image: UIImage, completion: return legacyController } -func legacyWallpaperPicker(applicationContext: TelegramApplicationContext, presentationData: PresentationData) -> Signal<(LegacyComponentsContext) -> TGMediaAssetsController, Void> { +func legacyWallpaperPicker(context: AccountContext, presentationData: PresentationData) -> Signal<(LegacyComponentsContext) -> TGMediaAssetsController, Void> { return Signal { subscriber in let intent = TGMediaAssetsControllerSetCustomWallpaperIntent - DeviceAccess.authorizeAccess(to: .mediaLibrary(.wallpaper), presentationData: presentationData, present: applicationContext.presentGlobalController, openSettings: applicationContext.applicationBindings.openSettings, { value in + DeviceAccess.authorizeAccess(to: .mediaLibrary(.wallpaper), presentationData: presentationData, present: context.presentGlobalController, openSettings: context.applicationBindings.openSettings, { value in if !value { subscriber.putError(Void()) return diff --git a/TelegramUI/LegacyWebSearchEditor.swift b/TelegramUI/LegacyWebSearchEditor.swift index e93cb6dbb0..1fddb727d1 100644 --- a/TelegramUI/LegacyWebSearchEditor.swift +++ b/TelegramUI/LegacyWebSearchEditor.swift @@ -8,13 +8,13 @@ import UIKit import Display func presentLegacyWebSearchEditor(context: AccountContext, theme: PresentationTheme, result: ChatContextResult, initialLayout: ContainerViewLayout?, updateHiddenMedia: @escaping (String?) -> Void, transitionHostView: @escaping () -> UIView?, transitionView: @escaping (ChatContextResult) -> UIView?, completed: @escaping (UIImage) -> Void, present: @escaping (ViewController, Any?) -> Void) { - guard let item = legacyWebSearchItem(account: account, result: result) else { + guard let item = legacyWebSearchItem(account: context.account, result: result) else { return } var screenImage: Signal = .single(nil) if let resource = item.thumbnailResource { - screenImage = account.postbox.mediaBox.resourceData(resource, option: .complete(waitUntilFetchStatus: false), attemptSynchronously: true) + screenImage = context.account.postbox.mediaBox.resourceData(resource, option: .complete(waitUntilFetchStatus: false), attemptSynchronously: true) |> map { maybeData -> UIImage? in if maybeData.complete { if let loadedData = try? Data(contentsOf: URL(fileURLWithPath: maybeData.path), options: []), let image = UIImage(data: loadedData) { diff --git a/TelegramUI/LegacyWebSearchGallery.swift b/TelegramUI/LegacyWebSearchGallery.swift index f59fe46c87..5190cdd9ef 100644 --- a/TelegramUI/LegacyWebSearchGallery.swift +++ b/TelegramUI/LegacyWebSearchGallery.swift @@ -309,11 +309,11 @@ func presentLegacyWebSearchGallery(context: AccountContext, peer: Peer?, theme: controller.asyncTransitionIn = true legacyController.bind(controller: controller) - let (items, focusItem) = galleryItems(account: account, results: results, current: current, selectionContext: selectionContext, editingContext: editingContext) + let (items, focusItem) = galleryItems(account: context.account, results: results, current: current, selectionContext: selectionContext, editingContext: editingContext) let model = TGMediaPickerGalleryModel(context: legacyController.context, items: items, focus: focusItem, selectionContext: selectionContext, editingContext: editingContext, hasCaptions: false, allowCaptionEntities: true, hasTimer: false, onlyCrop: false, inhibitDocumentCaptions: false, hasSelectionPanel: false, hasCamera: false, recipientName: peer?.displayTitle)! if let peer = peer { - model.suggestionContext = legacySuggestionContext(account: account, peerId: peer.id) + model.suggestionContext = legacySuggestionContext(account: context.account, peerId: peer.id) } controller.model = model model.controller = controller diff --git a/TelegramUI/ListMessageFileItemNode.swift b/TelegramUI/ListMessageFileItemNode.swift index a0c823fa32..f4b225b6d0 100644 --- a/TelegramUI/ListMessageFileItemNode.swift +++ b/TelegramUI/ListMessageFileItemNode.swift @@ -416,15 +416,15 @@ final class ListMessageFileItemNode: ListMessageNode { let context = item.context updatedFetchControls = FetchControls(fetch: { [weak self] in if let strongSelf = self { - strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: selectedMedia, userInitiated: true).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(context: context, message: message, file: selectedMedia, userInitiated: true).start()) } }, cancel: { - messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: selectedMedia) + messageMediaFileCancelInteractiveFetch(context: context, messageId: message.id, file: selectedMedia) }) } if statusUpdated { - updatedStatusSignal = messageFileMediaResourceStatus(account: item.context.account, file: selectedMedia, message: message, isRecentActions: false) + updatedStatusSignal = messageFileMediaResourceStatus(context: item.context, file: selectedMedia, message: message, isRecentActions: false) if isAudio { if let currentUpdatedStatusSignal = updatedStatusSignal { @@ -858,8 +858,8 @@ final class ListMessageFileItemNode: ListMessageNode { } } case .playbackStatus: - if let account = self.account, let applicationContext = account.applicationContext as? TelegramApplicationContext { - applicationContext.mediaManager?.playlistControl(.playback(.togglePlayPause)) + if let context = self.context { + context.mediaManager.playlistControl(.playback(.togglePlayPause)) } } } diff --git a/TelegramUI/MentionChatInputPanelItem.swift b/TelegramUI/MentionChatInputPanelItem.swift index 188bc5b89e..cbd4975a37 100644 --- a/TelegramUI/MentionChatInputPanelItem.swift +++ b/TelegramUI/MentionChatInputPanelItem.swift @@ -163,7 +163,7 @@ final class MentionChatInputPanelItemNode: ListViewItemNode { strongSelf.backgroundColor = item.theme.list.plainBackgroundColor strongSelf.highlightedBackgroundNode.backgroundColor = item.theme.list.itemHighlightedBackgroundColor - strongSelf.avatarNode.setPeer(account: item.account, peer: item.peer, emptyColor: item.theme.list.mediaPlaceholderColor) + strongSelf.avatarNode.setPeer(account: item.account, theme: item.theme, peer: item.peer, emptyColor: item.theme.list.mediaPlaceholderColor) let _ = textApply() diff --git a/TelegramUI/MultipleAvatarsNode.swift b/TelegramUI/MultipleAvatarsNode.swift index 49ce2f247d..b3fce7ddc7 100644 --- a/TelegramUI/MultipleAvatarsNode.swift +++ b/TelegramUI/MultipleAvatarsNode.swift @@ -9,9 +9,9 @@ private let avatarFont: UIFont = UIFont(name: ".SFCompactRounded-Semibold", size final class MultipleAvatarsNode: ASDisplayNode { private var nodes: [(Peer, AvatarNode)] = [] - static func asyncLayout(_ current: MultipleAvatarsNode?) -> (Account, [Peer], CGSize) -> (Bool) -> MultipleAvatarsNode { + static func asyncLayout(_ current: MultipleAvatarsNode?) -> (Account, PresentationTheme, [Peer], CGSize) -> (Bool) -> MultipleAvatarsNode { let currentNodes: [(Peer, AvatarNode)] = current?.nodes ?? [] - return { account, peers, size in + return { account, theme, peers, size in var node: MultipleAvatarsNode if let current = current { node = current @@ -60,7 +60,7 @@ final class MultipleAvatarsNode: ASDisplayNode { avatarNode.layer.animatePosition(from: distance, to: CGPoint(), duration: 0.2, timingFunction: kCAMediaTimingFunctionEaseInEaseOut, additive: true) } } - avatarNode.setPeer(account: account, peer: peer) + avatarNode.setPeer(account: account, theme: theme, peer: peer) index += 1 } index += 1 diff --git a/TelegramUI/NetworkUsageStatsController.swift b/TelegramUI/NetworkUsageStatsController.swift index 5850c746ad..81a2b7afbf 100644 --- a/TelegramUI/NetworkUsageStatsController.swift +++ b/TelegramUI/NetworkUsageStatsController.swift @@ -376,7 +376,7 @@ private func networkUsageStatsControllerEntries(presentationData: PresentationDa func networkUsageStatsController(context: AccountContext) -> ViewController { let section = ValuePromise(.cellular) let stats = Promise() - stats.set(accountNetworkUsageStats(account: account, reset: [])) + stats.set(accountNetworkUsageStats(account: context.account, reset: [])) var presentControllerImpl: ((ViewController) -> Void)? diff --git a/TelegramUI/NotificationContainerController.swift b/TelegramUI/NotificationContainerController.swift index 6db4142111..7c3431116b 100644 --- a/TelegramUI/NotificationContainerController.swift +++ b/TelegramUI/NotificationContainerController.swift @@ -12,14 +12,14 @@ public final class NotificationContainerController: ViewController { private var presentationData: PresentationData private var presentationDataDisposable: Disposable? - public init(account: Account) { - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + public init(context: AccountContext) { + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: nil) self.statusBar.statusBarStyle = .Ignore - self.presentationDataDisposable = (account.telegramApplicationContext.presentationData + self.presentationDataDisposable = (context.presentationData |> deliverOnMainQueue).start(next: { [weak self] presentationData in if let strongSelf = self { let previousTheme = strongSelf.presentationData.theme diff --git a/TelegramUI/NotificationExceptions.swift b/TelegramUI/NotificationExceptions.swift index f0d4af1963..daeed3b0a9 100644 --- a/TelegramUI/NotificationExceptions.swift +++ b/TelegramUI/NotificationExceptions.swift @@ -28,7 +28,7 @@ public class NotificationExceptionsController: ViewController { private var searchContentNode: NavigationBarSearchContentNode? public init(context: AccountContext, mode: NotificationExceptionMode, updatedMode: @escaping(NotificationExceptionMode) -> Void) { - self.account = account + self.context = context self.mode = mode self.updatedMode = updatedMode self.presentationData = context.currentPresentationData.with { $0 } diff --git a/TelegramUI/NotificationExcetionSettingsController.swift b/TelegramUI/NotificationExcetionSettingsController.swift index 1ad8a8581b..2b875b5c31 100644 --- a/TelegramUI/NotificationExcetionSettingsController.swift +++ b/TelegramUI/NotificationExcetionSettingsController.swift @@ -261,7 +261,7 @@ func notificationPeerExceptionController(context: AccountContext, peerId: PeerId let arguments = NotificationPeerExceptionArguments(account: context.account, selectSound: { sound in updateState { state in - playSoundDisposable.set(playSound(account: context.account, sound: sound, defaultSound: state.defaultSound).start()) + playSoundDisposable.set(playSound(context: context, sound: sound, defaultSound: state.defaultSound).start()) return state.withUpdatedSound(sound) } diff --git a/TelegramUI/NotificationSoundSelection.swift b/TelegramUI/NotificationSoundSelection.swift index 68a599bfc9..ed1cf73b1b 100644 --- a/TelegramUI/NotificationSoundSelection.swift +++ b/TelegramUI/NotificationSoundSelection.swift @@ -230,10 +230,10 @@ func playSound(context: AccountContext, sound: PeerMessageSound, defaultSound: P return .complete() }) deactivateImpl = { - session?.dispose() + session.dispose() } return ActionDisposable { - session?.dispose() + session.dispose() currentPlayer?.stop() currentPlayer = nil } diff --git a/TelegramUI/NotificationsAndSounds.swift b/TelegramUI/NotificationsAndSounds.swift index c2e4d01a50..a6ca02b568 100644 --- a/TelegramUI/NotificationsAndSounds.swift +++ b/TelegramUI/NotificationsAndSounds.swift @@ -5,7 +5,7 @@ import Postbox import TelegramCore private final class NotificationsAndSoundsArguments { - let account: Account + let context: AccountContext let presentController: (ViewController, ViewControllerPresentationArguments?) -> Void let pushController: (ViewController) -> Void let soundSelectionDisposable: MetaDisposable @@ -42,8 +42,8 @@ private final class NotificationsAndSoundsArguments { let openAppSettings: () -> Void - init(account: Account, presentController: @escaping (ViewController, ViewControllerPresentationArguments?) -> Void, pushController: @escaping(ViewController)->Void, soundSelectionDisposable: MetaDisposable, authorizeNotifications: @escaping () -> Void, suppressWarning: @escaping () -> Void, updateMessageAlerts: @escaping (Bool) -> Void, updateMessagePreviews: @escaping (Bool) -> Void, updateMessageSound: @escaping (PeerMessageSound) -> Void, updateGroupAlerts: @escaping (Bool) -> Void, updateGroupPreviews: @escaping (Bool) -> Void, updateGroupSound: @escaping (PeerMessageSound) -> Void, updateChannelAlerts: @escaping (Bool) -> Void, updateChannelPreviews: @escaping (Bool) -> Void, updateChannelSound: @escaping (PeerMessageSound) -> Void, updateInAppSounds: @escaping (Bool) -> Void, updateInAppVibration: @escaping (Bool) -> Void, updateInAppPreviews: @escaping (Bool) -> Void, updateDisplayNameOnLockscreen: @escaping (Bool) -> Void, updateTotalUnreadCountStyle: @escaping (Bool) -> Void, updateIncludeTag: @escaping (PeerSummaryCounterTags, Bool) -> Void, updateTotalUnreadCountCategory: @escaping (Bool) -> Void, resetNotifications: @escaping () -> Void, updatedExceptionMode: @escaping(NotificationExceptionMode) -> Void, openAppSettings: @escaping () -> Void, updateJoinedNotifications: @escaping (Bool) -> Void) { - self.account = account + init(context: AccountContext, presentController: @escaping (ViewController, ViewControllerPresentationArguments?) -> Void, pushController: @escaping(ViewController)->Void, soundSelectionDisposable: MetaDisposable, authorizeNotifications: @escaping () -> Void, suppressWarning: @escaping () -> Void, updateMessageAlerts: @escaping (Bool) -> Void, updateMessagePreviews: @escaping (Bool) -> Void, updateMessageSound: @escaping (PeerMessageSound) -> Void, updateGroupAlerts: @escaping (Bool) -> Void, updateGroupPreviews: @escaping (Bool) -> Void, updateGroupSound: @escaping (PeerMessageSound) -> Void, updateChannelAlerts: @escaping (Bool) -> Void, updateChannelPreviews: @escaping (Bool) -> Void, updateChannelSound: @escaping (PeerMessageSound) -> Void, updateInAppSounds: @escaping (Bool) -> Void, updateInAppVibration: @escaping (Bool) -> Void, updateInAppPreviews: @escaping (Bool) -> Void, updateDisplayNameOnLockscreen: @escaping (Bool) -> Void, updateTotalUnreadCountStyle: @escaping (Bool) -> Void, updateIncludeTag: @escaping (PeerSummaryCounterTags, Bool) -> Void, updateTotalUnreadCountCategory: @escaping (Bool) -> Void, resetNotifications: @escaping () -> Void, updatedExceptionMode: @escaping(NotificationExceptionMode) -> Void, openAppSettings: @escaping () -> Void, updateJoinedNotifications: @escaping (Bool) -> Void) { + self.context = context self.presentController = presentController self.pushController = pushController self.soundSelectionDisposable = soundSelectionDisposable @@ -478,14 +478,14 @@ private enum NotificationsAndSoundsEntry: ItemListNodeEntry { }) case let .messageSound(theme, text, value, sound): return ItemListDisclosureItem(theme: theme, title: text, label: value, sectionId: self.section, style: .blocks, action: { - let controller = notificationSoundSelectionController(account: arguments.account, isModal: true, currentSound: sound, defaultSound: nil, completion: { [weak arguments] value in + let controller = notificationSoundSelectionController(context: arguments.context, isModal: true, currentSound: sound, defaultSound: nil, completion: { [weak arguments] value in arguments?.updateMessageSound(value) }) arguments.presentController(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) case let .userExceptions(theme, strings, text, value): return ItemListDisclosureItem(theme: theme, title: text, label: strings.Notifications_Exceptions(Int32(value.settings.count)), sectionId: self.section, style: .blocks, action: { - let controller = NotificationExceptionsController(account: arguments.account, mode: value, updatedMode: arguments.updatedExceptionMode) + let controller = NotificationExceptionsController(context: arguments.context, mode: value, updatedMode: arguments.updatedExceptionMode) arguments.pushController(controller) }) case let .messageNotice(theme, text): @@ -502,14 +502,14 @@ private enum NotificationsAndSoundsEntry: ItemListNodeEntry { }) case let .groupSound(theme, text, value, sound): return ItemListDisclosureItem(theme: theme, title: text, label: value, sectionId: self.section, style: .blocks, action: { - let controller = notificationSoundSelectionController(account: arguments.account, isModal: true, currentSound: sound, defaultSound: nil, completion: { [weak arguments] value in + let controller = notificationSoundSelectionController(context: arguments.context, isModal: true, currentSound: sound, defaultSound: nil, completion: { [weak arguments] value in arguments?.updateGroupSound(value) }) arguments.presentController(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) case let .groupExceptions(theme, strings, text, value): return ItemListDisclosureItem(theme: theme, title: text, label: strings.Notifications_Exceptions(Int32(value.settings.count)), sectionId: self.section, style: .blocks, action: { - let controller = NotificationExceptionsController(account: arguments.account, mode: value, updatedMode: arguments.updatedExceptionMode) + let controller = NotificationExceptionsController(context: arguments.context, mode: value, updatedMode: arguments.updatedExceptionMode) arguments.pushController(controller) }) case let .groupNotice(theme, text): @@ -526,14 +526,14 @@ private enum NotificationsAndSoundsEntry: ItemListNodeEntry { }) case let .channelSound(theme, text, value, sound): return ItemListDisclosureItem(theme: theme, title: text, label: value, sectionId: self.section, style: .blocks, action: { - let controller = notificationSoundSelectionController(account: arguments.account, isModal: true, currentSound: sound, defaultSound: nil, completion: { [weak arguments] value in + let controller = notificationSoundSelectionController(context: arguments.context, isModal: true, currentSound: sound, defaultSound: nil, completion: { [weak arguments] value in arguments?.updateChannelSound(value) }) arguments.presentController(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) case let .channelExceptions(theme, strings, text, value): return ItemListDisclosureItem(theme: theme, title: text, label: strings.Notifications_Exceptions(Int32(value.settings.count)), sectionId: self.section, style: .blocks, action: { - let controller = NotificationExceptionsController(account: arguments.account, mode: value, updatedMode: arguments.updatedExceptionMode) + let controller = NotificationExceptionsController(context: arguments.context, mode: value, updatedMode: arguments.updatedExceptionMode) arguments.pushController(controller) }) case let .channelNotice(theme, text): @@ -689,17 +689,17 @@ public func notificationsAndSoundsController(context: AccountContext, exceptions notificationExceptions.set(.single(value)) } - let arguments = NotificationsAndSoundsArguments(account: context.account, presentController: { controller, arguments in + let arguments = NotificationsAndSoundsArguments(context: context, presentController: { controller, arguments in presentControllerImpl?(controller, arguments) }, pushController: { controller in pushControllerImpl?(controller) }, soundSelectionDisposable: MetaDisposable(), authorizeNotifications: { - let _ = (DeviceAccess.authorizationStatus(account: context.account, subject: .notifications) + let _ = (DeviceAccess.authorizationStatus(context: context, subject: .notifications) |> take(1) |> deliverOnMainQueue).start(next: { status in switch status { case .notDetermined: - DeviceAccess.authorizeAccess(to: .notifications, account: context.account) + DeviceAccess.authorizeAccess(to: .notifications, context: context) case .denied, .restricted: context.applicationBindings.openSettings() case .unreachable: @@ -922,7 +922,7 @@ public func notificationsAndSoundsController(context: AccountContext, exceptions })) } - let signal = combineLatest(context.presentationData, preferences, notificationExceptions.get(), DeviceAccess.authorizationStatus(account: context.account, subject: .notifications), notificationsWarningSuppressed.get()) + let signal = combineLatest(context.presentationData, preferences, notificationExceptions.get(), DeviceAccess.authorizationStatus(context: context, subject: .notifications), notificationsWarningSuppressed.get()) |> map { presentationData, view, exceptions, authorizationStatus, warningSuppressed -> (ItemListControllerState, (ItemListNodeState, NotificationsAndSoundsEntry.ItemGenerationArguments)) in let viewSettings: GlobalNotificationSettingsSet diff --git a/TelegramUI/OpenAddContact.swift b/TelegramUI/OpenAddContact.swift index aa58f67536..428c3c6f0c 100644 --- a/TelegramUI/OpenAddContact.swift +++ b/TelegramUI/OpenAddContact.swift @@ -4,19 +4,19 @@ import TelegramCore import Display func openAddContact(context: AccountContext, firstName: String = "", lastName: String = "", phoneNumber: String, label: String = "_$!!$_", present: @escaping (ViewController, Any?) -> Void, completed: @escaping () -> Void = {}) { - let _ = (DeviceAccess.authorizationStatus(account: account, subject: .contacts) + let _ = (DeviceAccess.authorizationStatus(context: context, subject: .contacts) |> take(1) |> deliverOnMainQueue).start(next: { value in switch value { case .allowed: let contactData = DeviceContactExtendedData(basicData: DeviceContactBasicData(firstName: firstName, lastName: lastName, phoneNumbers: [DeviceContactPhoneNumberData(label: label, value: phoneNumber)]), middleName: "", prefix: "", suffix: "", organization: "", jobTitle: "", department: "", emailAddresses: [], urls: [], addresses: [], birthdayDate: nil, socialProfiles: [], instantMessagingProfiles: []) - present(deviceContactInfoController(account: account, subject: .create(peer: nil, contactData: contactData, completion: { _, _,_ in }), completed: completed), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + present(deviceContactInfoController(context: context, subject: .create(peer: nil, contactData: contactData, completion: { _, _,_ in }), completed: completed), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) case .notDetermined: DeviceAccess.authorizeAccess(to: .contacts) default: - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: presentationData.strings.AccessDenied_Title, text: presentationData.strings.Contacts_AccessDeniedError, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: { - account.telegramApplicationContext.applicationBindings.openSettings() + context.applicationBindings.openSettings() })]), nil) } }) diff --git a/TelegramUI/OpenChatMessage.swift b/TelegramUI/OpenChatMessage.swift index 7bbf5a9fed..eeb407619d 100644 --- a/TelegramUI/OpenChatMessage.swift +++ b/TelegramUI/OpenChatMessage.swift @@ -20,7 +20,7 @@ private enum ChatMessageGalleryControllerData { case chatAvatars(AvatarGalleryController, Media) } -private func chatMessageGalleryControllerData(account: Account, message: Message, navigationController: NavigationController?, standalone: Bool, reverseMessageGalleryOrder: Bool, stream: Bool, synchronousLoad: Bool, excludeWebPageMedia: Bool = false, actionInteraction: GalleryControllerActionInteraction?) -> ChatMessageGalleryControllerData? { +private func chatMessageGalleryControllerData(context: AccountContext, message: Message, navigationController: NavigationController?, standalone: Bool, reverseMessageGalleryOrder: Bool, stream: Bool, synchronousLoad: Bool, excludeWebPageMedia: Bool = false, actionInteraction: GalleryControllerActionInteraction?) -> ChatMessageGalleryControllerData? { var galleryMedia: Media? var otherMedia: Media? var instantPageMedia: (TelegramMediaWebpage, [InstantPageGalleryEntry])? @@ -30,7 +30,7 @@ private func chatMessageGalleryControllerData(account: Account, message: Message case let .photoUpdated(image): if let peer = messageMainPeer(message), let image = image { let promise: Promise<[AvatarGalleryEntry]> = Promise([AvatarGalleryEntry.image(image.reference, image.representations.map({ ImageRepresentationWithReference(representation: $0, reference: .media(media: .message(message: MessageReference(message), media: media), resource: $0.resource)) }), peer, message.timestamp, nil)]) - let galleryController = AvatarGalleryController(account: account, peer: peer, remoteEntries: promise, replaceRootController: { controller, ready in + let galleryController = AvatarGalleryController(context: context, peer: peer, remoteEntries: promise, replaceRootController: { controller, ready in }) return .chatAvatars(galleryController, image) @@ -78,7 +78,7 @@ private func chatMessageGalleryControllerData(account: Account, message: Message } } - let gallery = InstantPageGalleryController(account: account, webPage: webPage, entries: instantPageMedia, centralIndex: centralIndex, replaceRootController: { [weak navigationController] controller, ready in + let gallery = InstantPageGalleryController(context: context, webPage: webPage, entries: instantPageMedia, centralIndex: centralIndex, replaceRootController: { [weak navigationController] controller, ready in if let navigationController = navigationController { navigationController.replaceTopController(controller, animated: false, ready: ready) } @@ -115,10 +115,10 @@ private func chatMessageGalleryControllerData(account: Account, message: Message } if message.containsSecretMedia { - let gallery = SecretMediaPreviewController(account: account, messageId: message.id) + let gallery = SecretMediaPreviewController(context: context, messageId: message.id) return .secretGallery(gallery) } else { - let gallery = GalleryController(account: account, source: standalone ? .standaloneMessage(message) : .peerMessagesAtId(message.id), invertItemOrder: reverseMessageGalleryOrder, streamSingleVideo: stream, synchronousLoad: synchronousLoad, replaceRootController: { [weak navigationController] controller, ready in + let gallery = GalleryController(context: context, source: standalone ? .standaloneMessage(message) : .peerMessagesAtId(message.id), invertItemOrder: reverseMessageGalleryOrder, streamSingleVideo: stream, synchronousLoad: synchronousLoad, replaceRootController: { [weak navigationController] controller, ready in navigationController?.replaceTopController(controller, animated: false, ready: ready) }, baseNavigationController: navigationController, actionInteraction: actionInteraction) return .gallery(gallery) @@ -137,8 +137,8 @@ enum ChatMessagePreviewControllerData { case gallery(GalleryController) } -func chatMessagePreviewControllerData(account: Account, message: Message, standalone: Bool, reverseMessageGalleryOrder: Bool, navigationController: NavigationController?) -> ChatMessagePreviewControllerData? { - if let mediaData = chatMessageGalleryControllerData(account: account, message: message, navigationController: navigationController, standalone: standalone, reverseMessageGalleryOrder: reverseMessageGalleryOrder, stream: false, synchronousLoad: true, actionInteraction: nil) { +func chatMessagePreviewControllerData(context: AccountContext, message: Message, standalone: Bool, reverseMessageGalleryOrder: Bool, navigationController: NavigationController?) -> ChatMessagePreviewControllerData? { + if let mediaData = chatMessageGalleryControllerData(context: context, message: message, navigationController: navigationController, standalone: standalone, reverseMessageGalleryOrder: reverseMessageGalleryOrder, stream: false, synchronousLoad: true, actionInteraction: nil) { switch mediaData { case let .gallery(gallery): return .gallery(gallery) @@ -152,13 +152,13 @@ func chatMessagePreviewControllerData(account: Account, message: Message, standa } func openChatMessage(context: AccountContext, message: Message, standalone: Bool, reverseMessageGalleryOrder: Bool, stream: Bool = false, excludeWebPageMedia: Bool = false, navigationController: NavigationController?, modal: Bool = false, dismissInput: @escaping () -> Void, present: @escaping (ViewController, Any?) -> Void, transitionNode: @escaping (MessageId, Media) -> (ASDisplayNode, () -> UIView?)?, addToTransitionSurface: @escaping (UIView) -> Void, openUrl: @escaping (String) -> Void, openPeer: @escaping (Peer, ChatControllerInteractionNavigateToPeer) -> Void, callPeer: @escaping (PeerId) -> Void, enqueueMessage: @escaping (EnqueueMessage) -> Void, sendSticker: ((FileMediaReference) -> Void)?, setupTemporaryHiddenMedia: @escaping (Signal, Int, Media) -> Void, chatAvatarHiddenMedia: @escaping (Signal, Media) -> Void, actionInteraction: GalleryControllerActionInteraction? = nil) -> Bool { - if let mediaData = chatMessageGalleryControllerData(account: context.account, message: message, navigationController: navigationController, standalone: standalone, reverseMessageGalleryOrder: reverseMessageGalleryOrder, stream: stream, synchronousLoad: false, excludeWebPageMedia: excludeWebPageMedia, actionInteraction: actionInteraction) { + if let mediaData = chatMessageGalleryControllerData(context: context, message: message, navigationController: navigationController, standalone: standalone, reverseMessageGalleryOrder: reverseMessageGalleryOrder, stream: stream, synchronousLoad: false, excludeWebPageMedia: excludeWebPageMedia, actionInteraction: actionInteraction) { switch mediaData { case let .url(url): openUrl(url) return true case let .pass(file): - let _ = (account.postbox.mediaBox.resourceData(file.resource, option: .complete(waitUntilFetchStatus: true)) + let _ = (context.account.postbox.mediaBox.resourceData(file.resource, option: .complete(waitUntilFetchStatus: true)) |> take(1) |> deliverOnMainQueue).start(next: { data in guard let navigationController = navigationController else { @@ -196,13 +196,13 @@ func openChatMessage(context: AccountContext, message: Message, standalone: Bool case let .map(mapMedia): dismissInput() - let controller = legacyLocationController(message: message, mapMedia: mapMedia, account: account, isModal: modal, openPeer: { peer in + let controller = legacyLocationController(message: message, mapMedia: mapMedia, context: context, isModal: modal, openPeer: { peer in openPeer(peer, .info) }, sendLiveLocation: { coordinate, period in let outMessage: EnqueueMessage = .message(text: "", attributes: [], mediaReference: .standalone(media: TelegramMediaMap(latitude: coordinate.latitude, longitude: coordinate.longitude, geoPlace: nil, venue: nil, liveBroadcastingTimeout: period)), replyToMessageId: nil, localGroupingKey: nil) enqueueMessage(outMessage) }, stopLiveLocation: { - account.telegramApplicationContext.liveLocationManager?.cancelLiveLocation(peerId: message.id.peerId) + context.liveLocationManager?.cancelLiveLocation(peerId: message.id.peerId) }, openUrl: openUrl) if modal { @@ -212,15 +212,15 @@ func openChatMessage(context: AccountContext, message: Message, standalone: Bool } return true case let .stickerPack(reference): - let controller = StickerPackPreviewController(account: account, stickerPack: reference, parentNavigationController: navigationController) + let controller = StickerPackPreviewController(context: context, stickerPack: reference, parentNavigationController: navigationController) controller.sendSticker = sendSticker dismissInput() present(controller, nil) return true case let .document(file): - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } if let rootController = navigationController?.view.window?.rootViewController { - presentDocumentPreviewController(rootController: rootController, theme: presentationData.theme, strings: presentationData.strings, postbox: account.postbox, file: file) + presentDocumentPreviewController(rootController: rootController, theme: presentationData.theme, strings: presentationData.strings, postbox: context.account.postbox, file: file) } //present(ShareController(account: account, subject: .messages([message]), showInChat: nil, externalShare: true, immediateExternalShare: true), nil) return true @@ -249,7 +249,7 @@ func openChatMessage(context: AccountContext, message: Message, standalone: Bool } playerType = (file.isVoice || file.isInstantVideo) ? .voice : .music } - account.telegramApplicationContext.mediaManager?.setPlaylist(PeerMessagesMediaPlaylist(postbox: account.postbox, network: account.network, location: location), type: playerType) + context.mediaManager.setPlaylist(PeerMessagesMediaPlaylist(postbox: context.account.postbox, network: context.account.network, location: location), type: playerType) return true case let .gallery(gallery): dismissInput() @@ -273,7 +273,7 @@ func openChatMessage(context: AccountContext, message: Message, standalone: Bool return true case let .other(otherMedia): if let contact = otherMedia as? TelegramMediaContact { - let _ = (account.postbox.transaction { transaction -> (Peer?, Bool?) in + let _ = (context.account.postbox.transaction { transaction -> (Peer?, Bool?) in if let peerId = contact.peerId { return (transaction.getPeer(peerId), transaction.isPeerContact(peerId: peerId)) } else { @@ -286,7 +286,7 @@ func openChatMessage(context: AccountContext, message: Message, standalone: Bool } else { contactData = DeviceContactExtendedData(basicData: DeviceContactBasicData(firstName: contact.firstName, lastName: contact.lastName, phoneNumbers: [DeviceContactPhoneNumberData(label: "_$!!$_", value: contact.phoneNumber)]), middleName: "", prefix: "", suffix: "", organization: "", jobTitle: "", department: "", emailAddresses: [], urls: [], addresses: [], birthdayDate: nil, socialProfiles: [], instantMessagingProfiles: []) } - let controller = deviceContactInfoController(account: account, subject: .vcard(peer, nil, contactData)) + let controller = deviceContactInfoController(context: context, subject: .vcard(peer, nil, contactData)) navigationController?.pushViewController(controller) guard let peer = peer else { @@ -393,7 +393,7 @@ func openChatInstantPage(context: AccountContext, message: Message, navigationCo anchor = String(textUrl[anchorRange.upperBound...]) } - let pageController = InstantPageController(account: account, webPage: webpage, anchor: anchor) + let pageController = InstantPageController(context: context, webPage: webpage, anchor: anchor) navigationController.pushViewController(pageController) } break @@ -404,7 +404,7 @@ func openChatInstantPage(context: AccountContext, message: Message, navigationCo func openChatWallpaper(context: AccountContext, message: Message, present: @escaping (ViewController, Any?) -> Void) { for media in message.media { if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { - let _ = (resolveUrl(account: account, url: content.url) + let _ = (resolveUrl(account: context.account, url: content.url) |> deliverOnMainQueue).start(next: { resolvedUrl in if case let .wallpaper(parameter) = resolvedUrl { let source: WallpaperListSource @@ -415,7 +415,7 @@ func openChatWallpaper(context: AccountContext, message: Message, present: @esca source = .wallpaper(.color(Int32(color.rgb))) } - let controller = WallpaperListPreviewController(account: account, source: source) + let controller = WallpaperListPreviewController(context: context, source: source) present(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } }) diff --git a/TelegramUI/OpenResolvedUrl.swift b/TelegramUI/OpenResolvedUrl.swift index e1b6abbf88..6f28e97d4c 100644 --- a/TelegramUI/OpenResolvedUrl.swift +++ b/TelegramUI/OpenResolvedUrl.swift @@ -39,25 +39,25 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon controller.peerSelected = { [weak controller] peerId in if payload.isEmpty { if peerId.namespace == Namespaces.Peer.CloudGroup { - let _ = (addGroupMember(account: account, peerId: peerId, memberId: botPeerId) + let _ = (addGroupMember(account: context.account, peerId: peerId, memberId: botPeerId) |> deliverOnMainQueue).start(completed: { controller?.dismiss() }) } else { - let _ = (addChannelMember(account: account, peerId: peerId, memberId: botPeerId) + let _ = (addChannelMember(account: context.account, peerId: peerId, memberId: botPeerId) |> deliverOnMainQueue).start(completed: { controller?.dismiss() }) } } else { - let _ = (requestStartBotInGroup(account: account, botPeerId: botPeerId, groupPeerId: peerId, payload: payload) + let _ = (requestStartBotInGroup(account: context.account, botPeerId: botPeerId, groupPeerId: peerId, payload: payload) |> deliverOnMainQueue).start(next: { result in if let navigationController = navigationController { - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId)) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId)) } switch result { case let .channelParticipant(participant): - account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.externallyAdded(peerId: peerId, participant: participant) + context.peerChannelMemberCategoriesContextsManager.externallyAdded(peerId: peerId, participant: participant) case .none: break } @@ -73,19 +73,19 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon openPeer(peerId, .chat(textInputState: nil, messageId: messageId)) case let .stickerPack(name): dismissInput() - let controller = StickerPackPreviewController(account: account, stickerPack: .name(name), parentNavigationController: navigationController) + let controller = StickerPackPreviewController(context: context, stickerPack: .name(name), parentNavigationController: navigationController) controller.sendSticker = sendFile present(controller, nil) case let .instantView(webpage, anchor): - navigationController?.pushViewController(InstantPageController(account: account, webPage: webpage, anchor: anchor)) + navigationController?.pushViewController(InstantPageController(context: context, webPage: webpage, anchor: anchor)) case let .join(link): dismissInput() - present(JoinLinkPreviewController(account: account, link: link, navigateToPeer: { peerId in + present(JoinLinkPreviewController(context: context, link: link, navigateToPeer: { peerId in openPeer(peerId, .chat(textInputState: nil, messageId: nil)) }), nil) case let .localization(identifier): dismissInput() - present(LanguageLinkPreviewController(account: account, identifier: identifier), nil) + present(LanguageLinkPreviewController(context: context, identifier: identifier), nil) case let .proxy(host, port, username, password, secret): let server: ProxyServerSettings if let secret = secret { @@ -95,7 +95,7 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon } dismissInput() - present(ProxyServerActionSheetController(account: account, server: server), nil) + present(ProxyServerActionSheetController(context: context, server: server), nil) case let .confirmationCode(code): if let topController = navigationController?.topViewController as? ChangePhoneNumberCodeController { topController.applyCode(code) @@ -108,18 +108,18 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon } }) if !found { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.AuthCode_Alert(formattedConfirmationCode(code)).0, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) } } case let .cancelAccountReset(phone, hash): - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let controller = OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .loading(cancelled: nil)) present(controller, nil) - let _ = (requestCancelAccountResetData(network: account.network, hash: hash) + let _ = (requestCancelAccountResetData(network: context.account.network, hash: hash) |> deliverOnMainQueue).start(next: { [weak controller] data in controller?.dismiss() - present(confirmPhoneNumberCodeController(account: account, phoneNumber: phone, codeData: data), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + present(confirmPhoneNumberCodeController(context: context, phoneNumber: phone, codeData: data), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, error: { [weak controller] error in controller?.dismiss() @@ -130,7 +130,7 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon case .generic: text = presentationData.strings.Login_UnknownError } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) }) dismissInput() @@ -154,7 +154,7 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon } if let textInputState = textInputState { - let _ = (account.postbox.transaction({ transaction -> Void in + let _ = (context.account.postbox.transaction({ transaction -> Void in transaction.updatePeerChatInterfaceState(peerId, update: { currentState in if let currentState = currentState as? ChatInterfaceState { return currentState.withUpdatedComposeInputState(textInputState) @@ -164,14 +164,14 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon }) }) |> deliverOnMainQueue).start(completed: { - navigationController?.pushViewController(ChatController(account: account, chatLocation: .peer(peerId), messageId: nil)) + navigationController?.pushViewController(ChatController(context: context, chatLocation: .peer(peerId), messageId: nil)) }) } } if let to = to { let query = to.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789").inverted) - let _ = (account.postbox.searchContacts(query: query) + let _ = (context.account.postbox.searchContacts(query: query) |> deliverOnMainQueue).start(next: { (peers, _) in for case let peer as TelegramUser in peers { if peer.phone == query { @@ -181,7 +181,7 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon } }) } else { - let controller = PeerSelectionController(account: account) + let controller = PeerSelectionController(context: context) controller.peerSelected = { [weak controller] peerId in if let strongController = controller { strongController.dismiss() @@ -189,18 +189,18 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon } } if let navigationController = navigationController { - account.telegramApplicationContext.applicationBindings.dismissNativeController() + context.applicationBindings.dismissNativeController() (navigationController.viewControllers.last as? ViewController)?.present(controller, in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: ViewControllerPresentationAnimation.modalSheet)) } } case let .wallpaper(parameter): - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } var controller: OverlayStatusController? let signal: Signal switch parameter { case let .slug(slug): - signal = getWallpaper(account: account, slug: slug) + signal = getWallpaper(account: context.account, slug: slug) controller = OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .loading(cancelled: nil)) present(controller!, nil) case let .color(color): @@ -210,7 +210,7 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlCon let _ = (signal |> deliverOnMainQueue).start(next: { [weak controller] wallpaper in controller?.dismiss() - let wallpaperController = WallpaperListPreviewController(account: account, source: .wallpaper(wallpaper)) + let wallpaperController = WallpaperListPreviewController(context: context, source: .wallpaper(wallpaper)) present(wallpaperController, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, error: { [weak controller] error in controller?.dismiss() diff --git a/TelegramUI/OpenUrl.swift b/TelegramUI/OpenUrl.swift index 381fe0cd80..9600090440 100644 --- a/TelegramUI/OpenUrl.swift +++ b/TelegramUI/OpenUrl.swift @@ -185,7 +185,7 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext } if let parsedUrlValue = parsedUrlValue, parsedUrlValue.scheme == "mailto" { - applicationContext.applicationBindings.openUrl(url) + context.applicationBindings.openUrl(url) return } @@ -199,19 +199,19 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext if let host = parsedUrl.host?.lowercased() { if host == "itunes.apple.com" { - if applicationContext.applicationBindings.canOpenUrl(parsedUrl.absoluteString) { - applicationContext.applicationBindings.openUrl(url) + if context.applicationBindings.canOpenUrl(parsedUrl.absoluteString) { + context.applicationBindings.openUrl(url) return } } if host == "twitter.com" || host == "mobile.twitter.com" { - if applicationContext.applicationBindings.canOpenUrl("twitter://status") { - applicationContext.applicationBindings.openUrl(url) + if context.applicationBindings.canOpenUrl("twitter://status") { + context.applicationBindings.openUrl(url) return } } else if host == "instagram.com" { - if applicationContext.applicationBindings.canOpenUrl("instagram://photo") { - applicationContext.applicationBindings.openUrl(url) + if context.applicationBindings.canOpenUrl("instagram://photo") { + context.applicationBindings.openUrl(url) return } } @@ -220,14 +220,14 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext let continueHandling: () -> Void = { let handleRevolvedUrl: (ResolvedUrl) -> Void = { resolved in if case let .externalUrl(value) = resolved { - applicationContext.applicationBindings.openUrl(value) + context.applicationBindings.openUrl(value) } else { - openResolvedUrl(resolved, account: account, navigationController: navigationController, openPeer: { peerId, navigation in + openResolvedUrl(resolved, context: context, navigationController: navigationController, openPeer: { peerId, navigation in switch navigation { case .info: - let _ = (account.postbox.loadedPeerWithId(peerId) + let _ = (context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { peer in - if let infoController = peerInfoController(account: account, peer: peer) { + if let infoController = peerInfoController(context: context, peer: peer) { if let navigationController = navigationController { navigationController.view.window?.rootViewController?.dismiss(animated: true, completion: nil) } @@ -237,22 +237,22 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext case let .chat(_, messageId): if let navigationController = navigationController { navigationController.view.window?.rootViewController?.dismiss(animated: true, completion: nil) - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId), messageId: messageId) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId), messageId: messageId) } case let .withBotStartPayload(payload): if let navigationController = navigationController { navigationController.view.window?.rootViewController?.dismiss(animated: true, completion: nil) - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId), botStart: payload) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId), botStart: payload) } default: break } }, present: { c, a in - account.telegramApplicationContext.applicationBindings.dismissNativeController() + context.applicationBindings.dismissNativeController() c.presentationArguments = a - account.telegramApplicationContext.applicationBindings.getWindowHost()?.present(c, on: .root, blockInteraction: false, completion: {}) + context.applicationBindings.getWindowHost()?.present(c, on: .root, blockInteraction: false, completion: {}) }, dismissInput: { dismissInput() }) @@ -260,11 +260,11 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext } let handleInternalUrl: (String) -> Void = { url in - let _ = (resolveUrl(account: account, url: url) + let _ = (resolveUrl(account: context.account, url: url) |> deliverOnMainQueue).start(next: handleRevolvedUrl) } - if let scheme = parsedUrl.scheme, (scheme == "tg" || scheme == applicationContext.applicationBindings.appSpecificScheme), let query = parsedUrl.query { + if let scheme = parsedUrl.scheme, (scheme == "tg" || scheme == context.applicationBindings.appSpecificScheme), let query = parsedUrl.query { var convertedUrl: String? if parsedUrl.host == "localpeer" { if let components = URLComponents(string: "/?" + query) { @@ -279,8 +279,8 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext } } if let peerId = peerId, let navigationController = navigationController { - account.telegramApplicationContext.applicationBindings.dismissNativeController() - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId)) + context.applicationBindings.dismissNativeController() + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId)) } } } else if parsedUrl.host == "join" { @@ -469,16 +469,16 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext } else if opaquePayload.isEmpty { return } - if case .chat = context { + if case .chat = urlContext { return } - let controller = SecureIdAuthController(account: account, 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: botId), scope: scope, publicKey: publicKey, callbackUrl: callbackUrl, opaquePayload: opaquePayload, opaqueNonce: opaqueNonce)) if let navigationController = navigationController { - account.telegramApplicationContext.applicationBindings.dismissNativeController() + context.applicationBindings.dismissNativeController() navigationController.view.window?.endEditing(true) - account.telegramApplicationContext.applicationBindings.getWindowHost()?.present(controller, on: .root, blockInteraction: false, completion: {}) + context.applicationBindings.getWindowHost()?.present(controller, on: .root, blockInteraction: false, completion: {}) } } return @@ -498,11 +498,11 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext } if let id = id, !id.isEmpty, let idValue = Int32(id), idValue > 0 { - let _ = (account.postbox.transaction { transaction -> Peer? in + let _ = (context.account.postbox.transaction { transaction -> Peer? in return transaction.getPeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: idValue)) } |> deliverOnMainQueue).start(next: { peer in - if let peer = peer, let controller = peerInfoController(account: account, peer: peer) { + if let peer = peer, let controller = peerInfoController(context: context, peer: peer) { navigationController?.pushViewController(controller) } }) @@ -625,14 +625,14 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext } window.rootViewController?.present(controller, animated: true) } else { - applicationContext.applicationBindings.openUrl(parsedUrl.absoluteString) + context.applicationBindings.openUrl(parsedUrl.absoluteString) } } else { - applicationContext.applicationBindings.openUrl(url) + context.applicationBindings.openUrl(url) } } } else { - applicationContext.applicationBindings.openUrl(url) + context.applicationBindings.openUrl(url) } } @@ -641,7 +641,7 @@ public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext if let host = parsedUrl.host, nativeHosts.contains(host) { continueHandling() } else { - applicationContext.applicationBindings.openUniversalUrl(url, TelegramApplicationOpenUrlCompletion(completion: { success in + context.applicationBindings.openUniversalUrl(url, TelegramApplicationOpenUrlCompletion(completion: { success in if !success { continueHandling() } diff --git a/TelegramUI/OverlayPlayerController.swift b/TelegramUI/OverlayPlayerController.swift index 987613581e..5a3770568c 100644 --- a/TelegramUI/OverlayPlayerController.swift +++ b/TelegramUI/OverlayPlayerController.swift @@ -43,13 +43,13 @@ final class OverlayPlayerController: ViewController { self?.dismiss() }, requestShare: { [weak self] messageId in if let strongSelf = self { - let _ = (strongSelf.account.postbox.transaction { transaction -> Message? in + let _ = (strongSelf.context.account.postbox.transaction { transaction -> Message? in return transaction.getMessage(messageId) } |> deliverOnMainQueue).start(next: { message in if let strongSelf = self, let message = message { - let shareController = ShareController(account: strongSelf.account, subject: .messages([message]), showInChat: { message in + let shareController = ShareController(context: strongSelf.context, subject: .messages([message]), showInChat: { message in if let strongSelf = self, let navigationController = strongSelf.parentNavigationController { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(message.id.peerId), messageId: messageId, animated: true) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(message.id.peerId), messageId: messageId, animated: true) strongSelf.dismiss() } }, externalShare: true) diff --git a/TelegramUI/PeerMediaCollectionControllerNode.swift b/TelegramUI/PeerMediaCollectionControllerNode.swift index a9e29d9eb5..183b4f4469 100644 --- a/TelegramUI/PeerMediaCollectionControllerNode.swift +++ b/TelegramUI/PeerMediaCollectionControllerNode.swift @@ -267,7 +267,7 @@ class PeerMediaCollectionControllerNode: ASDisplayNode { self.selectionPanelBackgroundNode = selectionPanelBackgroundNode let selectionPanel = ChatMessageSelectionInputPanelNode(theme: self.chatPresentationInterfaceState.theme) - selectionPanel.account = self.context.account + selectionPanel.context = self.context selectionPanel.backgroundColor = self.presentationData.theme.chat.inputPanel.panelBackgroundColor selectionPanel.interfaceInteraction = self.interfaceInteraction selectionPanel.selectedMessages = selectionState.selectedIds diff --git a/TelegramUI/PeerReportController.swift b/TelegramUI/PeerReportController.swift index 5c326448ff..f2096ef60c 100644 --- a/TelegramUI/PeerReportController.swift +++ b/TelegramUI/PeerReportController.swift @@ -85,7 +85,7 @@ func peerReportOptionsController(context: AccountContext, subject: PeerReportSub }) } } else { - controller?.present(peerReportController(account: context.account, subject: subject), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + controller?.present(peerReportController(context: context, subject: subject), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } controller?.dismissAnimated() diff --git a/TelegramUI/Permission.swift b/TelegramUI/Permission.swift index 59ee346fcd..bf651b469b 100644 --- a/TelegramUI/Permission.swift +++ b/TelegramUI/Permission.swift @@ -63,8 +63,8 @@ public enum PermissionState: Equatable { } } -public func requiredPermissions(account: Account) -> Signal<(PermissionState, PermissionState, PermissionState), NoError> { - return combineLatest(DeviceAccess.authorizationStatus(account: account, subject: .contacts), DeviceAccess.authorizationStatus(account: account, subject: .notifications), DeviceAccess.authorizationStatus(account: account, subject: .siri)) +public func requiredPermissions(context: AccountContext) -> Signal<(PermissionState, PermissionState, PermissionState), NoError> { + return combineLatest(DeviceAccess.authorizationStatus(context: context, subject: .contacts), DeviceAccess.authorizationStatus(context: context, subject: .notifications), DeviceAccess.authorizationStatus(context: context, subject: .siri)) |> map { contactsStatus, notificationsStatus, siriStatus in return (.contacts(status: PermissionRequestStatus(accessType: contactsStatus)), .notifications(status: PermissionRequestStatus(accessType: notificationsStatus)), .siri(status: PermissionRequestStatus(accessType: siriStatus))) } diff --git a/TelegramUI/PermissionController.swift b/TelegramUI/PermissionController.swift index 9af909f11b..2873fb9294 100644 --- a/TelegramUI/PermissionController.swift +++ b/TelegramUI/PermissionController.swift @@ -99,7 +99,7 @@ public final class PermissionController : ViewController { switch status { case .requestable: strongSelf.splitTest.addEvent(.ContactsRequest) - DeviceAccess.authorizeAccess(to: .contacts, account: strongSelf.context.account, { [weak self] result in + DeviceAccess.authorizeAccess(to: .contacts, context: strongSelf.context, { [weak self] result in if let strongSelf = self { if result { strongSelf.splitTest.addEvent(.ContactsAllowed) @@ -125,7 +125,7 @@ public final class PermissionController : ViewController { switch status { case .requestable: strongSelf.splitTest.addEvent(.NotificationsRequest) - DeviceAccess.authorizeAccess(to: .notifications, account: strongSelf.context.account, { [weak self] result in + DeviceAccess.authorizeAccess(to: .notifications, context: strongSelf.context, { [weak self] result in if let strongSelf = self { if result { strongSelf.splitTest.addEvent(.NotificationsAllowed) @@ -147,7 +147,7 @@ public final class PermissionController : ViewController { self.allow = { [weak self] in self?.proceed?(true) } - case let .cellularData: + case .cellularData: self.allow = { [weak self] in self?.proceed?(true) } @@ -168,7 +168,7 @@ public final class PermissionController : ViewController { } self.controllerNode.openPrivacyPolicy = { [weak self] in if let strongSelf = self { - openExternalUrl(context: strongSelf.context, context: .generic, url: "https://telegram.org/privacy", forceExternal: true, presentationData: strongSelf.context.currentPresentationData.with { $0 }, navigationController: nil, dismissInput: {}) + openExternalUrl(context: strongSelf.context, urlContext: .generic, url: "https://telegram.org/privacy", forceExternal: true, presentationData: strongSelf.context.currentPresentationData.with { $0 }, navigationController: nil, dismissInput: {}) } } } diff --git a/TelegramUI/PhotoResources.swift b/TelegramUI/PhotoResources.swift index 98a7c9763e..cf51dd8d82 100644 --- a/TelegramUI/PhotoResources.swift +++ b/TelegramUI/PhotoResources.swift @@ -1681,20 +1681,31 @@ func internalMediaGridMessageVideo(postbox: Postbox, videoReference: FileMediaRe } } -func chatMessagePhotoStatus(account: Account, messageId: MessageId, photoReference: ImageMediaReference) -> Signal { +func chatMessagePhotoStatus(context: AccountContext, messageId: MessageId, photoReference: ImageMediaReference) -> Signal { if let largestRepresentation = largestRepresentationForPhoto(photoReference.media) { - return account.telegramApplicationContext.fetchManager.fetchStatus(category: .image, location: .chat(messageId.peerId), locationKey: .messageId(messageId), resource: largestRepresentation.resource) + return context.fetchManager.fetchStatus(category: .image, location: .chat(messageId.peerId), locationKey: .messageId(messageId), resource: largestRepresentation.resource) } else { return .never() } } -public func chatMessagePhotoInteractiveFetched(account: Account, photoReference: ImageMediaReference, storeToDownloadsPeerType: AutomaticMediaDownloadPeerType?) -> Signal { +public func standaloneChatMessagePhotoInteractiveFetched(account: Account, photoReference: ImageMediaReference) -> Signal { if let largestRepresentation = largestRepresentationForPhoto(photoReference.media) { return fetchedMediaResource(postbox: account.postbox, reference: photoReference.resourceReference(largestRepresentation.resource), statsCategory: .image, reportResultStatus: true) + |> mapToSignal { type -> Signal in + return .single(type) + } + } else { + return .never() + } +} + +public func chatMessagePhotoInteractiveFetched(context: AccountContext, photoReference: ImageMediaReference, storeToDownloadsPeerType: AutomaticMediaDownloadPeerType?) -> Signal { + if let largestRepresentation = largestRepresentationForPhoto(photoReference.media) { + return fetchedMediaResource(postbox: context.account.postbox, reference: photoReference.resourceReference(largestRepresentation.resource), statsCategory: .image, reportResultStatus: true) |> mapToSignal { type -> Signal in if case .remote = type, let peerType = storeToDownloadsPeerType { - return storeDownloadedMedia(storeManager: account.telegramApplicationContext.mediaManager?.downloadedMediaStoreManager, media: photoReference.abstract, peerType: peerType) + return storeDownloadedMedia(storeManager: context.mediaManager.downloadedMediaStoreManager, media: photoReference.abstract, peerType: peerType) |> introduceError(FetchResourceError.self) |> mapToSignal { _ -> Signal in return .complete() diff --git a/TelegramUI/ProxyServerActionSheetController.swift b/TelegramUI/ProxyServerActionSheetController.swift index be0aaf76cd..5035c9ab4b 100644 --- a/TelegramUI/ProxyServerActionSheetController.swift +++ b/TelegramUI/ProxyServerActionSheetController.swift @@ -18,7 +18,7 @@ public final class ProxyServerActionSheetController: ActionSheetController { convenience init(context: AccountContext, server: ProxyServerSettings) { let presentationData = context.currentPresentationData.with { $0 } - self.init(theme: presentationData.theme, strings: context.presentationData.strings, postbox: context.account.postbox, network: context.account.network, server: server, presentationData: presentationData) + self.init(theme: presentationData.theme, strings: presentationData.strings, postbox: context.account.postbox, network: context.account.network, server: server, presentationData: context.presentationData) } public init(theme: PresentationTheme, strings: PresentationStrings, postbox: Postbox, network: Network, server: ProxyServerSettings, presentationData: Signal?) { diff --git a/TelegramUI/SearchPeerMembers.swift b/TelegramUI/SearchPeerMembers.swift index eecd21d4ab..48cb1bcc65 100644 --- a/TelegramUI/SearchPeerMembers.swift +++ b/TelegramUI/SearchPeerMembers.swift @@ -3,15 +3,15 @@ import Postbox import TelegramCore import SwiftSignalKit -func searchPeerMembers(account: Account, peerId: PeerId, query: String) -> Signal<[Peer], NoError> { +func searchPeerMembers(context: AccountContext, peerId: PeerId, query: String) -> Signal<[Peer], NoError> { if peerId.namespace == Namespaces.Peer.CloudChannel { - return account.postbox.transaction { transaction -> CachedChannelData? in + return context.account.postbox.transaction { transaction -> CachedChannelData? in return transaction.getPeerCachedData(peerId: peerId) as? CachedChannelData } |> mapToSignal { cachedData -> Signal<[Peer], NoError> in if let cachedData = cachedData, let memberCount = cachedData.participantsSummary.memberCount, memberCount <= 64 { return Signal { subscriber in - let (disposable, _) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recent(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, searchQuery: nil, requestUpdate: false, updated: { state in + let (disposable, _) = context.peerChannelMemberCategoriesContextsManager.recent(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, searchQuery: nil, requestUpdate: false, updated: { state in if case .ready = state.loadingState { let normalizedQuery = query.lowercased() subscriber.putNext(state.list.compactMap { participant -> Peer? in @@ -45,7 +45,7 @@ func searchPeerMembers(account: Account, peerId: PeerId, query: String) -> Signa } return Signal { subscriber in - let (disposable, _) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recent(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, searchQuery: query.isEmpty ? nil : query, updated: { state in + let (disposable, _) = context.peerChannelMemberCategoriesContextsManager.recent(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, searchQuery: query.isEmpty ? nil : query, updated: { state in if case .ready = state.loadingState { subscriber.putNext(state.list.compactMap { participant in if participant.peer.displayTitle.isEmpty { @@ -62,6 +62,6 @@ func searchPeerMembers(account: Account, peerId: PeerId, query: String) -> Signa } |> runOn(Queue.mainQueue()) } } else { - return searchGroupMembers(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, query: query) + return searchGroupMembers(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, query: query) } } diff --git a/TelegramUI/SecretChatKeyController.swift b/TelegramUI/SecretChatKeyController.swift index 3d899a3ad9..20c1694a09 100644 --- a/TelegramUI/SecretChatKeyController.swift +++ b/TelegramUI/SecretChatKeyController.swift @@ -16,7 +16,7 @@ final class SecretChatKeyController: ViewController { private var presentationData: PresentationData init(context: AccountContext, fingerprint: SecretChatKeyFingerprint, peer: Peer) { - self.account = account + self.context = context self.fingerprint = fingerprint self.peer = peer diff --git a/TelegramUI/SecureIdAuthControllerNode.swift b/TelegramUI/SecureIdAuthControllerNode.swift index 359057db5c..faef57666a 100644 --- a/TelegramUI/SecureIdAuthControllerNode.swift +++ b/TelegramUI/SecureIdAuthControllerNode.swift @@ -428,7 +428,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { } private func presentDocumentSelection(field: SecureIdParsedRequestedFormField) { - guard let state = self.state, case let .form(form) = state, let verificationState = form.verificationState, case let .verified(context) = verificationState, let encryptedFormData = form.encryptedFormData, let formData = form.formData else { + guard let state = self.state, case let .form(form) = state, let verificationState = form.verificationState, case let .verified(secureIdContext) = verificationState, let encryptedFormData = form.encryptedFormData, let formData = form.formData else { return } let updatedValues: ([SecureIdValueKey], [SecureIdValueWithContext]) -> Void = { [weak self] touchedKeys, updatedValues in @@ -508,7 +508,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { else if requireTranslation && !hasTranslation { scrollTo = .translation } - self.interaction.present(SecureIdDocumentFormController(context: self.context, context: context, requestedData: .identity(details: personalDetails, document: hasValueType, selfie: requireSelfie, translations: requireTranslation), scrollTo: scrollTo, primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in + self.interaction.present(SecureIdDocumentFormController(context: self.context, secureIdContext: secureIdContext, requestedData: .identity(details: personalDetails, document: hasValueType, selfie: requireSelfie, translations: requireTranslation), scrollTo: scrollTo, primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in var keys: [SecureIdValueKey] = [] if personalDetails != nil { keys.append(.personalDetails) @@ -519,7 +519,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { return } } else if personalDetails != nil { - self.interaction.present(SecureIdDocumentFormController(context: self.context, context: context, requestedData: .identity(details: personalDetails, document: nil, selfie: false, translations: false), primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in + self.interaction.present(SecureIdDocumentFormController(context: self.context, secureIdContext: secureIdContext, requestedData: .identity(details: personalDetails, document: nil, selfie: false, translations: false), primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in updatedValues([.personalDetails], values) }), nil) return @@ -583,7 +583,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { if requireTranslation && !hasTranslation { scrollTo = .translation } - self.interaction.present(SecureIdDocumentFormController(context: self.context, context: context, requestedData: .address(details: addressDetails, document: hasValueType, translations: requireTranslation), scrollTo: scrollTo, primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in + self.interaction.present(SecureIdDocumentFormController(context: self.context, secureIdContext: secureIdContext, requestedData: .address(details: addressDetails, document: hasValueType, translations: requireTranslation), scrollTo: scrollTo, primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in var keys: [SecureIdValueKey] = [] if addressDetails { keys.append(.address) @@ -594,7 +594,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { return } } else if addressDetails { - self.interaction.present(SecureIdDocumentFormController(context: self.context, context: context, requestedData: .address(details: addressDetails, document: nil, translations: false), primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in + self.interaction.present(SecureIdDocumentFormController(context: self.context, secureIdContext: secureIdContext, requestedData: .address(details: addressDetails, document: nil, translations: false), primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in updatedValues([.address], values) }), nil) return @@ -626,7 +626,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { attachmentTarget = .scan } - let controller = SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: requestedData, primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in + let controller = SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: requestedData, primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in var keys: [SecureIdValueKey] = [] switch requestedData { case let .identity(details, document, _, _): @@ -673,7 +673,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { } private func presentPlaintextSelection(type: SecureIdPlaintextFormType) { - guard let state = self.state, case let .form(form) = state, let formData = form.formData, let verificationState = form.verificationState, case let .verified(context) = verificationState else { + guard let state = self.state, case let .form(form) = state, let formData = form.formData, let verificationState = form.verificationState, case let .verified(secureIdContext) = verificationState else { return } @@ -695,7 +695,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { guard let strongSelf = self else { return } - strongSelf.interaction.present(SecureIdPlaintextFormController(context: strongSelf.context, context: context, type: type, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { valueWithContext in + strongSelf.interaction.present(SecureIdPlaintextFormController(context: strongSelf.context, secureIdContext: secureIdContext, type: type, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { valueWithContext in if let strongSelf = self { strongSelf.interaction.updateState { state in if case let .form(form) = state, let formData = form.formData { @@ -773,7 +773,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { } private func openListField(_ field: SecureIdAuthListContentField) { - guard let state = self.state, case let .list(list) = state, let verificationState = list.verificationState, case let .verified(context) = verificationState else { + guard let state = self.state, case let .list(list) = state, let verificationState = list.verificationState, case let .verified(secureIdContext) = verificationState else { return } guard let values = list.values else { @@ -809,27 +809,27 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { let primaryLanguageByCountry = list.primaryLanguageByCountry ?? [:] switch field { case .personalDetails: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .identity(details: ParsedRequestedPersonalDetails(nativeNames: false), document: nil, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .identity(details: ParsedRequestedPersonalDetails(nativeNames: false), document: nil, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .passport: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .identity(details: nil, document: .passport, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .identity(details: nil, document: .passport, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .internalPassport: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .identity(details: nil, document: .internalPassport, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .identity(details: nil, document: .internalPassport, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .driversLicense: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .identity(details: nil, document: .driversLicense, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .identity(details: nil, document: .driversLicense, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .idCard: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .identity(details: nil, document: .idCard, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .identity(details: nil, document: .idCard, selfie: false, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .address: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .address(details: true, document: nil, translations: false), primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .address(details: true, document: nil, translations: false), primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .utilityBill: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .address(details: false, document: .utilityBill, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .address(details: false, document: .utilityBill, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .bankStatement: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .address(details: false, document: .bankStatement, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .address(details: false, document: .bankStatement, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .rentalAgreement: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .address(details: false, document: .rentalAgreement, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .address(details: false, document: .rentalAgreement, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .passportRegistration: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .address(details: false, document: .passportRegistration, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .address(details: false, document: .passportRegistration, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .temporaryRegistration: - strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: .address(details: false, document: .temporaryRegistration, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) + strongSelf.interaction.present(SecureIdDocumentFormController(context: strongSelf.context, secureIdContext: secureIdContext, requestedData: .address(details: false, document: .temporaryRegistration, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .phone: break case .email: @@ -866,7 +866,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { } return state } - strongSelf.deleteValueDisposable.set((deleteSecureIdValues(network: strongSelf.account.network, keys: Set([field])) + strongSelf.deleteValueDisposable.set((deleteSecureIdValues(network: strongSelf.context.account.network, keys: Set([field])) |> deliverOnMainQueue).start(completed: { guard let strongSelf = self else { return @@ -936,7 +936,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { if let peer = list.accountPeer as? TelegramUser, let phone = peer.phone, !phone.isEmpty { immediatelyAvailableValue = .phone(SecureIdPhoneValue(phone: phone)) } - self.interaction.present(SecureIdPlaintextFormController(context: self.context, context: context, type: .phone, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { value in + self.interaction.present(SecureIdPlaintextFormController(context: self.context, secureIdContext: secureIdContext, type: .phone, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { value in updatedValues(.phone)(value.flatMap({ [$0] }) ?? []) }), nil) } @@ -948,7 +948,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { if let email = list.twoStepEmail { immediatelyAvailableValue = .email(SecureIdEmailValue(email: email)) } - self.interaction.present(SecureIdPlaintextFormController(context: self.context, context: context, type: .email, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { value in + self.interaction.present(SecureIdPlaintextFormController(context: self.context, secureIdContext: secureIdContext, type: .email, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { value in updatedValues(.email)(value.flatMap({ [$0] }) ?? []) }), nil) } diff --git a/TelegramUI/SecureIdDocumentFormController.swift b/TelegramUI/SecureIdDocumentFormController.swift index 0c4e79dd0c..2a64872399 100644 --- a/TelegramUI/SecureIdDocumentFormController.swift +++ b/TelegramUI/SecureIdDocumentFormController.swift @@ -40,7 +40,7 @@ final class SecureIdDocumentFormController: FormController Void)? @@ -2718,7 +2718,7 @@ final class SecureIdDocumentFormControllerNode: FormControllerNode] = [] for (_, value) in values { - saveValues.append(saveSecureIdValue(postbox: self.context.account.postbox, network: self.context.account.network, context: self.context, value: value, uploadedFiles: self.uploadContext.uploadedFiles)) + saveValues.append(saveSecureIdValue(postbox: self.context.account.postbox, network: self.context.account.network, context: self.secureIdContext, value: value, uploadedFiles: self.uploadContext.uploadedFiles)) } self.actionDisposable.set((combineLatest(saveValues) @@ -2965,7 +2965,7 @@ final class SecureIdDocumentFormControllerNode: FormControllerNode Void) -> GalleryItem { - return SecureIdDocumentGalleryItem(account: account, theme: theme, strings: strings, context: context, resource: self.resource, caption: self.error, location: self.location, delete: { + func item(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings, secureIdContext: SecureIdAccessContext, delete: @escaping (TelegramMediaResource) -> Void) -> GalleryItem { + return SecureIdDocumentGalleryItem(context: context, theme: theme, strings: strings, secureIdContext: secureIdContext, resource: self.resource, caption: self.error, location: self.location, delete: { delete(self.resource) }) } @@ -97,7 +97,7 @@ class SecureIdDocumentGalleryController: ViewController { strongSelf.centralEntryIndex = centralIndex if strongSelf.isViewLoaded { strongSelf.galleryNode.pager.replaceItems(strongSelf.entries.map({ - $0.item(account: context.account, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, context: strongSelf.secureIdContext, delete: { resource in + $0.item(context: context, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, secureIdContext: strongSelf.secureIdContext, delete: { resource in self?.deleteItem(resource) }) }), centralItemIndex: centralIndex, keepFirst: false) @@ -254,7 +254,7 @@ class SecureIdDocumentGalleryController: ViewController { firstLayout = false self.galleryNode.pager.replaceItems(self.entries.map({ - $0.item(account: context.account, theme: self.presentationData.theme, strings: self.presentationData.strings, context: self.secureIdContext, delete: { [weak self] resource in + $0.item(context: self.context, theme: self.presentationData.theme, strings: self.presentationData.strings, secureIdContext: self.secureIdContext, delete: { [weak self] resource in self?.deleteItem(resource) }) }), centralItemIndex: self.centralEntryIndex) diff --git a/TelegramUI/SecureIdDocumentImageGalleryItem.swift b/TelegramUI/SecureIdDocumentImageGalleryItem.swift index 29d8919d40..427e1e2e90 100644 --- a/TelegramUI/SecureIdDocumentImageGalleryItem.swift +++ b/TelegramUI/SecureIdDocumentImageGalleryItem.swift @@ -75,7 +75,7 @@ final class SecureIdDocumentGalleryItemNode: ZoomableContentGalleryItemNode { self.context = context self.imageNode = TransformImageNode() - self.footerContentNode = SecureIdDocumentGalleryFooterContentNode(account: account, theme: theme, strings: strings) + self.footerContentNode = SecureIdDocumentGalleryFooterContentNode(context: context, theme: theme, strings: strings) super.init() diff --git a/TelegramUI/SecureIdDocumentTypeSelectionController.swift b/TelegramUI/SecureIdDocumentTypeSelectionController.swift index 897ef44b18..e8e5c5ec3a 100644 --- a/TelegramUI/SecureIdDocumentTypeSelectionController.swift +++ b/TelegramUI/SecureIdDocumentTypeSelectionController.swift @@ -78,8 +78,8 @@ final class SecureIdDocumentTypeSelectionController: ActionSheetController { return self._ready } - init(account: Account, field: SecureIdParsedRequestedFormField, currentValues: [SecureIdValueWithContext], completion: @escaping (SecureIdDocumentFormRequestedData) -> Void) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, field: SecureIdParsedRequestedFormField, currentValues: [SecureIdValueWithContext], completion: @escaping (SecureIdDocumentFormRequestedData) -> Void) { + let presentationData = context.currentPresentationData.with { $0 } let theme = presentationData.theme let strings = presentationData.strings @@ -87,7 +87,7 @@ final class SecureIdDocumentTypeSelectionController: ActionSheetController { super.init(theme: ActionSheetControllerTheme(presentationTheme: theme)) - self.presentationDisposable = account.telegramApplicationContext.presentationData.start(next: { [weak self] presentationData in + self.presentationDisposable = context.presentationData.start(next: { [weak self] presentationData in if let strongSelf = self { strongSelf.theme = ActionSheetControllerTheme(presentationTheme: presentationData.theme) } diff --git a/TelegramUI/SecureIdPlaintextFormControllerNode.swift b/TelegramUI/SecureIdPlaintextFormControllerNode.swift index f4d095730b..ea87c8035a 100644 --- a/TelegramUI/SecureIdPlaintextFormControllerNode.swift +++ b/TelegramUI/SecureIdPlaintextFormControllerNode.swift @@ -849,7 +849,7 @@ final class SecureIdPlaintextFormControllerNode: FormControllerNode deliverOnMainQueue).start(next: { [weak self] result in guard let strongSelf = self else { return diff --git a/TelegramUI/SettingsController.swift b/TelegramUI/SettingsController.swift index 98a97d2bc8..a1bebd45ab 100644 --- a/TelegramUI/SettingsController.swift +++ b/TelegramUI/SettingsController.swift @@ -552,7 +552,7 @@ public func settingsController(context: AccountContext, accountManager: AccountM |> distinctUntilChanged |> mapToSignal { recordIds -> Signal<[(Account, Peer, Int32)], NoError> in return contextValue.get() - |> mapToSignal { currentAccount -> Signal<[(Account, Peer, Int32)], NoError> in + |> mapToSignal { currentContext -> Signal<[(Account, Peer, Int32)], NoError> in var accounts: [Signal<(Account, Peer, Int32)?, NoError>] = [] func accountWithPeer(_ account: Signal) -> Signal<(Account, Peer, Int32)?, NoError> { return account @@ -577,7 +577,7 @@ public func settingsController(context: AccountContext, accountManager: AccountM } } for id in recordIds { - if id == currentAccount.id { + if id == currentContext.account.id { continue } else { accounts.append(accountWithPeer(accountWithId(networkArguments: networkArguments, id: id, supplementary: true, rootPath: rootPath, beginWithTestingEnvironment: false, auxiliaryMethods: auxiliaryMethods) @@ -643,7 +643,7 @@ public func settingsController(context: AccountContext, accountManager: AccountM let _ = (contextValue.get() |> deliverOnMainQueue |> take(1)).start(next: { context in - let _ = (context.account.postbox.loadedPeerWithId(account.peerId) + let _ = (context.account.postbox.loadedPeerWithId(context.account.peerId) |> take(1) |> deliverOnMainQueue).start(next: { peer in if peer.smallProfileImage != nil { @@ -756,7 +756,7 @@ public func settingsController(context: AccountContext, accountManager: AccountM TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: { supportPeerDisposable.set((supportPeer.get() |> take(1) |> deliverOnMainQueue).start(next: { peerId in if let peerId = peerId { - pushControllerImpl?(ChatController(account: account, chatLocation: .peer(peerId))) + pushControllerImpl?(ChatController(context: context, chatLocation: .peer(peerId))) } })) }) @@ -789,7 +789,7 @@ public func settingsController(context: AccountContext, accountManager: AccountM let progressDisposable = progressSignal.start() let peerKey: PostboxViewKey = .peer(peerId: context.account.peerId, components: []) - let cachedDataKey: PostboxViewKey = .cachedPeerData(peerId: account.peerId) + let cachedDataKey: PostboxViewKey = .cachedPeerData(peerId: context.account.peerId) let signal = (context.account.postbox.combinedView(keys: [peerKey, cachedDataKey]) |> mapToSignal { view -> Signal<(TelegramUser, CachedUserData), NoError> in guard let cachedDataView = view.views[cachedDataKey] as? CachedPeerDataView, let cachedData = cachedDataView.cachedPeerData as? CachedUserData else { @@ -984,7 +984,7 @@ public func settingsController(context: AccountContext, accountManager: AccountM |> then( contextValue.get() |> mapToSignal { context -> Signal in - return DeviceAccess.authorizationStatus(account: context.account, subject: .notifications) + return DeviceAccess.authorizationStatus(context: context, subject: .notifications) } ) ) @@ -1124,17 +1124,17 @@ public func settingsController(context: AccountContext, accountManager: AccountM openSavedMessagesImpl = { [weak controller] in let _ = (contextValue.get() |> take(1) - |> deliverOnMainQueue).start(next: { account in + |> deliverOnMainQueue).start(next: { context in if let controller = controller, let navigationController = controller.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(account.peerId)) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(context.account.peerId)) } }) } controller.tabBarItemDebugTapAction = { let _ = (contextValue.get() |> take(1) - |> deliverOnMainQueue).start(next: { account in - pushControllerImpl?(debugController(account: account, accountManager: accountManager)) + |> deliverOnMainQueue).start(next: { context in + pushControllerImpl?(debugController(context: context, accountManager: accountManager)) }) } diff --git a/TelegramUI/SettingsThemeWallpaperNode.swift b/TelegramUI/SettingsThemeWallpaperNode.swift index fadf81150f..508c05c66f 100644 --- a/TelegramUI/SettingsThemeWallpaperNode.swift +++ b/TelegramUI/SettingsThemeWallpaperNode.swift @@ -51,7 +51,7 @@ final class SettingsThemeWallpaperNode: ASDisplayNode { self.buttonNode.addTarget(self, action: #selector(self.buttonPressed), forControlEvents: .touchUpInside) } - func setWallpaper(account: Account, wallpaper: TelegramWallpaper, selected: Bool, size: CGSize) { + func setWallpaper(context: AccountContext, wallpaper: TelegramWallpaper, selected: Bool, size: CGSize) { self.buttonNode.frame = CGRect(origin: CGPoint(), size: size) self.backgroundNode.frame = CGRect(origin: CGPoint(), size: size) self.imageNode.frame = CGRect(origin: CGPoint(), size: size) @@ -68,14 +68,14 @@ final class SettingsThemeWallpaperNode: ASDisplayNode { case .builtin: self.imageNode.isHidden = false self.backgroundNode.isHidden = true - self.imageNode.setSignal(settingsBuiltinWallpaperImage(account: account)) + self.imageNode.setSignal(settingsBuiltinWallpaperImage(account: context.account)) let apply = self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: CGSize(), boundingSize: size, intrinsicInsets: UIEdgeInsets())) apply() case let .color(color): if color == 0x00ffffff { self.imageNode.isHidden = false self.backgroundNode.isHidden = true - self.imageNode.setSignal(whiteColorImage(theme: account.telegramApplicationContext.currentPresentationData.with { $0 }.theme)) + self.imageNode.setSignal(whiteColorImage(theme: context.currentPresentationData.with { $0 }.theme)) let apply = self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: CGSize(), boundingSize: size, intrinsicInsets: UIEdgeInsets())) apply() } else { @@ -88,7 +88,7 @@ final class SettingsThemeWallpaperNode: ASDisplayNode { self.backgroundNode.isHidden = true let convertedRepresentations: [ImageRepresentationWithReference] = representations.map({ ImageRepresentationWithReference(representation: $0, reference: .wallpaper(resource: $0.resource)) }) - self.imageNode.setSignal(chatAvatarGalleryPhoto(account: account, representations: convertedRepresentations, autoFetchFullSize: true)) + self.imageNode.setSignal(chatAvatarGalleryPhoto(account: context.account, representations: convertedRepresentations, autoFetchFullSize: true)) let apply = self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: largestImageRepresentation(representations)!.dimensions.aspectFilled(size), boundingSize: size, intrinsicInsets: UIEdgeInsets())) apply() case let .file(file): @@ -100,7 +100,7 @@ final class SettingsThemeWallpaperNode: ASDisplayNode { convertedRepresentations.append(ImageRepresentationWithReference(representation: representation, reference: .wallpaper(resource: representation.resource))) } let dimensions = file.file.dimensions ?? CGSize(width: 100.0, height: 100.0) - self.imageNode.setSignal(chatAvatarGalleryPhoto(account: account, fileReference: .standalone(media: file.file), representations: convertedRepresentations, autoFetchFullSize: true)) + self.imageNode.setSignal(chatAvatarGalleryPhoto(account: context.account, fileReference: .standalone(media: file.file), representations: convertedRepresentations, autoFetchFullSize: true)) let apply = self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: dimensions.aspectFilled(size), boundingSize: size, intrinsicInsets: UIEdgeInsets())) apply() } diff --git a/TelegramUI/ShareControllerPeerGridItem.swift b/TelegramUI/ShareControllerPeerGridItem.swift index 478d7e6e69..9d608d0bee 100644 --- a/TelegramUI/ShareControllerPeerGridItem.swift +++ b/TelegramUI/ShareControllerPeerGridItem.swift @@ -148,7 +148,7 @@ final class ShareControllerPeerGridItemNode: GridItemNode { if self.currentState == nil || self.currentState!.0 !== account || self.currentState!.1 != peer { let itemTheme = SelectablePeerNodeTheme(textColor: theme.actionSheet.primaryTextColor, secretTextColor: theme.chatList.secretTitleColor, selectedTextColor: theme.actionSheet.controlAccentColor, checkBackgroundColor: theme.actionSheet.opaqueItemBackgroundColor, checkFillColor: theme.actionSheet.controlAccentColor, checkColor: theme.actionSheet.checkContentColor, avatarPlaceholderColor: theme.list.mediaPlaceholderColor) self.peerNode.theme = itemTheme - self.peerNode.setup(account: account, strings: strings, peer: peer, synchronousLoad: synchronousLoad) + self.peerNode.setup(account: account, theme: theme, strings: strings, peer: peer, synchronousLoad: synchronousLoad) self.currentState = (account, peer, search) self.setNeedsLayout() } diff --git a/TelegramUI/StickerPaneSearchContainerNode.swift b/TelegramUI/StickerPaneSearchContainerNode.swift index 9d76367590..ccec61fb73 100644 --- a/TelegramUI/StickerPaneSearchContainerNode.swift +++ b/TelegramUI/StickerPaneSearchContainerNode.swift @@ -163,7 +163,7 @@ final class StickerPaneSearchContainerNode: ASDisplayNode { self.backgroundNode = ASDisplayNode() - self.trendingPane = ChatMediaInputTrendingPane(account: context.account, controllerInteraction: controllerInteraction, getItemIsPreviewed: { [weak inputNodeInteraction] item in + self.trendingPane = ChatMediaInputTrendingPane(context: context, controllerInteraction: controllerInteraction, getItemIsPreviewed: { [weak inputNodeInteraction] item in return inputNodeInteraction?.previewedStickerPackItem == .pack(item) }) @@ -214,14 +214,14 @@ final class StickerPaneSearchContainerNode: ASDisplayNode { } }, install: { [weak self] info in if let strongSelf = self { - let _ = (loadedStickerPack(postbox: strongSelf.account.postbox, network: strongSelf.account.network, reference: .id(id: info.id.id, accessHash: info.accessHash), forceActualized: false) + let _ = (loadedStickerPack(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, reference: .id(id: info.id.id, accessHash: info.accessHash), forceActualized: false) |> mapToSignal { result -> Signal in switch result { case let .result(info, items, installed): if installed { return .complete() } else { - return addStickerPackInteractively(postbox: strongSelf.account.postbox, info: info, items: items) + return addStickerPackInteractively(postbox: strongSelf.context.account.postbox, info: info, items: items) } case .fetching: break @@ -254,13 +254,13 @@ final class StickerPaneSearchContainerNode: ASDisplayNode { var signals: [Signal<(String?, [FoundStickerItem]), NoError>] = [] if text.isSingleEmoji { - signals.append(searchStickers(account: account, query: text.firstEmoji) + signals.append(searchStickers(account: context.account, query: text.firstEmoji) |> take(1) |> map { (nil, $0) }) } else { for entry in TGEmojiSuggestions.suggestions(forQuery: text.lowercased()) { if let entry = entry as? TGAlphacodeEntry { - signals.append(searchStickers(account: account, query: entry.emoji) + signals.append(searchStickers(account: context.account, query: entry.emoji) |> take(1) |> map { (entry.emoji, $0) }) } @@ -280,8 +280,8 @@ final class StickerPaneSearchContainerNode: ASDisplayNode { }) } - let local = searchStickerSets(postbox: account.postbox, query: text) - let remote = searchStickerSetsRemotely(network: account.network, query: text) + let local = searchStickerSets(postbox: context.account.postbox, query: text) + let remote = searchStickerSetsRemotely(network: context.account.network, query: text) |> delay(0.2, queue: Queue.mainQueue()) let packs = local |> mapToSignal { result -> Signal<(FoundStickerSets, Bool, FoundStickerSets?), NoError> in @@ -355,7 +355,7 @@ final class StickerPaneSearchContainerNode: ASDisplayNode { } let previousEntries = currentEntries.swap(entries) - let transition = preparedChatMediaInputGridEntryTransition(account: account, theme: theme, strings: strings, from: previousEntries ?? [], to: entries, interaction: interaction, inputNodeInteraction: strongSelf.inputNodeInteraction) + let transition = preparedChatMediaInputGridEntryTransition(account: context.account, theme: theme, strings: strings, from: previousEntries ?? [], to: entries, interaction: interaction, inputNodeInteraction: strongSelf.inputNodeInteraction) strongSelf.enqueueTransition(transition) } })) diff --git a/TelegramUI/StickersChatInputContextPanelNode.swift b/TelegramUI/StickersChatInputContextPanelNode.swift index a9cb4de287..5462713201 100644 --- a/TelegramUI/StickersChatInputContextPanelNode.swift +++ b/TelegramUI/StickersChatInputContextPanelNode.swift @@ -59,14 +59,13 @@ private func preparedTransition(from fromEntries: [StickersChatInputContextPanel } final class StickersChatInputContextPanelNode: ChatInputContextPanelNode { - private let listView: ListView private var currentEntries: [StickersChatInputContextPanelEntry]? private var enqueuedTransitions: [(StickersChatInputContextPanelTransition, Bool)] = [] private var validLayout: (CGSize, CGFloat, CGFloat)? - override init(account: Account, theme: PresentationTheme, strings: PresentationStrings) { + override init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings) { self.listView = ListView() self.listView.isOpaque = false self.listView.stackFromBottom = true @@ -74,7 +73,7 @@ final class StickersChatInputContextPanelNode: ChatInputContextPanelNode { self.listView.limitHitTestToNodes = true self.listView.view.disablesInteractiveTransitionGestureRecognizer = true - super.init(account: account, theme: theme, strings: strings) + super.init(context: context, theme: theme, strings: strings) self.isOpaque = false self.clipsToBounds = true @@ -100,7 +99,7 @@ final class StickersChatInputContextPanelNode: ChatInputContextPanelNode { private func prepareTransition(from: [StickersChatInputContextPanelEntry]? , to: [StickersChatInputContextPanelEntry]) { let firstTime = from == nil - let transition = preparedTransition(from: from ?? [], to: to, account: self.account, hashtagSelected: { [weak self] text in + let transition = preparedTransition(from: from ?? [], to: to, account: self.context.account, hashtagSelected: { [weak self] text in }) self.currentEntries = to diff --git a/TelegramUI/StorageUsageController.swift b/TelegramUI/StorageUsageController.swift index 443b3bba89..6ae8339bdf 100644 --- a/TelegramUI/StorageUsageController.swift +++ b/TelegramUI/StorageUsageController.swift @@ -261,7 +261,7 @@ private func stringForCategory(strings: PresentationStrings, category: PeerCache } } -func storageUsageController(context: context, isModal: Bool = false) -> ViewController { +func storageUsageController(context: AccountContext, isModal: Bool = false) -> ViewController { let cacheSettingsPromise = Promise() cacheSettingsPromise.set(context.account.postbox.preferencesView(keys: [PreferencesKeys.cacheStorageSettings]) |> map { view -> CacheStorageSettings in diff --git a/TelegramUI/SuppressContactsWarning.swift b/TelegramUI/SuppressContactsWarning.swift index cceefb551c..a0a123f911 100644 --- a/TelegramUI/SuppressContactsWarning.swift +++ b/TelegramUI/SuppressContactsWarning.swift @@ -9,14 +9,14 @@ func presentContactsWarningSuppression(context: AccountContext, present: (ViewCo present(textAlertController(context: context, title: presentationData.strings.Contacts_PermissionsSuppressWarningTitle, text: presentationData.strings.Contacts_PermissionsSuppressWarningText, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Contacts_PermissionsKeepDisabled, action: { ApplicationSpecificNotice.setContactsPermissionWarning(postbox: context.account.postbox, value: Int32(Date().timeIntervalSince1970)) }), TextAlertAction(type: .defaultAction, title: presentationData.strings.Contacts_PermissionsEnable, action: { - let _ = (DeviceAccess.authorizationStatus(account: account, subject: .contacts) + let _ = (DeviceAccess.authorizationStatus(context: context, subject: .contacts) |> take(1) |> deliverOnMainQueue).start(next: { status in switch status { case .notDetermined: - DeviceAccess.authorizeAccess(to: .contacts, account: account) + DeviceAccess.authorizeAccess(to: .contacts, context: context) case .denied, .restricted: - account.telegramApplicationContext.applicationBindings.openSettings() + context.applicationBindings.openSettings() default: break } diff --git a/TelegramUI/TelegramInitializeLegacyComponents.swift b/TelegramUI/TelegramInitializeLegacyComponents.swift index 6bc81d10eb..3d941b23c1 100644 --- a/TelegramUI/TelegramInitializeLegacyComponents.swift +++ b/TelegramUI/TelegramInitializeLegacyComponents.swift @@ -27,17 +27,17 @@ public func updateLegacyComponentsAccount(_ account: Account?) { private var legacyDocumentsStorePath: String? private var legacyCanOpenUrl: (URL) -> Bool = { _ in return false } private var legacyOpenUrl: (URL) -> Void = { _ in } -private weak var legacyAccount: Account? +private weak var legacyContext: AccountContext? -func legacyAccountGet() -> Account? { - return legacyAccount +func legacyContextGet() -> AccountContext? { + return legacyContext } private final class LegacyComponentsAccessCheckerImpl: NSObject, LegacyComponentsAccessChecker { - private weak var applicationContext: TelegramApplicationContext? + private weak var context: AccountContext? - init(applicationContext: TelegramApplicationContext?) { - self.applicationContext = applicationContext + init(context: AccountContext?) { + self.context = context } public func checkAddressBookAuthorizationStatus(alertDismissComlpetion alertDismissCompletion: (() -> Void)!) -> Bool { @@ -68,8 +68,8 @@ private final class LegacyComponentsAccessCheckerImpl: NSObject, LegacyComponent assertionFailure() subject = .send } - if let applicationContext = self.applicationContext { - DeviceAccess.authorizeAccess(to: .location(subject), presentationData: applicationContext.currentPresentationData.with { $0 }, present: applicationContext.presentGlobalController, openSettings: applicationContext.applicationBindings.openSettings, { value in + if let context = self.context { + DeviceAccess.authorizeAccess(to: .location(subject), presentationData: context.currentPresentationData.with { $0 }, present: context.presentGlobalController, openSettings: context.applicationBindings.openSettings, { value in if !value { alertDismissCompletion?() } @@ -187,12 +187,12 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone } public func accessChecker() -> LegacyComponentsAccessChecker! { - return LegacyComponentsAccessCheckerImpl(applicationContext: legacyAccount?.telegramApplicationContext) + return LegacyComponentsAccessCheckerImpl(context: legacyContext) } public func stickerPacksSignal() -> SSignal! { - if let legacyAccount = legacyAccount { - return legacyComponentsStickers(postbox: legacyAccount.postbox, namespace: Namespaces.ItemCollection.CloudStickerPacks) + if let legacyContext = legacyContext { + return legacyComponentsStickers(postbox: legacyContext.account.postbox, namespace: Namespaces.ItemCollection.CloudStickerPacks) } else { var dict: [AnyHashable: Any] = [:] dict["packs"] = NSArray() @@ -201,8 +201,8 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone } public func maskStickerPacksSignal() -> SSignal! { - if let legacyAccount = legacyAccount { - return legacyComponentsStickers(postbox: legacyAccount.postbox, namespace: Namespaces.ItemCollection.CloudMaskPacks) + if let legacyContext = legacyContext { + return legacyComponentsStickers(postbox: legacyContext.account.postbox, namespace: Namespaces.ItemCollection.CloudMaskPacks) } else { var dict: [AnyHashable: Any] = [:] dict["packs"] = NSArray() @@ -215,7 +215,7 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone } public func request(_ type: TGAudioSessionType, interrupted: (() -> Void)!) -> SDisposable! { - if let legacyAccount = legacyAccount { + if let legacyContext = legacyContext { let convertedType: ManagedAudioSessionType switch type { case TGAudioSessionTypePlayAndRecord, TGAudioSessionTypePlayAndRecordHeadphones: @@ -223,35 +223,35 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone default: convertedType = .play } - let disposable = legacyAccount.telegramApplicationContext.mediaManager?.audioSession.push(audioSessionType: convertedType, once: true, activate: { _ in + let disposable = legacyContext.mediaManager.audioSession.push(audioSessionType: convertedType, once: true, activate: { _ in }, deactivate: { interrupted?() return .complete() }) return SBlockDisposable(block: { - disposable?.dispose() + disposable.dispose() }) } return nil } public func currentWallpaperInfo() -> TGWallpaperInfo! { - if let account = legacyComponentsAccount { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + if let legacyContext = legacyContext { + let presentationData = legacyContext.currentPresentationData.with { $0 } switch presentationData.chatWallpaper { case .builtin: return TGBuiltinWallpaperInfo() case let .color(color): return TGColorWallpaperInfo(color: UInt32(bitPattern: color)) case let .image(representations): - if let resource = largestImageRepresentation(representations)?.resource, let path = account.postbox.mediaBox.completedResourcePath(resource), let image = UIImage(contentsOfFile: path) { + if let resource = largestImageRepresentation(representations)?.resource, let path = legacyContext.account.postbox.mediaBox.completedResourcePath(resource), let image = UIImage(contentsOfFile: path) { return TGCustomImageWallpaperInfo(image: image) } else { return TGBuiltinWallpaperInfo() } case let .file(file): - if let path = account.postbox.mediaBox.completedResourcePath(file.file.resource), let image = UIImage(contentsOfFile: path) { + if let path = legacyContext.account.postbox.mediaBox.completedResourcePath(file.file.resource), let image = UIImage(contentsOfFile: path) { return TGCustomImageWallpaperInfo(image: image) } else { return TGBuiltinWallpaperInfo() @@ -263,8 +263,8 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone } public func currentWallpaperImage() -> UIImage! { - if let account = legacyComponentsAccount { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + if let legacyContext = legacyContext { + let presentationData = legacyContext.currentPresentationData.with { $0 } switch presentationData.chatWallpaper { case .builtin: return nil @@ -278,13 +278,13 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone context.fill(CGRect(origin: CGPoint(), size: size)) }) case let .image(representations): - if let resource = largestImageRepresentation(representations)?.resource, let path = account.postbox.mediaBox.completedResourcePath(resource), let image = UIImage(contentsOfFile: path) { + if let resource = largestImageRepresentation(representations)?.resource, let path = legacyContext.account.postbox.mediaBox.completedResourcePath(resource), let image = UIImage(contentsOfFile: path) { return image } else { return nil } case let .file(file): - if let path = account.postbox.mediaBox.completedResourcePath(file.file.resource), let image = UIImage(contentsOfFile: path) { + if let path = legacyContext.account.postbox.mediaBox.completedResourcePath(file.file.resource), let image = UIImage(contentsOfFile: path) { return image } else { return nil @@ -363,8 +363,8 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone func navigationBarPallete() -> TGNavigationBarPallete! { let theme: PresentationTheme - if let account = legacyComponentsAccount { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + if let legacyContext = legacyContext { + let presentationData = legacyContext.currentPresentationData.with { $0 } theme = presentationData.theme } else { theme = defaultPresentationTheme @@ -375,8 +375,8 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone func menuSheetPallete() -> TGMenuSheetPallete! { let theme: PresentationTheme - if let account = legacyComponentsAccount { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + if let legacyContext = legacyContext { + let presentationData = legacyContext.currentPresentationData.with { $0 } theme = presentationData.theme } else { theme = defaultPresentationTheme @@ -388,8 +388,8 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone func mediaAssetsPallete() -> TGMediaAssetsPallete! { let presentationTheme: PresentationTheme - if let account = legacyComponentsAccount { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + if let legacyContext = legacyContext { + let presentationData = legacyContext.currentPresentationData.with { $0 } presentationTheme = presentationData.theme } else { presentationTheme = defaultPresentationTheme @@ -403,8 +403,8 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone func checkButtonPallete() -> TGCheckButtonPallete! { let presentationTheme: PresentationTheme - if let account = legacyComponentsAccount { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + if let legacyContext = legacyContext { + let presentationData = legacyContext.currentPresentationData.with { $0 } presentationTheme = presentationData.theme } else { presentationTheme = defaultPresentationTheme @@ -415,8 +415,8 @@ private final class LegacyComponentsGlobalsProviderImpl: NSObject, LegacyCompone } } -public func setupLegacyComponents(account: Account) { - legacyAccount = account +public func setupLegacyComponents(context: AccountContext) { + legacyContext = context } public func initializeLegacyComponents(application: UIApplication?, currentSizeClassGetter: @escaping () -> UIUserInterfaceSizeClass, currentHorizontalClassGetter: @escaping () -> UIUserInterfaceSizeClass, documentsPath: String, currentApplicationBounds: @escaping () -> CGRect, canOpenUrl: @escaping (URL) -> Bool, openUrl: @escaping (URL) -> Void) { @@ -430,13 +430,13 @@ public func initializeLegacyComponents(application: UIApplication?, currentSizeC TGRemoteImageView.setSharedCache(TGCache()) TGImageDataSource.register(LegacyStickerImageDataSource(account: { - return legacyAccount + return legacyContext?.account })) TGImageDataSource.register(LegacyPeerAvatarPlaceholderDataSource(account: { - return legacyAccount + return legacyContext?.account })) TGImageDataSource.register(LegacyLocationVenueIconDataSource(account: { - return legacyAccount + return legacyContext?.account })) ASActor.registerClass(LegacyImageDownloadActor.self) LegacyComponentsGlobals.setProvider(LegacyComponentsGlobalsProviderImpl()) diff --git a/TelegramUI/ThemeAccentColorActionSheet.swift b/TelegramUI/ThemeAccentColorActionSheet.swift index dbf3045618..beff47802f 100644 --- a/TelegramUI/ThemeAccentColorActionSheet.swift +++ b/TelegramUI/ThemeAccentColorActionSheet.swift @@ -13,14 +13,14 @@ final class ThemeAccentColorActionSheet: ActionSheetController { return self._ready } - init(account: Account, currentValue: Int32, applyValue: @escaping (Int32) -> Void) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, currentValue: Int32, applyValue: @escaping (Int32) -> Void) { + let presentationData = context.currentPresentationData.with { $0 } let theme = presentationData.theme let strings = presentationData.strings super.init(theme: ActionSheetControllerTheme(presentationTheme: theme)) - self.presentationDisposable = (account.telegramApplicationContext.presentationData + self.presentationDisposable = (context.presentationData |> deliverOnMainQueue).start(next: { [weak self] presentationData in if let strongSelf = self { strongSelf.theme = ActionSheetControllerTheme(presentationTheme: presentationData.theme) diff --git a/TelegramUI/ThemeColorsGridControllerItem.swift b/TelegramUI/ThemeColorsGridControllerItem.swift index 82dc1bf040..7f4c8c6fb3 100644 --- a/TelegramUI/ThemeColorsGridControllerItem.swift +++ b/TelegramUI/ThemeColorsGridControllerItem.swift @@ -6,15 +6,15 @@ import AsyncDisplayKit import Postbox final class ThemeColorsGridControllerItem: GridItem { - let account: Account + let context: AccountContext let wallpaper: TelegramWallpaper let selected: Bool let interaction: ThemeColorsGridControllerInteraction let section: GridSection? = nil - init(account: Account, wallpaper: TelegramWallpaper, selected: Bool, interaction: ThemeColorsGridControllerInteraction) { - self.account = account + init(context: AccountContext, wallpaper: TelegramWallpaper, selected: Bool, interaction: ThemeColorsGridControllerInteraction) { + self.context = context self.wallpaper = wallpaper self.selected = selected self.interaction = interaction @@ -22,7 +22,7 @@ final class ThemeColorsGridControllerItem: GridItem { func node(layout: GridNodeLayout, synchronousLoad: Bool) -> GridItemNode { let node = ThemeColorsGridControllerItemNode() - node.setup(account: self.account, wallpaper: self.wallpaper, selected: self.selected, interaction: self.interaction) + node.setup(context: self.context, wallpaper: self.wallpaper, selected: self.selected, interaction: self.interaction) return node } @@ -31,7 +31,7 @@ final class ThemeColorsGridControllerItem: GridItem { assertionFailure() return } - node.setup(account: self.account, wallpaper: self.wallpaper, selected: self.selected, interaction: self.interaction) + node.setup(context: self.context, wallpaper: self.wallpaper, selected: self.selected, interaction: self.interaction) } } @@ -39,7 +39,7 @@ final class ThemeColorsGridControllerItemNode: GridItemNode { private let wallpaperNode: SettingsThemeWallpaperNode private var selectionNode: GridMessageSelectionNode? - private var currentState: (Account, TelegramWallpaper, Bool)? + private var currentState: (AccountContext, TelegramWallpaper, Bool)? private var interaction: ThemeColorsGridControllerInteraction? override init() { @@ -55,11 +55,11 @@ final class ThemeColorsGridControllerItemNode: GridItemNode { self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tapGesture(_:)))) } - func setup(account: Account, wallpaper: TelegramWallpaper, selected: Bool, interaction: ThemeColorsGridControllerInteraction) { + func setup(context: AccountContext, wallpaper: TelegramWallpaper, selected: Bool, interaction: ThemeColorsGridControllerInteraction) { self.interaction = interaction - if self.currentState == nil || self.currentState!.0 !== account || wallpaper != self.currentState!.1 || selected != self.currentState!.2 { - self.currentState = (account, wallpaper, selected) + if self.currentState == nil || self.currentState!.0 !== context || wallpaper != self.currentState!.1 || selected != self.currentState!.2 { + self.currentState = (context, wallpaper, selected) self.setNeedsLayout() } } @@ -76,8 +76,8 @@ final class ThemeColorsGridControllerItemNode: GridItemNode { super.layout() let bounds = self.bounds - if let (account, wallpaper, selected) = self.currentState { - self.wallpaperNode.setWallpaper(account: account, wallpaper: wallpaper, selected: selected, size: bounds.size) + if let (context, wallpaper, selected) = self.currentState { + self.wallpaperNode.setWallpaper(context: context, wallpaper: wallpaper, selected: selected, size: bounds.size) self.selectionNode?.frame = CGRect(origin: CGPoint(), size: bounds.size) } } diff --git a/TelegramUI/ThemeColorsGridControllerNode.swift b/TelegramUI/ThemeColorsGridControllerNode.swift index b799193bfb..f2673a1661 100644 --- a/TelegramUI/ThemeColorsGridControllerNode.swift +++ b/TelegramUI/ThemeColorsGridControllerNode.swift @@ -30,8 +30,8 @@ private struct ThemeColorsGridControllerEntry: Comparable, Identifiable { return self.index } - func item(account: Account, interaction: ThemeColorsGridControllerInteraction) -> ThemeColorsGridControllerItem { - return ThemeColorsGridControllerItem(account: account, wallpaper: self.wallpaper, selected: self.selected, interaction: interaction) + func item(context: AccountContext, interaction: ThemeColorsGridControllerInteraction) -> ThemeColorsGridControllerItem { + return ThemeColorsGridControllerItem(context: context, wallpaper: self.wallpaper, selected: self.selected, interaction: interaction) } } @@ -44,15 +44,15 @@ private struct ThemeColorsGridEntryTransition { let scrollToItem: GridNodeScrollToItem? } -private func preparedThemeColorsGridEntryTransition(account: Account, from fromEntries: [ThemeColorsGridControllerEntry], to toEntries: [ThemeColorsGridControllerEntry], interaction: ThemeColorsGridControllerInteraction) -> ThemeColorsGridEntryTransition { +private func preparedThemeColorsGridEntryTransition(context: AccountContext, from fromEntries: [ThemeColorsGridControllerEntry], to toEntries: [ThemeColorsGridControllerEntry], interaction: ThemeColorsGridControllerInteraction) -> ThemeColorsGridEntryTransition { let stationaryItems: GridNodeStationaryItems = .none let scrollToItem: GridNodeScrollToItem? = nil let (deleteIndices, indicesAndItems, updateIndices) = mergeListsStableWithUpdates(leftList: fromEntries, rightList: toEntries) let deletions = deleteIndices - let insertions = indicesAndItems.map { GridNodeInsertItem(index: $0.0, item: $0.1.item(account: account, interaction: interaction), previousIndex: $0.2) } - let updates = updateIndices.map { GridNodeUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(account: account, interaction: interaction)) } + let insertions = indicesAndItems.map { GridNodeInsertItem(index: $0.0, item: $0.1.item(context: context, interaction: interaction), previousIndex: $0.2) } + let updates = updateIndices.map { GridNodeUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, interaction: interaction)) } return ThemeColorsGridEntryTransition(deletions: deletions, insertions: insertions, updates: updates, updateFirstIndexInSectionOffset: nil, stationaryItems: stationaryItems, scrollToItem: scrollToItem) } @@ -143,7 +143,7 @@ final class ThemeColorsGridControllerNode: ASDisplayNode { } let previous = previousEntries.swap(entries) - return (preparedThemeColorsGridEntryTransition(account: context.account, from: previous ?? [], to: entries, interaction: interaction), previous == nil) + return (preparedThemeColorsGridEntryTransition(context: context, from: previous ?? [], to: entries, interaction: interaction), previous == nil) } self.disposable = (transition |> deliverOnMainQueue).start(next: { [weak self] (transition, _) in if let strongSelf = self { diff --git a/TelegramUI/ThemeGalleryController.swift b/TelegramUI/ThemeGalleryController.swift index 21e046cec3..b061171941 100644 --- a/TelegramUI/ThemeGalleryController.swift +++ b/TelegramUI/ThemeGalleryController.swift @@ -66,7 +66,7 @@ class ThemeGalleryController: ViewController { } init(context: AccountContext, wallpapers: [TelegramWallpaper], at centralWallpaper: TelegramWallpaper) { - self.account = account + self.context = context self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: presentationData)) diff --git a/TelegramUI/ThemeGridController.swift b/TelegramUI/ThemeGridController.swift index e56899fb2e..2410b6d8da 100644 --- a/TelegramUI/ThemeGridController.swift +++ b/TelegramUI/ThemeGridController.swift @@ -332,7 +332,7 @@ final class ThemeGridController: ViewController { } if mode.contains(.blur) { - let _ = context.account.postbox.mediaBox.cachedResourceRepresentation(resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true).start(completed: { + let _ = self.context.account.postbox.mediaBox.cachedResourceRepresentation(resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true).start(completed: { apply() }) } else { diff --git a/TelegramUI/ThemeGridControllerItem.swift b/TelegramUI/ThemeGridControllerItem.swift index e43219a64a..a2538d955c 100644 --- a/TelegramUI/ThemeGridControllerItem.swift +++ b/TelegramUI/ThemeGridControllerItem.swift @@ -6,7 +6,7 @@ import AsyncDisplayKit import Postbox final class ThemeGridControllerItem: GridItem { - let account: Account + let context: AccountContext let wallpaper: TelegramWallpaper let index: Int let selected: Bool @@ -14,8 +14,8 @@ final class ThemeGridControllerItem: GridItem { let section: GridSection? = nil - init(account: Account, wallpaper: TelegramWallpaper, index: Int, selected: Bool, interaction: ThemeGridControllerInteraction) { - self.account = account + init(context: AccountContext, wallpaper: TelegramWallpaper, index: Int, selected: Bool, interaction: ThemeGridControllerInteraction) { + self.context = context self.wallpaper = wallpaper self.index = index self.selected = selected @@ -24,7 +24,7 @@ final class ThemeGridControllerItem: GridItem { func node(layout: GridNodeLayout, synchronousLoad: Bool) -> GridItemNode { let node = ThemeGridControllerItemNode() - node.setup(account: self.account, wallpaper: self.wallpaper, index: self.index, selected: self.selected, interaction: self.interaction) + node.setup(context: self.context, wallpaper: self.wallpaper, index: self.index, selected: self.selected, interaction: self.interaction) return node } @@ -33,7 +33,7 @@ final class ThemeGridControllerItem: GridItem { assertionFailure() return } - node.setup(account: self.account, wallpaper: self.wallpaper, index: self.index, selected: self.selected, interaction: self.interaction) + node.setup(context: self.context, wallpaper: self.wallpaper, index: self.index, selected: self.selected, interaction: self.interaction) } } @@ -41,7 +41,7 @@ final class ThemeGridControllerItemNode: GridItemNode { private let wallpaperNode: SettingsThemeWallpaperNode private var selectionNode: GridMessageSelectionNode? - private var currentState: (Account, TelegramWallpaper, Int, Bool)? + private var currentState: (AccountContext, TelegramWallpaper, Int, Bool)? private var interaction: ThemeGridControllerInteraction? override init() { @@ -57,11 +57,11 @@ final class ThemeGridControllerItemNode: GridItemNode { self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tapGesture(_:)))) } - func setup(account: Account, wallpaper: TelegramWallpaper, index: Int, selected: Bool, interaction: ThemeGridControllerInteraction) { + func setup(context: AccountContext, wallpaper: TelegramWallpaper, index: Int, selected: Bool, interaction: ThemeGridControllerInteraction) { self.interaction = interaction - if self.currentState == nil || self.currentState!.0 !== account || wallpaper != self.currentState!.1 || index != self.currentState!.2 || selected != self.currentState!.3 { - self.currentState = (account, wallpaper, index, selected) + if self.currentState == nil || self.currentState!.0 !== context || wallpaper != self.currentState!.1 || index != self.currentState!.2 || selected != self.currentState!.3 { + self.currentState = (context, wallpaper, index, selected) self.setNeedsLayout() } } @@ -75,7 +75,7 @@ final class ThemeGridControllerItemNode: GridItemNode { } func updateSelectionState(animated: Bool) { - if let (account, wallpaper, index, _) = self.currentState { + if let (context, wallpaper, index, _) = self.currentState { var editing = false var selectable = false if case .file = wallpaper { @@ -94,7 +94,7 @@ final class ThemeGridControllerItemNode: GridItemNode { selectionNode.updateSelected(selected, animated: animated) selectionNode.frame = CGRect(origin: CGPoint(), size: self.bounds.size) } else { - let theme = account.telegramApplicationContext.currentPresentationData.with { $0 }.theme + let theme = context.currentPresentationData.with { $0 }.theme let selectionNode = GridMessageSelectionNode(theme: theme, toggle: { [weak self] value in if let strongSelf = self { strongSelf.interaction?.toggleWallpaperSelection(index, value) @@ -129,8 +129,8 @@ final class ThemeGridControllerItemNode: GridItemNode { super.layout() let bounds = self.bounds - if let (account, wallpaper, _, selected) = self.currentState { - self.wallpaperNode.setWallpaper(account: account, wallpaper: wallpaper, selected: selected, size: bounds.size) + if let (context, wallpaper, _, selected) = self.currentState { + self.wallpaperNode.setWallpaper(context: context, wallpaper: wallpaper, selected: selected, size: bounds.size) self.selectionNode?.frame = CGRect(origin: CGPoint(), size: bounds.size) } } diff --git a/TelegramUI/ThemeGridControllerNode.swift b/TelegramUI/ThemeGridControllerNode.swift index 40c528fedf..4794b918a7 100644 --- a/TelegramUI/ThemeGridControllerNode.swift +++ b/TelegramUI/ThemeGridControllerNode.swift @@ -89,8 +89,8 @@ private struct ThemeGridControllerEntry: Comparable, Identifiable { return self.index } - func item(account: Account, interaction: ThemeGridControllerInteraction) -> ThemeGridControllerItem { - return ThemeGridControllerItem(account: account, wallpaper: self.wallpaper, index: self.index, selected: self.selected, interaction: interaction) + func item(context: AccountContext, interaction: ThemeGridControllerInteraction) -> ThemeGridControllerItem { + return ThemeGridControllerItem(context: context, wallpaper: self.wallpaper, index: self.index, selected: self.selected, interaction: interaction) } } @@ -104,15 +104,15 @@ private struct ThemeGridEntryTransition { let scrollToItem: GridNodeScrollToItem? } -private func preparedThemeGridEntryTransition(account: Account, from fromEntries: [ThemeGridControllerEntry], to toEntries: [ThemeGridControllerEntry], interaction: ThemeGridControllerInteraction) -> ThemeGridEntryTransition { +private func preparedThemeGridEntryTransition(context: AccountContext, from fromEntries: [ThemeGridControllerEntry], to toEntries: [ThemeGridControllerEntry], interaction: ThemeGridControllerInteraction) -> ThemeGridEntryTransition { let stationaryItems: GridNodeStationaryItems = .none let scrollToItem: GridNodeScrollToItem? = nil let (deleteIndices, indicesAndItems, updateIndices) = mergeListsStableWithUpdates(leftList: fromEntries, rightList: toEntries) let deletions = deleteIndices - let insertions = indicesAndItems.map { GridNodeInsertItem(index: $0.0, item: $0.1.item(account: account, interaction: interaction), previousIndex: $0.2) } - let updates = updateIndices.map { GridNodeUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(account: account, interaction: interaction)) } + let insertions = indicesAndItems.map { GridNodeInsertItem(index: $0.0, item: $0.1.item(context: context, interaction: interaction), previousIndex: $0.2) } + let updates = updateIndices.map { GridNodeUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, interaction: interaction)) } var hasEditableItems = false for entry in toEntries { @@ -307,7 +307,7 @@ final class ThemeGridControllerNode: ASDisplayNode { } let previous = previousEntries.swap(entries) - return (preparedThemeGridEntryTransition(account: context.account, from: previous ?? [], to: entries, interaction: interaction), previous == nil) + return (preparedThemeGridEntryTransition(context: context, from: previous ?? [], to: entries, interaction: interaction), previous == nil) } self.disposable = (transition |> deliverOnMainQueue).start(next: { [weak self] (transition, _) in if let strongSelf = self { diff --git a/TelegramUI/ThemeGridSearchContentNode.swift b/TelegramUI/ThemeGridSearchContentNode.swift index b732001b74..1179f372e5 100644 --- a/TelegramUI/ThemeGridSearchContentNode.swift +++ b/TelegramUI/ThemeGridSearchContentNode.swift @@ -450,7 +450,7 @@ final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { if let user = peer as? TelegramUser, let botInfo = user.botInfo, let _ = botInfo.inlinePlaceholder { return (.complete() |> delay(0.1, queue: Queue.concurrentDefaultQueue())) |> then( - requestContextResults(account: context.account, botId: user.id, query: wallpaperQuery, peerId: account.peerId, limit: 16) + requestContextResults(account: context.account, botId: user.id, query: wallpaperQuery, peerId: context.account.peerId, limit: 16) |> map { collection -> ([ThemeGridSearchEntry], Bool)? in guard let collection = collection else { return nil diff --git a/TelegramUI/ThemeSettingsChatPreviewItem.swift b/TelegramUI/ThemeSettingsChatPreviewItem.swift index abdd13bfd4..336fc1344e 100644 --- a/TelegramUI/ThemeSettingsChatPreviewItem.swift +++ b/TelegramUI/ThemeSettingsChatPreviewItem.swift @@ -6,7 +6,7 @@ import TelegramCore import Postbox class ThemeSettingsChatPreviewItem: ListViewItem, ItemListItem { - let account: Account + let context: AccountContext let theme: PresentationTheme let componentTheme: PresentationTheme let strings: PresentationStrings @@ -17,8 +17,8 @@ class ThemeSettingsChatPreviewItem: ListViewItem, ItemListItem { let dateTimeFormat: PresentationDateTimeFormat let nameDisplayOrder: PresentationPersonNameOrder - init(account: Account, theme: PresentationTheme, componentTheme: PresentationTheme, strings: PresentationStrings, sectionId: ItemListSectionId, fontSize: PresentationFontSize, wallpaper: TelegramWallpaper, wallpaperMode: WallpaperPresentationOptions, dateTimeFormat: PresentationDateTimeFormat, nameDisplayOrder: PresentationPersonNameOrder) { - self.account = account + init(context: AccountContext, theme: PresentationTheme, componentTheme: PresentationTheme, strings: PresentationStrings, sectionId: ItemListSectionId, fontSize: PresentationFontSize, wallpaper: TelegramWallpaper, wallpaperMode: WallpaperPresentationOptions, dateTimeFormat: PresentationDateTimeFormat, nameDisplayOrder: PresentationPersonNameOrder) { + self.context = context self.theme = theme self.componentTheme = componentTheme self.strings = strings @@ -141,28 +141,28 @@ class ThemeSettingsChatPreviewItemNode: ListViewItemNode { if let largest = largestImageRepresentation(representations) { if item.wallpaperMode.contains(.blur) { var image: UIImage? - let _ = item.account.postbox.mediaBox.cachedResourceRepresentation(largest.resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true, attemptSynchronously: true).start(next: { data in + let _ = item.context.account.postbox.mediaBox.cachedResourceRepresentation(largest.resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true, attemptSynchronously: true).start(next: { data in if data.complete { image = UIImage(contentsOfFile: data.path)?.precomposed() } }) updatedBackgroundImage = image } - if updatedBackgroundImage == nil, let path = item.account.postbox.mediaBox.completedResourcePath(largest.resource) { + if updatedBackgroundImage == nil, let path = item.context.account.postbox.mediaBox.completedResourcePath(largest.resource) { updatedBackgroundImage = UIImage(contentsOfFile: path)?.precomposed() } } case let .file(file): if item.wallpaperMode.contains(.blur) { var image: UIImage? - let _ = item.account.postbox.mediaBox.cachedResourceRepresentation(file.file.resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true, attemptSynchronously: true).start(next: { data in + let _ = item.context.account.postbox.mediaBox.cachedResourceRepresentation(file.file.resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true, attemptSynchronously: true).start(next: { data in if data.complete { image = UIImage(contentsOfFile: data.path)?.precomposed() } }) updatedBackgroundImage = image } - if updatedBackgroundImage == nil, let path = item.account.postbox.mediaBox.completedResourcePath(file.file.resource) { + if updatedBackgroundImage == nil, let path = item.context.account.postbox.mediaBox.completedResourcePath(file.file.resource) { updatedBackgroundImage = UIImage(contentsOfFile: path)?.precomposed() } } @@ -182,8 +182,8 @@ class ThemeSettingsChatPreviewItemNode: ListViewItemNode { let chatPresentationData = ChatPresentationData(theme: ChatPresentationThemeData(theme: item.componentTheme, wallpaper: item.wallpaper), fontSize: item.fontSize, strings: item.strings, dateTimeFormat: item.dateTimeFormat, nameDisplayOrder: item.nameDisplayOrder, disableAnimations: false) - let item2: ChatMessageItem = ChatMessageItem(presentationData: chatPresentationData, account: item.account, chatLocation: .peer(peerId), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .contact, automaticDownloadNetworkType: .cellular, isRecentActions: false), controllerInteraction: controllerInteraction, content: .message(message: Message(stableId: 1, stableVersion: 0, id: MessageId(peerId: peerId, namespace: 0, id: 1), globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, timestamp: 66000, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: nil, text: item.strings.Appearance_PreviewIncomingText, attributes: [ReplyMessageAttribute(messageId: replyMessageId)], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true) - let item1: ChatMessageItem = ChatMessageItem(presentationData: chatPresentationData, account: item.account, chatLocation: .peer(peerId), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .contact, automaticDownloadNetworkType: .cellular, isRecentActions: false), controllerInteraction: controllerInteraction, content: .message(message: Message(stableId: 2, stableVersion: 0, id: MessageId(peerId: peerId, namespace: 0, id: 2), globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, timestamp: 66001, flags: [], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: TelegramUser(id: item.account.peerId, accessHash: nil, firstName: "", lastName: "", username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []), text: item.strings.Appearance_PreviewOutgoingText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true) + let item2: ChatMessageItem = ChatMessageItem(presentationData: chatPresentationData, context: item.context, chatLocation: .peer(peerId), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .contact, automaticDownloadNetworkType: .cellular, isRecentActions: false), controllerInteraction: controllerInteraction, content: .message(message: Message(stableId: 1, stableVersion: 0, id: MessageId(peerId: peerId, namespace: 0, id: 1), globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, timestamp: 66000, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: nil, text: item.strings.Appearance_PreviewIncomingText, attributes: [ReplyMessageAttribute(messageId: replyMessageId)], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true) + let item1: ChatMessageItem = ChatMessageItem(presentationData: chatPresentationData, context: item.context, chatLocation: .peer(peerId), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .contact, automaticDownloadNetworkType: .cellular, isRecentActions: false), controllerInteraction: controllerInteraction, content: .message(message: Message(stableId: 2, stableVersion: 0, id: MessageId(peerId: peerId, namespace: 0, id: 2), globallyUniqueId: nil, groupingKey: nil, groupInfo: nil, timestamp: 66001, flags: [], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: TelegramUser(id: item.context.account.peerId, accessHash: nil, firstName: "", lastName: "", username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []), text: item.strings.Appearance_PreviewOutgoingText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true) var node1: ListViewItemNode? if let current = currentNode1 { diff --git a/TelegramUI/ThemeSettingsController.swift b/TelegramUI/ThemeSettingsController.swift index 30296744c8..1ee947e033 100644 --- a/TelegramUI/ThemeSettingsController.swift +++ b/TelegramUI/ThemeSettingsController.swift @@ -5,7 +5,7 @@ import Postbox import TelegramCore private final class ThemeSettingsControllerArguments { - let account: Account + let context: AccountContext let selectTheme: (Int32) -> Void let selectFontSize: (PresentationFontSize) -> Void let openWallpaperSettings: () -> Void @@ -13,8 +13,8 @@ private final class ThemeSettingsControllerArguments { let openAutoNightTheme: () -> Void let disableAnimations: (Bool) -> Void - init(account: Account, selectTheme: @escaping (Int32) -> Void, selectFontSize: @escaping (PresentationFontSize) -> Void, openWallpaperSettings: @escaping () -> Void, openAccentColor: @escaping (Int32) -> Void, openAutoNightTheme: @escaping () -> Void, disableAnimations: @escaping (Bool) -> Void) { - self.account = account + init(context: AccountContext, selectTheme: @escaping (Int32) -> Void, selectFontSize: @escaping (PresentationFontSize) -> Void, openWallpaperSettings: @escaping () -> Void, openAccentColor: @escaping (Int32) -> Void, openAutoNightTheme: @escaping () -> Void, disableAnimations: @escaping (Bool) -> Void) { + self.context = context self.selectTheme = selectTheme self.selectFontSize = selectFontSize self.openWallpaperSettings = openWallpaperSettings @@ -179,7 +179,7 @@ private enum ThemeSettingsControllerEntry: ItemListNodeEntry { case let .chatPreviewHeader(theme, text): return ItemListSectionHeaderItem(theme: theme, text: text, sectionId: self.section) case let .chatPreview(theme, componentTheme, wallpaper, wallpaperMode, fontSize, strings, dateTimeFormat, nameDisplayOrder): - return ThemeSettingsChatPreviewItem(account: arguments.account, theme: theme, componentTheme: componentTheme, strings: strings, sectionId: self.section, fontSize: fontSize, wallpaper: wallpaper, wallpaperMode: wallpaperMode, dateTimeFormat: dateTimeFormat, nameDisplayOrder: nameDisplayOrder) + return ThemeSettingsChatPreviewItem(context: arguments.context, theme: theme, componentTheme: componentTheme, strings: strings, sectionId: self.section, fontSize: fontSize, wallpaper: wallpaper, wallpaperMode: wallpaperMode, dateTimeFormat: dateTimeFormat, nameDisplayOrder: nameDisplayOrder) case let .wallpaper(theme, text): return ItemListDisclosureItem(theme: theme, title: text, label: "", sectionId: self.section, style: .blocks, action: { arguments.openWallpaperSettings() @@ -253,7 +253,7 @@ public func themeSettingsController(context: AccountContext) -> ViewController { let _ = telegramWallpapers(postbox: context.account.postbox, network: context.account.network).start() - let arguments = ThemeSettingsControllerArguments(account: context.account, selectTheme: { index in + let arguments = ThemeSettingsControllerArguments(context: context, selectTheme: { index in let _ = updatePresentationThemeSettingsInteractively(postbox: context.account.postbox, { current in let wallpaper: TelegramWallpaper let theme: PresentationThemeReference diff --git a/TelegramUI/UniversalVideoGalleryItem.swift b/TelegramUI/UniversalVideoGalleryItem.swift index f0bf12e686..7e5941a8ec 100644 --- a/TelegramUI/UniversalVideoGalleryItem.swift +++ b/TelegramUI/UniversalVideoGalleryItem.swift @@ -331,7 +331,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { } } if let file = file { - let status = messageMediaFileStatus(account: item.context.account, messageId: message.id, file: file) + let status = messageMediaFileStatus(context: item.context, messageId: message.id, file: file) if !isWebpage { self.scrubberView.setFetchStatusSignal(status, strings: self.strings, fileSize: file.size) } @@ -340,10 +340,10 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { mediaFileStatus = status |> map(Optional.init) self.fetchControls = FetchControls(fetch: { [weak self] in if let strongSelf = self { - strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: item.context.account, message: message, file: file, userInitiated: true).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(context: item.context, message: message, file: file, userInitiated: true).start()) } }, cancel: { - messageMediaFileCancelInteractiveFetch(account: item.context.account, messageId: message.id, file: file) + messageMediaFileCancelInteractiveFetch(context: item.context, messageId: message.id, file: file) }) } } diff --git a/TelegramUI/WallpaperListPreviewControllerNode.swift b/TelegramUI/WallpaperListPreviewControllerNode.swift index 334b7d6edc..99745b688f 100644 --- a/TelegramUI/WallpaperListPreviewControllerNode.swift +++ b/TelegramUI/WallpaperListPreviewControllerNode.swift @@ -772,7 +772,7 @@ final class WallpaperListPreviewControllerNode: ViewControllerTracingNode { break inner } } - let itemNode = currentItemNode ?? WallpaperBackgroundNode(account: self.context.account, wallpaper: wallpapers[j]) + let itemNode = currentItemNode ?? WallpaperBackgroundNode(context: self.context, wallpaper: wallpapers[j]) visibleBackgroundNodes.append(itemNode) let itemNodeTransition: ContainedViewLayoutTransition if itemNode.supernode == nil { diff --git a/TelegramUI/WebSearchGalleryController.swift b/TelegramUI/WebSearchGalleryController.swift index 1097beb3ae..703b17d171 100644 --- a/TelegramUI/WebSearchGalleryController.swift +++ b/TelegramUI/WebSearchGalleryController.swift @@ -28,16 +28,16 @@ struct WebSearchGalleryEntry: Equatable { return lhs.result == rhs.result } - func item(account: Account, presentationData: PresentationData, controllerInteraction: WebSearchGalleryControllerInteraction?) -> GalleryItem { + func item(context: AccountContext, presentationData: PresentationData, controllerInteraction: WebSearchGalleryControllerInteraction?) -> GalleryItem { switch self.result { case let .externalReference(_, _, type, _, _, _, content, thumbnail, _): if let content = content, type == "gif", let thumbnailResource = thumbnail?.resource, let dimensions = content.dimensions { let fileReference = FileMediaReference.standalone(media: TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: 0), partialReference: nil, resource: content.resource, previewRepresentations: [TelegramMediaImageRepresentation(dimensions: dimensions, resource: thumbnailResource)], immediateThumbnailData: nil, mimeType: "video/mp4", size: nil, attributes: [.Animated, .Video(duration: 0, size: dimensions, flags: [])])) - return WebSearchVideoGalleryItem(account: account, presentationData: presentationData, result: self.result, content: NativeVideoContent(id: .contextResult(self.result.queryId, self.result.id), fileReference: fileReference, streamVideo: false, loopVideo: true, enableSound: false, fetchAutomatically: true), controllerInteraction: controllerInteraction) + return WebSearchVideoGalleryItem(context: context, presentationData: presentationData, result: self.result, content: NativeVideoContent(id: .contextResult(self.result.queryId, self.result.id), fileReference: fileReference, streamVideo: false, loopVideo: true, enableSound: false, fetchAutomatically: true), controllerInteraction: controllerInteraction) } case let .internalReference(_, _, _, _, _, _, file, _): if let file = file { - return WebSearchVideoGalleryItem(account: account, presentationData: presentationData, result: self.result, content: NativeVideoContent(id: .contextResult(self.result.queryId, self.result.id), fileReference: .standalone(media: file), streamVideo: false, loopVideo: true, enableSound: false, fetchAutomatically: true), controllerInteraction: controllerInteraction) + return WebSearchVideoGalleryItem(context: context, presentationData: presentationData, result: self.result, content: NativeVideoContent(id: .contextResult(self.result.queryId, self.result.id), fileReference: .standalone(media: file), streamVideo: false, loopVideo: true, enableSound: false, fetchAutomatically: true), controllerInteraction: controllerInteraction) } } preconditionFailure() @@ -61,7 +61,7 @@ class WebSearchGalleryController: ViewController { return self.displayNode as! GalleryControllerNode } - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private var controllerInteraction: WebSearchGalleryControllerInteraction? @@ -93,12 +93,12 @@ class WebSearchGalleryController: ViewController { private let replaceRootController: (ViewController, ValuePromise?) -> Void private let baseNavigationController: NavigationController? - init(account: Account, peer: Peer?, selectionState: TGMediaSelectionContext?, editingState: TGMediaEditingContext, entries: [WebSearchGalleryEntry], centralIndex: Int, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void, baseNavigationController: NavigationController?, sendCurrent: @escaping (ChatContextResult) -> Void) { - self.account = account + init(context: AccountContext, peer: Peer?, selectionState: TGMediaSelectionContext?, editingState: TGMediaEditingContext, entries: [WebSearchGalleryEntry], centralIndex: Int, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void, baseNavigationController: NavigationController?, sendCurrent: @escaping (ChatContextResult) -> Void) { + self.context = context self.replaceRootController = replaceRootController self.baseNavigationController = baseNavigationController - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(theme: WebSearchGalleryController.navigationTheme, strings: NavigationBarStrings(presentationStrings: self.presentationData.strings))) @@ -131,7 +131,7 @@ class WebSearchGalleryController: ViewController { strongSelf.centralEntryIndex = centralIndex if strongSelf.isViewLoaded { strongSelf.galleryNode.pager.replaceItems(strongSelf.entries.map({ - $0.item(account: account, presentationData: strongSelf.presentationData, controllerInteraction: strongSelf.controllerInteraction) + $0.item(context: context, presentationData: strongSelf.presentationData, controllerInteraction: strongSelf.controllerInteraction) }), centralItemIndex: centralIndex, keepFirst: false) let ready = strongSelf.galleryNode.pager.ready() |> timeout(2.0, queue: Queue.mainQueue(), alternate: .single(Void())) |> afterNext { [weak strongSelf] _ in @@ -244,7 +244,7 @@ class WebSearchGalleryController: ViewController { } self.galleryNode.pager.replaceItems(self.entries.map({ - $0.item(account: account, presentationData: self.presentationData, controllerInteraction: self.controllerInteraction) + $0.item(context: self.context, presentationData: self.presentationData, controllerInteraction: self.controllerInteraction) }), centralItemIndex: self.centralEntryIndex) self.galleryNode.pager.centralItemIndexUpdated = { [weak self] index in