diff --git a/TelegramUI.xcodeproj/project.pbxproj b/TelegramUI.xcodeproj/project.pbxproj index b552b91e82..96276d681a 100644 --- a/TelegramUI.xcodeproj/project.pbxproj +++ b/TelegramUI.xcodeproj/project.pbxproj @@ -131,7 +131,6 @@ D005808B21CAB8F000CB7CD3 /* VoipDerivedState.swift in Sources */ = {isa = PBXBuildFile; fileRef = D005808A21CAB8F000CB7CD3 /* VoipDerivedState.swift */; }; D00580A021DCF0A200CB7CD3 /* WallpaperListPreviewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D005809F21DCF0A200CB7CD3 /* WallpaperListPreviewController.swift */; }; D00580A221DCF0B700CB7CD3 /* WallpaperListPreviewControllerNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00580A121DCF0B700CB7CD3 /* WallpaperListPreviewControllerNode.swift */; }; - D00580B121E3DEF200CB7CD3 /* MergedItemListItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00580B021E3DEF200CB7CD3 /* MergedItemListItem.swift */; }; D00580B321E4B51600CB7CD3 /* DeleteChatPeerActionSheetItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00580B221E4B51600CB7CD3 /* DeleteChatPeerActionSheetItem.swift */; }; D00580B621E4C02100CB7CD3 /* UndoOverlayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00580B521E4C02100CB7CD3 /* UndoOverlayController.swift */; }; D00580B821E4C03400CB7CD3 /* UndoOverlayControllerNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00580B721E4C03400CB7CD3 /* UndoOverlayControllerNode.swift */; }; @@ -142,7 +141,6 @@ D00701A22029F6D0006B9E34 /* TGMimeTypeMap.m in Sources */ = {isa = PBXBuildFile; fileRef = D00701A02029F6D0006B9E34 /* TGMimeTypeMap.m */; }; D00781052084DFB100369A39 /* UrlEscaping.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00781042084DFB100369A39 /* UrlEscaping.swift */; }; D00ACA4B20222C280045D427 /* libtgvoip.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D00ACA4C20222C280045D427 /* libtgvoip.framework */; }; - D00ACA58202285090045D427 /* ChatRestrictedNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00ACA57202285090045D427 /* ChatRestrictedNode.swift */; }; D00ACA5A2022897D0045D427 /* ProcessedPeerRestrictionText.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00ACA592022897D0045D427 /* ProcessedPeerRestrictionText.swift */; }; D00ADFD91EBA2E9D00873D2E /* OngoingCallThreadLocalContext.h in Headers */ = {isa = PBXBuildFile; fileRef = D0EC6FFA1EBA1DE900EBF1C3 /* OngoingCallThreadLocalContext.h */; settings = {ATTRIBUTES = (Public, ); }; }; D00ADFDB1EBA2EAF00873D2E /* OngoingCallContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00ADFDA1EBA2EAF00873D2E /* OngoingCallContext.swift */; }; @@ -336,7 +334,6 @@ D0754D1E1EEDDF6200884F6E /* ChatMessageAttachedContentNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0754D1D1EEDDF6200884F6E /* ChatMessageAttachedContentNode.swift */; }; D0754D201EEDEBA000884F6E /* ChatMessageGameBubbleContentNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0754D1F1EEDEBA000884F6E /* ChatMessageGameBubbleContentNode.swift */; }; D0754D221EEDF89900884F6E /* ChatMessageInvoiceBubbleContentNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0754D211EEDF89900884F6E /* ChatMessageInvoiceBubbleContentNode.swift */; }; - D0754D241EEE0F4100884F6E /* ChatMessageInteractiveMediaLabelNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0754D231EEE0F4100884F6E /* ChatMessageInteractiveMediaLabelNode.swift */; }; D0754D271EEE10C800884F6E /* BotCheckoutController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0754D261EEE10C800884F6E /* BotCheckoutController.swift */; }; D079FCD91F05A5550038FADE /* BotCheckoutPasswordEntryController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D079FCD81F05A5550038FADE /* BotCheckoutPasswordEntryController.swift */; }; D079FCDD1F05C4F20038FADE /* LocalAuth.swift in Sources */ = {isa = PBXBuildFile; fileRef = D079FCDC1F05C4F20038FADE /* LocalAuth.swift */; }; @@ -464,7 +461,6 @@ D0BFAE5B20AB35D200793CF2 /* IconSwitchNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0BFAE5A20AB35D200793CF2 /* IconSwitchNode.swift */; }; D0BFAE5D20AB426300793CF2 /* PeerTitle.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0BFAE5C20AB426300793CF2 /* PeerTitle.swift */; }; D0C0B5901EDB505E000F4D2C /* ActivityIndicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0C0B58F1EDB505E000F4D2C /* ActivityIndicator.swift */; }; - D0C0B5921EDC5A3B000F4D2C /* LinkHighlightingNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0C0B5911EDC5A3B000F4D2C /* LinkHighlightingNode.swift */; }; D0C0B59B1EE019E5000F4D2C /* ChatSearchNavigationContentNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0C0B59A1EE019E5000F4D2C /* ChatSearchNavigationContentNode.swift */; }; D0C0B59F1EE082F5000F4D2C /* ChatSearchInputPanelNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0C0B59E1EE082F5000F4D2C /* ChatSearchInputPanelNode.swift */; }; D0C0B5B11EE1C421000F4D2C /* ChatDateSelectionSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0C0B5B01EE1C421000F4D2C /* ChatDateSelectionSheet.swift */; }; @@ -677,7 +673,7 @@ D0EC6CCA1EB9F58800EBF1C3 /* PeerPresenceStatusManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0B844571DAC44E8005F29E1 /* PeerPresenceStatusManager.swift */; }; D0EC6CCC1EB9F58800EBF1C3 /* ServiceSoundManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = D073CE641DCBC26B007511FD /* ServiceSoundManager.swift */; }; D0EC6CCD1EB9F58800EBF1C3 /* DeclareEncodables.swift in Sources */ = {isa = PBXBuildFile; fileRef = D073CE701DCBF23F007511FD /* DeclareEncodables.swift */; }; - D0EC6CCE1EB9F58800EBF1C3 /* TelegramApplicationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = D05811931DD5F9380057C769 /* TelegramApplicationContext.swift */; }; + D0EC6CCE1EB9F58800EBF1C3 /* AccountContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = D05811931DD5F9380057C769 /* AccountContext.swift */; }; D0EC6CD11EB9F58800EBF1C3 /* UrlHandling.swift in Sources */ = {isa = PBXBuildFile; fileRef = D023836F1DDF0462004018B6 /* UrlHandling.swift */; }; D0EC6CD31EB9F58800EBF1C3 /* GenerateTextEntities.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F917B41E0DA396003687E6 /* GenerateTextEntities.swift */; }; D0EC6CD41EB9F58800EBF1C3 /* StringWithAppliedEntities.swift in Sources */ = {isa = PBXBuildFile; fileRef = D017494D1E1059570057C89A /* StringWithAppliedEntities.swift */; }; @@ -775,7 +771,6 @@ D0EC6D361EB9F58800EBF1C3 /* SearchBarPlaceholderNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F69DCC1D6B8A0D0046BCD6 /* SearchBarPlaceholderNode.swift */; }; D0EC6D371EB9F58800EBF1C3 /* SearchDisplayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F69DCD1D6B8A0D0046BCD6 /* SearchDisplayController.swift */; }; D0EC6D381EB9F58800EBF1C3 /* SearchDisplayControllerContentNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F69DCE1D6B8A0D0046BCD6 /* SearchDisplayControllerContentNode.swift */; }; - D0EC6D391EB9F58800EBF1C3 /* ImageContainingNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00219051DDD1C9E00BE708A /* ImageContainingNode.swift */; }; D0EC6D3A1EB9F58800EBF1C3 /* AudioWaveformNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0568AAC1DF198130022E7DA /* AudioWaveformNode.swift */; }; D0EC6D3B1EB9F58800EBF1C3 /* EditableTokenListNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0BC38621E3F9EFA0044D6FE /* EditableTokenListNode.swift */; }; D0EC6D3C1EB9F58800EBF1C3 /* PhoneInputNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D050F2121E48B61500988324 /* PhoneInputNode.swift */; }; @@ -902,7 +897,6 @@ D0EC6DC11EB9F58900EBF1C3 /* ChatMediaInputTrendingItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0575AEE1E9FF881006F2541 /* ChatMediaInputTrendingItem.swift */; }; D0EC6DC21EB9F58900EBF1C3 /* ChatMediaInputStickerPackItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D021E0E41DB55D0A00C6B04F /* ChatMediaInputStickerPackItem.swift */; }; D0EC6DC31EB9F58900EBF1C3 /* ChatMediaInputStickerGridItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D08C36821DB66AD40064C744 /* ChatMediaInputStickerGridItem.swift */; }; - D0EC6DC41EB9F58900EBF1C3 /* MultiplexedSoftwareVideoNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F02CDA1E981D240065DEE2 /* MultiplexedSoftwareVideoNode.swift */; }; D0EC6DC51EB9F58900EBF1C3 /* SoftwareVideoSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = D002A0D01E9B99F500A81812 /* SoftwareVideoSource.swift */; }; D0EC6DC61EB9F58900EBF1C3 /* MultiplexedSoftwareVideoSourceManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = D002A0D21E9BBE6700A81812 /* MultiplexedSoftwareVideoSourceManager.swift */; }; D0EC6DC71EB9F58900EBF1C3 /* SampleBufferPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = D002A0D41E9BD48400A81812 /* SampleBufferPool.swift */; }; @@ -962,7 +956,6 @@ D0EC6E021EB9F58900EBF1C3 /* GalleryFooterNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D042C6801E8D9A6700C863B0 /* GalleryFooterNode.swift */; }; D0EC6E031EB9F58900EBF1C3 /* GalleryFooterContentNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D042C6851E8DA69D00C863B0 /* GalleryFooterContentNode.swift */; }; D0EC6E041EB9F58900EBF1C3 /* SecretMediaPreviewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00C7CDB1E3776E50080C3D5 /* SecretMediaPreviewController.swift */; }; - D0EC6E051EB9F58900EBF1C3 /* SecretMediaPreviewControllerNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00C7CDD1E37770A0080C3D5 /* SecretMediaPreviewControllerNode.swift */; }; D0EC6E061EB9F58900EBF1C3 /* ChatDocumentGalleryItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F69E5B1D6B8BF90046BCD6 /* ChatDocumentGalleryItem.swift */; }; D0EC6E071EB9F58900EBF1C3 /* ChatExternalFileGalleryItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F69E5C1D6B8BF90046BCD6 /* ChatExternalFileGalleryItem.swift */; }; D0EC6E081EB9F58900EBF1C3 /* ChatImageGalleryItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F69E5D1D6B8BF90046BCD6 /* ChatImageGalleryItem.swift */; }; @@ -970,8 +963,6 @@ D0EC6E0B1EB9F58900EBF1C3 /* ZoomableContentGalleryItemNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F69E601D6B8BF90046BCD6 /* ZoomableContentGalleryItemNode.swift */; }; D0EC6E0C1EB9F58900EBF1C3 /* ChatItemGalleryFooterContentNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D042C6891E8DAAB000C863B0 /* ChatItemGalleryFooterContentNode.swift */; }; D0EC6E0E1EB9F58900EBF1C3 /* PeerAvatarImageGalleryItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0575AFB1EA104A6006F2541 /* PeerAvatarImageGalleryItem.swift */; }; - D0EC6E0F1EB9F58900EBF1C3 /* MapInputController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F69E681D6B8C160046BCD6 /* MapInputController.swift */; }; - D0EC6E101EB9F58900EBF1C3 /* MapInputControllerNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0F69E691D6B8C160046BCD6 /* MapInputControllerNode.swift */; }; D0EC6E111EB9F58900EBF1C3 /* InstantPageNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0215D371E040F53001A0B1E /* InstantPageNode.swift */; }; D0EC6E121EB9F58900EBF1C3 /* InstantPageLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0215D391E041003001A0B1E /* InstantPageLayout.swift */; }; D0EC6E131EB9F58900EBF1C3 /* InstantPageItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0215D3B1E041014001A0B1E /* InstantPageItem.swift */; }; @@ -1261,7 +1252,6 @@ 9F06830A21A404C4001D8EDB /* NotificationExcetionSettingsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NotificationExcetionSettingsController.swift; sourceTree = ""; }; D000CAB921EE130D0011B15D /* MapResourceToAvatarSizes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MapResourceToAvatarSizes.swift; sourceTree = ""; }; D000CABB21F158AD0011B15D /* PrepareSecretThumbnailData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrepareSecretThumbnailData.swift; sourceTree = ""; }; - D00219051DDD1C9E00BE708A /* ImageContainingNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImageContainingNode.swift; sourceTree = ""; }; D002A0D01E9B99F500A81812 /* SoftwareVideoSource.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SoftwareVideoSource.swift; sourceTree = ""; }; D002A0D21E9BBE6700A81812 /* MultiplexedSoftwareVideoSourceManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MultiplexedSoftwareVideoSourceManager.swift; sourceTree = ""; }; D002A0D41E9BD48400A81812 /* SampleBufferPool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SampleBufferPool.swift; sourceTree = ""; }; @@ -1275,7 +1265,6 @@ D005808A21CAB8F000CB7CD3 /* VoipDerivedState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoipDerivedState.swift; sourceTree = ""; }; D005809F21DCF0A200CB7CD3 /* WallpaperListPreviewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WallpaperListPreviewController.swift; sourceTree = ""; }; D00580A121DCF0B700CB7CD3 /* WallpaperListPreviewControllerNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WallpaperListPreviewControllerNode.swift; sourceTree = ""; }; - D00580B021E3DEF200CB7CD3 /* MergedItemListItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MergedItemListItem.swift; sourceTree = ""; }; D00580B221E4B51600CB7CD3 /* DeleteChatPeerActionSheetItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeleteChatPeerActionSheetItem.swift; sourceTree = ""; }; D00580B521E4C02100CB7CD3 /* UndoOverlayController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UndoOverlayController.swift; sourceTree = ""; }; D00580B721E4C03400CB7CD3 /* UndoOverlayControllerNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UndoOverlayControllerNode.swift; sourceTree = ""; }; @@ -1286,7 +1275,6 @@ D00701A02029F6D0006B9E34 /* TGMimeTypeMap.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TGMimeTypeMap.m; sourceTree = ""; }; D00781042084DFB100369A39 /* UrlEscaping.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UrlEscaping.swift; sourceTree = ""; }; D00ACA4C20222C280045D427 /* libtgvoip.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = libtgvoip.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - D00ACA57202285090045D427 /* ChatRestrictedNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatRestrictedNode.swift; sourceTree = ""; }; D00ACA592022897D0045D427 /* ProcessedPeerRestrictionText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProcessedPeerRestrictionText.swift; sourceTree = ""; }; D00ADFDA1EBA2EAF00873D2E /* OngoingCallContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OngoingCallContext.swift; sourceTree = ""; }; D00ADFDC1EBB73C200873D2E /* OverlayMediaManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OverlayMediaManager.swift; sourceTree = ""; }; @@ -1299,7 +1287,6 @@ D00C7CD61E3664070080C3D5 /* ItemListMultilineInputItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ItemListMultilineInputItem.swift; sourceTree = ""; }; D00C7CD81E36B2DB0080C3D5 /* ContactListNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContactListNode.swift; sourceTree = ""; }; D00C7CDB1E3776E50080C3D5 /* SecretMediaPreviewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SecretMediaPreviewController.swift; sourceTree = ""; }; - D00C7CDD1E37770A0080C3D5 /* SecretMediaPreviewControllerNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SecretMediaPreviewControllerNode.swift; sourceTree = ""; }; D00C7CE51E378FD00080C3D5 /* RadialTimeoutNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RadialTimeoutNode.swift; sourceTree = ""; }; D00C7CE81E379B820080C3D5 /* ChatSecretAutoremoveTimerActionSheet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatSecretAutoremoveTimerActionSheet.swift; sourceTree = ""; }; D00C7CF51E37BF680080C3D5 /* SecretChatKeyVisualization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SecretChatKeyVisualization.h; sourceTree = ""; }; @@ -1651,7 +1638,7 @@ D0575AF61EA0ED4F006F2541 /* ChatMessageInstantVideoItemNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatMessageInstantVideoItemNode.swift; sourceTree = ""; }; D0575AF91EA0FDA7006F2541 /* AvatarGalleryController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvatarGalleryController.swift; sourceTree = ""; }; D0575AFB1EA104A6006F2541 /* PeerAvatarImageGalleryItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PeerAvatarImageGalleryItem.swift; sourceTree = ""; }; - D05811931DD5F9380057C769 /* TelegramApplicationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TelegramApplicationContext.swift; sourceTree = ""; }; + D05811931DD5F9380057C769 /* AccountContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AccountContext.swift; sourceTree = ""; }; D058E0CE1E8AD57300A442DE /* VideoPlayerProxy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VideoPlayerProxy.swift; sourceTree = ""; }; D05A32DB1E6EFCC2002760B4 /* NumericFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericFormat.swift; sourceTree = ""; }; D05A32DD1E6F0097002760B4 /* PrivacyAndSecurityController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrivacyAndSecurityController.swift; sourceTree = ""; }; @@ -1716,7 +1703,6 @@ D0754D1D1EEDDF6200884F6E /* ChatMessageAttachedContentNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatMessageAttachedContentNode.swift; sourceTree = ""; }; D0754D1F1EEDEBA000884F6E /* ChatMessageGameBubbleContentNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatMessageGameBubbleContentNode.swift; sourceTree = ""; }; D0754D211EEDF89900884F6E /* ChatMessageInvoiceBubbleContentNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatMessageInvoiceBubbleContentNode.swift; sourceTree = ""; }; - D0754D231EEE0F4100884F6E /* ChatMessageInteractiveMediaLabelNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatMessageInteractiveMediaLabelNode.swift; sourceTree = ""; }; D0754D261EEE10C800884F6E /* BotCheckoutController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BotCheckoutController.swift; sourceTree = ""; }; D07551871DDA4BB50073E051 /* TelegramLegacyComponents.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = TelegramLegacyComponents.framework; path = "../TelegramLegacyComponents/build/Debug-iphoneos/TelegramLegacyComponents.framework"; sourceTree = ""; }; D075518A1DDA4D7D0073E051 /* LegacyController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LegacyController.swift; sourceTree = ""; }; @@ -1918,7 +1904,6 @@ D0BFAE5A20AB35D200793CF2 /* IconSwitchNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IconSwitchNode.swift; sourceTree = ""; }; D0BFAE5C20AB426300793CF2 /* PeerTitle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerTitle.swift; sourceTree = ""; }; D0C0B58F1EDB505E000F4D2C /* ActivityIndicator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ActivityIndicator.swift; sourceTree = ""; }; - D0C0B5911EDC5A3B000F4D2C /* LinkHighlightingNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LinkHighlightingNode.swift; sourceTree = ""; }; D0C0B59A1EE019E5000F4D2C /* ChatSearchNavigationContentNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatSearchNavigationContentNode.swift; sourceTree = ""; }; D0C0B59E1EE082F5000F4D2C /* ChatSearchInputPanelNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatSearchInputPanelNode.swift; sourceTree = ""; }; D0C0B5B01EE1C421000F4D2C /* ChatDateSelectionSheet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatDateSelectionSheet.swift; sourceTree = ""; }; @@ -2207,7 +2192,6 @@ D0F02CCB1E96EF350065DEE2 /* ChatMediaInputStickerPane.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatMediaInputStickerPane.swift; sourceTree = ""; }; D0F02CCD1E96FACE0065DEE2 /* ChatMediaInputGifPane.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatMediaInputGifPane.swift; sourceTree = ""; }; D0F02CD81E97ED080065DEE2 /* RecentGifManagedMediaId.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecentGifManagedMediaId.swift; sourceTree = ""; }; - D0F02CDA1E981D240065DEE2 /* MultiplexedSoftwareVideoNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MultiplexedSoftwareVideoNode.swift; sourceTree = ""; }; D0F0AADF1EC1E12C005EE2A5 /* PresentationCall.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PresentationCall.swift; sourceTree = ""; }; D0F0AAE11EC20EF8005EE2A5 /* CallControllerStatusNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CallControllerStatusNode.swift; sourceTree = ""; }; D0F0AAE31EC21AAA005EE2A5 /* CallControllerButtonsNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CallControllerButtonsNode.swift; sourceTree = ""; }; @@ -2300,8 +2284,6 @@ D0F69E5D1D6B8BF90046BCD6 /* ChatImageGalleryItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatImageGalleryItem.swift; sourceTree = ""; }; D0F69E5F1D6B8BF90046BCD6 /* ChatVideoGalleryItemScrubberView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatVideoGalleryItemScrubberView.swift; sourceTree = ""; }; D0F69E601D6B8BF90046BCD6 /* ZoomableContentGalleryItemNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ZoomableContentGalleryItemNode.swift; sourceTree = ""; }; - D0F69E681D6B8C160046BCD6 /* MapInputController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapInputController.swift; sourceTree = ""; }; - D0F69E691D6B8C160046BCD6 /* MapInputControllerNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapInputControllerNode.swift; sourceTree = ""; }; D0F69E6D1D6B8C340046BCD6 /* ContactsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContactsController.swift; sourceTree = ""; }; D0F69E6E1D6B8C340046BCD6 /* ContactsControllerNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContactsControllerNode.swift; sourceTree = ""; }; D0F69E6F1D6B8C340046BCD6 /* ContactsPeerItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContactsPeerItem.swift; sourceTree = ""; }; @@ -2555,7 +2537,6 @@ isa = PBXGroup; children = ( D00C7CDB1E3776E50080C3D5 /* SecretMediaPreviewController.swift */, - D00C7CDD1E37770A0080C3D5 /* SecretMediaPreviewControllerNode.swift */, D0380DA8204E9C81000414AB /* SecretMediaPreviewFooterContentNode.swift */, ); name = "Secret Preview"; @@ -2720,7 +2701,6 @@ D01C06B41FBB7720001561AB /* ChatMediaInputSettingsItem.swift */, D021E0E41DB55D0A00C6B04F /* ChatMediaInputStickerPackItem.swift */, D08C36821DB66AD40064C744 /* ChatMediaInputStickerGridItem.swift */, - D0F02CDA1E981D240065DEE2 /* MultiplexedSoftwareVideoNode.swift */, D002A0D01E9B99F500A81812 /* SoftwareVideoSource.swift */, D002A0D21E9BBE6700A81812 /* MultiplexedSoftwareVideoSourceManager.swift */, D002A0D41E9BD48400A81812 /* SampleBufferPool.swift */, @@ -3970,13 +3950,6 @@ name = "Vertical List"; sourceTree = ""; }; - D0E412D1206A7DA100BEE4A2 /* Date Selection */ = { - isa = PBXGroup; - children = ( - ); - name = "Date Selection"; - sourceTree = ""; - }; D0E6521D1E3A2305004EEA91 /* Items */ = { isa = PBXGroup; children = ( @@ -4003,7 +3976,6 @@ D0E305AE1E5BA8E000D7A3A2 /* ItemListLoadingIndicatorEmptyStateItem.swift */, D09AEFD31E5BAF67005C1A8B /* ItemListTextEmptyStateItem.swift */, D0BFAE5A20AB35D200793CF2 /* IconSwitchNode.swift */, - D00580B021E3DEF200CB7CD3 /* MergedItemListItem.swift */, ); name = Items; sourceTree = ""; @@ -4225,13 +4197,6 @@ name = "Sign Up"; sourceTree = ""; }; - D0F69CCE1D6B87950046BCD6 /* Files */ = { - isa = PBXGroup; - children = ( - ); - name = Files; - sourceTree = ""; - }; D0F69DBB1D6B88330046BCD6 /* Media */ = { isa = PBXGroup; children = ( @@ -4328,14 +4293,12 @@ D0F69DC01D6B89D30046BCD6 /* ListSectionHeaderNode.swift */, D0F69DF71D6B8A880046BCD6 /* AvatarNode.swift */, D0943AF51FDAAE7E001522CC /* MultipleAvatarsNode.swift */, - D00219051DDD1C9E00BE708A /* ImageContainingNode.swift */, D0568AAC1DF198130022E7DA /* AudioWaveformNode.swift */, D0BC38621E3F9EFA0044D6FE /* EditableTokenListNode.swift */, D050F2121E48B61500988324 /* PhoneInputNode.swift */, D0B2F76B2052A7D600D3BFB9 /* SinglePhoneInputNode.swift */, D0DA44531E4E7302005FDCA7 /* ProgressNavigationButtonNode.swift */, D0C0B58F1EDB505E000F4D2C /* ActivityIndicator.swift */, - D0C0B5911EDC5A3B000F4D2C /* LinkHighlightingNode.swift */, D0FC4FBA1F751E8900B7443F /* SelectablePeerNode.swift */, D01C06BB1FBBB0D8001561AB /* CheckNode.swift */, D056CD6F1FF147B000880D28 /* IconButtonNode.swift */, @@ -4364,7 +4327,6 @@ D01B27931E38F3920022A4C0 /* Item List */, D0736F261DF4D2F300F2C02A /* Telegram Controller */, D093D81E20699A6000BC3599 /* Form */, - D0E412D1206A7DA100BEE4A2 /* Date Selection */, D00580B421E4BFE800CB7CD3 /* Undo Overlay */, ); name = Controllers; @@ -4473,7 +4435,6 @@ D0EF40DE1E73100D000DFCD4 /* ChatHistoryNavigationStack.swift */, D01C2AA01E758F90001F6F9A /* NavigateToChatController.swift */, D06E0F8D1F79ABFB003CF3DD /* ChatLoadingNode.swift */, - D00ACA57202285090045D427 /* ChatRestrictedNode.swift */, D0FA08C92049BEAC00DD23FC /* ChatEmptyNode.swift */, D0AF32391FB1D8D60097362B /* ChatOverlayNavigationBar.swift */, D0BCC3D320404CC7008126C2 /* ChatMessageActionSheetController.swift */, @@ -4528,7 +4489,6 @@ D01AC9171DD5033100E8160F /* ChatMessageActionButtonsNode.swift */, D0C932371E09E0EA0074F044 /* ChatBotInfoItem.swift */, D02298361E0C34E900707F91 /* ChatMessageBackground.swift */, - D0754D231EEE0F4100884F6E /* ChatMessageInteractiveMediaLabelNode.swift */, D091C7A31F8EBB1E00D7DE13 /* ChatPresentationData.swift */, D01C06BD1FBCAF06001561AB /* ChatMessageBubbleMosaicLayout.swift */, D02F4AE81FCF370B004DFBAE /* ChatMessageInteractiveMediaBadge.swift */, @@ -4583,7 +4543,6 @@ D0575AF81EA0FD94006F2541 /* Avatar Gallery */, D0EEE99F2165583B001292A6 /* Document */, D0104F261F471702004E4881 /* Instant Page Gallery */, - D0F69E671D6B8C030046BCD6 /* Map Input */, D07827CC1E03F32C00071108 /* Instant Page */, D0D748041E7AF62000F4B1F6 /* Stickers */, D020A9D81FEAE611008C66F7 /* Player */, @@ -4631,15 +4590,6 @@ name = Items; sourceTree = ""; }; - D0F69E671D6B8C030046BCD6 /* Map Input */ = { - isa = PBXGroup; - children = ( - D0F69E681D6B8C160046BCD6 /* MapInputController.swift */, - D0F69E691D6B8C160046BCD6 /* MapInputControllerNode.swift */, - ); - name = "Map Input"; - sourceTree = ""; - }; D0F69E6C1D6B8C220046BCD6 /* Contacts */ = { isa = PBXGroup; children = ( @@ -4725,7 +4675,7 @@ D0B844571DAC44E8005F29E1 /* PeerPresenceStatusManager.swift */, D073CE641DCBC26B007511FD /* ServiceSoundManager.swift */, D073CE701DCBF23F007511FD /* DeclareEncodables.swift */, - D05811931DD5F9380057C769 /* TelegramApplicationContext.swift */, + D05811931DD5F9380057C769 /* AccountContext.swift */, D023836F1DDF0462004018B6 /* UrlHandling.swift */, D0F917B41E0DA396003687E6 /* GenerateTextEntities.swift */, D01749541E1082770057C89A /* StoredMessageFromSearchPeer.swift */, @@ -4874,7 +4824,6 @@ D0F69DBB1D6B88330046BCD6 /* Media */, D0F69DBD1D6B897A0046BCD6 /* Components */, D0F69DE61D6B8A4E0046BCD6 /* Controllers */, - D0F69CCE1D6B87950046BCD6 /* Files */, D0F69E7E1D6B8C500046BCD6 /* Supporting Files */, D0FC40821D5B8E7400261D9D /* TelegramUI.h */, D0FC40831D5B8E7400261D9D /* Info.plist */, @@ -5202,7 +5151,7 @@ 0958FBBD218B03CA00E0CBD8 /* InstantPageDetailsNode.swift in Sources */, D02D60B1206C189900FEFE1E /* SecureIdPlaintextFormController.swift in Sources */, D0CFBB951FD8B05000B65C0D /* OverlayInstantVideoDecoration.swift in Sources */, - D0EC6CCE1EB9F58800EBF1C3 /* TelegramApplicationContext.swift in Sources */, + D0EC6CCE1EB9F58800EBF1C3 /* AccountContext.swift in Sources */, D09394132007F5BB00997F31 /* LocationBroadcastNavigationAccessoryPanel.swift in Sources */, D0471B5C1EFEB4F30074D609 /* BotPaymentFieldItemNode.swift in Sources */, D0C27B3D1F4B454800A4E170 /* InstantPagePlayableVideoNode.swift in Sources */, @@ -5437,7 +5386,6 @@ D04281ED200E3B28009DDE36 /* ItemListControllerSearch.swift in Sources */, D0EC6D381EB9F58800EBF1C3 /* SearchDisplayControllerContentNode.swift in Sources */, D06F1EA41F6C0A5D00FE8B74 /* ChatHistorySearchContainerNode.swift in Sources */, - D0EC6D391EB9F58800EBF1C3 /* ImageContainingNode.swift in Sources */, D0EC6D3A1EB9F58800EBF1C3 /* AudioWaveformNode.swift in Sources */, D0105D682182680E007C04A7 /* IsMediaStreamable.swift in Sources */, D0EB41F71F30D4A800838FE6 /* LegacyMediaLocations.swift in Sources */, @@ -5505,7 +5453,6 @@ D0754D201EEDEBA000884F6E /* ChatMessageGameBubbleContentNode.swift in Sources */, D09E63AA1F0FC681003444CD /* PictureInPictureVideoControlsNode.swift in Sources */, 09874E592107BD4100E190B8 /* GenericEmbedImplementation.swift in Sources */, - D0C0B5921EDC5A3B000F4D2C /* LinkHighlightingNode.swift in Sources */, D0EC6D621EB9F58800EBF1C3 /* ContactListNode.swift in Sources */, D0EC6D631EB9F58800EBF1C3 /* ContactListActionItem.swift in Sources */, D0EC6D641EB9F58800EBF1C3 /* ContactsPeerItem.swift in Sources */, @@ -5583,7 +5530,6 @@ 9F06830B21A404C4001D8EDB /* NotificationExcetionSettingsController.swift in Sources */, D0EC6D891EB9F58800EBF1C3 /* ChatSecretAutoremoveTimerActionSheet.swift in Sources */, D05D8B782195E0050064586F /* SetupTwoStepVerificationContentNode.swift in Sources */, - D00580B121E3DEF200CB7CD3 /* MergedItemListItem.swift in Sources */, D0EC6D8A1EB9F58800EBF1C3 /* ChatInfo.swift in Sources */, D0EC6D8B1EB9F58800EBF1C3 /* ChatHistoryNavigationStack.swift in Sources */, D0EC6D8C1EB9F58800EBF1C3 /* NavigateToChatController.swift in Sources */, @@ -5612,9 +5558,7 @@ D01C06B31FBB49A5001561AB /* JoinLinkPreviewPeerContentNode.swift in Sources */, D0EC6D931EB9F58900EBF1C3 /* ChatMessageFileBubbleContentNode.swift in Sources */, D0EC6D941EB9F58900EBF1C3 /* ChatMessageForwardInfoNode.swift in Sources */, - D00ACA58202285090045D427 /* ChatRestrictedNode.swift in Sources */, D0104F2C1F471EEB004E4881 /* InstantPageGalleryFooterContentNode.swift in Sources */, - D0754D241EEE0F4100884F6E /* ChatMessageInteractiveMediaLabelNode.swift in Sources */, D04B4D131EEA0A6500711AF6 /* ChatMessageMapBubbleContentNode.swift in Sources */, D0EC6D951EB9F58900EBF1C3 /* ChatMessageInteractiveFileNode.swift in Sources */, D01A21B11F3A050E00DDA104 /* InstantPageNavigationBar.swift in Sources */, @@ -5719,7 +5663,6 @@ D0EC6DC21EB9F58900EBF1C3 /* ChatMediaInputStickerPackItem.swift in Sources */, 091346982183498A00846E49 /* InstantPageArticleNode.swift in Sources */, D0EC6DC31EB9F58900EBF1C3 /* ChatMediaInputStickerGridItem.swift in Sources */, - D0EC6DC41EB9F58900EBF1C3 /* MultiplexedSoftwareVideoNode.swift in Sources */, D0BE30432061B80B00FBE6D8 /* SecureIdAuthControllerNode.swift in Sources */, 099529B221D24F5800805E13 /* RadialDownloadContentNode.swift in Sources */, D0E9BAE81F0574FF00F079A4 /* STPCustomer.m in Sources */, @@ -5847,7 +5790,6 @@ D0C26D571FDF2388004ABF18 /* OpenChatMessage.swift in Sources */, D0FA08BE20481EA300DD23FC /* Locale.swift in Sources */, D0E412CE206A707400BEE4A2 /* FormControllerTextItem.swift in Sources */, - D0EC6E051EB9F58900EBF1C3 /* SecretMediaPreviewControllerNode.swift in Sources */, D007019C2029E8F2006B9E34 /* LegqacyICloudFileController.swift in Sources */, 0902838D2194AEB90067EFBD /* ImageTransparency.swift in Sources */, D000CABC21F158AD0011B15D /* PrepareSecretThumbnailData.swift in Sources */, @@ -5864,10 +5806,8 @@ D0EC6E0C1EB9F58900EBF1C3 /* ChatItemGalleryFooterContentNode.swift in Sources */, D0E9BABD1F05735F00F079A4 /* STPPaymentConfiguration.m in Sources */, D0EC6E0E1EB9F58900EBF1C3 /* PeerAvatarImageGalleryItem.swift in Sources */, - D0EC6E0F1EB9F58900EBF1C3 /* MapInputController.swift in Sources */, D039FB152170D99D00BD1BAD /* RadialCloudProgressContentNode.swift in Sources */, D04B4D111EEA04D400711AF6 /* MapResources.swift in Sources */, - D0EC6E101EB9F58900EBF1C3 /* MapInputControllerNode.swift in Sources */, D0380DA9204E9C81000414AB /* SecretMediaPreviewFooterContentNode.swift in Sources */, D0AFCC7B1F4C8D39000720C6 /* InstantPageSlideshowItemNode.swift in Sources */, D0E9BA211F05577700F079A4 /* STPCardParams.m in Sources */, diff --git a/TelegramUI/TelegramApplicationContext.swift b/TelegramUI/AccountContext.swift similarity index 88% rename from TelegramUI/TelegramApplicationContext.swift rename to TelegramUI/AccountContext.swift index cdd5291349..19c5177576 100644 --- a/TelegramUI/TelegramApplicationContext.swift +++ b/TelegramUI/AccountContext.swift @@ -59,7 +59,9 @@ public final class TelegramApplicationBindings { } } -public final class TelegramApplicationContext { +public final class AccountContext { + public let account: Account + public let applicationBindings: TelegramApplicationBindings public let accountManager: AccountManager public let fetchManager: FetchManager @@ -67,7 +69,7 @@ public final class TelegramApplicationContext { public var keyShortcutsController: KeyShortcutsController? - public let mediaManager: MediaManager? + public let mediaManager: MediaManager let locationManager: DeviceLocationManager? public let liveLocationManager: LiveLocationManager? @@ -121,49 +123,41 @@ public final class TelegramApplicationContext { public var isCurrent: Bool = false { didSet { - self.mediaManager?.isCurrent = self.isCurrent + self.mediaManager.isCurrent = self.isCurrent if !self.isCurrent { self.callManager = nil } } } - public init(applicationBindings: TelegramApplicationBindings, accountManager: AccountManager, account: Account?, initialPresentationDataAndSettings: InitialPresentationDataAndSettings, postbox: Postbox) { - if account != nil { - self.mediaManager = MediaManager(postbox: postbox, inForeground: applicationBindings.applicationInForeground) - } else { - self.mediaManager = nil - } + public init(account: Account, applicationBindings: TelegramApplicationBindings, accountManager: AccountManager, initialPresentationDataAndSettings: InitialPresentationDataAndSettings, postbox: Postbox) { + self.account = account + + self.mediaManager = MediaManager(postbox: postbox, inForeground: applicationBindings.applicationInForeground) if applicationBindings.isMainApp { self.locationManager = DeviceLocationManager(queue: Queue.mainQueue()) } else { self.locationManager = nil } - if let account = account, let locationManager = self.locationManager { + if let locationManager = self.locationManager { self.liveLocationManager = LiveLocationManager(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, viewTracker: account.viewTracker, stateManager: account.stateManager, locationManager: locationManager, inForeground: applicationBindings.applicationInForeground) } else { self.liveLocationManager = nil } self.applicationBindings = applicationBindings self.accountManager = accountManager - self.fetchManager = FetchManager(postbox: postbox, storeManager: self.mediaManager?.downloadedMediaStoreManager) + self.fetchManager = FetchManager(postbox: postbox, storeManager: self.mediaManager.downloadedMediaStoreManager) self.currentPresentationData = Atomic(value: initialPresentationDataAndSettings.presentationData) self.currentAutomaticMediaDownloadSettings = Atomic(value: initialPresentationDataAndSettings.automaticMediaDownloadSettings) self.currentMediaInputSettings = Atomic(value: initialPresentationDataAndSettings.mediaInputSettings) - if let account = account { - self._presentationData.set(.single(initialPresentationDataAndSettings.presentationData) - |> then(updatedPresentationData(postbox: account.postbox, applicationBindings: applicationBindings))) - self._automaticMediaDownloadSettings.set(.single(initialPresentationDataAndSettings.automaticMediaDownloadSettings) |> then(updatedAutomaticMediaDownloadSettings(postbox: account.postbox))) - } else { - self._presentationData.set(.single(initialPresentationDataAndSettings.presentationData)) - self._automaticMediaDownloadSettings.set(.single(initialPresentationDataAndSettings.automaticMediaDownloadSettings)) - } + self._presentationData.set(.single(initialPresentationDataAndSettings.presentationData) + |> then(updatedPresentationData(postbox: account.postbox, applicationBindings: applicationBindings))) + self._automaticMediaDownloadSettings.set(.single(initialPresentationDataAndSettings.automaticMediaDownloadSettings) |> then(updatedAutomaticMediaDownloadSettings(postbox: account.postbox))) self.currentInAppNotificationSettings = Atomic(value: initialPresentationDataAndSettings.inAppNotificationSettings) - let inAppPreferencesKey = PostboxViewKey.preferences(keys: Set([ApplicationSpecificPreferencesKeys.inAppNotificationSettings])) inAppNotificationSettingsDisposable = (postbox.combinedView(keys: [inAppPreferencesKey]) |> deliverOnMainQueue).start(next: { [weak self] views in if let strongSelf = self { @@ -253,7 +247,7 @@ public final class TelegramApplicationContext { } public func attachOverlayMediaController(_ controller: OverlayMediaController) { - self.mediaManager?.overlayMediaManager.attachOverlayMediaController(controller) + self.mediaManager.overlayMediaManager.attachOverlayMediaController(controller) } public func storeSecureIdPassword(password: String) { @@ -277,9 +271,3 @@ public final class TelegramApplicationContext { } } } - -public extension Account { - public var telegramApplicationContext: TelegramApplicationContext { - return self.applicationContext as! TelegramApplicationContext - } -} diff --git a/TelegramUI/ArchivedStickerPacksController.swift b/TelegramUI/ArchivedStickerPacksController.swift index 1c792e9aaa..d19f3c9ae2 100644 --- a/TelegramUI/ArchivedStickerPacksController.swift +++ b/TelegramUI/ArchivedStickerPacksController.swift @@ -226,7 +226,7 @@ private func archivedStickerPacksControllerEntries(presentationData: Presentatio return entries } -public func archivedStickerPacksController(account: Account, mode: ArchivedStickerPacksControllerMode, archived: [ArchivedStickerPackItem]?, updatedPacks: @escaping ([ArchivedStickerPackItem]?) -> Void) -> ViewController { +public func archivedStickerPacksController(context: AccountContext, mode: ArchivedStickerPacksControllerMode, archived: [ArchivedStickerPackItem]?, updatedPacks: @escaping ([ArchivedStickerPackItem]?) -> Void) -> ViewController { let statePromise = ValuePromise(ArchivedStickerPacksControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: ArchivedStickerPacksControllerState()) let updateState: ((ArchivedStickerPacksControllerState) -> ArchivedStickerPacksControllerState) -> Void = { f in @@ -251,18 +251,18 @@ public func archivedStickerPacksController(account: Account, mode: ArchivedStick namespace = .masks } let stickerPacks = Promise<[ArchivedStickerPackItem]?>() - stickerPacks.set(.single(archived) |> then(archivedStickerPacks(account: account, namespace: namespace) |> map(Optional.init))) + stickerPacks.set(.single(archived) |> then(archivedStickerPacks(account: context.account, namespace: namespace) |> map(Optional.init))) actionsDisposable.add(stickerPacks.get().start(next: { packs in updatedPacks(packs) })) let installedStickerPacks = Promise() - installedStickerPacks.set(account.postbox.combinedView(keys: [.itemCollectionIds(namespaces: [Namespaces.ItemCollection.CloudStickerPacks])])) + installedStickerPacks.set(context.account.postbox.combinedView(keys: [.itemCollectionIds(namespaces: [Namespaces.ItemCollection.CloudStickerPacks])])) var presentStickerPackController: ((StickerPackCollectionInfo) -> Void)? - let arguments = ArchivedStickerPacksControllerArguments(account: account, openStickerPack: { info in + let arguments = ArchivedStickerPacksControllerArguments(account: context.account, openStickerPack: { info in presentStickerPackController?(info) }, setPackIdWithRevealedOptions: { packId, fromPackId in updateState { state in @@ -285,14 +285,14 @@ public func archivedStickerPacksController(account: Account, mode: ArchivedStick if !add { return } - let _ = (loadedStickerPack(postbox: account.postbox, network: account.network, reference: .id(id: info.id.id, accessHash: info.accessHash), forceActualized: false) + let _ = (loadedStickerPack(postbox: context.account.postbox, network: 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: account.postbox, info: info, items: items) + return addStickerPackInteractively(postbox: context.account.postbox, info: info, items: items) } case .fetching: break @@ -302,7 +302,7 @@ public func archivedStickerPacksController(account: Account, mode: ArchivedStick return .complete() } |> deliverOnMainQueue).start(completed: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .success), nil) let applyPacks: Signal = stickerPacks.get() @@ -355,7 +355,7 @@ public func archivedStickerPacksController(account: Account, mode: ArchivedStick return .complete() } - removePackDisposables.set((removeArchivedStickerPack(account: account, info: info) |> then(applyPacks) |> deliverOnMainQueue).start(completed: { + removePackDisposables.set((removeArchivedStickerPack(account: context.account, info: info) |> then(applyPacks) |> deliverOnMainQueue).start(completed: { updateState { state in var removingPackIds = state.removingPackIds removingPackIds.remove(info.id) @@ -367,7 +367,7 @@ public func archivedStickerPacksController(account: Account, mode: ArchivedStick var previousPackCount: Int? - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, stickerPacks.get() |> deliverOnMainQueue, installedStickerPacks.get() |> deliverOnMainQueue) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, stickerPacks.get() |> deliverOnMainQueue, installedStickerPacks.get() |> deliverOnMainQueue) |> deliverOnMainQueue |> map { presentationData, state, packs, installedView -> (ItemListControllerState, (ItemListNodeState, ArchivedStickerPacksEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? @@ -403,7 +403,7 @@ public func archivedStickerPacksController(account: Account, mode: ArchivedStick actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, p in if let controller = controller { controller.present(c, in: .window(.root), with: p) @@ -411,7 +411,7 @@ public func archivedStickerPacksController(account: Account, mode: ArchivedStick } 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/AutodownloadMediaCategoryController.swift b/TelegramUI/AutodownloadMediaCategoryController.swift index bf24ac3931..24549ff70f 100644 --- a/TelegramUI/AutodownloadMediaCategoryController.swift +++ b/TelegramUI/AutodownloadMediaCategoryController.swift @@ -344,9 +344,9 @@ private func autodownloadMediaCategoryControllerEntries(presentationData: Presen return entries } -func autodownloadMediaCategoryController(account: Account, category: AutomaticDownloadCategory) -> ViewController { +func autodownloadMediaCategoryController(context: AccountContext, category: AutomaticDownloadCategory) -> ViewController { let arguments = AutodownloadMediaCategoryControllerArguments(toggle: { connection, type in - let _ = updateMediaDownloadSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings switch category { case .photo: @@ -508,7 +508,7 @@ func autodownloadMediaCategoryController(account: Account, category: AutomaticDo return settings }).start() }, adjustSize: { size in - let _ = updateMediaDownloadSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings switch category { case .photo: @@ -541,7 +541,7 @@ func autodownloadMediaCategoryController(account: Account, category: AutomaticDo }).start() }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings])) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings])) |> deliverOnMainQueue |> map { presentationData, prefs -> (ItemListControllerState, (ItemListNodeState, AutodownloadMediaCategoryEntry.ItemGenerationArguments)) in let automaticMediaDownloadSettings: AutomaticMediaDownloadSettings if let value = prefs.values[ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings] as? AutomaticMediaDownloadSettings { @@ -570,7 +570,7 @@ func autodownloadMediaCategoryController(account: Account, category: AutomaticDo return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) return controller } diff --git a/TelegramUI/AvatarGalleryController.swift b/TelegramUI/AvatarGalleryController.swift index b4071d9460..da5e355e9f 100644 --- a/TelegramUI/AvatarGalleryController.swift +++ b/TelegramUI/AvatarGalleryController.swift @@ -101,7 +101,7 @@ class AvatarGalleryController: ViewController { return self.displayNode as! GalleryControllerNode } - private let account: Account + private let context: AccountContext private let peer: Peer private var presentationData: PresentationData @@ -132,10 +132,10 @@ class AvatarGalleryController: ViewController { private let replaceRootController: (ViewController, ValuePromise?) -> Void - init(account: Account, peer: Peer, remoteEntries: Promise<[AvatarGalleryEntry]>? = nil, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void, synchronousLoad: Bool = false) { - self.account = account + init(context: AccountContext, peer: Peer, remoteEntries: Promise<[AvatarGalleryEntry]>? = nil, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void, synchronousLoad: Bool = false) { + self.context = context self.peer = peer - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.replaceRootController = replaceRootController super.init(navigationBarPresentationData: NavigationBarPresentationData(theme: GalleryController.darkNavigationTheme, strings: NavigationBarStrings(presentationStrings: self.presentationData.strings))) @@ -149,7 +149,7 @@ class AvatarGalleryController: ViewController { if let remoteEntries = remoteEntries { remoteEntriesSignal = remoteEntries.get() } else { - remoteEntriesSignal = fetchedAvatarGalleryEntries(account: account, peer: peer) + remoteEntriesSignal = fetchedAvatarGalleryEntries(account: context.account, peer: peer) } let entriesSignal: Signal<[AvatarGalleryEntry], NoError> = .single(initialAvatarGalleryEntries(peer: peer)) |> then(remoteEntriesSignal) @@ -171,7 +171,7 @@ class AvatarGalleryController: ViewController { strongSelf.entries = entries strongSelf.centralEntryIndex = 0 if strongSelf.isViewLoaded { - strongSelf.galleryNode.pager.replaceItems(strongSelf.entries.map({ entry in PeerAvatarImageGalleryItem(account: account, peer: peer, presentationData: presentationData, entry: entry, delete: strongSelf.peer.id == strongSelf.account.peerId ? { + strongSelf.galleryNode.pager.replaceItems(strongSelf.entries.map({ entry in PeerAvatarImageGalleryItem(context: context, peer: peer, presentationData: presentationData, entry: entry, delete: strongSelf.peer.id == strongSelf.context.account.peerId ? { self?.deleteEntry(entry) } : nil) }), centralItemIndex: 0, keepFirst: true) @@ -307,7 +307,7 @@ class AvatarGalleryController: ViewController { } let presentationData = self.presentationData - self.galleryNode.pager.replaceItems(self.entries.map({ entry in PeerAvatarImageGalleryItem(account: self.account, peer: peer, presentationData: presentationData, entry: entry, delete: self.peer.id == self.account.peerId ? { [weak self] in + self.galleryNode.pager.replaceItems(self.entries.map({ entry in PeerAvatarImageGalleryItem(context: self.context, peer: peer, presentationData: presentationData, entry: entry, delete: self.peer.id == self.context.account.peerId ? { [weak self] in self?.deleteEntry(entry) } : nil) }), centralItemIndex: self.centralEntryIndex) @@ -394,7 +394,7 @@ class AvatarGalleryController: ViewController { break case let .image(reference, _, _, _, _): if let reference = reference { - let _ = removeAccountPhoto(network: self.account.network, reference: reference).start() + let _ = removeAccountPhoto(network: self.context.account.network, reference: reference).start() } if entry == self.entries.first { self.dismiss(forceAway: true) diff --git a/TelegramUI/AvatarGalleryItemFooterContentNode.swift b/TelegramUI/AvatarGalleryItemFooterContentNode.swift index b3d64b1e84..905942a8c1 100644 --- a/TelegramUI/AvatarGalleryItemFooterContentNode.swift +++ b/TelegramUI/AvatarGalleryItemFooterContentNode.swift @@ -13,7 +13,7 @@ private let nameFont = Font.medium(15.0) private let dateFont = Font.regular(14.0) final class AvatarGalleryItemFooterContentNode: GalleryFooterContentNode { - private let account: Account + private let context: AccountContext private var strings: PresentationStrings private var dateTimeFormat: PresentationDateTimeFormat @@ -33,8 +33,8 @@ final class AvatarGalleryItemFooterContentNode: GalleryFooterContentNode { var share: ((GalleryControllerInteraction) -> Void)? - init(account: Account, presentationData: PresentationData) { - self.account = account + init(context: AccountContext, presentationData: PresentationData) { + self.context = context self.strings = presentationData.strings self.dateTimeFormat = presentationData.dateTimeFormat @@ -136,7 +136,7 @@ final class AvatarGalleryItemFooterContentNode: GalleryFooterContentNode { } @objc private func deleteButtonPressed() { - let presentationData = self.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = self.context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) let items: [ActionSheetItem] = [ ActionSheetButtonItem(title: presentationData.strings.Common_Delete, color: .destructive, action: { [weak self, weak actionSheet] in diff --git a/TelegramUI/BlockedPeersController.swift b/TelegramUI/BlockedPeersController.swift index 79d6f937fa..6e91da17cc 100644 --- a/TelegramUI/BlockedPeersController.swift +++ b/TelegramUI/BlockedPeersController.swift @@ -190,7 +190,7 @@ private func blockedPeersControllerEntries(presentationData: PresentationData, s return entries } -public func blockedPeersController(account: Account) -> ViewController { +public func blockedPeersController(context: AccountContext) -> ViewController { let statePromise = ValuePromise(BlockedPeersControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: BlockedPeersControllerState()) let updateState: ((BlockedPeersControllerState) -> BlockedPeersControllerState) -> Void = { f in @@ -207,7 +207,7 @@ public func blockedPeersController(account: Account) -> ViewController { let peersPromise = Promise<[Peer]?>(nil) - let arguments = BlockedPeersControllerArguments(account: account, setPeerIdWithRevealedOptions: { peerId, fromPeerId in + let arguments = BlockedPeersControllerArguments(account: context.account, setPeerIdWithRevealedOptions: { peerId, fromPeerId in updateState { state in if (peerId == nil && fromPeerId == state.peerIdWithRevealedOptions) || (peerId != nil && fromPeerId == nil) { return state.withUpdatedPeerIdWithRevealedOptions(peerId) @@ -216,13 +216,13 @@ public func blockedPeersController(account: Account) -> ViewController { } } }, addPeer: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - let controller = PeerSelectionController(account: account, filter: [.onlyPrivateChats, .excludeSavedMessages, .removeSearchHeader, .excludeRecent], title: presentationData.strings.BlockedUsers_SelectUserTitle) + let presentationData = context.currentPresentationData.with { $0 } + let controller = PeerSelectionController(context: context, filter: [.onlyPrivateChats, .excludeSavedMessages, .removeSearchHeader, .excludeRecent], title: presentationData.strings.BlockedUsers_SelectUserTitle) controller.peerSelected = { [weak controller] peerId in if let strongController = controller { strongController.inProgress = true - let _ = (account.viewTracker.peerView(peerId) + let _ = (context.account.viewTracker.peerView(peerId) |> take(1) |> map { view -> Peer? in return peerViewMainPeer(view) @@ -251,7 +251,7 @@ public func blockedPeersController(account: Account) -> ViewController { return .complete() } if let peer = peer { - removePeerDisposable.set((requestUpdatePeerIsBlocked(account: account, peerId: peer.id, isBlocked: true) |> then(applyPeers) |> deliverOnMainQueue).start(completed: { + removePeerDisposable.set((requestUpdatePeerIsBlocked(account: context.account, peerId: peer.id, isBlocked: true) |> then(applyPeers) |> deliverOnMainQueue).start(completed: { if let strongController = controller { strongController.inProgress = false strongController.dismiss() @@ -285,7 +285,7 @@ public func blockedPeersController(account: Account) -> ViewController { return .complete() } - removePeerDisposable.set((requestUpdatePeerIsBlocked(account: account, peerId: memberId, isBlocked: false) |> then(applyPeers) |> deliverOnMainQueue).start(error: { _ in + removePeerDisposable.set((requestUpdatePeerIsBlocked(account: context.account, peerId: memberId, isBlocked: false) |> then(applyPeers) |> deliverOnMainQueue).start(error: { _ in updateState { return $0.withUpdatedRemovingPeerId(nil) } @@ -295,18 +295,18 @@ public func blockedPeersController(account: Account) -> ViewController { } })) }, openPeer: { peer in - if let controller = peerInfoController(account: account, peer: peer) { + if let controller = peerInfoController(context: context, peer: peer) { pushControllerImpl?(controller) } }) - let peersSignal: Signal<[Peer]?, NoError> = .single(nil) |> then(requestBlockedPeers(account: account) |> map(Optional.init)) + let peersSignal: Signal<[Peer]?, NoError> = .single(nil) |> then(requestBlockedPeers(account: context.account) |> map(Optional.init)) peersPromise.set(peersSignal) var previousPeers: [Peer]? - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), peersPromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get(), peersPromise.get()) |> deliverOnMainQueue |> map { presentationData, state, peers -> (ItemListControllerState, (ItemListNodeState, BlockedPeersEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? @@ -346,7 +346,7 @@ public func blockedPeersController(account: Account) -> ViewController { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] c in if let controller = controller { (controller.navigationController as? NavigationController)?.pushViewController(c) diff --git a/TelegramUI/BotCheckoutController.swift b/TelegramUI/BotCheckoutController.swift index e87bd49ef4..5cd02b9180 100644 --- a/TelegramUI/BotCheckoutController.swift +++ b/TelegramUI/BotCheckoutController.swift @@ -15,7 +15,7 @@ final class BotCheckoutController: ViewController { return self._ready } - private let account: Account + private let context: AccountContext private let invoice: TelegramMediaInvoice private let messageId: MessageId @@ -23,12 +23,12 @@ final class BotCheckoutController: ViewController { private var didPlayPresentationAnimation = false - init(account: Account, invoice: TelegramMediaInvoice, messageId: MessageId) { - self.account = account + init(context: AccountContext, invoice: TelegramMediaInvoice, messageId: MessageId) { + self.context = context self.invoice = invoice self.messageId = messageId - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -52,7 +52,7 @@ final class BotCheckoutController: ViewController { if let strongSelf = self { strongSelf.navigationOffset = offset } - }, account: self.account, invoice: self.invoice, messageId: self.messageId, present: { [weak self] c, a in + }, context: self.context, invoice: self.invoice, messageId: self.messageId, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a) }, dismissAnimated: { [weak self] in self?.dismiss() diff --git a/TelegramUI/BotCheckoutControllerNode.swift b/TelegramUI/BotCheckoutControllerNode.swift index 71d892d86d..2b3a63d48e 100644 --- a/TelegramUI/BotCheckoutControllerNode.swift +++ b/TelegramUI/BotCheckoutControllerNode.swift @@ -312,12 +312,35 @@ private func botCheckoutControllerEntries(presentationData: PresentationData, st private let hasApplePaySupport: Bool = PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: [.visa, .masterCard, .amex]) -private var applePayProviders = Set([ - "stripe", - "sberbank", - "yandex", - "privatbank" -]) +private func formSupportApplePay(_ paymentForm: BotPaymentForm) -> Bool { + guard let nativeProvider = paymentForm.nativeProvider else { + return false + } + let applePayProviders = Set([ + "stripe", + "sberbank", + "yandex", + "privatbank" + ]) + if !applePayProviders.contains(nativeProvider.name) { + return false + } + guard let nativeParamsData = nativeProvider.params.data(using: .utf8) else { + return false + } + guard let nativeParams = (try? JSONSerialization.jsonObject(with: nativeParamsData, options: [])) as? [String: Any] else { + return false + } + + var merchantId: String? + if nativeProvider.name == "stripe" { + merchantId = "merchant.ph.telegra.Telegraph" + } else if let paramsId = nativeParams["apple_pay_merchant_id"] as? String { + merchantId = paramsId + } + + return merchantId != nil +} private func availablePaymentMethods(current: BotCheckoutPaymentMethod?, supportsApplePay: Bool) -> [BotCheckoutPaymentMethod] { var methods: [BotCheckoutPaymentMethod] = [] @@ -333,7 +356,7 @@ private func availablePaymentMethods(current: BotCheckoutPaymentMethod?, support } final class BotCheckoutControllerNode: ItemListControllerNode, PKPaymentAuthorizationViewControllerDelegate { - private let account: Account + private let context: AccountContext private let messageId: MessageId private let present: (ViewController, Any?) -> Void private let dismissAnimated: () -> Void @@ -360,19 +383,19 @@ final class BotCheckoutControllerNode: ItemListControllerNode, private var applePayAuthrorizationCompletion: ((PKPaymentAuthorizationStatus) -> Void)? private var applePayController: PKPaymentAuthorizationViewController? - init(navigationBar: NavigationBar, updateNavigationOffset: @escaping (CGFloat) -> Void, account: Account, invoice: TelegramMediaInvoice, messageId: MessageId, present: @escaping (ViewController, Any?) -> Void, dismissAnimated: @escaping () -> Void) { - self.account = account + init(navigationBar: NavigationBar, updateNavigationOffset: @escaping (CGFloat) -> Void, context: AccountContext, invoice: TelegramMediaInvoice, messageId: MessageId, present: @escaping (ViewController, Any?) -> Void, dismissAnimated: @escaping () -> Void) { + self.context = context self.messageId = messageId self.present = present self.dismissAnimated = dismissAnimated - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } var openInfoImpl: ((BotCheckoutInfoControllerFocus) -> Void)? var openPaymentMethodImpl: (() -> Void)? var openShippingMethodImpl: (() -> Void)? - let arguments = BotCheckoutControllerArguments(account: account, openInfo: { item in + let arguments = BotCheckoutControllerArguments(account: context.account, openInfo: { item in openInfoImpl?(item) }, openPaymentMethod: { openPaymentMethodImpl?() @@ -380,7 +403,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, openShippingMethodImpl?() }) - let signal: Signal<(PresentationTheme, (ItemListNodeState, BotCheckoutEntry.ItemGenerationArguments)), NoError> = combineLatest(account.telegramApplicationContext.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(), 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) @@ -401,7 +424,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, openInfoImpl = { [weak self] focus in if let strongSelf = self, let paymentFormValue = strongSelf.paymentFormValue, let currentFormInfo = strongSelf.currentFormInfo { - strongSelf.present(BotCheckoutInfoController(account: account, invoice: paymentFormValue.invoice, messageId: messageId, initialFormInfo: currentFormInfo, focus: focus, formInfoUpdated: { formInfo, validatedInfo in + strongSelf.present(BotCheckoutInfoController(context: context, invoice: paymentFormValue.invoice, messageId: messageId, initialFormInfo: currentFormInfo, focus: focus, formInfoUpdated: { formInfo, validatedInfo in if let strongSelf = self, let paymentFormValue = strongSelf.paymentFormValue { strongSelf.currentFormInfo = formInfo strongSelf.currentValidatedFormInfo = validatedInfo @@ -452,7 +475,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, var dismissImpl: (() -> Void)? let canSave = paymentForm.canSaveCredentials || paymentForm.passwordMissing - let controller = BotCheckoutNativeCardEntryController(account: strongSelf.account, additionalFields: additionalFields, publishableKey: publishableKey, completion: { method in + let controller = BotCheckoutNativeCardEntryController(context: strongSelf.context, additionalFields: additionalFields, publishableKey: publishableKey, completion: { method in guard let strongSelf = self else { return } @@ -475,7 +498,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, updatedToken.saveOnServer = false applyPaymentMethod(.webToken(updatedToken)) - let controller = SetupTwoStepVerificationController(account: strongSelf.account, initialState: .automatic, stateUpdated: { update, shouldDismiss, controller in + let controller = SetupTwoStepVerificationController(context: strongSelf.context, initialState: .automatic, stateUpdated: { update, shouldDismiss, controller in if shouldDismiss { controller.dismiss() } @@ -509,7 +532,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, strongSelf.present(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } else { var dismissImpl: (() -> Void)? - let controller = BotCheckoutWebInteractionController(account: account, url: paymentForm.url, intent: .addPaymentMethod({ [weak self] token in + let controller = BotCheckoutWebInteractionController(context: context, url: paymentForm.url, intent: .addPaymentMethod({ [weak self] token in dismissImpl?() guard let strongSelf = self else { @@ -531,7 +554,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, updatedToken.saveOnServer = false applyPaymentMethod(.webToken(updatedToken)) - let controller = SetupTwoStepVerificationController(account: strongSelf.account, initialState: .automatic, stateUpdated: { update, shouldDismiss, controller in + let controller = SetupTwoStepVerificationController(context: strongSelf.context, initialState: .automatic, stateUpdated: { update, shouldDismiss, controller in if shouldDismiss { controller.dismiss() } @@ -573,7 +596,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, openPaymentMethodImpl = { [weak self] in if let strongSelf = self, let paymentForm = strongSelf.paymentFormValue { let supportsApplePay: Bool - if let nativeProvider = paymentForm.nativeProvider, applePayProviders.contains(nativeProvider.name) { + if formSupportApplePay(paymentForm) { supportsApplePay = true } else { supportsApplePay = false @@ -582,7 +605,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, if methods.isEmpty { openNewCard() } else { - strongSelf.present(BotCheckoutPaymentMethodSheetController(account: strongSelf.account, currentMethod: strongSelf.currentPaymentMethod, methods: methods, applyValue: { method in + strongSelf.present(BotCheckoutPaymentMethodSheetController(context: strongSelf.context, currentMethod: strongSelf.currentPaymentMethod, methods: methods, applyValue: { method in applyPaymentMethod(method) }, newCard: { openNewCard() @@ -593,7 +616,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, openShippingMethodImpl = { [weak self] in if let strongSelf = self, let paymentFormValue = strongSelf.paymentFormValue, let shippingOptions = strongSelf.currentValidatedFormInfo?.shippingOptions, !shippingOptions.isEmpty { - strongSelf.present(BotCheckoutPaymentShippingOptionSheetController(account: strongSelf.account, currency: paymentFormValue.invoice.currency, options: shippingOptions, currentId: strongSelf.currentShippingOptionId, applyValue: { id in + strongSelf.present(BotCheckoutPaymentShippingOptionSheetController(context: strongSelf.context, currency: paymentFormValue.invoice.currency, options: shippingOptions, currentId: strongSelf.currentShippingOptionId, applyValue: { id in if let strongSelf = self, let paymentFormValue = strongSelf.paymentFormValue, let currentFormInfo = strongSelf.currentFormInfo { strongSelf.currentShippingOptionId = id strongSelf.paymentFormAndInfo.set(.single((paymentFormValue, currentFormInfo, strongSelf.currentValidatedFormInfo, strongSelf.currentShippingOptionId, strongSelf.currentPaymentMethod))) @@ -604,10 +627,10 @@ final class BotCheckoutControllerNode: ItemListControllerNode, } } - let formAndMaybeValidatedInfo = fetchBotPaymentForm(postbox: account.postbox, network: account.network, messageId: messageId) + let formAndMaybeValidatedInfo = fetchBotPaymentForm(postbox: context.account.postbox, network: context.account.network, messageId: messageId) |> mapToSignal { paymentForm -> Signal<(BotPaymentForm, BotPaymentValidatedFormInfo?), BotPaymentFormRequestError> in if let current = paymentForm.savedInfo { - return validateBotPaymentForm(network: account.network, saveInfo: true, messageId: messageId, formInfo: current) + return validateBotPaymentForm(network: context.account.network, saveInfo: true, messageId: messageId, formInfo: current) |> mapError { _ -> BotPaymentFormRequestError in return .generic } @@ -732,10 +755,10 @@ final class BotCheckoutControllerNode: ItemListControllerNode, if let savedCredentialsToken = savedCredentialsToken { credentials = .saved(id: id, tempPassword: savedCredentialsToken.token) } else { - let _ = (cachedTwoStepPasswordToken(postbox: self.account.postbox) + let _ = (cachedTwoStepPasswordToken(postbox: self.context.account.postbox) |> deliverOnMainQueue).start(next: { [weak self] token in if let strongSelf = self { - let timestamp = strongSelf.account.network.getApproximateRemoteTimestamp() + let timestamp = strongSelf.context.account.network.getApproximateRemoteTimestamp() if let token = token, token.validUntilDate > timestamp - 1 * 60 { if token.requiresBiometrics { let reasonText: String @@ -788,7 +811,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, } let botPeerId = self.messageId.peerId - let _ = (self.account.postbox.transaction({ transaction -> Peer? in + let _ = (self.context.account.postbox.transaction({ transaction -> Peer? in return transaction.getPeer(botPeerId) }) |> deliverOnMainQueue).start(next: { [weak self] botPeer in if let strongSelf = self, let botPeer = botPeer { @@ -843,13 +866,13 @@ final class BotCheckoutControllerNode: ItemListControllerNode, if !liabilityNoticeAccepted { let messageId = self.messageId - let botPeer: Signal = self.account.postbox.transaction { transaction -> Peer? in + let botPeer: Signal = self.context.account.postbox.transaction { transaction -> Peer? in if let message = transaction.getMessage(messageId) { return message.author } return nil } - let _ = (combineLatest(ApplicationSpecificNotice.getBotPaymentLiability(postbox: self.account.postbox, peerId: self.messageId.peerId), botPeer, self.account.postbox.loadedPeerWithId(paymentForm.providerId)) + let _ = (combineLatest(ApplicationSpecificNotice.getBotPaymentLiability(postbox: self.context.account.postbox, peerId: self.messageId.peerId), botPeer, self.context.account.postbox.loadedPeerWithId(paymentForm.providerId)) |> deliverOnMainQueue).start(next: { [weak self] value, botPeer, providerPeer in if let strongSelf = self, let botPeer = botPeer { if value { @@ -857,7 +880,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, } else { strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: strongSelf.presentationData.theme), title: strongSelf.presentationData.strings.Checkout_LiabilityAlertTitle, text: strongSelf.presentationData.strings.Checkout_LiabilityAlert(botPeer.displayTitle, providerPeer.displayTitle).0, actions: [TextAlertAction(type: .genericAction, title: strongSelf.presentationData.strings.Common_Cancel, action: { }), TextAlertAction(type: .defaultAction, title: strongSelf.presentationData.strings.Common_OK, action: { if let strongSelf = self { - let _ = ApplicationSpecificNotice.setBotPaymentLiability(postbox: strongSelf.account.postbox, peerId: strongSelf.messageId.peerId).start() + let _ = ApplicationSpecificNotice.setBotPaymentLiability(postbox: strongSelf.context.account.postbox, peerId: strongSelf.messageId.peerId).start() strongSelf.pay(savedCredentialsToken: savedCredentialsToken, liabilityNoticeAccepted: true) } })]), nil) @@ -869,7 +892,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, self.inProgressDimNode.alpha = 1.0 self.actionButton.isEnabled = false self.updateActionButton() - self.payDisposable.set((sendBotPaymentForm(account: self.account, messageId: self.messageId, validatedInfoId: self.currentValidatedFormInfo?.id, shippingOptionId: self.currentShippingOptionId, credentials: credentials) |> deliverOnMainQueue).start(next: { [weak self] result in + self.payDisposable.set((sendBotPaymentForm(account: self.context.account, messageId: self.messageId, validatedInfoId: self.currentValidatedFormInfo?.id, shippingOptionId: self.currentShippingOptionId, credentials: credentials) |> deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { strongSelf.inProgressDimNode.isUserInteractionEnabled = false strongSelf.inProgressDimNode.alpha = 0.0 @@ -889,7 +912,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, case let .externalVerificationRequired(url): strongSelf.updateActionButton() var dismissImpl: (() -> Void)? - let controller = BotCheckoutWebInteractionController(account: strongSelf.account, url: url, intent: .externalVerification({ _ in + let controller = BotCheckoutWebInteractionController(context: strongSelf.context, url: url, intent: .externalVerification({ _ in dismissImpl?() })) dismissImpl = { [weak controller] in @@ -942,7 +965,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, period = 1 * 60 * 60 requiresBiometrics = false } - self.present(botCheckoutPasswordEntryController(account: self.account, strings: self.presentationData.strings, cartTitle: cardTitle, period: period, requiresBiometrics: requiresBiometrics, completion: { [weak self] token in + self.present(botCheckoutPasswordEntryController(context: self.context, strings: self.presentationData.strings, cartTitle: cardTitle, period: period, requiresBiometrics: requiresBiometrics, completion: { [weak self] token in if let strongSelf = self { let durationString = timeIntervalString(strings: strongSelf.presentationData.strings, value: period) @@ -965,7 +988,7 @@ final class BotCheckoutControllerNode: ItemListControllerNode, }), TextAlertAction(type: .genericAction, title: strongSelf.presentationData.strings.Common_Yes, action: { if let strongSelf = self { - let _ = cacheTwoStepPasswordToken(postbox: strongSelf.account.postbox, token: token).start() + let _ = cacheTwoStepPasswordToken(postbox: strongSelf.context.account.postbox, token: token).start() strongSelf.pay(savedCredentialsToken: token) } }) @@ -979,7 +1002,11 @@ final class BotCheckoutControllerNode: ItemListControllerNode, completion(.failure) return } - guard let nativeProvider = paymentForm.nativeProvider, applePayProviders.contains(nativeProvider.name) else { + if !formSupportApplePay(paymentForm) { + completion(.failure) + return + } + guard let nativeProvider = paymentForm.nativeProvider else { completion(.failure) return } diff --git a/TelegramUI/BotCheckoutInfoController.swift b/TelegramUI/BotCheckoutInfoController.swift index b640d47216..8ef4edf688 100644 --- a/TelegramUI/BotCheckoutInfoController.swift +++ b/TelegramUI/BotCheckoutInfoController.swift @@ -24,7 +24,7 @@ final class BotCheckoutInfoController: ViewController { return super.displayNode as! BotCheckoutInfoControllerNode } - private let account: Account + private let context: AccountContext private let invoice: BotPaymentInvoice private let messageId: MessageId private let initialFormInfo: BotPaymentRequestedInfo @@ -39,15 +39,15 @@ final class BotCheckoutInfoController: ViewController { private var doneItem: UIBarButtonItem? private var activityItem: UIBarButtonItem? - public init(account: Account, invoice: BotPaymentInvoice, messageId: MessageId, initialFormInfo: BotPaymentRequestedInfo, focus: BotCheckoutInfoControllerFocus, formInfoUpdated: @escaping (BotPaymentRequestedInfo, BotPaymentValidatedFormInfo) -> Void) { - self.account = account + public init(context: AccountContext, invoice: BotPaymentInvoice, messageId: MessageId, initialFormInfo: BotPaymentRequestedInfo, focus: BotCheckoutInfoControllerFocus, formInfoUpdated: @escaping (BotPaymentRequestedInfo, BotPaymentValidatedFormInfo) -> Void) { + self.context = context self.invoice = invoice self.messageId = messageId self.initialFormInfo = initialFormInfo self.focus = focus self.formInfoUpdated = formInfoUpdated - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) self.statusBar.statusBarStyle = self.presentationData.theme.rootController.statusBar.style.style @@ -69,7 +69,7 @@ final class BotCheckoutInfoController: ViewController { } override public func loadDisplayNode() { - self.displayNode = BotCheckoutInfoControllerNode(account: self.account, invoice: self.invoice, messageId: self.messageId, formInfo: self.initialFormInfo, focus: self.focus, theme: self.presentationData.theme, strings: self.presentationData.strings, dismiss: { [weak self] in + self.displayNode = BotCheckoutInfoControllerNode(context: self.context, invoice: self.invoice, messageId: self.messageId, formInfo: self.initialFormInfo, focus: self.focus, theme: self.presentationData.theme, strings: self.presentationData.strings, dismiss: { [weak self] in self?.presentingViewController?.dismiss(animated: false, completion: nil) }, openCountrySelection: { [weak self] in if let strongSelf = self { diff --git a/TelegramUI/BotCheckoutInfoControllerNode.swift b/TelegramUI/BotCheckoutInfoControllerNode.swift index 19bc6d1e12..0a7f6536d0 100644 --- a/TelegramUI/BotCheckoutInfoControllerNode.swift +++ b/TelegramUI/BotCheckoutInfoControllerNode.swift @@ -88,7 +88,7 @@ enum BotCheckoutInfoControllerStatus { } final class BotCheckoutInfoControllerNode: ViewControllerTracingNode, UIScrollViewDelegate { - private let account: Account + private let context: AccountContext private let invoice: BotPaymentInvoice private let messageId: MessageId private var focus: BotCheckoutInfoControllerFocus? @@ -118,8 +118,8 @@ final class BotCheckoutInfoControllerNode: ViewControllerTracingNode, UIScrollVi private let verifyDisposable = MetaDisposable() private var isVerifying = false - init(account: Account, invoice: BotPaymentInvoice, messageId: MessageId, formInfo: BotPaymentRequestedInfo, focus: BotCheckoutInfoControllerFocus, theme: PresentationTheme, strings: PresentationStrings, dismiss: @escaping () -> Void, openCountrySelection: @escaping () -> Void, updateStatus: @escaping (BotCheckoutInfoControllerStatus) -> Void, formInfoUpdated: @escaping (BotPaymentRequestedInfo, BotPaymentValidatedFormInfo) -> Void, present: @escaping (ViewController, Any?) -> Void) { - self.account = account + init(context: AccountContext, invoice: BotPaymentInvoice, messageId: MessageId, formInfo: BotPaymentRequestedInfo, focus: BotCheckoutInfoControllerFocus, theme: PresentationTheme, strings: PresentationStrings, dismiss: @escaping () -> Void, openCountrySelection: @escaping () -> Void, updateStatus: @escaping (BotCheckoutInfoControllerStatus) -> Void, formInfoUpdated: @escaping (BotPaymentRequestedInfo, BotPaymentValidatedFormInfo) -> Void, present: @escaping (ViewController, Any?) -> Void) { + self.context = context self.invoice = invoice self.messageId = messageId self.formInfo = formInfo @@ -331,7 +331,7 @@ final class BotCheckoutInfoControllerNode: ViewControllerTracingNode, UIScrollVi func verify() { self.isVerifying = true let formInfo = self.collectFormInfo() - self.verifyDisposable.set((validateBotPaymentForm(network: self.account.network, saveInfo: self.saveInfoItem.isOn, messageId: self.messageId, formInfo: formInfo) |> deliverOnMainQueue).start(next: { [weak self] result in + self.verifyDisposable.set((validateBotPaymentForm(network: self.context.account.network, saveInfo: self.saveInfoItem.isOn, messageId: self.messageId, formInfo: formInfo) |> deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { strongSelf.formInfoUpdated(formInfo, result) } diff --git a/TelegramUI/BotCheckoutNativeCardEntryController.swift b/TelegramUI/BotCheckoutNativeCardEntryController.swift index e79b91b747..afd9460a3b 100644 --- a/TelegramUI/BotCheckoutNativeCardEntryController.swift +++ b/TelegramUI/BotCheckoutNativeCardEntryController.swift @@ -27,7 +27,7 @@ final class BotCheckoutNativeCardEntryController: ViewController { return super.displayNode as! BotCheckoutNativeCardEntryControllerNode } - private let account: Account + private let context: AccountContext private let additionalFields: BotCheckoutNativeCardEntryAdditionalFields private let publishableKey: String private let completion: (BotCheckoutPaymentMethod) -> Void @@ -39,13 +39,13 @@ final class BotCheckoutNativeCardEntryController: ViewController { private var doneItem: UIBarButtonItem? private var activityItem: UIBarButtonItem? - public init(account: Account, additionalFields: BotCheckoutNativeCardEntryAdditionalFields, publishableKey: String, completion: @escaping (BotCheckoutPaymentMethod) -> Void) { - self.account = account + public init(context: AccountContext, additionalFields: BotCheckoutNativeCardEntryAdditionalFields, publishableKey: String, completion: @escaping (BotCheckoutPaymentMethod) -> Void) { + self.context = context self.additionalFields = additionalFields self.publishableKey = publishableKey self.completion = completion - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) self.statusBar.statusBarStyle = self.presentationData.theme.rootController.statusBar.style.style diff --git a/TelegramUI/BotCheckoutPasswordEntryController.swift b/TelegramUI/BotCheckoutPasswordEntryController.swift index 1bef9f84f5..f7d2b5f7fc 100644 --- a/TelegramUI/BotCheckoutPasswordEntryController.swift +++ b/TelegramUI/BotCheckoutPasswordEntryController.swift @@ -66,7 +66,7 @@ private final class BotCheckoutPasswordAlertActionNode: HighlightableButtonNode } private final class BotCheckoutPasswordAlertContentNode: AlertContentNode { - private let account: Account + private let context: AccountContext private let period: Int32 private let requiresBiometrics: Bool private let completion: (TemporaryTwoStepPasswordToken) -> Void @@ -90,8 +90,8 @@ private final class BotCheckoutPasswordAlertContentNode: AlertContentNode { private let hapticFeedback = HapticFeedback() - init(account: Account, theme: PresentationTheme, strings: PresentationStrings, cardTitle: String, period: Int32, requiresBiometrics: Bool, cancel: @escaping () -> Void, completion: @escaping (TemporaryTwoStepPasswordToken) -> Void) { - self.account = account + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings, cardTitle: String, period: Int32, requiresBiometrics: Bool, cancel: @escaping () -> Void, completion: @escaping (TemporaryTwoStepPasswordToken) -> Void) { + self.context = context self.period = period self.requiresBiometrics = requiresBiometrics self.completion = completion @@ -278,7 +278,7 @@ private final class BotCheckoutPasswordAlertContentNode: AlertContentNode { } self.isVerifying = true - self.disposable.set((requestTemporaryTwoStepPasswordToken(account: self.account, password: text, period: self.period, requiresBiometrics: self.requiresBiometrics) |> deliverOnMainQueue).start(next: { [weak self] token in + self.disposable.set((requestTemporaryTwoStepPasswordToken(account: self.context.account, password: text, period: self.period, requiresBiometrics: self.requiresBiometrics) |> deliverOnMainQueue).start(next: { [weak self] token in if let strongSelf = self { strongSelf.completion(token) } @@ -295,10 +295,10 @@ private final class BotCheckoutPasswordAlertContentNode: AlertContentNode { } } -func botCheckoutPasswordEntryController(account: Account, strings: PresentationStrings, cartTitle: String, period: Int32, requiresBiometrics: Bool, completion: @escaping (TemporaryTwoStepPasswordToken) -> Void) -> AlertController { +func botCheckoutPasswordEntryController(context: AccountContext, strings: PresentationStrings, cartTitle: String, period: Int32, requiresBiometrics: Bool, completion: @escaping (TemporaryTwoStepPasswordToken) -> Void) -> AlertController { var dismissImpl: (() -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - let controller = AlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), contentNode: BotCheckoutPasswordAlertContentNode(account: account, theme: presentationData.theme, strings: strings, cardTitle: cartTitle, period: period, requiresBiometrics: requiresBiometrics, cancel: { + let presentationData = context.currentPresentationData.with { $0 } + let controller = AlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), contentNode: BotCheckoutPasswordAlertContentNode(context: context, theme: presentationData.theme, strings: strings, cardTitle: cartTitle, period: period, requiresBiometrics: requiresBiometrics, cancel: { dismissImpl?() }, completion: { token in completion(token) diff --git a/TelegramUI/BotCheckoutPaymentMethodSheet.swift b/TelegramUI/BotCheckoutPaymentMethodSheet.swift index 3bb3e02a1b..288d9450e0 100644 --- a/TelegramUI/BotCheckoutPaymentMethodSheet.swift +++ b/TelegramUI/BotCheckoutPaymentMethodSheet.swift @@ -33,14 +33,14 @@ enum BotCheckoutPaymentMethod: Equatable { final class BotCheckoutPaymentMethodSheetController: ActionSheetController { private var presentationDisposable: Disposable? - init(account: Account, currentMethod: BotCheckoutPaymentMethod?, methods: [BotCheckoutPaymentMethod], applyValue: @escaping (BotCheckoutPaymentMethod) -> Void, newCard: @escaping () -> Void) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, currentMethod: BotCheckoutPaymentMethod?, methods: [BotCheckoutPaymentMethod], applyValue: @escaping (BotCheckoutPaymentMethod) -> Void, newCard: @escaping () -> 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.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/BotCheckoutPaymentShippingOptionSheetController.swift b/TelegramUI/BotCheckoutPaymentShippingOptionSheetController.swift index 0e70f336b5..f62061057a 100644 --- a/TelegramUI/BotCheckoutPaymentShippingOptionSheetController.swift +++ b/TelegramUI/BotCheckoutPaymentShippingOptionSheetController.swift @@ -7,14 +7,14 @@ import TelegramCore final class BotCheckoutPaymentShippingOptionSheetController: ActionSheetController { private var presentationDisposable: Disposable? - init(account: Account, currency: String, options: [BotPaymentShippingOption], currentId: String?, applyValue: @escaping (String) -> Void) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, currency: String, options: [BotPaymentShippingOption], currentId: String?, applyValue: @escaping (String) -> 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.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/BotCheckoutWebInteractionController.swift b/TelegramUI/BotCheckoutWebInteractionController.swift index 7917de139e..95902e9e15 100644 --- a/TelegramUI/BotCheckoutWebInteractionController.swift +++ b/TelegramUI/BotCheckoutWebInteractionController.swift @@ -15,7 +15,7 @@ final class BotCheckoutWebInteractionController: ViewController { return self.displayNode as! BotCheckoutWebInteractionControllerNode } - private let account: Account + private let context: AccountContext private let url: String private let intent: BotCheckoutWebInteractionControllerIntent @@ -23,14 +23,14 @@ final class BotCheckoutWebInteractionController: ViewController { private var didPlayPresentationAnimation = false - init(account: Account, url: String, intent: BotCheckoutWebInteractionControllerIntent) { - self.account = account + init(context: AccountContext, url: String, intent: BotCheckoutWebInteractionControllerIntent) { + self.context = context self.url = url self.intent = intent - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } - super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: (account.telegramApplicationContext.currentPresentationData.with { $0 }))) + super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: (context.currentPresentationData.with { $0 }))) self.statusBar.statusBarStyle = self.presentationData.theme.rootController.statusBar.style.style diff --git a/TelegramUI/BotReceiptController.swift b/TelegramUI/BotReceiptController.swift index 72fc10b7d0..e85e1a2f0b 100644 --- a/TelegramUI/BotReceiptController.swift +++ b/TelegramUI/BotReceiptController.swift @@ -15,7 +15,7 @@ final class BotReceiptController: ViewController { return self._ready } - private let account: Account + private let context: AccountContext private let invoice: TelegramMediaInvoice private let messageId: MessageId @@ -23,12 +23,12 @@ final class BotReceiptController: ViewController { private var didPlayPresentationAnimation = false - init(account: Account, invoice: TelegramMediaInvoice, messageId: MessageId) { - self.account = account + init(context: AccountContext, invoice: TelegramMediaInvoice, messageId: MessageId) { + self.context = context self.invoice = invoice self.messageId = messageId - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -50,7 +50,7 @@ final class BotReceiptController: ViewController { if let strongSelf = self { strongSelf.navigationOffset = offset } - }, account: self.account, invoice: self.invoice, messageId: self.messageId, dismissAnimated: { [weak self] in + }, context: self.context, invoice: self.invoice, messageId: self.messageId, dismissAnimated: { [weak self] in self?.dismiss() }) diff --git a/TelegramUI/BotReceiptControllerNode.swift b/TelegramUI/BotReceiptControllerNode.swift index ec17ea07ae..ebaef04ba3 100644 --- a/TelegramUI/BotReceiptControllerNode.swift +++ b/TelegramUI/BotReceiptControllerNode.swift @@ -249,7 +249,7 @@ private func availablePaymentMethods(current: BotCheckoutPaymentMethod?) -> [Bot } final class BotReceiptControllerNode: ItemListControllerNode { - private let account: Account + private let context: AccountContext private let dismissAnimated: () -> Void private var presentationData: PresentationData @@ -259,15 +259,15 @@ final class BotReceiptControllerNode: ItemListControllerNode { private let actionButton: BotCheckoutActionButton - init(navigationBar: NavigationBar, updateNavigationOffset: @escaping (CGFloat) -> Void, account: Account, invoice: TelegramMediaInvoice, messageId: MessageId, dismissAnimated: @escaping () -> Void) { + init(navigationBar: NavigationBar, updateNavigationOffset: @escaping (CGFloat) -> Void, context: AccountContext, invoice: TelegramMediaInvoice, messageId: MessageId, dismissAnimated: @escaping () -> Void) { self.account = account self.dismissAnimated = dismissAnimated - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } let arguments = BotReceiptControllerArguments(account: account) - let signal: Signal<(PresentationTheme, (ItemListNodeState, BotReceiptEntry.ItemGenerationArguments)), NoError> = combineLatest(account.telegramApplicationContext.presentationData, receiptData.get(), account.postbox.loadedPeerWithId(messageId.peerId)) + let signal: Signal<(PresentationTheme, (ItemListNodeState, BotReceiptEntry.ItemGenerationArguments)), NoError> = combineLatest(context.presentationData, receiptData.get(), 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) @@ -279,7 +279,7 @@ final class BotReceiptControllerNode: ItemListControllerNode { super.init(navigationBar: navigationBar, updateNavigationOffset: updateNavigationOffset, state: signal) - self.dataRequestDisposable = (requestBotPaymentReceipt(network: account.network, messageId: messageId) |> deliverOnMainQueue).start(next: { [weak self] receipt in + self.dataRequestDisposable = (requestBotPaymentReceipt(network: context.account.network, messageId: messageId) |> deliverOnMainQueue).start(next: { [weak self] receipt in if let strongSelf = self { strongSelf.receiptData.set(.single((receipt.invoice, receipt.info, receipt.shippingOption, receipt.credentialsTitle))) } diff --git a/TelegramUI/CallController.swift b/TelegramUI/CallController.swift index 3046b3e256..2844900324 100644 --- a/TelegramUI/CallController.swift +++ b/TelegramUI/CallController.swift @@ -15,7 +15,7 @@ public final class CallController: ViewController { return self._ready } - private let account: Account + private let context: AccountContext public let call: PresentationCall private var presentationData: PresentationData @@ -32,11 +32,11 @@ public final class CallController: ViewController { private var audioOutputStateDisposable: Disposable? private var audioOutputState: ([AudioSessionOutput], AudioSessionOutput?)? - public init(account: Account, call: PresentationCall) { - self.account = account + public init(context: AccountContext, call: PresentationCall) { + self.context = context self.call = call - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: nil) @@ -89,7 +89,7 @@ public final class CallController: ViewController { } override public func loadDisplayNode() { - self.displayNode = CallControllerNode(account: self.account, presentationData: self.presentationData, statusBar: self.statusBar, debugInfo: self.call.debugInfo(), shouldStayHiddenUntilConnection: !self.call.isOutgoing && self.call.isIntegratedWithCallKit) + self.displayNode = CallControllerNode(context: self.context, presentationData: self.presentationData, statusBar: self.statusBar, debugInfo: self.call.debugInfo(), shouldStayHiddenUntilConnection: !self.call.isOutgoing && self.call.isIntegratedWithCallKit) self.displayNodeDidLoad() self.controllerNode.toggleMute = { [weak self] in @@ -167,7 +167,7 @@ public final class CallController: ViewController { self?.presentingViewController?.dismiss(animated: false, completion: nil) } - self.peerDisposable = (account.postbox.peerView(id: self.call.peerId) + self.peerDisposable = (context.account.postbox.peerView(id: self.call.peerId) |> deliverOnMainQueue).start(next: { [weak self] view in if let strongSelf = self { if let peer = view.peers[view.peerId] { diff --git a/TelegramUI/CallControllerNode.swift b/TelegramUI/CallControllerNode.swift index e56f6b1b66..3d23899106 100644 --- a/TelegramUI/CallControllerNode.swift +++ b/TelegramUI/CallControllerNode.swift @@ -8,7 +8,7 @@ import SwiftSignalKit import TelegramUIPrivateModule final class CallControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private let statusBar: StatusBar @@ -52,8 +52,8 @@ final class CallControllerNode: ASDisplayNode { var back: (() -> Void)? var dismissedInteractively: (() -> Void)? - init(account: Account, presentationData: PresentationData, statusBar: StatusBar, debugInfo: Signal<(String, String), NoError>, shouldStayHiddenUntilConnection: Bool = false) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, statusBar: StatusBar, debugInfo: Signal<(String, String), NoError>, shouldStayHiddenUntilConnection: Bool = false) { + self.context = context self.presentationData = presentationData self.statusBar = statusBar self.debugInfo = debugInfo @@ -152,7 +152,7 @@ final class CallControllerNode: ASDisplayNode { self.peer = peer if let peerReference = PeerReference(peer), !peer.profileImageRepresentations.isEmpty { let representations: [ImageRepresentationWithReference] = peer.profileImageRepresentations.map({ ImageRepresentationWithReference(representation: $0, reference: .avatar(peer: peerReference, resource: $0.resource)) }) - self.imageNode.setSignal(chatAvatarGalleryPhoto(account: self.account, representations: representations, autoFetchFullSize: true)) + self.imageNode.setSignal(chatAvatarGalleryPhoto(account: self.context.account, representations: representations, autoFetchFullSize: true)) self.dimNode.isHidden = false } else { self.imageNode.setSignal(callDefaultBackground()) diff --git a/TelegramUI/CallListController.swift b/TelegramUI/CallListController.swift index 2432c26eac..a8e065c611 100644 --- a/TelegramUI/CallListController.swift +++ b/TelegramUI/CallListController.swift @@ -20,7 +20,7 @@ public final class CallListController: ViewController { return self._ready } - private let account: Account + private let context: AccountContext private let mode: CallListControllerMode private var presentationData: PresentationData @@ -35,10 +35,10 @@ public final class CallListController: ViewController { private let createActionDisposable = MetaDisposable() - public init(account: Account, mode: CallListControllerMode) { - self.account = account + public init(context: AccountContext, mode: CallListControllerMode) { + self.context = context self.mode = mode - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.segmentedTitleView = ItemListControllerSegmentedTitleView(segments: [self.presentationData.strings.Calls_All, self.presentationData.strings.Calls_Missed], index: 0, color: self.presentationData.theme.rootController.navigationBar.accentTextColor) @@ -67,7 +67,7 @@ public final class CallListController: 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 @@ -136,17 +136,17 @@ public final class CallListController: ViewController { } override public func loadDisplayNode() { - self.displayNode = CallListControllerNode(account: self.account, mode: self.mode, presentationData: self.presentationData, call: { [weak self] peerId in + self.displayNode = CallListControllerNode(context: self.context, mode: self.mode, presentationData: self.presentationData, call: { [weak self] peerId in if let strongSelf = self { strongSelf.call(peerId) } }, openInfo: { [weak self] peerId, messages in if let strongSelf = self { - let _ = (strongSelf.account.postbox.loadedPeerWithId(peerId) + let _ = (strongSelf.context.account.postbox.loadedPeerWithId(peerId) |> take(1) |> deliverOnMainQueue).start(next: { peer in if let strongSelf = self { - let infoController = userInfoController(account: strongSelf.account, peerId: peer.id, mode: .calls(messages: messages)) + let infoController = userInfoController(context: strongSelf.context, peerId: peer.id, mode: .calls(messages: messages)) (strongSelf.navigationController as? NavigationController)?.pushViewController(infoController) } }) @@ -193,7 +193,7 @@ public final class CallListController: ViewController { } @objc func callPressed() { - let controller = ContactSelectionController(account: self.account, title: { $0.Calls_NewCall }) + let controller = ContactSelectionController(context: self.context, title: { $0.Calls_NewCall }) self.createActionDisposable.set((controller.result |> take(1) |> deliverOnMainQueue).start(next: { [weak controller, weak self] peer in @@ -201,7 +201,7 @@ public final class CallListController: ViewController { if let strongSelf = self, let contactPeer = peer, case let .peer(peer, _) = contactPeer { strongSelf.call(peer.id, began: { if let strongSelf = self { - if let hasOngoingCall = strongSelf.account.telegramApplicationContext.hasOngoingCall { + if let hasOngoingCall = strongSelf.context.hasOngoingCall { let _ = (hasOngoingCall |> filter { $0 } |> timeout(1.0, queue: Queue.mainQueue(), alternate: .single(true)) @@ -250,7 +250,7 @@ public final class CallListController: ViewController { } private func call(_ peerId: PeerId, began: (() -> Void)? = nil) { - self.peerViewDisposable.set((self.account.viewTracker.peerView(peerId) + self.peerViewDisposable.set((self.context.account.viewTracker.peerView(peerId) |> take(1) |> deliverOnMainQueue).start(next: { [weak self] view in if let strongSelf = self { @@ -259,27 +259,27 @@ public final class CallListController: ViewController { } if let cachedUserData = view.cachedData as? CachedUserData, cachedUserData.callsPrivate { - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: presentationData.strings.Call_ConnectionErrorTitle, text: presentationData.strings.Call_PrivacyErrorMessage(peer.compactDisplayTitle).0, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), in: .window(.root)) return } - let callResult = strongSelf.account.telegramApplicationContext.callManager?.requestCall(peerId: peerId, endCurrentIfAny: false) + let callResult = strongSelf.context.callManager?.requestCall(peerId: peerId, endCurrentIfAny: false) if let callResult = callResult { if case let .alreadyInProgress(currentPeerId) = callResult { if currentPeerId == peerId { began?() - strongSelf.account.telegramApplicationContext.navigateToCurrentCall?() + strongSelf.context.navigateToCurrentCall?() } else { let presentationData = strongSelf.presentationData - let _ = (strongSelf.account.postbox.transaction { transaction -> (Peer?, Peer?) in + let _ = (strongSelf.context.account.postbox.transaction { transaction -> (Peer?, Peer?) in return (transaction.getPeer(peerId), transaction.getPeer(currentPeerId)) } |> deliverOnMainQueue).start(next: { [weak self] peer, current in if let strongSelf = self, let peer = peer, let current = current { strongSelf.present(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: { if let strongSelf = self { - let _ = strongSelf.account.telegramApplicationContext.callManager?.requestCall(peerId: peerId, endCurrentIfAny: true) + let _ = strongSelf.context.callManager?.requestCall(peerId: peerId, endCurrentIfAny: true) began?() } })]), in: .window(.root)) diff --git a/TelegramUI/CallListControllerNode.swift b/TelegramUI/CallListControllerNode.swift index fbde141dcc..2913b6f2b5 100644 --- a/TelegramUI/CallListControllerNode.swift +++ b/TelegramUI/CallListControllerNode.swift @@ -152,7 +152,7 @@ private final class CallListOpaqueTransactionState { } final class CallListControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private let mode: CallListControllerMode private var presentationData: PresentationData @@ -191,8 +191,8 @@ final class CallListControllerNode: ASDisplayNode { private let emptyStatePromise = Promise() private let emptyStateDisposable = MetaDisposable() - init(account: Account, mode: CallListControllerMode, presentationData: PresentationData, call: @escaping (PeerId) -> Void, openInfo: @escaping (PeerId, [Message]) -> Void, emptyStateUpdated: @escaping (Bool) -> Void) { - self.account = account + init(context: AccountContext, mode: CallListControllerMode, presentationData: PresentationData, call: @escaping (PeerId) -> Void, openInfo: @escaping (PeerId, [Message]) -> Void, emptyStateUpdated: @escaping (Bool) -> Void) { + self.context = context self.mode = mode self.presentationData = presentationData self.call = call @@ -244,11 +244,11 @@ final class CallListControllerNode: ASDisplayNode { self?.openInfo(peerId, messages) }, delete: { [weak self] messageIds in if let strongSelf = self { - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: messageIds, type: .forLocalPeer).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: messageIds, type: .forLocalPeer).start() } }, updateShowCallsTab: { [weak self] value in if let strongSelf = self { - let _ = updateCallListSettingsInteractively(postbox: strongSelf.account.postbox, { + let _ = updateCallListSettingsInteractively(postbox: strongSelf.context.account.postbox, { $0.withUpdatedShowTab(value) }).start() } @@ -259,7 +259,7 @@ final class CallListControllerNode: ASDisplayNode { let callListViewUpdate = self.callListLocationAndType.get() |> distinctUntilChanged |> mapToSignal { locationAndType in - return callListViewForLocationAndType(locationAndType: locationAndType, account: account) + return callListViewForLocationAndType(locationAndType: locationAndType, account: context.account) } let previousView = Atomic(value: nil) @@ -272,7 +272,7 @@ final class CallListControllerNode: ASDisplayNode { showSettings = true } - let showCallsTab = account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.callListSettings]) + let showCallsTab = context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.callListSettings]) |> map { view -> Bool in var value = true if let settings = view.values[ApplicationSpecificPreferencesKeys.callListSettings] as? CallListSettings { @@ -324,8 +324,8 @@ final class CallListControllerNode: ASDisplayNode { } } - return preparedCallListNodeViewTransition(from: previous, to: processedView, reason: reason, disableAnimations: false, account: account, scrollPosition: update.scrollPosition) - |> map({ mappedCallListNodeViewListTransition(account: account, showSettings: showSettings, nodeInteraction: nodeInteraction, transition: $0) }) + return preparedCallListNodeViewTransition(from: previous, to: processedView, reason: reason, disableAnimations: false, account: context.account, scrollPosition: update.scrollPosition) + |> map({ mappedCallListNodeViewListTransition(account: context.account, showSettings: showSettings, nodeInteraction: nodeInteraction, transition: $0) }) |> runOn(prepareOnMainQueue ? Queue.mainQueue() : viewProcessingQueue) } diff --git a/TelegramUI/CallRatingController.swift b/TelegramUI/CallRatingController.swift index 82e3e8384a..27e27041eb 100644 --- a/TelegramUI/CallRatingController.swift +++ b/TelegramUI/CallRatingController.swift @@ -349,8 +349,8 @@ private func rateCallAndSendLogs(account: Account, callId: CallId, starsCount: I } } -func callRatingController(account: Account, callId: CallId, present: @escaping (ViewController) -> Void) -> AlertController { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } +func callRatingController(context: AccountContext, callId: CallId, present: @escaping (ViewController) -> Void) -> AlertController { + let presentationData = context.currentPresentationData.with { $0 } let theme = presentationData.theme let strings = presentationData.strings @@ -362,14 +362,14 @@ func callRatingController(account: Account, callId: CallId, present: @escaping ( dismissImpl?(true) if let contentNode = contentNode, let rating = contentNode.rating { if rating < 4 { - let controller = textAlertController(account: account, title: strings.Call_ReportIncludeLog, text: strings.Call_ReportIncludeLogDescription, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Call_ReportSkip, action: { - let _ = rateCallAndSendLogs(account: account, callId: callId, starsCount: rating, comment: contentNode.comment, includeLogs: false).start() + let controller = textAlertController(context: context, title: strings.Call_ReportIncludeLog, text: strings.Call_ReportIncludeLogDescription, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Call_ReportSkip, action: { + let _ = rateCallAndSendLogs(account: context.account, callId: callId, starsCount: rating, comment: contentNode.comment, includeLogs: false).start() }), TextAlertAction(type: .defaultAction, title: presentationData.strings.Call_ReportSend, action: { - let _ = rateCallAndSendLogs(account: account, callId: callId, starsCount: rating, comment: contentNode.comment, includeLogs: true).start() + let _ = rateCallAndSendLogs(account: context.account, callId: callId, starsCount: rating, comment: contentNode.comment, includeLogs: true).start() })]) present(controller) } else { - let _ = rateCallAndSendLogs(account: account, callId: callId, starsCount: rating, comment: contentNode.comment, includeLogs: false).start + let _ = rateCallAndSendLogs(account: context.account, callId: callId, starsCount: rating, comment: contentNode.comment, includeLogs: false).start } } })] diff --git a/TelegramUI/ChangePhoneNumberCodeController.swift b/TelegramUI/ChangePhoneNumberCodeController.swift index 3af34a4b30..8b744519e6 100644 --- a/TelegramUI/ChangePhoneNumberCodeController.swift +++ b/TelegramUI/ChangePhoneNumberCodeController.swift @@ -168,11 +168,11 @@ protocol ChangePhoneNumberCodeController: class { private final class ChangePhoneNumberCodeControllerImpl: ItemListController, ChangePhoneNumberCodeController { private let applyCodeImpl: (Int) -> Void - init(account: Account, state: Signal<(ItemListControllerState, (ItemListNodeState, ChangePhoneNumberCodeEntry.ItemGenerationArguments)), NoError>, applyCodeImpl: @escaping (Int) -> Void) { + init(context: AccountContext, state: Signal<(ItemListControllerState, (ItemListNodeState, ChangePhoneNumberCodeEntry.ItemGenerationArguments)), NoError>, applyCodeImpl: @escaping (Int) -> Void) { self.applyCodeImpl = applyCodeImpl - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - super.init(theme: presentationData.theme, strings: presentationData.strings, updatedPresentationData: account.telegramApplicationContext.presentationData |> map { ($0.theme, $0.strings) }, state: state, tabBarItem: nil) + let presentationData = context.currentPresentationData.with { $0 } + super.init(theme: presentationData.theme, strings: presentationData.strings, updatedPresentationData: context.presentationData |> map { ($0.theme, $0.strings) }, state: state, tabBarItem: nil) } required init(coder aDecoder: NSCoder) { @@ -184,7 +184,7 @@ private final class ChangePhoneNumberCodeControllerImpl: ItemListController ViewController { +func changePhoneNumberCodeController(context: AccountContext, phoneNumber: String, codeData: ChangeAccountPhoneNumberData) -> ViewController { let initialState = ChangePhoneNumberCodeControllerState(codeText: "", checking: false) let statePromise = ValuePromise(initialState, ignoreRepeated: true) @@ -218,7 +218,7 @@ func changePhoneNumberCodeController(account: Account, phoneNumber: String, code |> take(1) |> mapToSignal { _ -> Signal in return Signal { subscriber in - return requestNextChangeAccountPhoneNumberVerification(account: account, phoneNumber: phoneNumber, phoneCodeHash: data.hash).start(next: { next in + return requestNextChangeAccountPhoneNumberVerification(account: context.account, phoneNumber: phoneNumber, phoneCodeHash: data.hash).start(next: { next in currentDataPromise?.set(.single(next)) }, error: { error in @@ -242,11 +242,11 @@ func changePhoneNumberCodeController(account: Account, phoneNumber: String, code } } if let code = code { - changePhoneDisposable.set((requestChangeAccountPhoneNumber(account: account, phoneNumber: phoneNumber, phoneCodeHash: codeData.hash, phoneCode: code) |> deliverOnMainQueue).start(error: { error in + changePhoneDisposable.set((requestChangeAccountPhoneNumber(account: context.account, phoneNumber: phoneNumber, phoneCodeHash: codeData.hash, phoneCode: code) |> deliverOnMainQueue).start(error: { error in updateState { return $0.withUpdatedChecking(false) } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let alertText: String switch error { case .generic: @@ -263,7 +263,7 @@ func changePhoneNumberCodeController(account: Account, phoneNumber: String, code updateState { return $0.withUpdatedChecking(false) } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .success), nil) dismissImpl?() })) @@ -285,7 +285,7 @@ func changePhoneNumberCodeController(account: Account, phoneNumber: String, code checkCode() }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, currentDataPromise.get() |> deliverOnMainQueue, timeout.get() |> deliverOnMainQueue) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, currentDataPromise.get() |> deliverOnMainQueue, timeout.get() |> deliverOnMainQueue) |> deliverOnMainQueue |> map { presentationData, state, data, timeout -> (ItemListControllerState, (ItemListNodeState, ChangePhoneNumberCodeEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? @@ -309,7 +309,7 @@ func changePhoneNumberCodeController(account: Account, phoneNumber: String, code actionsDisposable.dispose() } - let controller = ChangePhoneNumberCodeControllerImpl(account: account, state: signal, applyCodeImpl: { code in + let controller = ChangePhoneNumberCodeControllerImpl(context: context, state: signal, applyCodeImpl: { code in updateState { state in return state.withUpdatedCodeText("\(code)") } diff --git a/TelegramUI/ChangePhoneNumberController.swift b/TelegramUI/ChangePhoneNumberController.swift index 43b4df1647..ea26638afa 100644 --- a/TelegramUI/ChangePhoneNumberController.swift +++ b/TelegramUI/ChangePhoneNumberController.swift @@ -9,7 +9,7 @@ final class ChangePhoneNumberController: ViewController { return self.displayNode as! ChangePhoneNumberControllerNode } - private let account: Account + private let context: AccountContext private var currentData: (Int32, String?, String)? private let requestDisposable = MetaDisposable() @@ -31,9 +31,9 @@ final class ChangePhoneNumberController: ViewController { private var presentationData: PresentationData - init(account: Account) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -105,16 +105,16 @@ final class ChangePhoneNumberController: ViewController { } if !number.isEmpty { self.inProgress = true - self.requestDisposable.set((requestChangeAccountPhoneNumberVerification(account: self.account, phoneNumber: self.controllerNode.currentNumber) |> deliverOnMainQueue).start(next: { [weak self] next in + self.requestDisposable.set((requestChangeAccountPhoneNumberVerification(account: self.context.account, phoneNumber: self.controllerNode.currentNumber) |> deliverOnMainQueue).start(next: { [weak self] next in if let strongSelf = self { strongSelf.inProgress = false - (strongSelf.navigationController as? NavigationController)?.pushViewController(changePhoneNumberCodeController(account: strongSelf.account, phoneNumber: strongSelf.controllerNode.currentNumber, codeData: next)) + (strongSelf.navigationController as? NavigationController)?.pushViewController(changePhoneNumberCodeController(context: strongSelf.context, phoneNumber: strongSelf.controllerNode.currentNumber, codeData: next)) } }, error: { [weak self] error in if let strongSelf = self { strongSelf.inProgress = false - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } let text: String switch error { diff --git a/TelegramUI/ChangePhoneNumberIntroController.swift b/TelegramUI/ChangePhoneNumberIntroController.swift index 1c14148ac8..37e0476d9a 100644 --- a/TelegramUI/ChangePhoneNumberIntroController.swift +++ b/TelegramUI/ChangePhoneNumberIntroController.swift @@ -76,15 +76,15 @@ private final class ChangePhoneNumberIntroControllerNode: ASDisplayNode { } final class ChangePhoneNumberIntroController: ViewController { - private let account: Account + private let context: AccountContext private var didPlayPresentationAnimation = false private var presentationData: PresentationData - init(account: Account, phoneNumber: String) { - self.account = account + init(context: AccountContext, phoneNumber: String) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -132,7 +132,7 @@ final class ChangePhoneNumberIntroController: ViewController { func proceed() { self.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: self.presentationData.theme), title: nil, text: self.presentationData.strings.PhoneNumberHelp_Alert, actions: [TextAlertAction(type: .defaultAction, title: self.presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .genericAction, title: self.presentationData.strings.Common_OK, action: { [weak self] in if let strongSelf = self { - (strongSelf.navigationController as? NavigationController)?.replaceTopController(ChangePhoneNumberController(account: strongSelf.account), animated: true) + (strongSelf.navigationController as? NavigationController)?.replaceTopController(ChangePhoneNumberController(context: strongSelf.context), animated: true) } })]), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } diff --git a/TelegramUI/ChannelAdminController.swift b/TelegramUI/ChannelAdminController.swift index 93851a52bf..ae5cf298fc 100644 --- a/TelegramUI/ChannelAdminController.swift +++ b/TelegramUI/ChannelAdminController.swift @@ -500,7 +500,7 @@ private func channelAdminControllerEntries(presentationData: PresentationData, s return entries } -public func channelAdminController(account: Account, peerId: PeerId, adminId: PeerId, initialParticipant: ChannelParticipant?, updated: @escaping (TelegramChatAdminRights) -> Void, upgradedToSupergroup: @escaping (PeerId, @escaping () -> Void) -> Void) -> ViewController { +public func channelAdminController(context: AccountContext, peerId: PeerId, adminId: PeerId, initialParticipant: ChannelParticipant?, updated: @escaping (TelegramChatAdminRights) -> Void, upgradedToSupergroup: @escaping (PeerId, @escaping () -> Void) -> Void) -> ViewController { let statePromise = ValuePromise(ChannelAdminControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: ChannelAdminControllerState()) let updateState: ((ChannelAdminControllerState) -> ChannelAdminControllerState) -> Void = { f in @@ -515,7 +515,7 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe var dismissImpl: (() -> Void)? var presentControllerImpl: ((ViewController, Any?) -> Void)? - let arguments = ChannelAdminControllerArguments(account: account, toggleRight: { right, flags in + let arguments = ChannelAdminControllerArguments(account: context.account, toggleRight: { right, flags in updateState { current in var updated = flags if flags.contains(right) { @@ -526,7 +526,7 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe return current.withUpdatedUpdatedFlags(updated) } }, dismissAdmin: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) var items: [ActionSheetItem] = [] items.append(ActionSheetButtonItem(title: presentationData.strings.Channel_Moderator_AccessLevelRevoke, color: .destructive, font: .default, enabled: true, action: { [weak actionSheet] in @@ -536,14 +536,14 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe return current.withUpdatedUpdating(true) } if peerId.namespace == Namespaces.Peer.CloudGroup { - updateRightsDisposable.set((removeGroupAdmin(account: account, peerId: peerId, adminId: adminId) + updateRightsDisposable.set((removeGroupAdmin(account: context.account, peerId: peerId, adminId: adminId) |> deliverOnMainQueue).start(error: { _ in }, completed: { updated(TelegramChatAdminRights(flags: [])) dismissImpl?() })) } else { - updateRightsDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: account, peerId: peerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: [])) |> deliverOnMainQueue).start(error: { _ in + updateRightsDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: context.account, peerId: peerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: [])) |> deliverOnMainQueue).start(error: { _ in }, completed: { updated(TelegramChatAdminRights(flags: [])) @@ -559,14 +559,14 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe presentControllerImpl?(actionSheet, nil) }) - let combinedView = account.postbox.combinedView(keys: [.peer(peerId: peerId, components: .all), .peer(peerId: adminId, components: .all)]) + let combinedView = context.account.postbox.combinedView(keys: [.peer(peerId: peerId, components: .all), .peer(peerId: adminId, components: .all)]) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), combinedView) + let signal = combineLatest(context.presentationData, statePromise.get(), combinedView) |> deliverOnMainQueue |> map { presentationData, state, combinedView -> (ItemListControllerState, (ItemListNodeState, ChannelAdminEntry.ItemGenerationArguments)) in let channelView = combinedView.views[.peer(peerId: peerId, components: .all)] as! PeerView let adminView = combinedView.views[.peer(peerId: adminId, components: .all)] as! PeerView - let canEdit = canEditAdminRights(accountPeerId: account.peerId, channelView: channelView, initialParticipant: initialParticipant) + let canEdit = canEditAdminRights(accountPeerId: context.account.peerId, channelView: channelView, initialParticipant: initialParticipant) let leftNavigationButton: ItemListNavigationButton if canEdit { @@ -625,7 +625,7 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe updateState { current in return current.withUpdatedUpdating(true) } - updateRightsDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: account, peerId: peerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: updateFlags)) |> deliverOnMainQueue).start(error: { _ in + updateRightsDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: context.account, peerId: peerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: updateFlags)) |> deliverOnMainQueue).start(error: { _ in }, completed: { updated(TelegramChatAdminRights(flags: updateFlags)) @@ -663,7 +663,7 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe updateState { current in return current.withUpdatedUpdating(true) } - updateRightsDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: account, peerId: peerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: updateFlags)) |> deliverOnMainQueue).start(error: { _ in + updateRightsDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: context.account, peerId: peerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: updateFlags)) |> deliverOnMainQueue).start(error: { _ in }, completed: { updated(TelegramChatAdminRights(flags: updateFlags)) @@ -690,12 +690,12 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe updateState { current in return current.withUpdatedUpdating(true) } - updateRightsDisposable.set((addGroupAdmin(account: account, peerId: peerId, adminId: adminId) + updateRightsDisposable.set((addGroupAdmin(account: context.account, peerId: peerId, adminId: adminId) |> deliverOnMainQueue).start(completed: { dismissImpl?() })) } else if updateFlags != defaultFlags { - let signal = convertGroupToSupergroup(account: account, peerId: peerId) + let signal = convertGroupToSupergroup(account: context.account, peerId: peerId) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -704,7 +704,7 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe guard let upgradedPeerId = upgradedPeerId else { return .single(nil) } - return account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: account, peerId: upgradedPeerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: updateFlags)) + return context.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: context.account, peerId: upgradedPeerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: updateFlags)) |> mapToSignal { _ -> Signal in return .complete() } @@ -738,7 +738,7 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.Channel_Management_LabelEditor), leftNavigationButton: leftNavigationButton, rightNavigationButton: rightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: false) - let listState = ItemListNodeState(entries: channelAdminControllerEntries(presentationData: presentationData, state: state, accountPeerId: account.peerId, channelView: channelView, adminView: adminView, initialParticipant: initialParticipant), style: .blocks, emptyStateItem: nil, animateChanges: true) + let listState = ItemListNodeState(entries: channelAdminControllerEntries(presentationData: presentationData, state: state, accountPeerId: context.account.peerId, channelView: channelView, adminView: adminView, initialParticipant: initialParticipant), style: .blocks, emptyStateItem: nil, animateChanges: true) return (controllerState, (listState, arguments)) } @@ -746,7 +746,7 @@ public func channelAdminController(account: Account, peerId: PeerId, adminId: Pe actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) dismissImpl = { [weak controller] in controller?.dismiss() } diff --git a/TelegramUI/ChannelAdminsController.swift b/TelegramUI/ChannelAdminsController.swift index 77ee1e687c..ae4d3db558 100644 --- a/TelegramUI/ChannelAdminsController.swift +++ b/TelegramUI/ChannelAdminsController.swift @@ -459,7 +459,7 @@ private func channelAdminsControllerEntries(presentationData: PresentationData, return entries } -public func channelAdminsController(account: Account, peerId: PeerId, loadCompleted: @escaping () -> Void = {}) -> ViewController { +public func channelAdminsController(context: AccountContext, peerId: PeerId, loadCompleted: @escaping () -> Void = {}) -> ViewController { let statePromise = ValuePromise(ChannelAdminsControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: ChannelAdminsControllerState()) let updateState: ((ChannelAdminsControllerState) -> ChannelAdminsControllerState) -> Void = { f in @@ -482,7 +482,7 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple let adminsPromise = Promise<[RenderedChannelParticipant]?>(nil) - let presentationDataSignal = (account.applicationContext as! TelegramApplicationContext).presentationData + let presentationDataSignal = context.presentationData var upgradedToSupergroupImpl: ((PeerId, @escaping () -> Void) -> Void)? @@ -491,14 +491,14 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple } let peerView = Promise() - peerView.set(account.viewTracker.peerView(peerId)) + peerView.set(context.account.viewTracker.peerView(peerId)) - let arguments = ChannelAdminsControllerArguments(account: account, openRecentActions: { - let _ = (account.postbox.loadedPeerWithId(peerId) + let arguments = ChannelAdminsControllerArguments(account: context.account, openRecentActions: { + let _ = (context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { peer in if peer is TelegramGroup { } else { - pushControllerImpl?(ChatRecentActionsController(account: account, peer: peer)) + pushControllerImpl?(ChatRecentActionsController(context: context, peer: peer)) } }) }, setPeerIdWithRevealedOptions: { peerId, fromPeerId in @@ -514,14 +514,14 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple return $0.withUpdatedRemovingPeerId(adminId) } if peerId.namespace == Namespaces.Peer.CloudGroup { - removeAdminDisposable.set((removeGroupAdmin(account: account, peerId: peerId, adminId: adminId) + removeAdminDisposable.set((removeGroupAdmin(account: context.account, peerId: peerId, adminId: adminId) |> deliverOnMainQueue).start(completed: { updateState { return $0.withUpdatedRemovingPeerId(nil) } })) } else { - removeAdminDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: account, peerId: peerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: [])) + removeAdminDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: context.account, peerId: peerId, memberId: adminId, adminRights: TelegramChatAdminRights(flags: [])) |> deliverOnMainQueue).start(completed: { updateState { return $0.withUpdatedRemovingPeerId(nil) @@ -534,10 +534,10 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple |> deliverOnMainQueue).start(next: { peerView in updateState { current in var dismissController: (() -> Void)? - let controller = ChannelMembersSearchController(account: account, peerId: peerId, mode: .promote, filters: [], openPeer: { peer, participant in + let controller = ChannelMembersSearchController(context: context, peerId: peerId, mode: .promote, filters: [], openPeer: { peer, participant in dismissController?() - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - if peer.id == account.peerId { + let presentationData = context.currentPresentationData.with { $0 } + if peer.id == context.account.peerId { return } if let participant = participant { @@ -547,7 +547,7 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple case let .member(_, _, _, banInfo): if let banInfo = banInfo { var canUnban = false - if banInfo.restrictedBy != account.peerId { + if banInfo.restrictedBy != context.account.peerId { canUnban = true } if let channel = peerView.peers[peerId] as? TelegramChannel { @@ -562,7 +562,7 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple } } } - presentControllerImpl?(channelAdminController(account: account, peerId: peerId, adminId: peer.id, initialParticipant: participant?.participant, updated: { _ in + presentControllerImpl?(channelAdminController(context: context, peerId: peerId, adminId: peer.id, initialParticipant: participant?.participant, updated: { _ in }, upgradedToSupergroup: upgradedToSupergroup), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) dismissController = { [weak controller] in @@ -574,14 +574,14 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple } }) }, openAdmin: { participant in - presentControllerImpl?(channelAdminController(account: account, peerId: peerId, adminId: participant.peerId, initialParticipant: participant, updated: { _ in + presentControllerImpl?(channelAdminController(context: context, peerId: peerId, adminId: participant.peerId, initialParticipant: participant, updated: { _ in }, upgradedToSupergroup: upgradedToSupergroup), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) let membersAndLoadMoreControl: (Disposable, PeerChannelMemberCategoryControl?) if peerId.namespace == Namespaces.Peer.CloudChannel { var didReportLoadCompleted = false - membersAndLoadMoreControl = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.admins(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId) { membersState in + membersAndLoadMoreControl = context.peerChannelMemberCategoriesContextsManager.admins(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId) { membersState in if case .loading = membersState.loadingState, membersState.list.isEmpty { adminsPromise.set(.single(nil)) } else { @@ -623,7 +623,7 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple var peers: [PeerId: Peer] = [:] peers[creator.id] = creator peers[peer.id] = peer - result.append(RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(flags: .groupSpecific), promotedBy: creator.id, canBeEditedByAccountPeer: creator.id == account.peerId), banInfo: nil), peer: peer, peers: peers)) + result.append(RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(flags: .groupSpecific), promotedBy: creator.id, canBeEditedByAccountPeer: creator.id == context.account.peerId), banInfo: nil), peer: peer, peers: peers)) case .member: break } @@ -690,13 +690,13 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple var searchItem: ItemListControllerSearch? if state.searchingMembers { - searchItem = ChannelMembersSearchItem(account: account, peerId: peerId, searchMode: .searchAdmins, cancel: { + searchItem = ChannelMembersSearchItem(context: context, peerId: peerId, searchMode: .searchAdmins, cancel: { updateState { state in return state.withUpdatedSearchingMembers(false) } }, openPeer: { _, participant in if let participant = participant?.participant, case .member = participant { - presentControllerImpl?(channelAdminController(account: account, peerId: peerId, adminId: participant.peerId, initialParticipant: participant, updated: { _ in + presentControllerImpl?(channelAdminController(context: context, peerId: peerId, adminId: participant.peerId, initialParticipant: participant, updated: { _ in updateState { state in return state.withUpdatedSearchingMembers(false) } @@ -713,14 +713,14 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple } let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(isGroup ? presentationData.strings.ChatAdmins_Title : presentationData.strings.Channel_Management_Title), leftNavigationButton: nil, rightNavigationButton: rightNavigationButton, secondaryRightNavigationButton: secondaryRightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: true) - let listState = ItemListNodeState(entries: channelAdminsControllerEntries(presentationData: presentationData, accountPeerId: account.peerId, view: view, state: state, participants: admins), style: .blocks, emptyStateItem: emptyStateItem, searchItem: searchItem, animateChanges: previous != nil && admins != nil && previous!.count >= admins!.count) + let listState = ItemListNodeState(entries: channelAdminsControllerEntries(presentationData: presentationData, accountPeerId: context.account.peerId, view: view, state: state, participants: admins), style: .blocks, emptyStateItem: emptyStateItem, searchItem: searchItem, animateChanges: previous != nil && admins != nil && previous!.count >= admins!.count) return (controllerState, (listState, arguments)) } |> afterDisposed { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] c in (controller?.navigationController as? NavigationController)?.pushViewController(c) } @@ -734,15 +734,15 @@ public func channelAdminsController(account: Account, peerId: PeerId, loadComple guard let controller = controller, let navigationController = controller.navigationController as? NavigationController else { return } - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(upgradedPeerId), keepStack: .never, animated: false, completion: { - navigationController.pushViewController(channelAdminsController(account: account, peerId: upgradedPeerId, loadCompleted: { + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(upgradedPeerId), keepStack: .never, animated: false, completion: { + navigationController.pushViewController(channelAdminsController(context: context, peerId: upgradedPeerId, loadCompleted: { f() }), animated: false) }) } controller.visibleBottomContentOffsetChanged = { offset in if case let .known(value) = offset, value < 40.0 { - account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: loadMoreControl) + context.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: loadMoreControl) } } return controller diff --git a/TelegramUI/ChannelBannedMemberController.swift b/TelegramUI/ChannelBannedMemberController.swift index 720587d34b..86bebd03a4 100644 --- a/TelegramUI/ChannelBannedMemberController.swift +++ b/TelegramUI/ChannelBannedMemberController.swift @@ -359,7 +359,7 @@ private func channelBannedMemberControllerEntries(presentationData: Presentation return entries } -public func channelBannedMemberController(account: Account, peerId: PeerId, memberId: PeerId, initialParticipant: ChannelParticipant?, updated: @escaping (TelegramChatBannedRights?) -> Void, upgradedToSupergroup: @escaping (PeerId, @escaping () -> Void) -> Void) -> ViewController { +public func channelBannedMemberController(context: AccountContext, peerId: PeerId, memberId: PeerId, initialParticipant: ChannelParticipant?, updated: @escaping (TelegramChatBannedRights?) -> Void, upgradedToSupergroup: @escaping (PeerId, @escaping () -> Void) -> Void) -> ViewController { let initialState = ChannelBannedMemberControllerState(referenceTimestamp: Int32(Date().timeIntervalSince1970), updatedFlags: nil, updatedTimeout: nil, updating: false) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) @@ -376,9 +376,9 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb var presentControllerImpl: ((ViewController, Any?) -> Void)? let peerView = Promise() - peerView.set(account.viewTracker.peerView(peerId)) + peerView.set(context.account.viewTracker.peerView(peerId)) - let arguments = ChannelBannedMemberControllerArguments(account: account, toggleRight: { rights, value in + let arguments = ChannelBannedMemberControllerArguments(account: context.account, toggleRight: { rights, value in let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { view in @@ -421,7 +421,7 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb } }) }, openTimeout: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) let intervals: [Int32] = [ 1 * 60 * 60 * 24, @@ -448,7 +448,7 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb })) items.append(ActionSheetButtonItem(title: presentationData.strings.MessageTimer_Custom, color: .accent, action: { [weak actionSheet] in actionSheet?.dismissAnimated() - presentControllerImpl?(PeerBanTimeoutController(account: account, currentValue: Int32(Date().timeIntervalSince1970), applyValue: { value in + presentControllerImpl?(PeerBanTimeoutController(context: context, currentValue: Int32(Date().timeIntervalSince1970), applyValue: { value in applyValue(value) }), nil) })) @@ -459,7 +459,7 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb ])]) presentControllerImpl?(actionSheet, nil) }, delete: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) var items: [ActionSheetItem] = [] items.append(ActionSheetButtonItem(title: presentationData.strings.GroupPermission_Delete, color: .destructive, font: .default, enabled: true, action: { [weak actionSheet] in @@ -469,7 +469,7 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb state.updating = true return state } - updateRightsDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerId, memberId: memberId, bannedRights: nil) + updateRightsDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerId, memberId: memberId, bannedRights: nil) |> deliverOnMainQueue).start(error: { _ in }, completed: { @@ -489,11 +489,11 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb if let banInfo = initialParticipant?.banInfo { keys.append(.peer(peerId: banInfo.restrictedBy, components: [])) } - let combinedView = account.postbox.combinedView(keys: keys) + let combinedView = context.account.postbox.combinedView(keys: keys) let canEdit = true - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), combinedView) + let signal = combineLatest(context.presentationData, statePromise.get(), combinedView) |> deliverOnMainQueue |> map { presentationData, state, combinedView -> (ItemListControllerState, (ItemListNodeState, ChannelBannedMemberEntry.ItemGenerationArguments)) in let channelView = combinedView.views[.peer(peerId: peerId, components: .all)] as! PeerView @@ -613,7 +613,7 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb } if peerId.namespace == Namespaces.Peer.CloudGroup { - let signal = convertGroupToSupergroup(account: account, peerId: peerId) + let signal = convertGroupToSupergroup(account: context.account, peerId: peerId) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -622,7 +622,7 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb guard let upgradedPeerId = upgradedPeerId else { return .single(nil) } - return account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: upgradedPeerId, memberId: memberId, bannedRights: cleanResolvedRights) + return context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: upgradedPeerId, memberId: memberId, bannedRights: cleanResolvedRights) |> mapToSignal { _ -> Signal in return .complete() } @@ -649,12 +649,12 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb } })) } else { - updateRightsDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerId, memberId: memberId, bannedRights: cleanResolvedRights) + updateRightsDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerId, memberId: memberId, bannedRights: cleanResolvedRights) |> deliverOnMainQueue).start(error: { _ in }, completed: { if previousRights == nil { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .genericSuccess(presentationData.strings.GroupPermission_AddSuccess)), nil) } updated(cleanResolvedRights.flags.isEmpty ? nil : cleanResolvedRights) @@ -663,7 +663,7 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb } } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) var items: [ActionSheetItem] = [] items.append(ActionSheetTextItem(title: presentationData.strings.GroupPermission_ApplyAlertText(peer.displayTitle).0)) @@ -694,7 +694,7 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb 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: channelBannedMemberControllerEntries(presentationData: presentationData, state: state, accountPeerId: account.peerId, channelView: channelView, memberView: memberView, initialParticipant: initialParticipant, initialBannedBy: initialBannedByPeer), style: .blocks, emptyStateItem: nil, animateChanges: true) + let listState = ItemListNodeState(entries: channelBannedMemberControllerEntries(presentationData: presentationData, state: state, accountPeerId: context.account.peerId, channelView: channelView, memberView: memberView, initialParticipant: initialParticipant, initialBannedBy: initialBannedByPeer), style: .blocks, emptyStateItem: nil, animateChanges: true) return (controllerState, (listState, arguments)) } @@ -702,7 +702,7 @@ public func channelBannedMemberController(account: Account, peerId: PeerId, memb actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) dismissImpl = { [weak controller] in controller?.dismiss() } diff --git a/TelegramUI/ChannelBlacklistController.swift b/TelegramUI/ChannelBlacklistController.swift index 28176e7cf4..7f0fa2bd38 100644 --- a/TelegramUI/ChannelBlacklistController.swift +++ b/TelegramUI/ChannelBlacklistController.swift @@ -256,7 +256,7 @@ private func channelBlacklistControllerEntries(presentationData: PresentationDat return entries } -public func channelBlacklistController(account: Account, peerId: PeerId) -> ViewController { +public func channelBlacklistController(context: AccountContext, peerId: PeerId) -> ViewController { let statePromise = ValuePromise(ChannelBlacklistControllerState(referenceTimestamp: Int32(Date().timeIntervalSince1970)), ignoreRepeated: true) let stateValue = Atomic(value: ChannelBlacklistControllerState(referenceTimestamp: Int32(Date().timeIntervalSince1970))) let updateState: ((ChannelBlacklistControllerState) -> ChannelBlacklistControllerState) -> Void = { f in @@ -275,10 +275,10 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View actionsDisposable.add(removePeerDisposable) let peerView = Promise() - peerView.set(account.viewTracker.peerView(peerId)) + peerView.set(context.account.viewTracker.peerView(peerId)) let blacklistPromise = Promise<[RenderedChannelParticipant]?>(nil) - let arguments = ChannelBlacklistControllerArguments(account: account, setPeerIdWithRevealedOptions: { peerId, fromPeerId in + let arguments = ChannelBlacklistControllerArguments(account: context.account, setPeerIdWithRevealedOptions: { peerId, fromPeerId in updateState { state in if (peerId == nil && fromPeerId == state.peerIdWithRevealedOptions) || (peerId != nil && fromPeerId == nil) { return state.withUpdatedPeerIdWithRevealedOptions(peerId) @@ -288,29 +288,29 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View } }, addPeer: { var dismissController: (() -> Void)? - let controller = ChannelMembersSearchController(account: account, peerId: peerId, mode: .ban, openPeer: { peer, participant in + let controller = ChannelMembersSearchController(context: context, peerId: peerId, mode: .ban, openPeer: { peer, participant in if let participant = participant { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } switch participant.participant { case .creator: return case let .member(_, _, adminInfo, _): - if let adminInfo = adminInfo, adminInfo.promotedBy != account.peerId { + if let adminInfo = adminInfo, adminInfo.promotedBy != context.account.peerId { presentControllerImpl?(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.Channel_Members_AddBannedErrorAdmin, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) return } } } - let _ = (account.postbox.loadedPeerWithId(peerId) + let _ = (context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { channel in guard let _ = channel as? TelegramChannel else { return } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let progress = OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .loading(cancelled: nil)) presentControllerImpl?(progress, nil) - removePeerDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerId, memberId: peer.id, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: Int32.max)) + removePeerDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerId, memberId: peer.id, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: Int32.max)) |> deliverOnMainQueue).start(error: { [weak progress] _ in progress?.dismiss() dismissController?() @@ -329,7 +329,7 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View return $0.withUpdatedRemovingPeerId(memberId) } - removePeerDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerId, memberId: memberId, bannedRights: nil) |> deliverOnMainQueue).start(error: { _ in + removePeerDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerId, memberId: memberId, bannedRights: nil) |> deliverOnMainQueue).start(error: { _ in updateState { return $0.withUpdatedRemovingPeerId(nil) } @@ -345,7 +345,7 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View guard let channel = peerView.peers[peerId] as? TelegramChannel else { return } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) var items: [ActionSheetItem] = [] if !participant.peer.displayTitle.isEmpty { @@ -353,7 +353,7 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View } items.append(ActionSheetButtonItem(title: presentationData.strings.GroupRemoved_ViewUserInfo, action: { [weak actionSheet] in actionSheet?.dismissAnimated() - if let infoController = peerInfoController(account: account, peer: participant.peer) { + if let infoController = peerInfoController(context: context, peer: participant.peer) { pushControllerImpl?(infoController) } })) @@ -364,10 +364,10 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View updateState { return $0.withUpdatedRemovingPeerId(memberId) } - let signal = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerId, memberId: memberId, bannedRights: nil) + let signal = context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerId, memberId: memberId, bannedRights: nil) |> ignoreValues |> then( - account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.addMember(account: account, peerId: peerId, memberId: memberId) + context.peerChannelMemberCategoriesContextsManager.addMember(account: context.account, peerId: peerId, memberId: memberId) |> ignoreValues ) removePeerDisposable.set((signal |> deliverOnMainQueue).start(error: { _ in @@ -388,7 +388,7 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View return $0.withUpdatedRemovingPeerId(memberId) } - removePeerDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerId, memberId: memberId, bannedRights: nil) |> deliverOnMainQueue).start(error: { _ in + removePeerDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerId, memberId: memberId, bannedRights: nil) |> deliverOnMainQueue).start(error: { _ in updateState { return $0.withUpdatedRemovingPeerId(nil) } @@ -407,7 +407,7 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View }) }) - let (listDisposable, loadMoreControl) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.banned(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, updated: { listState in + let (listDisposable, loadMoreControl) = context.peerChannelMemberCategoriesContextsManager.banned(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, updated: { listState in if case .loading(true) = listState.loadingState, listState.list.isEmpty { blacklistPromise.set(.single(nil)) } else { @@ -418,7 +418,7 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View let previousParticipantsValue = Atomic<[RenderedChannelParticipant]?>(value: nil) - let signal = combineLatest(queue: .mainQueue(), (account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), peerView.get(), blacklistPromise.get()) + let signal = combineLatest(queue: .mainQueue(), context.presentationData, statePromise.get(), peerView.get(), blacklistPromise.get()) |> deliverOnMainQueue |> map { presentationData, state, view, participants -> (ItemListControllerState, (ItemListNodeState, ChannelBlacklistEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? @@ -464,7 +464,7 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View var searchItem: ItemListControllerSearch? if state.searchingMembers { - searchItem = ChannelMembersSearchItem(account: account, peerId: peerId, searchMode: .searchKicked, cancel: { + searchItem = ChannelMembersSearchItem(context: context, peerId: peerId, searchMode: .searchKicked, cancel: { updateState { state in return state.withUpdatedSearchingMembers(false) } @@ -486,7 +486,7 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, p in if let controller = controller { controller.present(c, in: .window(.root), with: p) @@ -501,7 +501,7 @@ public func channelBlacklistController(account: Account, peerId: PeerId) -> View } controller.visibleBottomContentOffsetChanged = { offset in if case let .known(value) = offset, value < 40.0 { - account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: loadMoreControl) + context.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: loadMoreControl) } } return controller diff --git a/TelegramUI/ChannelInfoController.swift b/TelegramUI/ChannelInfoController.swift index 59ec443cb4..23a2658a4b 100644 --- a/TelegramUI/ChannelInfoController.swift +++ b/TelegramUI/ChannelInfoController.swift @@ -524,7 +524,7 @@ private func valuesRequiringUpdate(state: ChannelInfoState, view: PeerView) -> ( } } -public func channelInfoController(account: Account, peerId: PeerId) -> ViewController { +public func channelInfoController(context: AccountContext, peerId: PeerId) -> ViewController { let statePromise = ValuePromise(ChannelInfoState(), ignoreRepeated: true) let stateValue = Atomic(value: ChannelInfoState()) let updateState: ((ChannelInfoState) -> ChannelInfoState) -> Void = { f in @@ -564,13 +564,13 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr var displayContextMenuImpl: ((ChannelInfoEntryTag, String) -> Void)? var aboutLinkActionImpl: ((TextLinkItemActionType, TextLinkItem) -> Void)? - let arguments = ChannelInfoControllerArguments(account: account, avatarAndNameInfoContext: avatarAndNameInfoContext, tapAvatarAction: { - let _ = (account.postbox.loadedPeerWithId(peerId) |> take(1) |> deliverOnMainQueue).start(next: { peer in + let arguments = ChannelInfoControllerArguments(account: context.account, avatarAndNameInfoContext: avatarAndNameInfoContext, tapAvatarAction: { + let _ = (context.account.postbox.loadedPeerWithId(peerId) |> take(1) |> deliverOnMainQueue).start(next: { peer in if peer.profileImageRepresentations.isEmpty { return } - let galleryController = AvatarGalleryController(account: 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 @@ -584,10 +584,10 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr }, changeProfilePhoto: { endEditingImpl?() - let _ = (account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in + let _ = (context.account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in return (transaction.getPeer(peerId), currentSearchBotsConfiguration(transaction: transaction)) } |> deliverOnMainQueue).start(next: { peer, searchBotsConfiguration in - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: .custom, theme: presentationData.theme) legacyController.statusBar.statusBarStyle = .Ignore @@ -609,21 +609,22 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr 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) updateState { $0.withUpdatedUpdatingAvatar(.image(representation, true)) } - updateAvatarDisposable.set((updatePeerPhoto(postbox: account.postbox, network: account.network, stateManager: account.stateManager, accountPeerId: account.peerId, peerId: peerId, photo: uploadedPeerPhoto(postbox: account.postbox, network: account.network, resource: resource), mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) - }) |> deliverOnMainQueue).start(next: { result in + updateAvatarDisposable.set((updatePeerPhoto(postbox: context.account.postbox, network: context.account.network, stateManager: context.account.stateManager, accountPeerId: context.account.peerId, peerId: peerId, photo: uploadedPeerPhoto(postbox: context.account.postbox, network: context.account.network, resource: resource), mapResourceToAvatarSizes: { resource, representations in + return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations) + }) + |> deliverOnMainQueue).start(next: { result in switch result { - case .complete: - updateState { - $0.withUpdatedUpdatingAvatar(nil) - } - case .progress: - break + case .complete: + updateState { + $0.withUpdatedUpdatingAvatar(nil) + } + case .progress: + break } })) } @@ -632,7 +633,7 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr let mixin = TGMediaAvatarMenuMixin(context: legacyController.context, parentController: emptyController, hasSearchButton: true, hasDeleteButton: hasPhotos, 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: peer?.displayTitle, completion: { result in + let controller = WebSearchController(context: context, peer: peer, configuration: searchBotsConfiguration, mode: .avatar(initialQuery: peer?.displayTitle, completion: { result in assetsController?.dismiss() completedImpl(result) })) @@ -652,8 +653,8 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr return $0.withUpdatedUpdatingAvatar(.none) } } - updateAvatarDisposable.set((updatePeerPhoto(postbox: account.postbox, network: account.network, stateManager: account.stateManager, accountPeerId: account.peerId, peerId: peerId, photo: nil, mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) + updateAvatarDisposable.set((updatePeerPhoto(postbox: context.account.postbox, network: context.account.network, stateManager: context.account.stateManager, accountPeerId: context.account.peerId, peerId: peerId, photo: nil, mapResourceToAvatarSizes: { resource, representations in + return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations) }) |> deliverOnMainQueue).start(next: { result in switch result { case .complete: @@ -692,10 +693,10 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr return state } }, openChannelTypeSetup: { - presentControllerImpl?(channelVisibilityController(account: account, peerId: peerId, mode: .generic, upgradedToSupergroup: { _, f in f() }), ViewControllerPresentationArguments(presentationAnimation: ViewControllerPresentationAnimation.modalSheet)) + presentControllerImpl?(channelVisibilityController(context: context, peerId: peerId, mode: .generic, upgradedToSupergroup: { _, f in f() }), ViewControllerPresentationArguments(presentationAnimation: ViewControllerPresentationAnimation.modalSheet)) }, changeNotificationMuteSettings: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - let _ = (account.postbox.transaction { transaction -> (TelegramPeerNotificationSettings, GlobalNotificationSettings) in + let presentationData = context.currentPresentationData.with { $0 } + let _ = (context.account.postbox.transaction { transaction -> (TelegramPeerNotificationSettings, GlobalNotificationSettings) in let peerSettings: TelegramPeerNotificationSettings = (transaction.getPeerNotificationSettings(peerId) as? TelegramPeerNotificationSettings) ?? TelegramPeerNotificationSettings.defaultSettings let globalSettings: GlobalNotificationSettings = (transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications) as? GlobalNotificationSettings) ?? GlobalNotificationSettings.defaultSettings return (peerSettings, globalSettings) @@ -708,38 +709,38 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr soundSettings = NotificationSoundSettings(value: peerSettings.messageSound) } let controller = notificationMuteSettingsController(presentationData: presentationData, notificationSettings: globalSettings.effective.groupChats, soundSettings: soundSettings, openSoundSettings: { - let controller = notificationSoundSelectionController(account: account, isModal: true, currentSound: peerSettings.messageSound, defaultSound: globalSettings.effective.groupChats.sound, completion: { sound in - let _ = updatePeerNotificationSoundInteractive(account: account, peerId: peerId, sound: sound).start() + let controller = notificationSoundSelectionController(context: context, isModal: true, currentSound: peerSettings.messageSound, defaultSound: globalSettings.effective.groupChats.sound, completion: { sound in + let _ = updatePeerNotificationSoundInteractive(account: context.account, peerId: peerId, sound: sound).start() }) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, updateSettings: { value in - changeMuteSettingsDisposable.set(updatePeerMuteSetting(account: account, peerId: peerId, muteInterval: value).start()) + changeMuteSettingsDisposable.set(updatePeerMuteSetting(account: context.account, peerId: peerId, muteInterval: value).start()) }) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) }, openSharedMedia: { - if let controller = peerSharedMediaController(account: account, peerId: peerId) { + if let controller = peerSharedMediaController(context: context, peerId: peerId) { pushControllerImpl?(controller) } }, openAdmins: { - pushControllerImpl?(channelAdminsController(account: account, peerId: peerId)) + pushControllerImpl?(channelAdminsController(context: context, peerId: peerId)) }, openMembers: { - pushControllerImpl?(channelMembersController(account: account, peerId: peerId)) + pushControllerImpl?(channelMembersController(context: context, peerId: peerId)) }, openBanned: { - pushControllerImpl?(channelBlacklistController(account: account, peerId: peerId)) + pushControllerImpl?(channelBlacklistController(context: context, peerId: peerId)) }, reportChannel: { - presentControllerImpl?(peerReportOptionsController(account: account, subject: .peer(peerId), present: { c, a in + presentControllerImpl?(peerReportOptionsController(context: context, subject: .peer(peerId), present: { c, a in presentControllerImpl?(c, a) }), nil) }, leaveChannel: { - let _ = (account.postbox.transaction { transaction -> Peer? in + let _ = (context.account.postbox.transaction { transaction -> Peer? in return transaction.getPeer(peerId) } |> deliverOnMainQueue).start(next: { peer in guard let peer = peer else { return } - 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() @@ -756,14 +757,14 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) }, deleteChannel: { - let _ = (account.postbox.transaction { transaction -> Peer? in + let _ = (context.account.postbox.transaction { transaction -> Peer? in return transaction.getPeer(peerId) } |> deliverOnMainQueue).start(next: { peer in guard let peer = peer else { return } - 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() @@ -781,18 +782,18 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) }, displayAddressNameContextMenu: { text in - let shareController = ShareController(account: account, subject: .url(text)) + let shareController = ShareController(context: context, subject: .url(text)) presentControllerImpl?(shareController, nil) }, displayContextMenu: { tag, text in displayContextMenuImpl?(tag, text) }, aboutLinkAction: { action, itemLink in aboutLinkActionImpl?(action, itemLink) }, toggleSignatures: { enabled in - actionsDisposable.add(toggleShouldChannelMessagesSignatures(account: account, peerId: peerId, enabled: enabled).start()) + actionsDisposable.add(toggleShouldChannelMessagesSignatures(account: context.account, peerId: peerId, enabled: enabled).start()) }) let globalNotificationsKey: PostboxViewKey = .preferences(keys: Set([PreferencesKeys.globalNotifications])) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), account.viewTracker.peerView(peerId), account.postbox.combinedView(keys: [globalNotificationsKey])) + let signal = combineLatest(context.presentationData, statePromise.get(), context.account.viewTracker.peerView(peerId), context.account.postbox.combinedView(keys: [globalNotificationsKey])) |> map { presentationData, state, view, combinedView -> (ItemListControllerState, (ItemListNodeState, ChannelInfoEntry.ItemGenerationArguments)) in let peer = peerViewMainPeer(view) @@ -852,7 +853,7 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr let updateTitle: Signal if let titleValue = updateValues.title { - updateTitle = updatePeerTitle(account: account, peerId: peerId, title: titleValue) + updateTitle = updatePeerTitle(account: context.account, peerId: peerId, title: titleValue) |> mapError { _ in return Void() } } else { updateTitle = .complete() @@ -860,7 +861,7 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr let updateDescription: Signal if let descriptionValue = updateValues.description { - updateDescription = updatePeerDescription(account: account, peerId: peerId, description: descriptionValue.isEmpty ? nil : descriptionValue) + updateDescription = updatePeerDescription(account: context.account, peerId: peerId, description: descriptionValue.isEmpty ? nil : descriptionValue) |> mapError { _ in return Void() } } else { updateDescription = .complete() @@ -894,14 +895,14 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr } let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.UserInfo_Title), leftNavigationButton: leftNavigationButton, rightNavigationButton: rightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) - let listState = ItemListNodeState(entries: channelInfoEntries(account: account, presentationData: presentationData, view: view, globalNotificationSettings: globalNotificationSettings, state: state), style: .plain) + let listState = ItemListNodeState(entries: channelInfoEntries(account: context.account, presentationData: presentationData, view: view, globalNotificationSettings: globalNotificationSettings, state: state), style: .plain) return (controllerState, (listState, arguments)) } |> afterDisposed { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] value in (controller?.navigationController as? NavigationController)?.pushViewController(value) @@ -950,7 +951,7 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr } displayContextMenuImpl = { [weak controller] tag, text 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 { @@ -980,7 +981,7 @@ public func channelInfoController(account: Account, peerId: PeerId) -> ViewContr } aboutLinkActionImpl = { [weak controller] action, itemLink in if let controller = controller { - handlePeerInfoAboutTextAction(account: account, peerId: peerId, navigateDisposable: navigateDisposable, controller: controller, action: action, itemLink: itemLink) + handlePeerInfoAboutTextAction(context: context, peerId: peerId, navigateDisposable: navigateDisposable, controller: controller, action: action, itemLink: itemLink) } } endEditingImpl = { diff --git a/TelegramUI/ChannelMembersController.swift b/TelegramUI/ChannelMembersController.swift index a3d1a59b27..40465d3760 100644 --- a/TelegramUI/ChannelMembersController.swift +++ b/TelegramUI/ChannelMembersController.swift @@ -245,7 +245,7 @@ private struct ChannelMembersControllerState: Equatable { } } -private func ChannelMembersControllerEntries(account: Account, presentationData: PresentationData, view: PeerView, state: ChannelMembersControllerState, participants: [RenderedChannelParticipant]?) -> [ChannelMembersEntry] { +private func ChannelMembersControllerEntries(context: Account, presentationData: PresentationData, view: PeerView, state: ChannelMembersControllerState, participants: [RenderedChannelParticipant]?) -> [ChannelMembersEntry] { if participants == nil || participants?.count == nil { return [] } @@ -309,7 +309,7 @@ private func ChannelMembersControllerEntries(account: Account, presentationData: return entries } -public func channelMembersController(account: Account, peerId: PeerId) -> ViewController { +public func channelMembersController(context: AccountContext, peerId: PeerId) -> ViewController { let statePromise = ValuePromise(ChannelMembersControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: ChannelMembersControllerState()) let updateState: ((ChannelMembersControllerState) -> ChannelMembersControllerState) -> Void = { f in @@ -329,12 +329,12 @@ public func channelMembersController(account: Account, peerId: PeerId) -> ViewCo let peersPromise = Promise<[RenderedChannelParticipant]?>(nil) - let arguments = ChannelMembersControllerArguments(account: account, addMember: { + let arguments = ChannelMembersControllerArguments(account: context.account, addMember: { actionsDisposable.add((peersPromise.get() |> take(1) |> deliverOnMainQueue).start(next: { members in let disabledIds = members?.compactMap({$0.peer.id}) ?? [] - let contactsController = ContactMultiselectionController(account: account, mode: .peerSelection(searchChatList: false), options: [], filters: [.excludeSelf, .disable(disabledIds)]) + let contactsController = ContactMultiselectionController(context: context, mode: .peerSelection(searchChatList: false), options: [], filters: [.excludeSelf, .disable(disabledIds)]) addMembersDisposable.set((contactsController.result |> deliverOnMainQueue @@ -342,7 +342,7 @@ public func channelMembersController(account: Account, peerId: PeerId) -> ViewCo |> mapToSignal { [weak contactsController] contacts -> Signal in contactsController?.displayProgress = true - let signal = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.addMembers(account: account, peerId: peerId, memberIds: contacts.compactMap({ contact -> PeerId? in + let signal = context.peerChannelMemberCategoriesContextsManager.addMembers(account: context.account, peerId: peerId, memberIds: contacts.compactMap({ contact -> PeerId? in switch contact { case let .peer(contactId): return contactId @@ -358,7 +358,7 @@ public func channelMembersController(account: Account, peerId: PeerId) -> ViewCo contactsController?.dismiss() } }).start(error: { [weak contactsController] error in - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let text: String switch error { case .limitExceeded: @@ -388,30 +388,30 @@ public func channelMembersController(account: Account, peerId: PeerId) -> ViewCo return $0.withUpdatedRemovingPeerId(memberId) } - removePeerDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerId, memberId: memberId, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: Int32.max)) + removePeerDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerId, memberId: memberId, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: Int32.max)) |> deliverOnMainQueue).start(completed: { updateState { return $0.withUpdatedRemovingPeerId(nil) } })) }, openPeer: { peer in - if let controller = peerInfoController(account: account, peer: peer) { + if let controller = peerInfoController(context: context, peer: peer) { pushControllerImpl?(controller) } }, inviteViaLink: { - presentControllerImpl?(channelVisibilityController(account: account, peerId: peerId, mode: .privateLink, upgradedToSupergroup: { _, f in f() }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + presentControllerImpl?(channelVisibilityController(context: context, peerId: peerId, mode: .privateLink, upgradedToSupergroup: { _, f in f() }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) - let peerView = account.viewTracker.peerView(peerId) + let peerView = context.account.viewTracker.peerView(peerId) - let (disposable, loadMoreControl) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recent(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, updated: { state in + let (disposable, loadMoreControl) = context.peerChannelMemberCategoriesContextsManager.recent(postbox: contextaccount.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, updated: { state in peersPromise.set(.single(state.list)) }) actionsDisposable.add(disposable) var previousPeers: [RenderedChannelParticipant]? - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), peerView, peersPromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get(), peerView, peersPromise.get()) |> deliverOnMainQueue |> map { presentationData, state, view, peers -> (ItemListControllerState, (ItemListNodeState, ChannelMembersEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? @@ -442,12 +442,12 @@ public func channelMembersController(account: Account, peerId: PeerId) -> ViewCo var searchItem: ItemListControllerSearch? if state.searchingMembers { - searchItem = ChannelMembersSearchItem(account: account, peerId: peerId, cancel: { + searchItem = ChannelMembersSearchItem(context: context, peerId: peerId, cancel: { updateState { state in return state.withUpdatedSearchingMembers(false) } }, openPeer: { peer, _ in - if let infoController = peerInfoController(account: account, peer: peer) { + if let infoController = peerInfoController(context: context, peer: peer) { pushControllerImpl?(infoController) // arguments.pushController(infoController) } @@ -465,14 +465,14 @@ public func channelMembersController(account: Account, peerId: PeerId) -> ViewCo 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: 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(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) return (controllerState, (listState, arguments)) } |> afterDisposed { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, p in if let controller = controller { controller.present(c, in: .window(.root), with: p) @@ -485,7 +485,7 @@ public func channelMembersController(account: Account, peerId: PeerId) -> ViewCo } controller.visibleBottomContentOffsetChanged = { offset in if let loadMoreControl = loadMoreControl, case let .known(value) = offset, value < 40.0 { - account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: loadMoreControl) + context.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: loadMoreControl) } } return controller diff --git a/TelegramUI/ChannelMembersSearchContainerNode.swift b/TelegramUI/ChannelMembersSearchContainerNode.swift index 5c40857d05..80b87ba041 100644 --- a/TelegramUI/ChannelMembersSearchContainerNode.swift +++ b/TelegramUI/ChannelMembersSearchContainerNode.swift @@ -179,7 +179,7 @@ private struct ChannelMembersSearchContainerState: Equatable { } final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNode { - private let account: Account + private let context: AccountContext private let openPeer: (Peer, RenderedChannelParticipant?) -> Void private let mode: ChannelMembersSearchMode @@ -199,12 +199,12 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod private let themeAndStringsPromise: Promise<(PresentationTheme, PresentationStrings, PresentationPersonNameOrder, PresentationPersonNameOrder, PresentationDateTimeFormat)> - init(account: Account, peerId: PeerId, mode: ChannelMembersSearchMode, filters: [ChannelMembersSearchFilter], openPeer: @escaping (Peer, RenderedChannelParticipant?) -> Void, updateActivity: @escaping (Bool) -> Void, present: @escaping (ViewController, Any?) -> Void) { - self.account = account + init(context: AccountContext, peerId: PeerId, mode: ChannelMembersSearchMode, filters: [ChannelMembersSearchFilter], openPeer: @escaping (Peer, RenderedChannelParticipant?) -> Void, updateActivity: @escaping (Bool) -> Void, present: @escaping (ViewController, Any?) -> Void) { + self.context = context self.openPeer = openPeer self.mode = mode - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.themeAndStringsPromise = Promise((self.presentationData.theme, self.presentationData.strings, self.presentationData.nameSortOrder, self.presentationData.nameDisplayOrder, self.presentationData.dateTimeFormat)) self.dimNode = ASDisplayNode() @@ -238,13 +238,13 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod return state } }, promotePeer: { participant in - present(channelAdminController(account: account, peerId: peerId, adminId: participant.peer.id, initialParticipant: participant.participant, updated: { _ in + present(channelAdminController(context: context, peerId: peerId, adminId: participant.peer.id, initialParticipant: participant.participant, updated: { _ in }, upgradedToSupergroup: { _, f in f() }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, restrictPeer: { participant in - present(channelBannedMemberController(account: account, peerId: peerId, memberId: participant.peer.id, initialParticipant: participant.participant, updated: { _ in + present(channelBannedMemberController(context: context, peerId: peerId, memberId: participant.peer.id, initialParticipant: participant.participant, updated: { _ in }, upgradedToSupergroup: { _, f in f() }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, removePeer: { memberId in - let signal = account.postbox.loadedPeerWithId(memberId) + let signal = context.account.postbox.loadedPeerWithId(memberId) |> deliverOnMainQueue |> mapToSignal { peer -> Signal in let result = ValuePromise() @@ -261,7 +261,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod if peerId.namespace == Namespaces.Peer.CloudChannel { if case .searchAdmins = mode { - return account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: account, peerId: peerId, memberId: memberId, adminRights: TelegramChatAdminRights(flags: [])) + return context.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(account: context.account, peerId: peerId, memberId: memberId, adminRights: TelegramChatAdminRights(flags: [])) |> afterDisposed { Queue.mainQueue().async { updateState { state in @@ -273,7 +273,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod } } - return account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerId, memberId: memberId, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: Int32.max)) + return context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerId, memberId: memberId, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: Int32.max)) |> afterDisposed { Queue.mainQueue().async { updateState { state in @@ -286,7 +286,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod } if case .searchAdmins = mode { - return removeGroupAdmin(account: account, peerId: peerId, adminId: memberId) + return removeGroupAdmin(account: context.account, peerId: peerId, adminId: memberId) |> `catch` { _ -> Signal in return .complete() } @@ -300,7 +300,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod } } - return removePeerMember(account: account, peerId: peerId, memberId: memberId) + return removePeerMember(account: context.account, peerId: peerId, memberId: memberId) |> deliverOnMainQueue |> afterDisposed { updateState { state in @@ -317,7 +317,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod }) let themeAndStringsPromise = self.themeAndStringsPromise - let foundItems = combineLatest(searchQuery.get(), account.postbox.peerView(id: peerId) |> take(1)) + let foundItems = combineLatest(searchQuery.get(), context.account.postbox.peerView(id: peerId) |> take(1)) |> mapToSignal { query, peerView -> Signal<[ChannelMembersSearchEntry]?, NoError> in guard let query = query, !query.isEmpty else { return .single(nil) @@ -330,7 +330,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod switch mode { case .searchMembers, .banAndPromoteActions: foundGroupMembers = Signal { subscriber in - let (disposable, _) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recent(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, searchQuery: 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, updated: { state in if case .ready = state.loadingState { subscriber.putNext(state.list) } @@ -341,11 +341,11 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod foundMembers = .single([]) case .inviteActions: foundGroupMembers = .single([]) - foundMembers = channelMembers(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, category: .recent(.search(query))) + foundMembers = channelMembers(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, category: .recent(.search(query))) |> map { $0 ?? [] } case .searchAdmins: foundGroupMembers = Signal { subscriber in - let (disposable, _) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.admins(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, searchQuery: query, updated: { state in + let (disposable, _) = context.peerChannelMemberCategoriesContextsManager.admins(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, searchQuery: query, updated: { state in if case .ready = state.loadingState { subscriber.putNext(state.list) } @@ -355,7 +355,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod foundMembers = .single([]) case .searchBanned: foundGroupMembers = Signal { subscriber in - let (disposable, _) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.restricted(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, searchQuery: query, updated: { state in + let (disposable, _) = context.peerChannelMemberCategoriesContextsManager.restricted(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, searchQuery: query, updated: { state in if case .ready = state.loadingState { subscriber.putNext(state.list) subscriber.putCompletion() @@ -365,10 +365,10 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod } |> runOn(Queue.mainQueue()) foundMembers = Signal { subscriber in - let (disposable, _) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recent(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, searchQuery: 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, updated: { state in if case .ready = state.loadingState { subscriber.putNext(state.list.filter({ participant in - return participant.peer.id != account.peerId + return participant.peer.id != context.account.peerId })) } }) @@ -377,7 +377,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod |> runOn(Queue.mainQueue()) case .searchKicked: foundGroupMembers = Signal { subscriber in - let (disposable, _) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.banned(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, searchQuery: query, updated: { state in + let (disposable, _) = context.peerChannelMemberCategoriesContextsManager.banned(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, searchQuery: query, updated: { state in if case .ready = state.loadingState { subscriber.putNext(state.list) subscriber.putCompletion() @@ -393,8 +393,8 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod let foundRemotePeers: Signal<([FoundPeer], [FoundPeer]), NoError> switch mode { case .inviteActions, .banAndPromoteActions: - foundContacts = account.postbox.searchContacts(query: query.lowercased()) - foundRemotePeers = .single(([], [])) |> then(searchPeers(account: account, query: query) + foundContacts = context.account.postbox.searchContacts(query: query.lowercased()) + foundRemotePeers = .single(([], [])) |> then(searchPeers(account: context.account, query: query) |> delay(0.2, queue: Queue.concurrentDefaultQueue())) case .searchMembers, .searchBanned, .searchKicked, .searchAdmins: foundContacts = .single(([], [:])) @@ -416,7 +416,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod } switch mode { case .inviteActions, .banAndPromoteActions: - existingPeerIds.insert(account.peerId) + existingPeerIds.insert(context.account.peerId) case .searchMembers, .searchAdmins, .searchBanned, .searchKicked: break } @@ -455,14 +455,14 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod } if canPromote { if let bannedRights = bannedRights { - if bannedRights.restrictedBy != account.peerId && !channel.flags.contains(.isCreator) { + if bannedRights.restrictedBy != context.account.peerId && !channel.flags.contains(.isCreator) { canPromote = false } } } if canRestrict { if let adminRights = adminRights { - if adminRights.promotedBy != account.peerId && !channel.flags.contains(.isCreator) { + if adminRights.promotedBy != context.account.peerId && !channel.flags.contains(.isCreator) { canRestrict = false } } @@ -648,7 +648,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod peers[creator.id] = creator } peers[peer.id] = peer - renderedParticipant = RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(flags: .groupSpecific), promotedBy: creatorPeer?.id ?? account.peerId, canBeEditedByAccountPeer: creatorPeer?.id == account.peerId), banInfo: nil), peer: peer, peers: peers) + renderedParticipant = RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(flags: .groupSpecific), promotedBy: creatorPeer?.id ?? context.account.peerId, canBeEditedByAccountPeer: creatorPeer?.id == context.account.peerId), banInfo: nil), peer: peer, peers: peers) case .member: var peers: [PeerId: Peer] = [:] peers[peer.id] = peer @@ -688,7 +688,7 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod } switch mode { case .inviteActions, .banAndPromoteActions: - existingPeerIds.insert(account.peerId) + existingPeerIds.insert(context.account.peerId) case .searchMembers, .searchAdmins, .searchBanned, .searchKicked: break } @@ -865,12 +865,12 @@ final class ChannelMembersSearchContainerNode: SearchDisplayControllerContentNod let previousEntries = previousSearchItems.swap(entries) updateActivity(false) let firstTime = previousEntries == nil - let transition = channelMembersSearchContainerPreparedRecentTransition(from: previousEntries ?? [], to: entries ?? [], isSearching: entries != nil, account: account, theme: themeAndStrings.0, strings: themeAndStrings.1, nameSortOrder: themeAndStrings.2, nameDisplayOrder: themeAndStrings.3, interaction: interaction) + let transition = channelMembersSearchContainerPreparedRecentTransition(from: previousEntries ?? [], to: entries ?? [], isSearching: entries != nil, account: context.account, theme: themeAndStrings.0, strings: themeAndStrings.1, nameSortOrder: themeAndStrings.2, nameDisplayOrder: themeAndStrings.3, interaction: interaction) strongSelf.enqueueTransition(transition, firstTime: firstTime) } })) - 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/ChannelMembersSearchController.swift b/TelegramUI/ChannelMembersSearchController.swift index 83d15177ff..522be23b4c 100644 --- a/TelegramUI/ChannelMembersSearchController.swift +++ b/TelegramUI/ChannelMembersSearchController.swift @@ -17,7 +17,7 @@ enum ChannelMembersSearchFilter { final class ChannelMembersSearchController: ViewController { private let queue = Queue() - private let account: Account + private let context: AccountContext private let peerId: PeerId private let mode: ChannelMembersSearchControllerMode private let filters: [ChannelMembersSearchFilter] @@ -33,13 +33,13 @@ final class ChannelMembersSearchController: ViewController { private var searchContentNode: NavigationBarSearchContentNode? - init(account: Account, peerId: PeerId, mode: ChannelMembersSearchControllerMode, filters: [ChannelMembersSearchFilter] = [], openPeer: @escaping (Peer, RenderedChannelParticipant?) -> Void) { - self.account = account + init(context: AccountContext, peerId: PeerId, mode: ChannelMembersSearchControllerMode, filters: [ChannelMembersSearchFilter] = [], openPeer: @escaping (Peer, RenderedChannelParticipant?) -> Void) { + self.context = context self.peerId = peerId self.mode = mode self.openPeer = openPeer self.filters = filters - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -68,7 +68,7 @@ final class ChannelMembersSearchController: ViewController { } override func loadDisplayNode() { - self.displayNode = ChannelMembersSearchControllerNode(account: self.account, presentationData: self.presentationData, peerId: self.peerId, mode: self.mode, filters: self.filters) + self.displayNode = ChannelMembersSearchControllerNode(context: self.context, presentationData: self.presentationData, peerId: self.peerId, mode: self.mode, filters: self.filters) self.controllerNode.navigationBar = self.navigationBar self.controllerNode.requestActivateSearch = { [weak self] in self?.activateSearch() diff --git a/TelegramUI/ChannelMembersSearchControllerNode.swift b/TelegramUI/ChannelMembersSearchControllerNode.swift index 54011c74eb..01b27be722 100644 --- a/TelegramUI/ChannelMembersSearchControllerNode.swift +++ b/TelegramUI/ChannelMembersSearchControllerNode.swift @@ -83,7 +83,7 @@ private func preparedTransition(from fromEntries: [ChannelMembersSearchEntry]?, } class ChannelMembersSearchControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private let peerId: PeerId private let mode: ChannelMembersSearchControllerMode private let filters: [ChannelMembersSearchFilter] @@ -106,8 +106,8 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { private var disposable: Disposable? private var listControl: PeerChannelMemberCategoryControl? - init(account: Account, presentationData: PresentationData, peerId: PeerId, mode: ChannelMembersSearchControllerMode, filters: [ChannelMembersSearchFilter]) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, peerId: PeerId, mode: ChannelMembersSearchControllerMode, filters: [ChannelMembersSearchFilter]) { + self.context = context self.listNode = ListView() self.peerId = peerId self.mode = mode @@ -133,7 +133,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { let disposableAndLoadMoreControl: (Disposable, PeerChannelMemberCategoryControl?) if peerId.namespace == Namespaces.Peer.CloudGroup { - let disposable = (account.postbox.peerView(id: peerId) + let disposable = (context.account.postbox.peerView(id: peerId) |> deliverOnMainQueue).start(next: { [weak self] peerView in guard let strongSelf = self else { return @@ -166,7 +166,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { var enabled = true switch mode { case .ban: - if peer.id == account.peerId { + if peer.id == context.account.peerId { continue } for filter in filters { @@ -180,7 +180,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { } } case .promote: - if peer.id == account.peerId { + if peer.id == context.account.peerId { continue } for filter in filters { @@ -206,7 +206,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { var peers: [PeerId: Peer] = [:] peers[creator.id] = creator peers[peer.id] = peer - renderedParticipant = RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(flags: .groupSpecific), promotedBy: creator.id, canBeEditedByAccountPeer: creator.id == account.peerId), banInfo: nil), peer: peer, peers: peers) + renderedParticipant = RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(flags: .groupSpecific), promotedBy: creator.id, canBeEditedByAccountPeer: creator.id == context.account.peerId), banInfo: nil), peer: peer, peers: peers) case .member: var peers: [PeerId: Peer] = [:] peers[peer.id] = peer @@ -218,11 +218,11 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { } let previous = previousEntries.swap(entries) - strongSelf.enqueueTransition(preparedTransition(from: previous, to: entries, account: account, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, nameSortOrder: strongSelf.presentationData.nameSortOrder, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder, interaction: interaction)) + strongSelf.enqueueTransition(preparedTransition(from: previous, to: entries, account: context.account, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, nameSortOrder: strongSelf.presentationData.nameSortOrder, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder, interaction: interaction)) }) disposableAndLoadMoreControl = (disposable, nil) } else { - disposableAndLoadMoreControl = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recent(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, updated: { [weak self] state in + disposableAndLoadMoreControl = context.peerChannelMemberCategoriesContextsManager.recent(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, updated: { [weak self] state in guard let strongSelf = self else { return } @@ -234,7 +234,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { var enabled = true switch mode { case .ban: - if participant.peer.id == account.peerId { + if participant.peer.id == context.account.peerId { continue } for filter in filters { @@ -248,7 +248,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { } } case .promote: - if participant.peer.id == account.peerId { + if participant.peer.id == context.account.peerId { continue } for filter in filters { @@ -272,7 +272,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { let previous = previousEntries.swap(entries) - strongSelf.enqueueTransition(preparedTransition(from: previous, to: entries, account: account, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, nameSortOrder: strongSelf.presentationData.nameSortOrder, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder, interaction: interaction)) + strongSelf.enqueueTransition(preparedTransition(from: previous, to: entries, account: context.account, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, nameSortOrder: strongSelf.presentationData.nameSortOrder, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder, interaction: interaction)) }) } self.disposable = disposableAndLoadMoreControl.0 @@ -281,7 +281,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { if peerId.namespace == Namespaces.Peer.CloudChannel { self.listNode.visibleBottomContentOffsetChanged = { offset in if case let .known(value) = offset, value < 40.0 { - account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: disposableAndLoadMoreControl.1) + context.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: disposableAndLoadMoreControl.1) } } } @@ -348,7 +348,7 @@ class ChannelMembersSearchControllerNode: ASDisplayNode { return } - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ChannelMembersSearchContainerNode(account: self.account, peerId: self.peerId, mode: .banAndPromoteActions, filters: self.filters, openPeer: { [weak self] peer, participant in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ChannelMembersSearchContainerNode(context: self.context, peerId: self.peerId, mode: .banAndPromoteActions, filters: self.filters, openPeer: { [weak self] peer, participant in self?.requestOpenPeerFromSearch?(peer, participant) }, updateActivity: { value in diff --git a/TelegramUI/ChannelPermissionsController.swift b/TelegramUI/ChannelPermissionsController.swift index b8f940c5f3..fb5a46112f 100644 --- a/TelegramUI/ChannelPermissionsController.swift +++ b/TelegramUI/ChannelPermissionsController.swift @@ -386,7 +386,7 @@ private func channelPermissionsControllerEntries(presentationData: PresentationD return entries } -public func channelPermissionsController(account: Account, peerId: PeerId, loadCompleted: @escaping () -> Void = {}) -> ViewController { +public func channelPermissionsController(context: AccountContext, peerId: PeerId, loadCompleted: @escaping () -> Void = {}) -> ViewController { let statePromise = ValuePromise(ChannelPermissionsControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: ChannelPermissionsControllerState()) let updateState: ((ChannelPermissionsControllerState) -> ChannelPermissionsControllerState) -> Void = { f in @@ -412,7 +412,7 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC peersPromise.set(.single(nil)) } else { var loadCompletedCalled = false - disposableAndLoadMoreControl = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.restricted(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, updated: { state in + disposableAndLoadMoreControl = context.peerChannelMemberCategoriesContextsManager.restricted(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId, updated: { state in if case .loading(true) = state.loadingState { peersPromise.set(.single(nil)) } else { @@ -430,11 +430,11 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC actionsDisposable.add(updateDefaultRightsDisposable) let peerView = Promise() - peerView.set(account.viewTracker.peerView(peerId)) + peerView.set(context.account.viewTracker.peerView(peerId)) var upgradedToSupergroupImpl: ((PeerId, @escaping () -> Void) -> Void)? - let arguments = ChannelPermissionsControllerArguments(account: account, updatePermission: { rights, value in + let arguments = ChannelPermissionsControllerArguments(account: context.account, updatePermission: { rights, value in let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { view in @@ -465,7 +465,7 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC } let state = stateValue.with { $0 } if let modifiedRightsFlags = state.modifiedRightsFlags { - updateDefaultRightsDisposable.set((updateDefaultChannelMemberBannedRights(account: account, peerId: peerId, rights: TelegramChatBannedRights(flags: completeRights(modifiedRightsFlags), untilDate: Int32.max)) + updateDefaultRightsDisposable.set((updateDefaultChannelMemberBannedRights(account: context.account, peerId: peerId, rights: TelegramChatBannedRights(flags: completeRights(modifiedRightsFlags), untilDate: Int32.max)) |> deliverOnMainQueue).start()) } } else if let group = view.peers[peerId] as? TelegramGroup, let _ = view.cachedData as? CachedGroupData { @@ -495,7 +495,7 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC } let state = stateValue.with { $0 } if let modifiedRightsFlags = state.modifiedRightsFlags { - updateDefaultRightsDisposable.set((updateDefaultChannelMemberBannedRights(account: account, peerId: peerId, rights: TelegramChatBannedRights(flags: completeRights(modifiedRightsFlags), untilDate: Int32.max)) + updateDefaultRightsDisposable.set((updateDefaultChannelMemberBannedRights(account: context.account, peerId: peerId, rights: TelegramChatBannedRights(flags: completeRights(modifiedRightsFlags), untilDate: Int32.max)) |> deliverOnMainQueue).start()) } } @@ -510,27 +510,27 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC } }, addPeer: { var dismissController: (() -> Void)? - let controller = ChannelMembersSearchController(account: account, peerId: peerId, mode: .ban, openPeer: { peer, participant in + let controller = ChannelMembersSearchController(context: context, peerId: peerId, mode: .ban, openPeer: { peer, participant in if let participant = participant { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } switch participant.participant { case .creator: return case let .member(_, _, adminInfo, _): - if let adminInfo = adminInfo, adminInfo.promotedBy != account.peerId { + if let adminInfo = adminInfo, adminInfo.promotedBy != context.account.peerId { presentControllerImpl?(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.Channel_Members_AddBannedErrorAdmin, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) return } } } - let _ = (account.postbox.loadedPeerWithId(peerId) - |> deliverOnMainQueue).start(next: { channel in - dismissController?() - presentControllerImpl?(channelBannedMemberController(account: account, peerId: peerId, memberId: peer.id, initialParticipant: participant?.participant, updated: { _ in - }, upgradedToSupergroup: { upgradedPeerId, f in - upgradedToSupergroupImpl?(upgradedPeerId, f) - }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) - }) + let _ = (context.account.postbox.loadedPeerWithId(peerId) + |> deliverOnMainQueue).start(next: { channel in + dismissController?() + presentControllerImpl?(channelBannedMemberController(context: context, peerId: peerId, memberId: peer.id, initialParticipant: participant?.participant, updated: { _ in + }, upgradedToSupergroup: { upgradedPeerId, f in + upgradedToSupergroupImpl?(upgradedPeerId, f) + }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + }) }) dismissController = { [weak controller] in controller?.dismiss() @@ -543,7 +543,7 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC return state } - removePeerDisposable.set((account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerId, memberId: memberId, bannedRights: nil) + removePeerDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerId, memberId: memberId, bannedRights: nil) |> deliverOnMainQueue).start(error: { _ in updateState { state in var state = state @@ -558,24 +558,24 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC } })) }, openPeer: { participant in - presentControllerImpl?(channelBannedMemberController(account: account, peerId: peerId, memberId: participant.peerId, initialParticipant: participant, updated: { _ in + presentControllerImpl?(channelBannedMemberController(context: context, peerId: peerId, memberId: participant.peerId, initialParticipant: participant, updated: { _ in }, upgradedToSupergroup: { upgradedPeerId, f in upgradedToSupergroupImpl?(upgradedPeerId, f) }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, openPeerInfo: { peer in - if let controller = peerInfoController(account: account, peer: peer) { + if let controller = peerInfoController(context: context, peer: peer) { pushControllerImpl?(controller) } }, openKicked: { - pushControllerImpl?(channelBlacklistController(account: account, peerId: peerId)) + pushControllerImpl?(channelBlacklistController(context: context, peerId: peerId)) }, presentRestrictedPublicGroupPermissionsAlert: { - 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.GroupPermission_NotAvailableInPublicGroups, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) }) let previousParticipants = Atomic<[RenderedChannelParticipant]?>(value: nil) - let signal = combineLatest(queue: .mainQueue(), (account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), peerView.get(), peersPromise.get()) + let signal = combineLatest(queue: .mainQueue(), context.presentationData, statePromise.get(), peerView.get(), peersPromise.get()) |> deliverOnMainQueue |> map { presentationData, state, view, participants -> (ItemListControllerState, (ItemListNodeState, ChannelPermissionsEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? @@ -598,7 +598,7 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC var searchItem: ItemListControllerSearch? if state.searchingMembers { - searchItem = ChannelMembersSearchItem(account: account, peerId: peerId, searchMode: .searchBanned, cancel: { + searchItem = ChannelMembersSearchItem(context: context, peerId: peerId, searchMode: .searchBanned, cancel: { updateState { state in var state = state state.searchingMembers = false @@ -611,7 +611,7 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC state.searchingMembers = false return state } - presentControllerImpl?(channelBannedMemberController(account: account, peerId: peerId, memberId: participant.peerId, initialParticipant: participant, updated: { _ in + presentControllerImpl?(channelBannedMemberController(context: context, peerId: peerId, memberId: participant.peerId, initialParticipant: participant, updated: { _ in }, upgradedToSupergroup: { upgradedPeerId, f in upgradedToSupergroupImpl?(upgradedPeerId, f) }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) @@ -630,7 +630,7 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, p in if let controller = controller { controller.present(c, in: .window(.root), with: p) @@ -647,8 +647,8 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC guard let controller = controller, let navigationController = controller.navigationController as? NavigationController else { return } - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(upgradedPeerId), keepStack: .never, animated: false, completion: { - navigationController.pushViewController(channelPermissionsController(account: account, peerId: upgradedPeerId, loadCompleted: { + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(upgradedPeerId), keepStack: .never, animated: false, completion: { + navigationController.pushViewController(channelPermissionsController(context: context, peerId: upgradedPeerId, loadCompleted: { f() }), animated: false) }) @@ -656,7 +656,7 @@ public func channelPermissionsController(account: Account, peerId: PeerId, loadC if peerId.namespace == Namespaces.Peer.CloudChannel { controller.visibleBottomContentOffsetChanged = { offset in if case let .known(value) = offset, value < 40.0 { - account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: disposableAndLoadMoreControl.1) + context.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: disposableAndLoadMoreControl.1) } } } diff --git a/TelegramUI/ChannelVisibilityController.swift b/TelegramUI/ChannelVisibilityController.swift index 048f1c574c..50dfa4e946 100644 --- a/TelegramUI/ChannelVisibilityController.swift +++ b/TelegramUI/ChannelVisibilityController.swift @@ -761,7 +761,7 @@ public enum ChannelVisibilityControllerMode { case privateLink } -public func channelVisibilityController(account: Account, peerId: PeerId, mode: ChannelVisibilityControllerMode, upgradedToSupergroup: @escaping (PeerId, @escaping () -> Void) -> Void) -> ViewController { +public func channelVisibilityController(context: AccountContext, peerId: PeerId, mode: ChannelVisibilityControllerMode, upgradedToSupergroup: @escaping (PeerId, @escaping () -> Void) -> Void) -> ViewController { let statePromise = ValuePromise(ChannelVisibilityControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: ChannelVisibilityControllerState()) let updateState: ((ChannelVisibilityControllerState) -> ChannelVisibilityControllerState) -> Void = { f in @@ -769,9 +769,9 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: } let peersDisablingAddressNameAssignment = Promise<[Peer]?>() - peersDisablingAddressNameAssignment.set(.single(nil) |> then(channelAddressNameAssignmentAvailability(account: account, peerId: peerId.namespace == Namespaces.Peer.CloudChannel ? peerId : nil) |> mapToSignal { result -> Signal<[Peer]?, NoError> in + peersDisablingAddressNameAssignment.set(.single(nil) |> then(channelAddressNameAssignmentAvailability(account: context.account, peerId: peerId.namespace == Namespaces.Peer.CloudChannel ? peerId : nil) |> mapToSignal { result -> Signal<[Peer]?, NoError> in if case .addressNameLimitReached = result { - return adminedPublicChannels(account: account) + return adminedPublicChannels(account: context.account) |> map(Optional.init) } else { return .single([]) @@ -798,11 +798,11 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: let revokeLinkDisposable = MetaDisposable() actionsDisposable.add(revokeLinkDisposable) - actionsDisposable.add( (account.viewTracker.peerView(peerId) |> filter { $0.cachedData != nil } |> take(1) |> mapToSignal { view -> Signal in - return ensuredExistingPeerExportedInvitation(account: account, peerId: peerId) + actionsDisposable.add( (context.account.viewTracker.peerView(peerId) |> filter { $0.cachedData != nil } |> take(1) |> mapToSignal { view -> Signal in + return ensuredExistingPeerExportedInvitation(account: context.account, peerId: peerId) }).start()) - let arguments = ChannelVisibilityControllerArguments(account: account, updateCurrentType: { type in + let arguments = ChannelVisibilityControllerArguments(account: context.account, updateCurrentType: { type in updateState { state in return state.withUpdatedSelectedType(type) } @@ -822,7 +822,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: return state.withUpdatedEditingPublicLinkText(text) } - checkAddressNameDisposable.set((validateAddressNameInteractive(account: account, domain: .peer(peerId), name: text) + checkAddressNameDisposable.set((validateAddressNameInteractive(account: context.account, domain: .peer(peerId), name: text) |> deliverOnMainQueue).start(next: { result in updateState { state in return state.withUpdatedAddressNameValidationStatus(result) @@ -846,7 +846,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: return state.withUpdatedRevokingPeerId(peerId) } - revokeAddressNameDisposable.set((updateAddressName(account: account, domain: .peer(peerId), name: nil) |> deliverOnMainQueue).start(error: { _ in + revokeAddressNameDisposable.set((updateAddressName(account: context.account, domain: .peer(peerId), name: nil) |> deliverOnMainQueue).start(error: { _ in updateState { state in return state.withUpdatedRevokingPeerId(nil) } @@ -858,7 +858,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: }) })) }, copyPrivateLink: { - 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 @@ -870,12 +870,12 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: } |> deliverOnMainQueue).start(next: { link in if let link = link { UIPasteboard.general.string = link - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .genericSuccess(presentationData.strings.Username_LinkCopied)), nil) } }) }, revokePrivateLink: { - 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() @@ -896,7 +896,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: } } if revoke { - revokeLinkDisposable.set((ensuredExistingPeerExportedInvitation(account: account, peerId: peerId, revokeExisted: true) |> deliverOnMainQueue).start(completed: { + revokeLinkDisposable.set((ensuredExistingPeerExportedInvitation(account: context.account, peerId: peerId, revokeExisted: true) |> deliverOnMainQueue).start(completed: { updateState { $0.withUpdatedRevokingPrivateLink(false) } @@ -919,19 +919,19 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: return nil } |> deliverOnMainQueue).start(next: { link in if let link = link { - let shareController = ShareController(account: account, subject: .url(link)) + let shareController = ShareController(context: context, subject: .url(link)) presentControllerImpl?(shareController, nil) } }) }) - let peerView = account.viewTracker.peerView(peerId) + let peerView = context.account.viewTracker.peerView(peerId) |> deliverOnMainQueue let previousHadNamesToRevoke = Atomic(value: nil) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, peerView, peersDisablingAddressNameAssignment.get() |> deliverOnMainQueue) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, peerView, peersDisablingAddressNameAssignment.get() |> deliverOnMainQueue) |> deliverOnMainQueue |> map { presentationData, state, view, publicChannelsToRevoke -> (ItemListControllerState, (ItemListNodeState, ChannelVisibilityEntry.ItemGenerationArguments)) in let peer = peerViewMainPeer(view) @@ -969,9 +969,9 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: updateState { state in return state.withUpdatedUpdatingAddressName(true) } - _ = ApplicationSpecificNotice.markAsSeenSetPublicChannelLink(postbox: account.postbox).start() + _ = ApplicationSpecificNotice.markAsSeenSetPublicChannelLink(postbox: context.account.postbox).start() - updateAddressNameDisposable.set((updateAddressName(account: account, domain: .peer(peerId), name: updatedAddressNameValue.isEmpty ? nil : updatedAddressNameValue) |> timeout(10, queue: Queue.mainQueue(), alternate: .fail(.generic)) + updateAddressNameDisposable.set((updateAddressName(account: context.account, domain: .peer(peerId), name: updatedAddressNameValue.isEmpty ? nil : updatedAddressNameValue) |> timeout(10, queue: Queue.mainQueue(), alternate: .fail(.generic)) |> deliverOnMainQueue).start(error: { _ in updateState { state in return state.withUpdatedUpdatingAddressName(false) @@ -993,7 +993,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: } - _ = (ApplicationSpecificNotice.getSetPublicChannelLink(postbox: account.postbox) |> deliverOnMainQueue).start(next: { showAlert in + _ = (ApplicationSpecificNotice.getSetPublicChannelLink(postbox: context.account.postbox) |> deliverOnMainQueue).start(next: { showAlert in if showAlert { let confirm = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.Channel_Edit_PrivatePublicLinkAlert, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: invokeAction)]) @@ -1043,9 +1043,9 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: updateState { state in return state.withUpdatedUpdatingAddressName(true) } - _ = ApplicationSpecificNotice.markAsSeenSetPublicChannelLink(postbox: account.postbox).start() + _ = ApplicationSpecificNotice.markAsSeenSetPublicChannelLink(postbox: context.account.postbox).start() - let signal = convertGroupToSupergroup(account: account, peerId: peerId) + let signal = convertGroupToSupergroup(account: context.account, peerId: peerId) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -1054,7 +1054,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: guard let upgradedPeerId = upgradedPeerId else { return .single(nil) } - return updateAddressName(account: account, domain: .peer(upgradedPeerId), name: updatedAddressNameValue.isEmpty ? nil : updatedAddressNameValue) + return updateAddressName(account: context.account, domain: .peer(upgradedPeerId), name: updatedAddressNameValue.isEmpty ? nil : updatedAddressNameValue) |> `catch` { _ -> Signal in return .complete() } @@ -1083,7 +1083,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: })) } - _ = (ApplicationSpecificNotice.getSetPublicChannelLink(postbox: account.postbox) |> deliverOnMainQueue).start(next: { showAlert in + _ = (ApplicationSpecificNotice.getSetPublicChannelLink(postbox: context.account.postbox) |> deliverOnMainQueue).start(next: { showAlert in if showAlert { let confirm = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.Channel_Edit_PrivatePublicLinkAlert, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: invokeAction)]) @@ -1164,7 +1164,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) dismissImpl = { [weak controller] in controller?.view.endEditing(true) controller?.dismiss() @@ -1172,7 +1172,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: nextImpl = { [weak controller] in if let controller = controller { if case .initialSetup = mode { - let selectionController = ContactMultiselectionController(account: account, mode: .channelCreation, options: []) + let selectionController = ContactMultiselectionController(context: context, mode: .channelCreation, options: []) (controller.navigationController as? NavigationController)?.replaceAllButRootController(selectionController, animated: true) let _ = (selectionController.result |> deliverOnMainQueue).start(next: { [weak selectionController] peerIds in @@ -1187,7 +1187,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: } }) if filteredPeerIds.isEmpty { - navigateToChatController(navigationController: navigationController, chatController: nil, account: account, chatLocation: .peer(peerId), keepStack: .never, animated: true) + 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) @@ -1196,12 +1196,12 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: return } - navigateToChatController(navigationController: navigationController, chatController: nil, account: account, chatLocation: .peer(peerId), keepStack: .never, animated: true) + navigateToChatController(navigationController: navigationController, chatController: nil, context: context, chatLocation: .peer(peerId), keepStack: .never, animated: true) }) } }) } else { - (controller.navigationController as? NavigationController)?.replaceAllButRootController(ChatController(account: account, chatLocation: .peer(peerId)), animated: true) + (controller.navigationController as? NavigationController)?.replaceAllButRootController(ChatController(context: context, chatLocation: .peer(peerId)), animated: true) } } } @@ -1220,7 +1220,7 @@ public func channelVisibilityController(account: Account, peerId: PeerId, mode: return false }) if let resultItemNode = resultItemNode { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let contextMenuController = ContextMenuController(actions: [ContextMenuAction(content: .text(presentationData.strings.Conversation_ContextMenuCopyLink), action: { UIPasteboard.general.string = text })]) diff --git a/TelegramUI/ChatBotStartInputPanelNode.swift b/TelegramUI/ChatBotStartInputPanelNode.swift index 19464c4e71..96b0b6e8dc 100644 --- a/TelegramUI/ChatBotStartInputPanelNode.swift +++ b/TelegramUI/ChatBotStartInputPanelNode.swift @@ -79,7 +79,7 @@ final class ChatBotStartInputPanelNode: ChatInputPanelNode { } @objc func buttonPressed() { - guard let account = self.account, let presentationInterfaceState = self.presentationInterfaceState, let peer = presentationInterfaceState.renderedPeer?.peer else { + guard let context = self.context, let presentationInterfaceState = self.presentationInterfaceState, let peer = presentationInterfaceState.renderedPeer?.peer else { return } diff --git a/TelegramUI/ChatButtonKeyboardInputNode.swift b/TelegramUI/ChatButtonKeyboardInputNode.swift index 818b170140..78d6054038 100644 --- a/TelegramUI/ChatButtonKeyboardInputNode.swift +++ b/TelegramUI/ChatButtonKeyboardInputNode.swift @@ -27,7 +27,7 @@ private final class ChatButtonKeyboardInputButtonNode: ASButtonNode { } final class ChatButtonKeyboardInputNode: ChatInputNode { - private let account: Account + private let context: AccountContext private let controllerInteraction: ChatControllerInteraction private let separatorNode: ASDisplayNode @@ -38,8 +38,8 @@ final class ChatButtonKeyboardInputNode: ChatInputNode { private var theme: PresentationTheme? - init(account: Account, controllerInteraction: ChatControllerInteraction) { - self.account = account + init(context: AccountContext, controllerInteraction: ChatControllerInteraction) { + self.context = context self.controllerInteraction = controllerInteraction self.scrollNode = ASScrollNode() diff --git a/TelegramUI/ChatChannelSubscriberInputPanelNode.swift b/TelegramUI/ChatChannelSubscriberInputPanelNode.swift index b6b6e64821..2597d77946 100644 --- a/TelegramUI/ChatChannelSubscriberInputPanelNode.swift +++ b/TelegramUI/ChatChannelSubscriberInputPanelNode.swift @@ -82,7 +82,7 @@ final class ChatChannelSubscriberInputPanelNode: ChatInputPanelNode { } @objc func buttonPressed() { - guard let account = self.account, let action = self.action, let presentationInterfaceState = self.presentationInterfaceState, let peer = presentationInterfaceState.renderedPeer?.peer else { + guard let context = self.context, let action = self.action, let presentationInterfaceState = self.presentationInterfaceState, let peer = presentationInterfaceState.renderedPeer?.peer else { return } @@ -90,7 +90,7 @@ final class ChatChannelSubscriberInputPanelNode: ChatInputPanelNode { case .join: self.activityIndicator.isHidden = false self.activityIndicator.startAnimating() - self.actionDisposable.set((joinChannel(account: account, peerId: peer.id) + self.actionDisposable.set((joinChannel(account: context.account, peerId: peer.id) |> afterDisposed { [weak self] in Queue.mainQueue().async { if let strongSelf = self { @@ -102,8 +102,8 @@ final class ChatChannelSubscriberInputPanelNode: ChatInputPanelNode { case .kicked: break case .muteNotifications, .unmuteNotifications: - if let account = self.account, let presentationInterfaceState = self.presentationInterfaceState, let peer = presentationInterfaceState.renderedPeer?.peer { - self.actionDisposable.set(togglePeerMuted(account: account, peerId: peer.id).start()) + if let context = self.context, let presentationInterfaceState = self.presentationInterfaceState, let peer = presentationInterfaceState.renderedPeer?.peer { + self.actionDisposable.set(togglePeerMuted(account: context.account, peerId: peer.id).start()) } } } diff --git a/TelegramUI/ChatController.swift b/TelegramUI/ChatController.swift index 23282e885d..b4c8dae9ee 100644 --- a/TelegramUI/ChatController.swift +++ b/TelegramUI/ChatController.swift @@ -91,7 +91,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal public var peekActions: ChatControllerPeekActions = .standard private var didSetup3dTouch: Bool = false - private let account: Account + private let context: AccountContext public let chatLocation: ChatLocation private let messageId: MessageId? private let botStart: ChatControllerInitialBotStart? @@ -218,12 +218,12 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal var purposefulAction: (() -> Void)? - public init(account: Account, chatLocation: ChatLocation, messageId: MessageId? = nil, botStart: ChatControllerInitialBotStart? = nil, mode: ChatControllerPresentationMode = .standard(previewing: false)) { + public init(context: AccountContext, chatLocation: ChatLocation, messageId: MessageId? = nil, botStart: ChatControllerInitialBotStart? = nil, mode: ChatControllerPresentationMode = .standard(previewing: false)) { let _ = ChatControllerCount.modify { value in return value + 1 } - self.account = account + self.context = context self.chatLocation = chatLocation self.messageId = messageId self.botStart = botStart @@ -239,10 +239,10 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.chatLocationInfoData = .group(Promise()) } - self.presentationData = (account.applicationContext as! TelegramApplicationContext).currentPresentationData.with { $0 } - self.automaticMediaDownloadSettings = (account.applicationContext as! TelegramApplicationContext).currentAutomaticMediaDownloadSettings.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } + self.automaticMediaDownloadSettings = context.currentAutomaticMediaDownloadSettings.with { $0 } - self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, chatWallpaperMode: self.presentationData.chatWallpaperMode, theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, fontSize: self.presentationData.fontSize, accountPeerId: account.peerId, mode: mode, chatLocation: chatLocation) + self.presentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, chatWallpaperMode: self.presentationData.chatWallpaperMode, theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, fontSize: self.presentationData.fontSize, accountPeerId: context.account.peerId, mode: mode, chatLocation: chatLocation) var mediaAccessoryPanelVisibility = MediaAccessoryPanelVisibility.none if case .standard = mode { @@ -257,7 +257,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal default: navigationBarPresentationData = NavigationBarPresentationData(presentationData: self.presentationData) } - super.init(account: account, navigationBarPresentationData: navigationBarPresentationData, mediaAccessoryPanelVisibility: mediaAccessoryPanelVisibility, locationBroadcastPanelSource: locationBroadcastPanelSource) + super.init(context: context, navigationBarPresentationData: navigationBarPresentationData, mediaAccessoryPanelVisibility: mediaAccessoryPanelVisibility, locationBroadcastPanelSource: locationBroadcastPanelSource) self.navigationItem.backBarButtonItem = UIBarButtonItem(title: self.presentationData.strings.Common_Back, style: .plain, target: nil, action: nil) @@ -321,7 +321,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } } - return openChatMessage(account: account, message: message, standalone: false, reverseMessageGalleryOrder: false, stream: mode == .stream, navigationController: strongSelf.navigationController as? NavigationController, dismissInput: { + return openChatMessage(context: context, message: message, standalone: false, reverseMessageGalleryOrder: false, stream: mode == .stream, navigationController: strongSelf.navigationController as? NavigationController, dismissInput: { self?.chatDisplayNode.dismissInput() }, present: { c, a in self?.present(c, in: .window(.root), with: a, blockInteraction: true) @@ -438,7 +438,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal break } } - let _ = contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: strongSelf.presentationInterfaceState, account: strongSelf.account, messages: updatedMessages, controllerInteraction: strongSelf.controllerInteraction, selectAll: selectAll, interfaceInteraction: strongSelf.interfaceInteraction).start(next: { actions in + let _ = contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: strongSelf.presentationInterfaceState, context: strongSelf.context, messages: updatedMessages, controllerInteraction: strongSelf.controllerInteraction, selectAll: selectAll, interfaceInteraction: strongSelf.interfaceInteraction).start(next: { actions in guard let strongSelf = self, !actions.isEmpty else { return } @@ -578,7 +578,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } }) - strongSelf.messageActionCallbackDisposable.set(((requestMessageActionCallback(account: strongSelf.account, messageId: messageId, isGame: isGame, data: data) |> afterDisposed { + strongSelf.messageActionCallbackDisposable.set(((requestMessageActionCallback(account: strongSelf.context.account, messageId: messageId, isGame: isGame, data: data) |> afterDisposed { Queue.mainQueue().async { if let strongSelf = self { strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { @@ -615,7 +615,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal case let .url(url): if isGame { strongSelf.chatDisplayNode.dismissInput() - (strongSelf.navigationController as? NavigationController)?.pushViewController(GameController(account: strongSelf.account, url: url, message: message)) + (strongSelf.navigationController as? NavigationController)?.pushViewController(GameController(context: strongSelf.context, url: url, message: message)) } else { strongSelf.openUrl(url, concealed: false) } @@ -640,7 +640,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal }, shareCurrentLocation: { [weak self] in if let strongSelf = self { strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: strongSelf.presentationData.theme), title: strongSelf.presentationData.strings.Conversation_ShareBotLocationConfirmationTitle, text: strongSelf.presentationData.strings.Conversation_ShareBotLocationConfirmation, actions: [TextAlertAction(type: .genericAction, title: strongSelf.presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .defaultAction, title: strongSelf.presentationData.strings.Common_OK, action: { - if let strongSelf = self, let locationManager = strongSelf.account.telegramApplicationContext.locationManager { + if let strongSelf = self, let locationManager = strongSelf.context.locationManager { let _ = (currentLocationManagerCoordinate(manager: locationManager, timeout: 5.0) |> deliverOnMainQueue).start(next: { coordinate in if let strongSelf = self { @@ -658,7 +658,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let strongSelf = self { strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: strongSelf.presentationData.theme), title: strongSelf.presentationData.strings.Conversation_ShareBotContactConfirmationTitle, text: strongSelf.presentationData.strings.Conversation_ShareBotContactConfirmation, actions: [TextAlertAction(type: .genericAction, title: strongSelf.presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .defaultAction, title: strongSelf.presentationData.strings.Common_OK, action: { if let strongSelf = self { - let _ = (strongSelf.account.postbox.loadedPeerWithId(strongSelf.account.peerId) + let _ = (strongSelf.context.account.postbox.loadedPeerWithId(strongSelf.context.account.peerId) |> deliverOnMainQueue).start(next: { peer in if let peer = peer as? TelegramUser, let phone = peer.phone, !phone.isEmpty { strongSelf.sendMessages([.message(text: "", attributes: [], mediaReference: .standalone(media: TelegramMediaContact(firstName: peer.firstName ?? "", lastName: peer.lastName ?? "", phoneNumber: phone, peerId: peer.id, vCardData: nil)), replyToMessageId: nil, localGroupingKey: nil)]) @@ -698,11 +698,11 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } }, openInstantPage: { [weak self] message in if let strongSelf = self, strongSelf.isNodeLoaded, let navigationController = strongSelf.navigationController as? NavigationController, let message = strongSelf.chatDisplayNode.historyNode.messageInCurrentHistoryView(message.id) { - openChatInstantPage(account: strongSelf.account, message: message, navigationController: navigationController) + openChatInstantPage(context: strongSelf.context, message: message, navigationController: navigationController) } }, openWallpaper: { [weak self] message in if let strongSelf = self, strongSelf.isNodeLoaded, let message = strongSelf.chatDisplayNode.historyNode.messageInCurrentHistoryView(message.id) { - openChatWallpaper(account: strongSelf.account, message: message, present: { [weak self] c, a in + openChatWallpaper(context: strongSelf.context, message: message, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a, blockInteraction: true) }) } @@ -713,9 +713,10 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if strongSelf.resolvePeerByNameDisposable == nil { strongSelf.resolvePeerByNameDisposable = MetaDisposable() } + let account = strongSelf.context.account var resolveSignal: Signal if let peerName = peerName { - resolveSignal = resolvePeerByName(account: strongSelf.account, name: peerName) + resolveSignal = resolvePeerByName(account: strongSelf.context.account, name: peerName) |> mapToSignal { peerId -> Signal in if let peerId = peerId { return account.postbox.loadedPeerWithId(peerId) @@ -725,7 +726,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } } } else if case let .peer(peerId) = strongSelf.chatLocation { - resolveSignal = account.postbox.loadedPeerWithId(peerId) + resolveSignal = context.account.postbox.loadedPeerWithId(peerId) |> map(Optional.init) } else { resolveSignal = .single(nil) @@ -759,7 +760,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal strongSelf.resolvePeerByNameDisposable?.set((resolveSignal |> deliverOnMainQueue).start(next: { peer in if let strongSelf = self, !hashtag.isEmpty { - let searchController = HashtagSearchController(account: strongSelf.account, peer: peer, query: hashtag) + let searchController = HashtagSearchController(context: strongSelf.context, peer: peer, query: hashtag) (strongSelf.navigationController as? NavigationController)?.pushViewController(searchController) } })) @@ -783,7 +784,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal }) }, openMessageShareMenu: { [weak self] id in if let strongSelf = self, let messages = strongSelf.chatDisplayNode.historyNode.messageGroupInCurrentHistoryView(id) { - let shareController = ShareController(account: strongSelf.account, subject: .messages(messages)) + let shareController = ShareController(context: strongSelf.context, subject: .messages(messages)) shareController.dismissed = { shared in if shared { self?.commitPurposefulAction() @@ -802,7 +803,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let strongSelf = self { strongSelf.commitPurposefulAction() - let _ = (account.viewTracker.peerView(peerId) + let _ = (context.account.viewTracker.peerView(peerId) |> take(1) |> map { view -> Peer? in return peerViewMainPeer(view) @@ -813,27 +814,28 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } if let cachedUserData = strongSelf.peerView?.cachedData as? CachedUserData, cachedUserData.callsPrivate { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: presentationData.strings.Call_ConnectionErrorTitle, text: presentationData.strings.Call_PrivacyErrorMessage(peer.compactDisplayTitle).0, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), in: .window(.root)) return } - let callResult = account.telegramApplicationContext.callManager?.requestCall(peerId: peer.id, endCurrentIfAny: false) + let callResult = context.callManager?.requestCall(peerId: peer.id, endCurrentIfAny: false) if let callResult = callResult, case let .alreadyInProgress(currentPeerId) = callResult { if currentPeerId == peer.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(peer.id), transaction.getPeer(currentPeerId)) - } |> deliverOnMainQueue).start(next: { peer, current in - if let peer = peer, let current = current { - strongSelf.present(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) - })]), in: .window(.root)) - } - }) + } + |> deliverOnMainQueue).start(next: { peer, current in + if let peer = peer, let current = current { + strongSelf.present(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 _ = context.callManager?.requestCall(peerId: peer.id, endCurrentIfAny: true) + })]), in: .window(.root)) + } + }) } } }) @@ -844,7 +846,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal case let .url(url): var cleanUrl = url var canAddToReadingList = true - let canOpenIn = availableOpenInOptions(applicationContext: strongSelf.account.telegramApplicationContext, item: .url(url: url)).count > 1 + let canOpenIn = availableOpenInOptions(context: strongSelf.context, item: .url(url: url)).count > 1 let mailtoString = "mailto:" let telString = "tel:" var openText = strongSelf.presentationData.strings.Conversation_LinkDialogOpen @@ -979,7 +981,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let strongSelf = self { let peerSignal: Signal if case let .peer(peerId) = strongSelf.chatLocation { - peerSignal = strongSelf.account.postbox.loadedPeerWithId(peerId) + peerSignal = strongSelf.context.account.postbox.loadedPeerWithId(peerId) |> map(Optional.init) } else { peerSignal = .single(nil) @@ -987,7 +989,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal let _ = (peerSignal |> deliverOnMainQueue).start(next: { peer in if let strongSelf = self { - let searchController = HashtagSearchController(account: strongSelf.account, peer: peer, query: hashtag) + let searchController = HashtagSearchController(context: strongSelf.context, peer: peer, query: hashtag) (strongSelf.navigationController as? NavigationController)?.pushViewController(searchController) } }) @@ -1014,9 +1016,9 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let invoice = media as? TelegramMediaInvoice { strongSelf.chatDisplayNode.dismissInput() if let receiptMessageId = invoice.receiptMessageId { - strongSelf.present(BotReceiptController(account: strongSelf.account, invoice: invoice, messageId: receiptMessageId), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + strongSelf.present(BotReceiptController(context: strongSelf.context, invoice: invoice, messageId: receiptMessageId), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } else { - strongSelf.present(BotCheckoutController(account: strongSelf.account, invoice: invoice, messageId: messageId), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + strongSelf.present(BotCheckoutController(context: strongSelf.context, invoice: invoice, messageId: messageId), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } } } @@ -1049,7 +1051,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard let strongSelf = self else { return } - let _ = (strongSelf.account.postbox.transaction { transaction -> [Message] in + let _ = (strongSelf.context.account.postbox.transaction { transaction -> [Message] in return transaction.getMessageFailedGroup(id) ?? [] } |> deliverOnMainQueue).start(next: { messages in guard let strongSelf = self, !messages.isEmpty else { @@ -1062,7 +1064,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard let strongSelf = self else { return } - let _ = resendMessages(account: strongSelf.account, messageIds: [id]).start() + let _ = resendMessages(account: strongSelf.context.account, messageIds: [id]).start() })) if messages.count != 1 { items.append(ActionSheetButtonItem(title: strongSelf.presentationData.strings.Conversation_MessageDialogRetryAll(messages.count).0, color: .accent, action: { [weak actionSheet] in @@ -1070,7 +1072,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard let strongSelf = self else { return } - let _ = resendMessages(account: strongSelf.account, messageIds: messages.map({ $0.id })).start() + let _ = resendMessages(account: strongSelf.context.account, messageIds: messages.map({ $0.id })).start() })) } items.append(ActionSheetButtonItem(title: strongSelf.presentationData.strings.Conversation_MessageDialogDelete, color: .destructive, action: { [weak actionSheet] in @@ -1078,7 +1080,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard let strongSelf = self else { return } - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: messages.map({ $0.id }), type: .forLocalPeer).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: messages.map({ $0.id }), type: .forLocalPeer).start() })) actionSheet.setItemGroups([ActionSheetItemGroup(items: items), ActionSheetItemGroup(items: [ ActionSheetButtonItem(title: strongSelf.presentationData.strings.Common_Cancel, color: .accent, action: { [weak actionSheet] in @@ -1090,13 +1092,13 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal }) }, addContact: { [weak self] phoneNumber in if let strongSelf = self { - openAddContact(account: strongSelf.account, phoneNumber: phoneNumber, present: { [weak self] controller, arguments in + openAddContact(context: strongSelf.context, phoneNumber: phoneNumber, present: { [weak self] controller, arguments in self?.present(controller, in: .window(.root), with: arguments) }) } }, rateCall: { [weak self] message, callId in if let strongSelf = self { - let controller = callRatingController(account: strongSelf.account, callId: callId, present: { [weak self] controller in + let controller = callRatingController(context: strongSelf.context, callId: callId, present: { [weak self] controller in if let strongSelf = self { strongSelf.present(controller, in: .window(.root)) } @@ -1117,7 +1119,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal disposables = DisposableDict() strongSelf.selectMessagePollOptionDisposables = disposables } - let signal = requestMessageSelectPollOption(account: strongSelf.account, messageId: id, opaqueIdentifier: opaqueIdentifier) + let signal = requestMessageSelectPollOption(account: strongSelf.context.account, messageId: id, opaqueIdentifier: opaqueIdentifier) disposables.set((signal |> deliverOnMainQueue).start(error: { _ in guard let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction else { @@ -1141,7 +1143,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } }, openAppStorePage: { [weak self] in if let strongSelf = self { - strongSelf.account.telegramApplicationContext.applicationBindings.openAppStorePage() + strongSelf.context.applicationBindings.openAppStorePage() } }, requestMessageUpdate: { [weak self] id in if let strongSelf = self { @@ -1155,12 +1157,12 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.controllerInteraction = controllerInteraction - self.chatTitleView = ChatTitleView(account: self.account, theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder) + self.chatTitleView = ChatTitleView(account: self.context.account, theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder) self.navigationItem.titleView = self.chatTitleView self.chatTitleView?.pressed = { [weak self] in if let strongSelf = self { - if strongSelf.chatLocation == .peer(strongSelf.account.peerId) { - (strongSelf.navigationController as? NavigationController)?.pushViewController(PeerMediaCollectionController(account: strongSelf.account, peerId: strongSelf.account.peerId)) + if strongSelf.chatLocation == .peer(strongSelf.context.account.peerId) { + (strongSelf.navigationController as? NavigationController)?.pushViewController(PeerMediaCollectionController(context: strongSelf.context, peerId: strongSelf.context.account.peerId)) } else { strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { return $0.updatedTitlePanelContext { @@ -1210,10 +1212,10 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal switch chatLocation { case let .peer(peerId): if case let .peer(peerView) = self.chatLocationInfoData { - peerView.set(account.viewTracker.peerView(peerId)) + peerView.set(context.account.viewTracker.peerView(peerId)) var onlineMemberCount: Signal = .single(nil) if peerId.namespace == Namespaces.Peer.CloudChannel { - onlineMemberCount = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recentOnline(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId) + onlineMemberCount = context.peerChannelMemberCategoriesContextsManager.recentOnline(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerId) |> map(Optional.init) } self.peerDisposable.set((combineLatest(queue: Queue.mainQueue(), peerView.get(), onlineMemberCount) @@ -1221,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.account, peer: peer) + (strongSelf.chatInfoNavigationButton?.buttonItem.customDisplayNode as? ChatAvatarNavigationNode)?.avatarNode.setPeer(account: strongSelf.context.account, peer: peer) } if strongSelf.peerView === peerView { return @@ -1249,8 +1251,8 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal strongSelf.peerView = peerView if wasGroupChannel != isGroupChannel { if let isGroupChannel = isGroupChannel, isGroupChannel { - let (recentDisposable, _) = strongSelf.account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recent(postbox: strongSelf.account.postbox, network: strongSelf.account.network, accountPeerId: account.peerId, peerId: peerView.peerId, updated: { _ in }) - let (adminsDisposable, _) = strongSelf.account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.admins(postbox: strongSelf.account.postbox, network: strongSelf.account.network, accountPeerId: account.peerId, peerId: peerView.peerId, updated: { _ in }) + let (recentDisposable, _) = strongSelf.context.peerChannelMemberCategoriesContextsManager.recent(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, accountPeerId: context.account.peerId, peerId: peerView.peerId, updated: { _ in }) + let (adminsDisposable, _) = strongSelf.context.peerChannelMemberCategoriesContextsManager.admins(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, accountPeerId: context.account.peerId, peerId: peerView.peerId, updated: { _ in }) let disposable = DisposableSet() disposable.add(recentDisposable) disposable.add(adminsDisposable) @@ -1301,7 +1303,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal var explicitelyCanPinMessages: Bool = false if let cachedUserData = peerView.cachedData as? CachedUserData { explicitelyCanPinMessages = cachedUserData.canPinMessages - } else if peerView.peerId == account.peerId { + } else if peerView.peerId == context.account.peerId { explicitelyCanPinMessages = true } @@ -1321,7 +1323,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let navigationController = strongSelf.navigationController as? NavigationController { var viewControllers = navigationController.viewControllers if let index = viewControllers.index(where: { $0 === strongSelf }) { - viewControllers[index] = ChatController(account: strongSelf.account, chatLocation: .peer(upgradedToPeerId)) + viewControllers[index] = ChatController(context: strongSelf.context, chatLocation: .peer(upgradedToPeerId)) navigationController.setViewControllers(viewControllers, animated: false) } } @@ -1332,7 +1334,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal case let .group(groupId): if case let .group(topPeersView) = self.chatLocationInfoData { let key: PostboxViewKey = .chatListTopPeers(groupId: groupId) - topPeersView.set(account.postbox.combinedView(keys: [key]) + topPeersView.set(context.account.postbox.combinedView(keys: [key]) |> mapToSignal { view -> Signal in if let entry = view.views[key] as? ChatListTopPeersView { return .single(entry) @@ -1343,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.account, peers: topPeersView.peers, animated: strongSelf.didSetChatLocationInfoReady) + (strongSelf.chatInfoNavigationButton?.buttonItem.customDisplayNode as? ChatMultipleAvatarsNavigationNode)?.setPeers(account: strongSelf.context.account, peers: topPeersView.peers, animated: strongSelf.didSetChatLocationInfoReady) if !strongSelf.didSetChatLocationInfoReady { strongSelf.didSetChatLocationInfoReady = true @@ -1498,7 +1500,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.inputActivityDisposable = (self.typingActivityPromise.get() |> deliverOnMainQueue).start(next: { [weak self] value in if let strongSelf = self, case let .peer(peerId) = strongSelf.chatLocation { - strongSelf.account.updateLocalInputActivity(peerId: peerId, activity: .typingText, isPresent: value) + strongSelf.context.account.updateLocalInputActivity(peerId: peerId, activity: .typingText, isPresent: value) } }) @@ -1508,55 +1510,55 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal strongSelf.acquiredRecordingActivityDisposable?.dispose() switch value { case .voice: - strongSelf.acquiredRecordingActivityDisposable = strongSelf.account.acquireLocalInputActivity(peerId: peerId, activity: .recordingVoice) + strongSelf.acquiredRecordingActivityDisposable = strongSelf.context.account.acquireLocalInputActivity(peerId: peerId, activity: .recordingVoice) case .instantVideo: - strongSelf.acquiredRecordingActivityDisposable = strongSelf.account.acquireLocalInputActivity(peerId: peerId, activity: .recordingInstantVideo) + strongSelf.acquiredRecordingActivityDisposable = strongSelf.context.account.acquireLocalInputActivity(peerId: peerId, activity: .recordingInstantVideo) case .none: strongSelf.acquiredRecordingActivityDisposable = nil } } }) - self.presentationDataDisposable = (account.telegramApplicationContext.presentationData - |> deliverOnMainQueue).start(next: { [weak self] presentationData in - if let strongSelf = self { - let previousTheme = strongSelf.presentationData.theme - let previousStrings = strongSelf.presentationData.strings - let previousChatWallpaper = strongSelf.presentationData.chatWallpaper + self.presentationDataDisposable = (context.presentationData + |> deliverOnMainQueue).start(next: { [weak self] presentationData in + if let strongSelf = self { + let previousTheme = strongSelf.presentationData.theme + let previousStrings = strongSelf.presentationData.strings + let previousChatWallpaper = strongSelf.presentationData.chatWallpaper + + strongSelf.presentationData = presentationData + + if previousTheme !== presentationData.theme || previousStrings !== presentationData.strings || presentationData.chatWallpaper != previousChatWallpaper { + strongSelf.themeAndStringsUpdated() + } + } + }) + + self.automaticMediaDownloadSettingsDisposable = (context.automaticMediaDownloadSettings + |> deliverOnMainQueue).start(next: { [weak self] downloadSettings in + if let strongSelf = self, strongSelf.automaticMediaDownloadSettings != downloadSettings { + strongSelf.automaticMediaDownloadSettings = downloadSettings + strongSelf.controllerInteraction?.automaticMediaDownloadSettings = downloadSettings + if strongSelf.isNodeLoaded { + strongSelf.chatDisplayNode.updateAutomaticMediaDownloadSettings() + } + } + }) + + self.applicationInForegroundDisposable = (context.applicationBindings.applicationInForeground + |> distinctUntilChanged + |> deliverOn(Queue.mainQueue())).start(next: { [weak self] value in + if let strongSelf = self, strongSelf.isNodeLoaded { + if !value { + strongSelf.saveInterfaceState() + strongSelf.raiseToListen?.applicationResignedActive() - strongSelf.presentationData = presentationData - - if previousTheme !== presentationData.theme || previousStrings !== presentationData.strings || presentationData.chatWallpaper != previousChatWallpaper { - strongSelf.themeAndStringsUpdated() - } + strongSelf.stopMediaRecorder() } - }) + } + }) - self.automaticMediaDownloadSettingsDisposable = (account.telegramApplicationContext.automaticMediaDownloadSettings - |> deliverOnMainQueue).start(next: { [weak self] downloadSettings in - if let strongSelf = self, strongSelf.automaticMediaDownloadSettings != downloadSettings { - strongSelf.automaticMediaDownloadSettings = downloadSettings - strongSelf.controllerInteraction?.automaticMediaDownloadSettings = downloadSettings - if strongSelf.isNodeLoaded { - strongSelf.chatDisplayNode.updateAutomaticMediaDownloadSettings() - } - } - }) - - self.applicationInForegroundDisposable = (account.telegramApplicationContext.applicationBindings.applicationInForeground - |> distinctUntilChanged - |> deliverOn(Queue.mainQueue())).start(next: { [weak self] value in - if let strongSelf = self, strongSelf.isNodeLoaded { - if !value { - strongSelf.saveInterfaceState() - strongSelf.raiseToListen?.applicationResignedActive() - - strongSelf.stopMediaRecorder() - } - } - }) - - self.canReadHistoryDisposable = (combineLatest((self.account.applicationContext as! TelegramApplicationContext).applicationBindings.applicationInForeground, self.canReadHistory.get()) |> map { a, b in + self.canReadHistoryDisposable = (combineLatest(context.applicationBindings.applicationInForeground, self.canReadHistory.get()) |> map { a, b in return a && b } |> deliverOnMainQueue).start(next: { [weak self] value in if let strongSelf = self, strongSelf.canReadHistoryValue != value { @@ -1565,7 +1567,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } }) - self.networkStateDisposable = (account.networkState |> deliverOnMainQueue).start(next: { [weak self] state in + self.networkStateDisposable = (context.account.networkState |> deliverOnMainQueue).start(next: { [weak self] state in if let strongSelf = self { strongSelf.chatTitleView?.networkState = state } @@ -1574,7 +1576,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if case let .peer(peerId) = self.chatLocation, peerId.namespace == Namespaces.Peer.SecretChat { self.screenCaptureEventsDisposable = screenCaptureEvents().start(next: { [weak self] _ in if let strongSelf = self, strongSelf.canReadHistoryValue, strongSelf.traceVisibility() { - let _ = addSecretChatMessageScreenshot(account: account, peerId: peerId).start() + let _ = addSecretChatMessageScreenshot(account: context.account, peerId: peerId).start() } }) } @@ -1631,7 +1633,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.screenCaptureEventsDisposable?.dispose() self.chatAdditionalDataDisposable.dispose() self.shareStatusDisposable?.dispose() - self.account.telegramApplicationContext.mediaManager?.galleryHiddenMediaManager.removeTarget(self) + self.context.mediaManager.galleryHiddenMediaManager.removeTarget(self) } public func updatePresentationMode(_ mode: ChatControllerPresentationMode) { @@ -1662,7 +1664,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } override public func loadDisplayNode() { - self.displayNode = ChatControllerNode(account: self.account, chatLocation: self.chatLocation, messageId: self.messageId, controllerInteraction: self.controllerInteraction!, chatPresentationInterfaceState: self.presentationInterfaceState, automaticMediaDownloadSettings: self.automaticMediaDownloadSettings, navigationBar: self.navigationBar, controller: self) + self.displayNode = ChatControllerNode(context: self.context, chatLocation: self.chatLocation, messageId: self.messageId, controllerInteraction: self.controllerInteraction!, chatPresentationInterfaceState: self.presentationInterfaceState, automaticMediaDownloadSettings: self.automaticMediaDownloadSettings, navigationBar: self.navigationBar, controller: self) self.chatDisplayNode.peerView = self.peerView @@ -1981,7 +1983,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let strongSelf = self, case let .peer(peerId) = strongSelf.chatLocation { strongSelf.commitPurposefulAction() - let _ = (enqueueMessages(account: strongSelf.account, peerId: peerId, messages: strongSelf.transformEnqueueMessages(messages)) |> deliverOnMainQueue).start(next: { _ in + let _ = (enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: strongSelf.transformEnqueueMessages(messages)) |> deliverOnMainQueue).start(next: { _ in if let strongSelf = self { strongSelf.chatDisplayNode.historyNode.scrollToEndOfHistory() } @@ -2002,7 +2004,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal return } if case .peer = strongSelf.chatLocation, let messageId = strongSelf.presentationInterfaceState.interfaceState.editMessage?.messageId { - 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 guard let strongSelf = self, let editMessageState = strongSelf.presentationInterfaceState.editMessageState, case let .media(options) = editMessageState.content else { @@ -2078,7 +2080,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.chatDisplayNode.navigateButtons.mentionsPressed = { [weak self] in if let strongSelf = self, strongSelf.isNodeLoaded, case let .peer(peerId) = strongSelf.chatLocation { - let signal = earliestUnseenPersonalMentionMessage(postbox: strongSelf.account.postbox, network: strongSelf.account.network, accountPeerId: strongSelf.account.peerId, peerId: peerId) + let signal = earliestUnseenPersonalMentionMessage(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, accountPeerId: strongSelf.context.account.peerId, peerId: peerId) strongSelf.navigationActionDisposable.set((signal |> deliverOnMainQueue).start(next: { result in if let strongSelf = self { switch result { @@ -2105,7 +2107,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard let strongSelf = self, case let .peer(peerId) = strongSelf.chatLocation else { return } - let _ = clearPeerUnseenPersonalMessagesInteractively(account: strongSelf.account, peerId: peerId).start() + let _ = clearPeerUnseenPersonalMessagesInteractively(account: strongSelf.context.account, peerId: peerId).start() }) ]), ActionSheetItemGroup(items: [ ActionSheetButtonItem(title: strongSelf.presentationData.strings.Common_Cancel, color: .accent, action: { [weak actionSheet] in @@ -2167,11 +2169,11 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal }, deleteSelectedMessages: { [weak self] in if let strongSelf = self { if let messageIds = strongSelf.presentationInterfaceState.interfaceState.selectionState?.selectedIds, !messageIds.isEmpty { - strongSelf.messageContextDisposable.set((chatAvailableMessageActions(postbox: strongSelf.account.postbox, accountPeerId: strongSelf.account.peerId, messageIds: messageIds) + strongSelf.messageContextDisposable.set((chatAvailableMessageActions(postbox: strongSelf.context.account.postbox, accountPeerId: strongSelf.context.account.peerId, messageIds: messageIds) |> deliverOnMainQueue).start(next: { actions in if let strongSelf = self, !actions.options.isEmpty { if let banAuthor = actions.banAuthor { - strongSelf.presentBanMessageOptions(accountPeerId: strongSelf.account.peerId, author: banAuthor, messageIds: messageIds, options: actions.options) + strongSelf.presentBanMessageOptions(accountPeerId: strongSelf.context.account.peerId, author: banAuthor, messageIds: messageIds, options: actions.options) } else { strongSelf.presentDeleteMessageOptions(messageIds: messageIds, options: actions.options) } @@ -2181,24 +2183,24 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } }, reportSelectedMessages: { [weak self] in if let strongSelf = self, let messageIds = strongSelf.presentationInterfaceState.interfaceState.selectionState?.selectedIds, !messageIds.isEmpty { - strongSelf.present(peerReportOptionsController(account: strongSelf.account, subject: .messages(Array(messageIds).sorted()), present: { c, a in + strongSelf.present(peerReportOptionsController(context: strongSelf.context, subject: .messages(Array(messageIds).sorted()), present: { c, a in self?.present(c, in: .window(.root), with: a) }), in: .window(.root)) } }, reportMessages: { [weak self] messages in if let strongSelf = self, !messages.isEmpty { - strongSelf.present(peerReportOptionsController(account: strongSelf.account, subject: .messages(messages.map({ $0.id }).sorted()), present: { c, a in + strongSelf.present(peerReportOptionsController(context: strongSelf.context, subject: .messages(messages.map({ $0.id }).sorted()), present: { c, a in self?.present(c, in: .window(.root), with: a) }), in: .window(.root)) } }, deleteMessages: { [weak self] messages in if let strongSelf = self, !messages.isEmpty { let messageIds = Set(messages.map { $0.id }) - strongSelf.messageContextDisposable.set((chatAvailableMessageActions(postbox: strongSelf.account.postbox, accountPeerId: strongSelf.account.peerId, messageIds: messageIds) + strongSelf.messageContextDisposable.set((chatAvailableMessageActions(postbox: strongSelf.context.account.postbox, accountPeerId: strongSelf.context.account.peerId, messageIds: messageIds) |> deliverOnMainQueue).start(next: { actions in if let strongSelf = self, !actions.options.isEmpty { if let banAuthor = actions.banAuthor { - strongSelf.presentBanMessageOptions(accountPeerId: strongSelf.account.peerId, author: banAuthor, messageIds: messageIds, options: actions.options) + strongSelf.presentBanMessageOptions(accountPeerId: strongSelf.context.account.peerId, author: banAuthor, messageIds: messageIds, options: actions.options) } else { var isAction = false if messages.count == 1 { @@ -2209,7 +2211,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } } if isAction && (actions.options == .deleteGlobally || actions.options == .deleteLocally) { - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: Array(messageIds), type: actions.options == .deleteLocally ? .forLocalPeer : .forEveryone).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: Array(messageIds), type: actions.options == .deleteLocally ? .forLocalPeer : .forEveryone).start() } else { strongSelf.presentDeleteMessageOptions(messageIds: messageIds, options: actions.options) } @@ -2234,7 +2236,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal }, shareSelectedMessages: { [weak self] in if let strongSelf = self, let selectedIds = strongSelf.presentationInterfaceState.interfaceState.selectionState?.selectedIds, !selectedIds.isEmpty { strongSelf.commitPurposefulAction() - let _ = (strongSelf.account.postbox.transaction { transaction -> [Message] in + let _ = (strongSelf.context.account.postbox.transaction { transaction -> [Message] in var messages: [Message] = [] for id in selectedIds { if let message = transaction.getMessage(id) { @@ -2246,7 +2248,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let strongSelf = self, !messages.isEmpty { strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { $0.updatedInterfaceState({ $0.withoutSelectionState() }) }) - let shareController = ShareController(account: strongSelf.account, subject: .messages(messages.sorted(by: { lhs, rhs in + let shareController = ShareController(context: strongSelf.context, subject: .messages(messages.sorted(by: { lhs, rhs in return MessageIndex(lhs) < MessageIndex(rhs) })), externalShare: true, immediateExternalShare: true) strongSelf.chatDisplayNode.dismissInput() @@ -2299,7 +2301,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal media = .keep } - strongSelf.editMessageDisposable.set((requestEditMessage(account: strongSelf.account, messageId: editMessage.messageId, text: text.string, media: media + strongSelf.editMessageDisposable.set((requestEditMessage(account: strongSelf.context.account, messageId: editMessage.messageId, text: text.string, media: media , entities: entitiesAttribute, disableUrlPreview: disableUrlPreview) |> deliverOnMainQueue |> afterDisposed({ editingMessage.set(nil) })).start(next: { result in @@ -2414,7 +2416,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal let controller = ChatDateSelectionSheet(theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, completion: { timestamp in if let strongSelf = self { strongSelf.loadingMessage.set(true) - strongSelf.messageIndexDisposable.set((searchMessageIdByTimestamp(account: strongSelf.account, peerId: peerId, timestamp: timestamp) |> deliverOnMainQueue).start(next: { messageId in + strongSelf.messageIndexDisposable.set((searchMessageIdByTimestamp(account: strongSelf.context.account, peerId: peerId, timestamp: timestamp) |> deliverOnMainQueue).start(next: { messageId in if let strongSelf = self { strongSelf.loadingMessage.set(false) if let messageId = messageId { @@ -2451,7 +2453,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self?.navigationButtonAction(.openChatInfo) }, togglePeerNotifications: { [weak self] in if let strongSelf = self, case let .peer(peerId) = strongSelf.chatLocation { - let _ = togglePeerMuted(account: strongSelf.account, peerId: peerId).start() + let _ = togglePeerMuted(account: strongSelf.context.account, peerId: peerId).start() } }, sendContextResult: { [weak self] results, result in self?.enqueueChatContextResult(results, result) @@ -2497,13 +2499,13 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard let strongSelf = self, strongSelf.beginMediaRecordingRequestId == requestId else { return } - guard checkAvailableDiskSpace(account: strongSelf.account, present: { [weak self] c, a in + guard checkAvailableDiskSpace(account: strongSelf.context.account, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a) }) else { return } let hasOngoingCall: Signal - if let signal = strongSelf.account.telegramApplicationContext.hasOngoingCall { + if let signal = strongSelf.context.hasOngoingCall { hasOngoingCall = signal } else { hasOngoingCall = .single(false) @@ -2528,7 +2530,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal DeviceAccess.authorizeAccess(to: .microphone(isVideo ? .video : .audio), presentationData: strongSelf.presentationData, present: { c, a in self?.present(c, in: .window(.root), with: a) }, openSettings: { - self?.account.telegramApplicationContext.applicationBindings.openSettings() + self?.context.applicationBindings.openSettings() }, { granted in guard let strongSelf = self, granted else { return @@ -2537,7 +2539,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal DeviceAccess.authorizeAccess(to: .camera, presentationData: strongSelf.presentationData, present: { c, a in self?.present(c, in: .window(.root), with: a) }, openSettings: { - self?.account.telegramApplicationContext.applicationBindings.openSettings() + self?.context.applicationBindings.openSettings() }, { granted in if granted { begin() @@ -2680,7 +2682,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal }) if let updatedMode = updatedMode, updatedMode == .video { - let _ = ApplicationSpecificNotice.incrementChatMediaMediaRecordingTips(postbox: strongSelf.account.postbox, count: 3).start() + let _ = ApplicationSpecificNotice.incrementChatMediaMediaRecordingTips(postbox: strongSelf.context.account.postbox, count: 3).start() } strongSelf.displayMediaRecordingTip() @@ -2690,9 +2692,9 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal strongSelf.chatDisplayNode.dismissInput() if let peer = strongSelf.presentationInterfaceState.renderedPeer?.peer as? TelegramSecretChat { - let controller = ChatSecretAutoremoveTimerActionSheetController(account: strongSelf.account, currentValue: peer.messageAutoremoveTimeout == nil ? 0 : peer.messageAutoremoveTimeout!, applyValue: { value in + let controller = ChatSecretAutoremoveTimerActionSheetController(context: strongSelf.context, currentValue: peer.messageAutoremoveTimeout == nil ? 0 : peer.messageAutoremoveTimeout!, applyValue: { value in if let strongSelf = self { - let _ = setSecretChatMessageAutoremoveTimeoutInteractively(account: strongSelf.account, peerId: peer.id, timeout: value == 0 ? nil : value).start() + let _ = setSecretChatMessageAutoremoveTimeoutInteractively(account: strongSelf.context.account, peerId: peer.id, timeout: value == 0 ? nil : value).start() } }) strongSelf.present(controller, in: .window(.root)) @@ -2750,7 +2752,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal disposable = MetaDisposable() strongSelf.unpinMessageDisposable = disposable } - disposable.set(requestUpdatePinnedMessage(account: strongSelf.account, peerId: currentPeerId, update: .pin(id: messageId, silent: !notify)).start()) + disposable.set(requestUpdatePinnedMessage(account: strongSelf.context.account, peerId: currentPeerId, update: .pin(id: messageId, silent: !notify)).start()) } } @@ -2810,7 +2812,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal disposable = MetaDisposable() strongSelf.unpinMessageDisposable = disposable } - disposable.set(requestUpdatePinnedMessage(account: strongSelf.account, peerId: peer.id, update: .clear).start()) + disposable.set(requestUpdatePinnedMessage(account: strongSelf.context.account, peerId: peer.id, update: .clear).start()) } })]), in: .window(.root)) } else { @@ -2843,9 +2845,9 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } } if let stickerFile = stickerFile { - let postbox = strongSelf.account.postbox - let network = strongSelf.account.network - let _ = (strongSelf.account.postbox.transaction { transaction -> Signal in + let postbox = strongSelf.context.account.postbox + let network = strongSelf.context.account.network + let _ = (strongSelf.context.account.postbox.transaction { transaction -> Signal in if getIsStickerSaved(transaction: transaction, fileId: stickerFile.fileId) { removeSavedSticker(transaction: transaction, mediaId: stickerFile.fileId) return .complete() @@ -2870,7 +2872,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } }, openGrouping: { [weak self] in if let strongSelf = self, case let .group(groupId) = strongSelf.chatLocation { - (strongSelf.navigationController as? NavigationController)?.pushViewController(FeedGroupingController(account: strongSelf.account, groupId: groupId)) + (strongSelf.navigationController as? NavigationController)?.pushViewController(FeedGroupingController(context: strongSelf.context, groupId: groupId)) } }, toggleSilentPost: { [weak self] in if let strongSelf = self { @@ -2925,7 +2927,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } let controller = OverlayStatusController(theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, type: .loading(cancelled: nil)) strongSelf.present(controller, in: .window(.root)) - let signal = requestMessageSelectPollOption(account: strongSelf.account, messageId: id, opaqueIdentifier: nil) + let signal = requestMessageSelectPollOption(account: strongSelf.context.account, messageId: id, opaqueIdentifier: nil) |> afterDisposed { [weak controller] in Queue.mainQueue().async { controller?.dismiss() @@ -2964,7 +2966,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } let controller = OverlayStatusController(theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, type: .loading(cancelled: nil)) strongSelf.present(controller, in: .window(.root)) - let signal = requestClosePoll(postbox: strongSelf.account.postbox, network: strongSelf.account.network, stateManager: strongSelf.account.stateManager, messageId: id) + let signal = requestClosePoll(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, stateManager: strongSelf.context.account.stateManager, messageId: id) |> afterDisposed { [weak controller] in Queue.mainQueue().async { controller?.dismiss() @@ -2999,7 +3001,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal case let .peer(peerId): let unreadCountsKey: PostboxViewKey = .unreadCounts(items: [.peer(peerId), .total(ApplicationSpecificPreferencesKeys.inAppNotificationSettings)]) let notificationSettingsKey: PostboxViewKey = .peerNotificationSettings(peerIds: Set([peerId])) - self.chatUnreadCountDisposable = (self.account.postbox.combinedView(keys: [unreadCountsKey, notificationSettingsKey]) + self.chatUnreadCountDisposable = (self.context.account.postbox.combinedView(keys: [unreadCountsKey, notificationSettingsKey]) |> deliverOnMainQueue).start(next: { [weak self] views in if let strongSelf = self { var unreadCount: Int32 = 0 @@ -3040,15 +3042,15 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } }) - self.chatUnreadMentionCountDisposable = (self.account.viewTracker.unseenPersonalMessagesCount(peerId: peerId) |> deliverOnMainQueue).start(next: { [weak self] count in + self.chatUnreadMentionCountDisposable = (self.context.account.viewTracker.unseenPersonalMessagesCount(peerId: peerId) |> deliverOnMainQueue).start(next: { [weak self] count in if let strongSelf = self { strongSelf.chatDisplayNode.navigateButtons.mentionCount = count } }) - let postbox = self.account.postbox + let postbox = self.context.account.postbox let previousPeerCache = Atomic<[PeerId: Peer]>(value: [:]) - self.peerInputActivitiesDisposable = (self.account.peerInputActivities(peerId: peerId) + self.peerInputActivitiesDisposable = (self.context.account.peerInputActivities(peerId: peerId) |> mapToSignal { activities -> Signal<[(Peer, PeerInputActivity)], NoError> in var foundAllPeers = true var cachedResult: [(Peer, PeerInputActivity)] = [] @@ -3085,9 +3087,9 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } }) - self.sentMessageEventsDisposable.set(self.account.pendingMessageManager.deliveredMessageEvents(peerId: peerId).start(next: { [weak self] _ in + self.sentMessageEventsDisposable.set(self.context.account.pendingMessageManager.deliveredMessageEvents(peerId: peerId).start(next: { [weak self] _ in if let strongSelf = self { - let inAppNotificationSettings: InAppNotificationSettings = strongSelf.account.telegramApplicationContext.currentInAppNotificationSettings.with { $0 } + let inAppNotificationSettings: InAppNotificationSettings = strongSelf.context.currentInAppNotificationSettings.with { $0 } if inAppNotificationSettings.playSounds { serviceSoundManager.playMessageDeliveredSound() @@ -3095,7 +3097,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } })) - self.failedMessageEventsDisposable.set((self.account.pendingMessageManager.failedMessageEvents(peerId: peerId) + self.failedMessageEventsDisposable.set((self.context.account.pendingMessageManager.failedMessageEvents(peerId: peerId) |> deliverOnMainQueue).start(next: { [weak self] reason in if let strongSelf = self { let text: String @@ -3113,7 +3115,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal })) case let .group(groupId): let unreadCountsKey: PostboxViewKey = .unreadCounts(items: [.group(groupId), .total(ApplicationSpecificPreferencesKeys.inAppNotificationSettings)]) - self.chatUnreadCountDisposable = (self.account.postbox.combinedView(keys: [unreadCountsKey]) |> deliverOnMainQueue).start(next: { [weak self] views in + self.chatUnreadCountDisposable = (self.context.account.postbox.combinedView(keys: [unreadCountsKey]) |> deliverOnMainQueue).start(next: { [weak self] views in if let strongSelf = self { var unreadCount: Int32 = 0 var totalCount: Int32 = 0 @@ -3137,30 +3139,29 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.interfaceInteraction = interfaceInteraction self.chatDisplayNode.interfaceInteraction = interfaceInteraction - if let mediaManager = self.account.telegramApplicationContext.mediaManager { - mediaManager.galleryHiddenMediaManager.addTarget(self) - self.galleryHiddenMesageAndMediaDisposable.set(mediaManager.galleryHiddenMediaManager.hiddenIds().start(next: { [weak self] ids in - if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { - var messageIdAndMedia: [MessageId: [Media]] = [:] - - for id in ids { - if case let .chat(messageId, media) = id { - messageIdAndMedia[messageId] = [media] + let mediaManager = self.context.mediaManager + mediaManager.galleryHiddenMediaManager.addTarget(self) + self.galleryHiddenMesageAndMediaDisposable.set(mediaManager.galleryHiddenMediaManager.hiddenIds().start(next: { [weak self] ids in + if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { + var messageIdAndMedia: [MessageId: [Media]] = [:] + + for id in ids { + if case let .chat(messageId, media) = id { + messageIdAndMedia[messageId] = [media] + } + } + + //if controllerInteraction.hiddenMedia != messageIdAndMedia { + controllerInteraction.hiddenMedia = messageIdAndMedia + + strongSelf.chatDisplayNode.historyNode.forEachItemNode { itemNode in + if let itemNode = itemNode as? ChatMessageItemView { + itemNode.updateHiddenMedia() } } - - //if controllerInteraction.hiddenMedia != messageIdAndMedia { - controllerInteraction.hiddenMedia = messageIdAndMedia - - strongSelf.chatDisplayNode.historyNode.forEachItemNode { itemNode in - if let itemNode = itemNode as? ChatMessageItemView { - itemNode.updateHiddenMedia() - } - } - //} - } - })) - } + //} + } + })) self.chatDisplayNode.dismissAsOverlay = { [weak self] in if let strongSelf = self { @@ -3181,13 +3182,13 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal super.viewDidAppear(animated) self.chatDisplayNode.historyNode.preloadPages = true - self.chatDisplayNode.historyNode.canReadHistory.set(combineLatest((self.account.applicationContext as! TelegramApplicationContext).applicationBindings.applicationInForeground, self.canReadHistory.get()) |> map { a, b in + self.chatDisplayNode.historyNode.canReadHistory.set(combineLatest(context.applicationBindings.applicationInForeground, self.canReadHistory.get()) |> map { a, b in return a && b }) self.chatDisplayNode.loadInputPanels(theme: self.presentationInterfaceState.theme, strings: self.presentationInterfaceState.strings) - self.recentlyUsedInlineBotsDisposable = (recentlyUsedInlineBots(postbox: self.account.postbox) |> deliverOnMainQueue).start(next: { [weak self] peers in + self.recentlyUsedInlineBotsDisposable = (recentlyUsedInlineBots(postbox: self.context.account.postbox) |> deliverOnMainQueue).start(next: { [weak self] peers in self?.recentlyUsedInlineBotsValue = peers.filter({ $0.1 >= 0.14 }).map({ $0.0 }) }) @@ -3207,7 +3208,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } if strongSelf.firstLoadedMessageToListen() != nil || strongSelf.chatDisplayNode.isTextInputPanelActive { - if strongSelf.account.telegramApplicationContext.immediateHasOngoingCall { + if strongSelf.context.immediateHasOngoingCall { return false } @@ -3215,7 +3216,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal return false } - if !strongSelf.account.telegramApplicationContext.currentMediaInputSettings.with { $0.enableRaiseToSpeak } { + if !strongSelf.context.currentMediaInputSettings.with { $0.enableRaiseToSpeak } { return false } @@ -3272,7 +3273,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if !self.checkedPeerChatServiceActions { self.checkedPeerChatServiceActions = true if case let .peer(peerId) = self.chatLocation { - let _ = checkPeerChatServiceActions(postbox: self.account.postbox, peerId: peerId).start() + let _ = checkPeerChatServiceActions(postbox: self.context.account.postbox, peerId: peerId).start() } if self.chatDisplayNode.frameForInputActionButton() != nil, self.presentationInterfaceState.interfaceState.mediaRecordingMode == .audio { @@ -3289,7 +3290,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal canSendMedia = true } if canSendMedia { - let _ = (ApplicationSpecificNotice.getChatMediaMediaRecordingTips(postbox: self.account.postbox) + let _ = (ApplicationSpecificNotice.getChatMediaMediaRecordingTips(postbox: self.context.account.postbox) |> deliverOnMainQueue).start(next: { [weak self] counter in guard let strongSelf = self else { return @@ -3301,7 +3302,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal displayTip = true } if displayTip { - let _ = ApplicationSpecificNotice.incrementChatMediaMediaRecordingTips(postbox: strongSelf.account.postbox).start() + let _ = ApplicationSpecificNotice.incrementChatMediaMediaRecordingTips(postbox: strongSelf.context.account.postbox).start() strongSelf.displayMediaRecordingTip() } }) @@ -3335,7 +3336,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal interfaceState = interfaceState.withUpdatedHistoryScrollState(scrollState) } interfaceState = interfaceState.withUpdatedInputLanguage(self.chatDisplayNode.currentTextInputLanguage) - let _ = updatePeerChatInterfaceState(account: account, peerId: peerId, state: interfaceState).start() + let _ = updatePeerChatInterfaceState(account: self.context.account, peerId: peerId, state: interfaceState).start() } } @@ -3410,10 +3411,10 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } } - let inputTextPanelState = inputTextPanelStateForChatPresentationInterfaceState(temporaryChatPresentationInterfaceState, account: self.account) + let inputTextPanelState = inputTextPanelStateForChatPresentationInterfaceState(temporaryChatPresentationInterfaceState, context: self.context) var updatedChatPresentationInterfaceState = temporaryChatPresentationInterfaceState.updatedInputTextPanelState({ _ in return inputTextPanelState }) - let contextQueryUpdates = contextQueryResultStateForChatInterfacePresentationState(updatedChatPresentationInterfaceState, account: self.account, currentQueryStates: &self.contextQueryStates) + let contextQueryUpdates = contextQueryResultStateForChatInterfacePresentationState(updatedChatPresentationInterfaceState, context: self.context, currentQueryStates: &self.contextQueryStates) for (kind, update) in contextQueryUpdates { switch update { @@ -3455,10 +3456,10 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if case let .peer(peerId) = self.chatLocation, peerId.namespace == Namespaces.Peer.SecretChat { if case .contextRequest = query { - let _ = (ApplicationSpecificNotice.getSecretChatInlineBotUsage(postbox: self.account.postbox) + let _ = (ApplicationSpecificNotice.getSecretChatInlineBotUsage(postbox: self.context.account.postbox) |> deliverOnMainQueue).start(next: { [weak self] value in if let strongSelf = self, !value { - let _ = ApplicationSpecificNotice.setSecretChatInlineBotUsage(postbox: strongSelf.account.postbox).start() + let _ = ApplicationSpecificNotice.setSecretChatInlineBotUsage(postbox: strongSelf.context.account.postbox).start() strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: strongSelf.presentationData.theme), title: nil, text: strongSelf.presentationData.strings.Conversation_SecretChatContextBotAlert, actions: [TextAlertAction(type: .defaultAction, title: strongSelf.presentationData.strings.Common_OK, action: {})]), in: .window(.root)) } }) @@ -3467,7 +3468,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } } - if let (updatedSearchQuerySuggestionState, updatedSearchQuerySuggestionSignal) = searchQuerySuggestionResultStateForChatInterfacePresentationState(updatedChatPresentationInterfaceState, account: self.account, currentQuery: self.searchQuerySuggestionState?.0) { + if let (updatedSearchQuerySuggestionState, updatedSearchQuerySuggestionSignal) = searchQuerySuggestionResultStateForChatInterfacePresentationState(updatedChatPresentationInterfaceState, context: context, currentQuery: self.searchQuerySuggestionState?.0) { self.searchQuerySuggestionState?.1.dispose() var inScope = true var inScopeResult: ((ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?)? @@ -3493,13 +3494,13 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } } - if let (updatedUrlPreviewUrl, updatedUrlPreviewSignal) = urlPreviewStateForInputText(updatedChatPresentationInterfaceState.interfaceState.composeInputState.inputText.string, account: self.account, currentQuery: self.urlPreviewQueryState?.0) { + if let (updatedUrlPreviewUrl, updatedUrlPreviewSignal) = urlPreviewStateForInputText(updatedChatPresentationInterfaceState.interfaceState.composeInputState.inputText.string, context: self.context, currentQuery: self.urlPreviewQueryState?.0) { self.urlPreviewQueryState?.1.dispose() var inScope = true var inScopeResult: ((TelegramMediaWebpage?) -> TelegramMediaWebpage?)? let linkPreviews: Signal if case let .peer(peerId) = self.chatLocation, peerId.namespace == Namespaces.Peer.SecretChat { - linkPreviews = interactiveChatLinkPreviewsEnabled(postbox: self.account.postbox, displayAlert: { [weak self] f in + linkPreviews = interactiveChatLinkPreviewsEnabled(postbox: self.context.account.postbox, displayAlert: { [weak self] f in if let strongSelf = self { strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: strongSelf.presentationData.theme), title: nil, text: strongSelf.presentationData.strings.Conversation_SecretLinkPreviewAlert, actions: [ TextAlertAction(type: .defaultAction, title: strongSelf.presentationData.strings.Common_Yes, action: { @@ -3560,7 +3561,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal let isEditingMedia: Bool = updatedChatPresentationInterfaceState.editMessageState?.content != .plaintext let editingUrlPreviewText: String? = isEditingMedia ? nil : updatedChatPresentationInterfaceState.interfaceState.editMessage?.inputState.inputText.string - if let (updatedEditingUrlPreviewUrl, updatedEditingUrlPreviewSignal) = urlPreviewStateForInputText(editingUrlPreviewText, account: self.account, currentQuery: self.editingUrlPreviewQueryState?.0) { + if let (updatedEditingUrlPreviewUrl, updatedEditingUrlPreviewSignal) = urlPreviewStateForInputText(editingUrlPreviewText, context: self.context, currentQuery: self.editingUrlPreviewQueryState?.0) { self.editingUrlPreviewQueryState?.1.dispose() var inScope = true var inScopeResult: ((TelegramMediaWebpage?) -> TelegramMediaWebpage?)? @@ -3703,7 +3704,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal case .clearHistory: if case let .peer(peerId) = self.chatLocation { let text: String - if peerId == account.peerId { + if peerId == self.context.account.peerId { text = self.presentationData.strings.Conversation_ClearSelfHistory } else if peerId.namespace == Namespaces.Peer.SecretChat { text = self.presentationData.strings.Conversation_ClearSecretHistory @@ -3721,8 +3722,8 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let strongSelf = self { strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { $0.updatedInterfaceState { $0.withoutSelectionState() } }) strongSelf.chatDisplayNode.historyNode.historyAppearsCleared = true - let account = strongSelf.account - strongSelf.present(UndoOverlayController(account: strongSelf.account, text: strongSelf.presentationData.strings.Undo_MessagesDeleted, action: { shouldCommit in + let account = strongSelf.context.account + strongSelf.present(UndoOverlayController(context: strongSelf.context, text: strongSelf.presentationData.strings.Undo_MessagesDeleted, action: { shouldCommit in if shouldCommit { let _ = clearHistoryInteractively(postbox: account.postbox, peerId: peerId).start(completed: { self?.chatDisplayNode.historyNode.historyAppearsCleared = false @@ -3749,14 +3750,14 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal |> take(1) |> deliverOnMainQueue).start(next: { [weak self] peerView in if let strongSelf = self, let peer = peerView.peers[peerView.peerId], peer.restrictionText == nil { - if let infoController = peerInfoController(account: strongSelf.account, peer: peer) { + if let infoController = peerInfoController(context: strongSelf.context, peer: peer) { (strongSelf.navigationController as? NavigationController)?.pushViewController(infoController) } } })) case .group: if case let .group(groupId) = self.chatLocation { - (self.navigationController as? NavigationController)?.pushViewController(ChatListController(account: self.account, groupId: groupId, controlsHistoryPreload: false)) + (self.navigationController as? NavigationController)?.pushViewController(ChatListController(context: self.context, groupId: groupId, controlsHistoryPreload: false)) } } case .search: @@ -3789,14 +3790,14 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal return } - let _ = (legacyAssetPickerEnqueueMessages(account: self.account, signals: signals) + let _ = (legacyAssetPickerEnqueueMessages(account: self.context.account, signals: signals) |> deliverOnMainQueue).start(next: { [weak self] messages in self?.editMessageMediaWithMessages(messages) }) } private func presentAttachmentMenu(editMediaOptions: MessageMediaEditingOptions?) { - let _ = (self.account.postbox.transaction { transaction -> GeneratedMediaStoreSettings in + let _ = (self.context.account.postbox.transaction { transaction -> GeneratedMediaStoreSettings in let entry = transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.generatedMediaStoreSettings) as? GeneratedMediaStoreSettings return entry ?? GeneratedMediaStoreSettings.defaultSettings } @@ -3873,7 +3874,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal legacyController.bind(controller: navigationController) legacyController.enableSizeClassSignal = true - let controller = legacyAttachmentMenu(account: strongSelf.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(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: { self?.presentMediaPicker(fileMode: false, editingMedia: editMediaOptions != nil, completion: { signals in if editMediaOptions != nil { self?.editMessageMediaWithLegacySignals(signals) @@ -3883,7 +3884,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal }) }, openCamera: { cameraView, menuController in if let strongSelf = self, let peer = strongSelf.presentationInterfaceState.renderedPeer?.peer { - presentedLegacyCamera(account: strongSelf.account, peer: peer, cameraView: cameraView, menuController: menuController, parentController: strongSelf, editingMedia: editMediaOptions != nil, saveCapturedPhotos: settings.storeEditedPhotos, mediaGrouping: true, sendMessagesWithSignals: { signals in + presentedLegacyCamera(context: strongSelf.context, peer: peer, cameraView: cameraView, menuController: menuController, parentController: strongSelf, editingMedia: editMediaOptions != nil, saveCapturedPhotos: settings.storeEditedPhotos, mediaGrouping: true, sendMessagesWithSignals: { signals in if editMediaOptions != nil { self?.editMessageMediaWithLegacySignals(signals!) } else { @@ -3928,7 +3929,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal strongSelf.present(legacyController, in: .window(.root)) controller.present(in: emptyController, sourceView: nil, animated: true) - let presentationDisposable = strongSelf.account.telegramApplicationContext.presentationData.start(next: { [weak controller] presentationData in + let presentationDisposable = strongSelf.context.presentationData.start(next: { [weak controller] presentationData in if let controller = controller { controller.pallete = legacyMenuPaletteFromTheme(presentationData.theme) } @@ -4007,7 +4008,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } private func presentMediaPicker(fileMode: Bool, editingMedia: Bool, completion: @escaping ([Any]) -> Void) { - let _ = (self.account.postbox.transaction { transaction -> (GeneratedMediaStoreSettings, SearchBotsConfiguration) in + let _ = (self.context.account.postbox.transaction { transaction -> (GeneratedMediaStoreSettings, SearchBotsConfiguration) in let entry = transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.generatedMediaStoreSettings) as? GeneratedMediaStoreSettings let configuration = currentSearchBotsConfiguration(transaction: transaction) return (entry ?? GeneratedMediaStoreSettings.defaultSettings, configuration) @@ -4016,7 +4017,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard let strongSelf = self, let peer = strongSelf.presentationInterfaceState.renderedPeer?.peer else { return } - let _ = legacyAssetPicker(applicationContext: strongSelf.account.telegramApplicationContext, presentationData: strongSelf.presentationData, editingMedia: editingMedia, fileMode: fileMode, peer: peer, saveEditedPhotos: settings.storeEditedPhotos, allowGrouping: true).start(next: { generator in + let _ = legacyAssetPicker(context: strongSelf.context, presentationData: strongSelf.presentationData, editingMedia: editingMedia, fileMode: fileMode, peer: peer, saveEditedPhotos: settings.storeEditedPhotos, allowGrouping: true).start(next: { generator in if let strongSelf = self { let legacyController = LegacyController(presentation: .modal(animateIn: true), theme: strongSelf.presentationData.theme, initialLayout: strongSelf.validLayout) legacyController.statusBar.statusBarStyle = strongSelf.presentationData.theme.rootController.statusBar.style.style @@ -4027,9 +4028,9 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal legacyController.bind(controller: controller) legacyController.deferScreenEdgeGestures = [.top] - configureLegacyAssetPicker(controller, account: strongSelf.account, peer: peer, presentWebSearch: { [weak self, weak legacyController] in + configureLegacyAssetPicker(controller, context: strongSelf.context, peer: peer, presentWebSearch: { [weak self, weak legacyController] in if let strongSelf = self { - let controller = WebSearchController(account: strongSelf.account, peer: peer, configuration: searchBotsConfiguration, mode: .media(completion: { results, selectionState, editingState in + let controller = WebSearchController(context: strongSelf.context, peer: peer, configuration: searchBotsConfiguration, mode: .media(completion: { results, selectionState, editingState in if let legacyController = legacyController { legacyController.dismiss() } @@ -4070,7 +4071,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal return } - let _ = (self.account.postbox.transaction { transaction -> SearchBotsConfiguration in + let _ = (self.context.account.postbox.transaction { transaction -> SearchBotsConfiguration in if let entry = transaction.getPreferencesEntry(key: PreferencesKeys.searchBotsConfiguration) as? SearchBotsConfiguration { return entry } else { @@ -4079,7 +4080,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } |> deliverOnMainQueue).start(next: { [weak self] configuration in if let strongSelf = self { - let controller = WebSearchController(account: strongSelf.account, peer: peer, configuration: configuration, mode: .media(completion: { [weak self] results, selectionState, editingState in + let controller = WebSearchController(context: strongSelf.context, peer: peer, configuration: configuration, mode: .media(completion: { [weak self] results, selectionState, editingState in legacyEnqueueWebSearchMessages(selectionState, editingState, enqueueChatContextResult: { [weak self] result in if let strongSelf = self { strongSelf.enqueueChatContextResult(results, result, hideVia: true) @@ -4103,9 +4104,9 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let peer = peer as? TelegramChannel, case .broadcast = peer.info { selfPeerId = peer.id } else { - selfPeerId = self.account.peerId + selfPeerId = self.context.account.peerId } - let _ = (self.account.postbox.transaction { transaction -> Peer? in + let _ = (self.context.account.postbox.transaction { transaction -> Peer? in return transaction.getPeer(selfPeerId) } |> deliverOnMainQueue).start(next: { [weak self] selfPeer in @@ -4114,7 +4115,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } strongSelf.chatDisplayNode.dismissInput() - strongSelf.present(legacyLocationPickerController(account: strongSelf.account, selfPeer: selfPeer, peer: peer, sendLocation: { coordinate, venue in + strongSelf.present(legacyLocationPickerController(context: strongSelf.context, selfPeer: selfPeer, peer: peer, sendLocation: { coordinate, venue in guard let strongSelf = self else { return } @@ -4156,7 +4157,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } private func presentContactPicker() { - let contactsController = ContactSelectionController(account: self.account, title: { $0.Contacts_Title }, displayDeviceContacts: true) + let contactsController = ContactSelectionController(context: self.context, title: { $0.Contacts_Title }, displayDeviceContacts: true) self.chatDisplayNode.dismissInput() self.present(contactsController, in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) self.controllerNavigationDisposable.set((contactsController.result |> deliverOnMainQueue).start(next: { [weak self] peer in @@ -4168,8 +4169,8 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal return } let contactData = DeviceContactExtendedData(basicData: DeviceContactBasicData(firstName: contact.firstName ?? "", lastName: contact.lastName ?? "", phoneNumbers: [DeviceContactPhoneNumberData(label: "_$!!$_", value: phoneNumber)]), middleName: "", prefix: "", suffix: "", organization: "", jobTitle: "", department: "", emailAddresses: [], urls: [], addresses: [], birthdayDate: nil, socialProfiles: [], instantMessagingProfiles: []) - let account = strongSelf.account - dataSignal = strongSelf.account.telegramApplicationContext.contactDataManager.basicData() + let context = strongSelf.context + dataSignal = strongSelf.context.contactDataManager.basicData() |> take(1) |> mapToSignal { basicData -> Signal<(Peer?, DeviceContactExtendedData?), NoError> in var stableId: String? @@ -4184,7 +4185,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } if let stableId = stableId { - return account.telegramApplicationContext.contactDataManager.extendedData(stableId: stableId) + return context.contactDataManager.extendedData(stableId: stableId) |> take(1) |> map { extendedData -> (Peer?, DeviceContactExtendedData?) in return (contact, extendedData) @@ -4194,7 +4195,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } } case let .deviceContact(id, _): - dataSignal = strongSelf.account.telegramApplicationContext.contactDataManager.extendedData(stableId: id) + dataSignal = strongSelf.context.contactDataManager.extendedData(stableId: id) |> take(1) |> map { extendedData -> (Peer?, DeviceContactExtendedData?) in return (nil, extendedData) @@ -4217,7 +4218,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal let message = EnqueueMessage.message(text: "", attributes: [], mediaReference: .standalone(media: media), replyToMessageId: replyMessageId, localGroupingKey: nil) strongSelf.sendMessages([message]) } else { - strongSelf.present(deviceContactInfoController(account: strongSelf.account, subject: .filter(peer: peerAndContactData.0, contactId: nil, contactData: contactData, completion: { peer, contactData in + strongSelf.present(deviceContactInfoController(context: strongSelf.context, subject: .filter(peer: peerAndContactData.0, contactId: nil, contactData: contactData, completion: { peer, contactData in guard let strongSelf = self, !contactData.basicData.phoneNumbers.isEmpty else { return } @@ -4245,7 +4246,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal private func presentPollCreation() { if case let .peer(peerId) = self.chatLocation { - self.present(createPollController(account: self.account, peerId: peerId, completion: { [weak self] message in + self.present(createPollController(context: self.context, peerId: peerId, completion: { [weak self] message in guard let strongSelf = self else { return } @@ -4287,7 +4288,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if case let .peer(peerId) = self.chatLocation { self.commitPurposefulAction() - let _ = (enqueueMessages(account: self.account, peerId: peerId, messages: self.transformEnqueueMessages(messages)) + let _ = (enqueueMessages(account: self.context.account, peerId: peerId, messages: self.transformEnqueueMessages(messages)) |> deliverOnMainQueue).start(next: { [weak self] _ in self?.chatDisplayNode.historyNode.scrollToEndOfHistory() }) @@ -4296,7 +4297,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal private func enqueueMediaMessages(signals: [Any]?) { if case .peer = self.chatLocation { - self.enqueueMediaMessageDisposable.set((legacyAssetPickerEnqueueMessages(account: self.account, signals: signals!) + self.enqueueMediaMessageDisposable.set((legacyAssetPickerEnqueueMessages(account: self.context.account, signals: signals!) |> deliverOnMainQueue).start(next: { [weak self] messages in if let strongSelf = self { let replyMessageId = strongSelf.presentationInterfaceState.interfaceState.replyMessageId @@ -4314,14 +4315,14 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } private func displayPasteMenu(_ images: [UIImage]) { - let _ = (self.account.postbox.transaction { transaction -> GeneratedMediaStoreSettings in + let _ = (self.context.account.postbox.transaction { transaction -> GeneratedMediaStoreSettings in let entry = transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.generatedMediaStoreSettings) as? GeneratedMediaStoreSettings return entry ?? GeneratedMediaStoreSettings.defaultSettings } |> deliverOnMainQueue).start(next: { [weak self] settings in if let strongSelf = self, let peer = strongSelf.presentationInterfaceState.renderedPeer?.peer { strongSelf.chatDisplayNode.dismissInput() - let _ = presentLegacyPasteMenu(account: strongSelf.account, peer: peer, saveEditedPhotos: settings.storeEditedPhotos, allowGrouping: true, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, images: images, sendMessagesWithSignals: { signals in + 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 self?.enqueueMediaMessages(signals: signals) }, present: { [weak self] controller, arguments in if let strongSelf = self { @@ -4333,7 +4334,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } private func enqueueGifData(_ data: Data) { - self.enqueueMediaMessageDisposable.set((legacyEnqueueGifMessage(account: self.account, data: data) |> deliverOnMainQueue).start(next: { [weak self] message in + self.enqueueMediaMessageDisposable.set((legacyEnqueueGifMessage(account: self.context.account, data: data) |> deliverOnMainQueue).start(next: { [weak self] message in if let strongSelf = self { let replyMessageId = strongSelf.presentationInterfaceState.interfaceState.replyMessageId strongSelf.chatDisplayNode.setupSendActionOnViewUpdate({ @@ -4353,7 +4354,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.enqueueMediaMessageDisposable.set((convertToWebP(image: image, targetSize: size, quality: 0.85) |> deliverOnMainQueue).start(next: { [weak self] data in if let strongSelf = self, !data.isEmpty { let resource = LocalFileMediaResource(fileId: arc4random64()) - strongSelf.account.postbox.mediaBox.storeResourceData(resource.id, data: data) + strongSelf.context.account.postbox.mediaBox.storeResourceData(resource.id, data: data) var fileAttributes: [TelegramMediaFileAttribute] = [] fileAttributes.append(.FileName(fileName: "sticker.webp")) @@ -4433,17 +4434,13 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal private func requestAudioRecorder(beginWithTone: Bool) { if self.audioRecorderValue == nil { - if let applicationContext = self.account.applicationContext as? TelegramApplicationContext { - if self.recorderFeedback == nil { - self.recorderFeedback = HapticFeedback() - self.recorderFeedback?.prepareImpact(.light) - } - - if let mediaManager = applicationContext.mediaManager { - self.audioRecorder.set(mediaManager.audioRecorder(beginWithTone: beginWithTone, applicationBindings: applicationContext.applicationBindings, beganWithTone: { _ in - })) - } + if self.recorderFeedback == nil { + self.recorderFeedback = HapticFeedback() + self.recorderFeedback?.prepareImpact(.light) } + + self.audioRecorder.set(self.context.mediaManager.audioRecorder(beginWithTone: beginWithTone, applicationBindings: self.context.applicationBindings, beganWithTone: { _ in + })) } } @@ -4459,7 +4456,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.recorderFeedback?.prepareImpact(.light) } - self.videoRecorder.set(.single(legacyInstantVideoController(theme: self.presentationData.theme, panelFrame: currentInputPanelFrame, account: self.account, peerId: peerId, send: { [weak self] message in + self.videoRecorder.set(.single(legacyInstantVideoController(theme: self.presentationData.theme, panelFrame: currentInputPanelFrame, context: self.context, peerId: peerId, send: { [weak self] message in if let strongSelf = self { let replyMessageId = strongSelf.presentationInterfaceState.interfaceState.replyMessageId strongSelf.chatDisplayNode.setupSendActionOnViewUpdate({ @@ -4495,7 +4492,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal let resource = LocalFileMediaResource(fileId: randomId, size: data.compressedData.count) - strongSelf.account.postbox.mediaBox.storeResourceData(resource.id, data: data.compressedData) + strongSelf.context.account.postbox.mediaBox.storeResourceData(resource.id, data: data.compressedData) strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { $0.updatedRecordedMediaPreview(ChatRecordedMediaPreview(resource: resource, duration: Int32(data.duration), fileSize: Int32(data.compressedData.count), waveform: AudioWaveform(bitstream: waveform, bitsPerSample: 5))) @@ -4514,7 +4511,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal let randomId = arc4random64() let resource = LocalFileMediaResource(fileId: randomId) - strongSelf.account.postbox.mediaBox.storeResourceData(resource.id, data: data.compressedData) + strongSelf.context.account.postbox.mediaBox.storeResourceData(resource.id, data: data.compressedData) var waveformBuffer: MemoryBuffer? if let waveform = data.waveform { @@ -4671,7 +4668,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal searchDisposable = MetaDisposable() self.searchDisposable = searchDisposable } - searchDisposable.set((searchMessages(account: self.account, location: searchState.location, query: searchState.query, state: nil, limit: limit) + searchDisposable.set((searchMessages(account: self.context.account, location: searchState.location, query: searchState.query, state: nil, limit: limit) |> delay(0.2, queue: Queue.mainQueue()) |> deliverOnMainQueue).start(next: { [weak self] results, updatedState in guard let strongSelf = self else { @@ -4721,7 +4718,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal searchDisposable = MetaDisposable() self.searchDisposable = searchDisposable } - searchDisposable.set((searchMessages(account: self.account, location: searchState.location, query: searchState.query, state: loadMoreState, limit: limit) + searchDisposable.set((searchMessages(account: self.context.account, location: searchState.location, query: searchState.query, state: loadMoreState, limit: limit) |> delay(0.2, queue: Queue.mainQueue()) |> deliverOnMainQueue).start(next: { [weak self] results, updatedState in guard let strongSelf = self else { @@ -4780,7 +4777,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if case let .peer(peerId) = self.chatLocation, let messageId = messageLocation.messageId, (messageId.peerId != peerId && !forceInCurrentChat) { if let navigationController = self.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: self.account, chatLocation: .peer(messageId.peerId), messageId: messageId, keepStack: .always) + navigateToChatController(navigationController: navigationController, context: self.context, chatLocation: .peer(messageId.peerId), messageId: messageId, keepStack: .always) } } else if case let .peer(peerId) = self.chatLocation, (messageLocation.peerId == peerId || forceInCurrentChat) { if let fromIndex = fromIndex { @@ -4804,7 +4801,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal case .upperBound: searchLocation = .index(MessageIndex.upperBound(peerId: peerId)) } - let historyView = chatHistoryViewForLocation(.InitialSearch(location: searchLocation, count: 50), account: self.account, chatLocation: self.chatLocation, fixedCombinedReadStates: nil, tagMask: nil, additionalData: []) + let historyView = chatHistoryViewForLocation(.InitialSearch(location: searchLocation, count: 50), account: self.context.account, chatLocation: self.chatLocation, fixedCombinedReadStates: nil, tagMask: nil, additionalData: []) let signal = historyView |> mapToSignal { historyView -> Signal<(MessageIndex?, Bool), NoError> in switch historyView { @@ -4891,7 +4888,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.historyNavigationStack.add(fromIndex) } self.loadingMessage.set(true) - let historyView = chatHistoryViewForLocation(.InitialSearch(location: searchLocation, count: 50), account: self.account, chatLocation: self.chatLocation, fixedCombinedReadStates: nil, tagMask: nil, additionalData: []) + let historyView = chatHistoryViewForLocation(.InitialSearch(location: searchLocation, count: 50), account: self.context.account, chatLocation: self.chatLocation, fixedCombinedReadStates: nil, tagMask: nil, additionalData: []) let signal = historyView |> mapToSignal { historyView -> Signal in switch historyView { @@ -4915,7 +4912,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal strongSelf.chatDisplayNode.historyNode.scrollToMessage(from: fromIndex, to: index, animated: animated, scrollPosition: scrollPosition) completion?() } else { - (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(account: strongSelf.account, chatLocation: .peer(messageLocation.peerId), messageId: messageLocation.messageId)) + (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(context: strongSelf.context, chatLocation: .peer(messageLocation.peerId), messageId: messageLocation.messageId)) completion?() } } @@ -4932,7 +4929,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } private func forwardMessages(messageIds: [MessageId]) { - let controller = PeerSelectionController(account: self.account, filter: .onlyWriteable) + let controller = PeerSelectionController(context: self.context, filter: .onlyWriteable) controller.peerSelected = { [weak self, weak controller] peerId in guard let strongSelf = self, let strongController = controller else { return @@ -4941,8 +4938,8 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if case .peer(peerId) = strongSelf.chatLocation, strongSelf.parentController == nil { strongSelf.updateChatPresentationInterfaceState(animated: false, interactive: true, { $0.updatedInterfaceState({ $0.withUpdatedForwardMessageIds(messageIds).withoutSelectionState() }) }) strongController.dismiss() - } else if peerId == strongSelf.account.peerId { - let _ = (enqueueMessages(account: strongSelf.account, peerId: peerId, messages: messageIds.map { id -> EnqueueMessage in + } else if peerId == strongSelf.context.account.peerId { + let _ = (enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: messageIds.map { id -> EnqueueMessage in return .forward(source: id, grouping: .auto) }) |> deliverOnMainQueue).start(next: { messageIds in @@ -4951,7 +4948,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard let id = id else { return nil } - return strongSelf.account.pendingMessageManager.pendingMessageStatus(id) + return strongSelf.context.account.pendingMessageManager.pendingMessageStatus(id) |> mapToSignal { status -> Signal in if status != nil { return .never() @@ -4976,7 +4973,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal strongSelf.updateChatPresentationInterfaceState(animated: false, interactive: true, { $0.updatedInterfaceState({ $0.withoutSelectionState() }) }) strongController.dismiss() } else { - let _ = (strongSelf.account.postbox.transaction({ transaction -> Void in + let _ = (strongSelf.context.account.postbox.transaction({ transaction -> Void in transaction.updatePeerChatInterfaceState(peerId, update: { currentState in if let currentState = currentState as? ChatInterfaceState { return currentState.withUpdatedForwardMessageIds(messageIds) @@ -4997,9 +4994,9 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal })) if let parentController = strongSelf.parentController { - (parentController.navigationController as? NavigationController)?.replaceTopController(ChatController(account: strongSelf.account, chatLocation: .peer(peerId)), animated: false, ready: ready) + (parentController.navigationController as? NavigationController)?.replaceTopController(ChatController(context: strongSelf.context, chatLocation: .peer(peerId)), animated: false, ready: ready) } else { - (strongSelf.navigationController as? NavigationController)?.replaceTopController(ChatController(account: strongSelf.account, chatLocation: .peer(peerId)), animated: false, ready: ready) + (strongSelf.navigationController as? NavigationController)?.replaceTopController(ChatController(context: strongSelf.context, chatLocation: .peer(peerId)), animated: false, ready: ready) } } }) @@ -5039,20 +5036,20 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal case .info: let peerSignal: Signal if let fromMessage = fromMessage { - peerSignal = loadedPeerFromMessage(account: self.account, peerId: peerId, messageId: fromMessage.id) + peerSignal = loadedPeerFromMessage(account: self.context.account, peerId: peerId, messageId: fromMessage.id) } else { - peerSignal = self.account.postbox.loadedPeerWithId(peerId) |> map(Optional.init) + peerSignal = self.context.account.postbox.loadedPeerWithId(peerId) |> map(Optional.init) } self.navigationActionDisposable.set((peerSignal |> take(1) |> deliverOnMainQueue).start(next: { [weak self] peer in if let strongSelf = self, let peer = peer { - if let infoController = peerInfoController(account: strongSelf.account, peer: peer) { + if let infoController = peerInfoController(context: strongSelf.context, peer: peer) { (strongSelf.navigationController as? NavigationController)?.pushViewController(infoController) } } })) case let .chat(textInputState, messageId): if let textInputState = textInputState { - let _ = (self.account.postbox.transaction({ transaction -> Void in + let _ = (self.context.account.postbox.transaction({ transaction -> Void in transaction.updatePeerChatInterfaceState(peerId, update: { currentState in if let currentState = currentState as? ChatInterfaceState { return currentState.withUpdatedComposeInputState(textInputState) @@ -5063,19 +5060,19 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal }) |> deliverOnMainQueue).start(completed: { [weak self] in if let strongSelf = self { - (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(account: strongSelf.account, chatLocation: .peer(peerId), messageId: nil)) + (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(context: strongSelf.context, chatLocation: .peer(peerId), messageId: nil)) } }) } else { - (self.navigationController as? NavigationController)?.pushViewController(ChatController(account: self.account, chatLocation: .peer(peerId), messageId: nil)) + (self.navigationController as? NavigationController)?.pushViewController(ChatController(context: self.context, chatLocation: .peer(peerId), messageId: nil)) } case let .withBotStartPayload(botStart): - (self.navigationController as? NavigationController)?.pushViewController(ChatController(account: self.account, chatLocation: .peer(peerId), messageId: nil, botStart: botStart)) + (self.navigationController as? NavigationController)?.pushViewController(ChatController(context: self.context, chatLocation: .peer(peerId), messageId: nil, botStart: botStart)) default: break } case .group: - (self.navigationController as? NavigationController)?.pushViewController(ChatController(account: self.account, chatLocation: .peer(peerId), messageId: fromMessage?.id, botStart: nil)) + (self.navigationController as? NavigationController)?.pushViewController(ChatController(context: self.context, chatLocation: .peer(peerId), messageId: fromMessage?.id, botStart: nil)) } } else { switch navigation { @@ -5083,7 +5080,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal break case let .chat(textInputState, _): if let textInputState = textInputState { - let controller = PeerSelectionController(account: self.account) + let controller = PeerSelectionController(context: self.context) controller.peerSelected = { [weak self, weak controller] peerId in if let strongSelf = self, let strongController = controller { if case let .peer(currentPeerId) = strongSelf.chatLocation, peerId == currentPeerId { @@ -5096,7 +5093,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal }) strongController.dismiss() } else { - let _ = (strongSelf.account.postbox.transaction({ transaction -> Void in + let _ = (strongSelf.context.account.postbox.transaction({ transaction -> Void in transaction.updatePeerChatInterfaceState(peerId, update: { currentState in if let currentState = currentState as? ChatInterfaceState { return currentState.withUpdatedComposeInputState(textInputState) @@ -5116,7 +5113,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } })) - (strongSelf.navigationController as? NavigationController)?.replaceTopController(ChatController(account: strongSelf.account, chatLocation: .peer(peerId)), animated: false, ready: ready) + (strongSelf.navigationController as? NavigationController)?.replaceTopController(ChatController(context: strongSelf.context, chatLocation: .peer(peerId)), animated: false, ready: ready) } }) } @@ -5140,7 +5137,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal disposable = MetaDisposable() self.resolvePeerByNameDisposable = disposable } - var resolveSignal = resolvePeerByName(account: self.account, name: name, ageLimit: 10) + var resolveSignal = resolvePeerByName(account: self.context.account, name: name, ageLimit: 10) var cancelImpl: (() -> Void)? let presentationData = self.presentationData @@ -5168,7 +5165,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal cancelImpl = { [weak self] in self?.resolvePeerByNameDisposable?.set(nil) } - let account = self.account + let account = self.context.account disposable.set((resolveSignal |> take(1) |> mapToSignal { peerId -> Signal in @@ -5208,12 +5205,12 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let user = self.presentationInterfaceState.renderedPeer?.peer as? TelegramUser, user.botInfo != nil { restartBot = true } - self.editMessageDisposable.set((requestUpdatePeerIsBlocked(account: self.account, peerId: peerId, isBlocked: false) + self.editMessageDisposable.set((requestUpdatePeerIsBlocked(account: self.context.account, peerId: peerId, isBlocked: false) |> afterDisposed({ [weak self] in Queue.mainQueue().async { unblockingPeer.set(false) if let strongSelf = self, restartBot { - let _ = enqueueMessages(account: strongSelf.account, peerId: peerId, messages: [.message(text: "/start", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() + let _ = enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: [.message(text: "/start", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() } } })).start()) @@ -5224,7 +5221,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal self.chatDisplayNode.dismissInput() if let peer = peer as? TelegramChannel, let username = peer.username, !username.isEmpty { - self.present(peerReportOptionsController(account: account, subject: .peer(peer.id), present: { [weak self] c, a in + self.present(peerReportOptionsController(context: self.context, subject: .peer(peer.id), present: { [weak self] c, a in self?.present(c, in: .window(.root)) }), in: .window(.root)) } else { @@ -5263,7 +5260,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal private func addPeerContact() { if let peer = self.presentationInterfaceState.renderedPeer?.peer as? TelegramUser, let phone = peer.phone, !phone.isEmpty, let contactData = DeviceContactExtendedData(peer: peer) { - self.present(addContactOptionsController(account: self.account, peer: peer, contactData: contactData), in: .window(.root)) + self.present(addContactOptionsController(context: self.context, peer: peer, contactData: contactData), in: .window(.root)) } } @@ -5271,7 +5268,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal guard case let .peer(peerId) = self.chatLocation else { return } - self.editMessageDisposable.set((TelegramCore.dismissReportPeer(account: self.account, peerId: peerId) |> afterDisposed({ + self.editMessageDisposable.set((TelegramCore.dismissReportPeer(account: self.context.account, peerId: peerId) |> afterDisposed({ Queue.mainQueue().async { } })).start()) @@ -5283,10 +5280,10 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } self.commitPurposefulAction() self.chatDisplayNode.historyNode.disconnect() - let _ = removePeerChat(postbox: self.account.postbox, peerId: peerId, reportChatSpam: reportChatSpam).start() + let _ = removePeerChat(postbox: self.context.account.postbox, peerId: peerId, reportChatSpam: reportChatSpam).start() (self.navigationController as? NavigationController)?.popToRoot(animated: true) - let _ = requestUpdatePeerIsBlocked(account: self.account, peerId: peerId, isBlocked: true).start() + let _ = requestUpdatePeerIsBlocked(account: self.context.account, peerId: peerId, isBlocked: true).start() } private func startBot(_ payload: String?) { @@ -5296,7 +5293,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal let startingBot = self.startingBot startingBot.set(true) - self.editMessageDisposable.set((requestStartBot(account: self.account, botPeerId: peerId, payload: payload) |> deliverOnMainQueue |> afterDisposed({ + self.editMessageDisposable.set((requestStartBot(account: self.context.account, botPeerId: peerId, payload: payload) |> deliverOnMainQueue |> afterDisposed({ startingBot.set(false) })).start(completed: { [weak self] in if let strongSelf = self { @@ -5306,7 +5303,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } private func openResolved(_ result: ResolvedUrl) { - openResolvedUrl(result, account: self.account, context: .chat, navigationController: self.navigationController as? NavigationController, openPeer: { [weak self] peerId, navigation in + openResolvedUrl(result, context: self.context, urlContext: .chat, navigationController: self.navigationController as? NavigationController, openPeer: { [weak self] peerId, navigation in guard let strongSelf = self else { return } @@ -5317,14 +5314,14 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal strongSelf.navigateToMessage(from: nil, to: .id(messageId)) } } else if let navigationController = strongSelf.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(peerId), messageId: messageId, keepStack: .always) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peerId), messageId: messageId, keepStack: .always) } case .info: - strongSelf.navigationActionDisposable.set((strongSelf.account.postbox.loadedPeerWithId(peerId) + strongSelf.navigationActionDisposable.set((strongSelf.context.account.postbox.loadedPeerWithId(peerId) |> take(1) |> deliverOnMainQueue).start(next: { [weak self] peer in if let strongSelf = self, peer.restrictionText == nil { - if let infoController = peerInfoController(account: strongSelf.account, peer: peer) { + if let infoController = peerInfoController(context: strongSelf.context, peer: peer) { (strongSelf.navigationController as? NavigationController)?.pushViewController(infoController) } } @@ -5335,7 +5332,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal $0.updatedBotStartPayload(startPayload.payload) }) } else if let navigationController = strongSelf.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(peerId), botStart: startPayload) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peerId), botStart: startPayload) } default: break @@ -5384,7 +5381,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal cancelImpl = { [weak self] in self?.resolveUrlDisposable?.set(nil) } - disposable.set((resolveUrl(account: strongSelf.account, url: url) + disposable.set((resolveUrl(account: strongSelf.context.account, url: url) |> afterDisposed { Queue.mainQueue().async { progressDisposable.dispose() @@ -5419,17 +5416,15 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } private func openUrlIn(_ url: String) { - if let applicationContext = self.account.applicationContext as? TelegramApplicationContext { - let actionSheet = OpenInActionSheetController(account: self.account, item: .url(url: url), openUrl: { [weak self] url in - if let strongSelf = self, let applicationContext = strongSelf.account.applicationContext as? TelegramApplicationContext, let navigationController = strongSelf.navigationController as? NavigationController { - openExternalUrl(account: strongSelf.account, url: url, forceExternal: true, presentationData: strongSelf.presentationData, applicationContext: applicationContext, navigationController: navigationController, dismissInput: { - self?.chatDisplayNode.dismissInput() - }) - } - }) - self.chatDisplayNode.dismissInput() - self.present(actionSheet, in: .window(.root)) - } + let actionSheet = OpenInActionSheetController(context: self.context, item: .url(url: url), openUrl: { [weak self] url in + if let strongSelf = self, let navigationController = strongSelf.navigationController as? NavigationController { + openExternalUrl(context: strongSelf.context, url: url, forceExternal: true, presentationData: strongSelf.presentationData, navigationController: navigationController, dismissInput: { + self?.chatDisplayNode.dismissInput() + }) + } + }) + self.chatDisplayNode.dismissInput() + self.present(actionSheet, in: .window(.root)) } func avatarPreviewingController(from sourceView: UIView) -> (UIViewController, CGRect)? { @@ -5437,7 +5432,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal return nil } if let peer = self.presentationInterfaceState.renderedPeer?.chatMainPeer, peer.smallProfileImage != nil { - let galleryController = AvatarGalleryController(account: self.account, peer: peer, remoteEntries: nil, replaceRootController: { controller, ready in + let galleryController = AvatarGalleryController(context: self.context, peer: peer, remoteEntries: nil, replaceRootController: { controller, ready in }, synchronousLoad: true) galleryController.setHintWillBePresentedInPreviewingContext(true) galleryController.containerLayoutUpdated(ContainerViewLayout(size: CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height), metrics: LayoutMetrics(), intrinsicInsets: UIEdgeInsets(), safeInsets: UIEdgeInsets(), statusBarHeight: nil, inputHeight: nil, standardInputHeight: 216.0, inputHeightIsInteractivellyChanging: false), transition: .immediate) @@ -5471,7 +5466,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } if let selectedTransitionNode = selectedTransitionNode { - if let previewData = chatMessagePreviewControllerData(account: self.account, message: message, standalone: false, reverseMessageGalleryOrder: false, navigationController: self.navigationController as? NavigationController) { + if let previewData = chatMessagePreviewControllerData(account: self.context.account, message: message, standalone: false, reverseMessageGalleryOrder: false, navigationController: self.navigationController as? NavigationController) { switch previewData { case let .gallery(gallery): gallery.setHintWillBePresentedInPreviewingContext(true) @@ -5557,7 +5552,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal let chatLocation = self.chatLocation let data = Atomic(value: nil) let semaphore = DispatchSemaphore(value: 0) - let _ = self.account.postbox.transaction({ transaction -> Void in + let _ = self.context.account.postbox.transaction({ transaction -> Void in switch chatLocation { case let .peer(peerId): let _ = data.swap(PreviewActionsData(notificationSettings: transaction.getPeerNotificationSettings(peerId), peer: transaction.getPeer(peerId))) @@ -5571,15 +5566,15 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal return data.with { [weak self] data -> [UIPreviewActionItem] in var items: [UIPreviewActionItem] = [] if let data = data, let strongSelf = self { - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } switch strongSelf.peekActions { case .standard: - if let peer = data.peer, peer.id != strongSelf.account.peerId { + if let peer = data.peer, peer.id != strongSelf.context.account.peerId { if let _ = data.peer as? TelegramUser { items.append(UIPreviewAction(title: "👍", style: .default, handler: { _, _ in if let strongSelf = self { - let _ = enqueueMessages(account: strongSelf.account, peerId: peer.id, messages: strongSelf.transformEnqueueMessages([.message(text: "👍", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)])).start() + let _ = enqueueMessages(account: strongSelf.context.account, peerId: peer.id, messages: strongSelf.transformEnqueueMessages([.message(text: "👍", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)])).start() } })) } @@ -5588,7 +5583,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if case let .muted(until) = notificationSettings.muteState, until >= Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) { items.append(UIPreviewAction(title: presentationData.strings.Conversation_Unmute, style: .default, handler: { _, _ in if let strongSelf = self { - let _ = togglePeerMuted(account: strongSelf.account, peerId: peer.id).start() + let _ = togglePeerMuted(account: strongSelf.context.account, peerId: peer.id).start() } })) } else { @@ -5607,7 +5602,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal items.append(UIPreviewAction(title: title, style: .default, handler: { _, _ in if let strongSelf = self { - let _ = updatePeerMuteSetting(account: strongSelf.account, peerId: peer.id, muteInterval: muteInterval).start() + let _ = updatePeerMuteSetting(account: strongSelf.context.account, peerId: peer.id, muteInterval: muteInterval).start() } })) } @@ -5624,11 +5619,11 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal } private func debugStreamSingleVideo(_ id: MessageId) { - let gallery = GalleryController(account: self.account, source: .peerMessagesAtId(id), streamSingleVideo: true, replaceRootController: { [weak self] controller, ready in + let gallery = GalleryController(context: self.context, source: .peerMessagesAtId(id), streamSingleVideo: true, replaceRootController: { [weak self] controller, ready in if let strongSelf = self { (strongSelf.navigationController as? NavigationController)?.replaceTopController(controller, animated: false, ready: ready) } - }, baseNavigationController: self.navigationController as? NavigationController) + }, baseNavigationController: self.navigationController as? NavigationController) self.chatDisplayNode.dismissInput() self.present(gallery, in: .window(.root), with: GalleryControllerPresentationArguments(transitionArguments: { [weak self] messageId, media in @@ -5655,7 +5650,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal private func presentBanMessageOptions(accountPeerId: PeerId, author: Peer, messageIds: Set, options: ChatAvailableMessageActionOptions) { if case let .peer(peerId) = self.chatLocation { - self.navigationActionDisposable.set((fetchChannelParticipant(account: self.account, peerId: peerId, participantId: author.id) + self.navigationActionDisposable.set((fetchChannelParticipant(account: self.context.account, peerId: peerId, participantId: author.id) |> deliverOnMainQueue).start(next: { [weak self] participant in if let strongSelf = self { var canBan = true @@ -5721,15 +5716,15 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let strongSelf = self { strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { $0.updatedInterfaceState { $0.withoutSelectionState() } }) if actions.contains(3) { - let _ = strongSelf.account.postbox.transaction({ transaction -> Void in + let _ = strongSelf.context.account.postbox.transaction({ transaction -> Void in transaction.removeAllMessagesWithAuthor(peerId, authorId: author.id) }).start() - let _ = clearAuthorHistory(account: strongSelf.account, peerId: peerId, memberId: author.id).start() + let _ = clearAuthorHistory(account: strongSelf.context.account, peerId: peerId, memberId: author.id).start() } else if actions.contains(0) { - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: Array(messageIds), type: .forEveryone).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: Array(messageIds), type: .forEveryone).start() } if actions.contains(1) { - let _ = removePeerMember(account: strongSelf.account, peerId: peerId, memberId: author.id).start() + let _ = removePeerMember(account: strongSelf.context.account, peerId: peerId, memberId: author.id).start() } } })) @@ -5772,13 +5767,13 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal actionSheet?.dismissAnimated() if let strongSelf = self { strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { $0.updatedInterfaceState { $0.withoutSelectionState() } }) - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: Array(messageIds), type: .forEveryone).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: Array(messageIds), type: .forEveryone).start() } })) } if options.contains(.deleteLocally) { var localOptionText = self.presentationData.strings.Conversation_DeleteMessagesForMe - if case .peer(self.account.peerId) = self.chatLocation { + if case .peer(self.context.account.peerId) = self.chatLocation { if messageIds.count == 1 { localOptionText = self.presentationData.strings.Conversation_Moderate_Delete } else { @@ -5789,7 +5784,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal actionSheet?.dismissAnimated() if let strongSelf = self { strongSelf.updateChatPresentationInterfaceState(animated: true, interactive: true, { $0.updatedInterfaceState { $0.withoutSelectionState() } }) - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: Array(messageIds), type: .forLocalPeer).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: Array(messageIds), type: .forLocalPeer).start() } })) } @@ -5990,7 +5985,7 @@ public final class ChatController: TelegramController, KeyShortcutResponder, Gal if let (host, port, username, password, secret) = parseProxyUrl(code) { self.openResolved(ResolvedUrl.proxy(host: host, port: port, username: username, password: password, secret: secret)) } else { - let _ = resolveUrl(account: self.account, url: code).start(next: { [weak self] resolved in + let _ = resolveUrl(account: self.context.account, url: code).start(next: { [weak self] resolved in self?.openResolved(resolved) }) } diff --git a/TelegramUI/ChatControllerNode.swift b/TelegramUI/ChatControllerNode.swift index 142a699ca0..05c9d43264 100644 --- a/TelegramUI/ChatControllerNode.swift +++ b/TelegramUI/ChatControllerNode.swift @@ -49,7 +49,7 @@ private struct ChatControllerNodeDerivedLayoutState { } class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { - let account: Account + let context: AccountContext let chatLocation: ChatLocation let controllerInteraction: ChatControllerInteraction private weak var controller: ChatController? @@ -171,8 +171,8 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { private var openStickersDisposable: Disposable? - init(account: Account, chatLocation: ChatLocation, messageId: MessageId?, controllerInteraction: ChatControllerInteraction, chatPresentationInterfaceState: ChatPresentationInterfaceState, automaticMediaDownloadSettings: AutomaticMediaDownloadSettings, navigationBar: NavigationBar?, controller: ChatController?) { - self.account = account + init(context: AccountContext, chatLocation: ChatLocation, messageId: MessageId?, controllerInteraction: ChatControllerInteraction, chatPresentationInterfaceState: ChatPresentationInterfaceState, automaticMediaDownloadSettings: AutomaticMediaDownloadSettings, navigationBar: NavigationBar?, controller: ChatController?) { + self.context = context self.chatLocation = chatLocation self.controllerInteraction = controllerInteraction self.chatPresentationInterfaceState = chatPresentationInterfaceState @@ -186,7 +186,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { self.titleAccessoryPanelContainer = ChatControllerTitlePanelNodeContainer() self.titleAccessoryPanelContainer.clipsToBounds = true - self.historyNode = ChatHistoryListNode(account: account, chatLocation: chatLocation, tagMask: nil, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: self.selectedMessagesPromise.get()) + self.historyNode = ChatHistoryListNode(context: context, chatLocation: chatLocation, tagMask: nil, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: self.selectedMessagesPromise.get()) self.historyNode.rotated = true self.historyNodeContainer = ASDisplayNode() self.historyNodeContainer.addSubnode(self.historyNode) @@ -238,7 +238,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { } } - self.backgroundNode.image = chatControllerBackgroundImage(wallpaper: chatPresentationInterfaceState.chatWallpaper, mode: chatPresentationInterfaceState.chatWallpaperMode, postbox: account.postbox) + self.backgroundNode.image = chatControllerBackgroundImage(wallpaper: chatPresentationInterfaceState.chatWallpaper, mode: chatPresentationInterfaceState.chatWallpaperMode, postbox: context.account.postbox) if chatPresentationInterfaceState.chatWallpaperMode.contains(.motion) { self.backgroundNode.parallaxEnabled = true } @@ -389,7 +389,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { private func updateIsEmpty(_ isEmpty: Bool, animated: Bool) { if isEmpty && self.emptyNode == nil { - let emptyNode = ChatEmptyNode(accountPeerId: self.account.peerId) + let emptyNode = ChatEmptyNode(accountPeerId: self.context.account.peerId) if let (size, insets) = self.validEmptyNodeLayout { emptyNode.updateLayout(interfaceState: self.chatPresentationInterfaceState, size: size, insets: insets, transition: .immediate) } @@ -564,7 +564,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { var dismissedTitleAccessoryPanelNode: ChatTitleAccessoryPanelNode? var immediatelyLayoutTitleAccessoryPanelNodeAndAnimateAppearance = false var titleAccessoryPanelHeight: CGFloat? - if let titleAccessoryPanelNode = titlePanelForChatPresentationInterfaceState(self.chatPresentationInterfaceState, account: self.account, currentPanel: self.titleAccessoryPanelNode, interfaceInteraction: self.interfaceInteraction) { + if let titleAccessoryPanelNode = titlePanelForChatPresentationInterfaceState(self.chatPresentationInterfaceState, context: self.context, currentPanel: self.titleAccessoryPanelNode, interfaceInteraction: self.interfaceInteraction) { if self.titleAccessoryPanelNode != titleAccessoryPanelNode { dismissedTitleAccessoryPanelNode = self.titleAccessoryPanelNode self.titleAccessoryPanelNode = titleAccessoryPanelNode @@ -588,7 +588,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { var dismissedInputNode: ChatInputNode? var immediatelyLayoutInputNodeAndAnimateAppearance = false var inputNodeHeightAndOverflow: (CGFloat, CGFloat)? - if let inputNode = inputNodeForChatPresentationIntefaceState(self.chatPresentationInterfaceState, account: self.account, currentNode: self.inputNode, interfaceInteraction: self.interfaceInteraction, inputMediaNode: self.inputMediaNode, controllerInteraction: self.controllerInteraction, inputPanelNode: self.inputPanelNode) { + if let inputNode = inputNodeForChatPresentationIntefaceState(self.chatPresentationInterfaceState, context: self.context, currentNode: self.inputNode, interfaceInteraction: self.interfaceInteraction, inputMediaNode: self.inputMediaNode, controllerInteraction: self.controllerInteraction, inputPanelNode: self.inputPanelNode) { if let inputTextPanelNode = self.inputPanelNode as? ChatTextInputPanelNode { inputTextPanelNode.ensureUnfocused() } @@ -663,7 +663,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { var inputPanelSize: CGSize? var immediatelyLayoutInputPanelAndAnimateAppearance = false - if let inputPanelNode = inputPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, account: self.account, currentPanel: self.inputPanelNode, textInputPanelNode: self.textInputPanelNode, interfaceInteraction: self.interfaceInteraction), !previewing { + if let inputPanelNode = inputPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, context: self.context, currentPanel: self.inputPanelNode, textInputPanelNode: self.textInputPanelNode, interfaceInteraction: self.interfaceInteraction), !previewing { if inputPanelNode !== self.inputPanelNode { if let inputTextPanelNode = self.inputPanelNode as? ChatTextInputPanelNode { inputTextPanelNode.ensureUnfocused() @@ -738,7 +738,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { var accessoryPanelSize: CGSize? var immediatelyLayoutAccessoryPanelAndAnimateAppearance = false - if let accessoryPanelNode = accessoryPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, account: self.account, currentPanel: self.accessoryPanelNode, interfaceInteraction: self.interfaceInteraction) { + if let accessoryPanelNode = accessoryPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, context: self.context, currentPanel: self.accessoryPanelNode, interfaceInteraction: self.interfaceInteraction) { accessoryPanelSize = accessoryPanelNode.measure(CGSize(width: layout.size.width, height: layout.size.height)) accessoryPanelNode.updateState(size: CGSize(width: layout.size.width, height: layout.size.height), interfaceState: self.chatPresentationInterfaceState) @@ -775,7 +775,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { } var immediatelyLayoutInputContextPanelAndAnimateAppearance = false - if let inputContextPanelNode = inputContextPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, account: self.account, currentPanel: self.inputContextPanelNode, controllerInteraction: self.controllerInteraction, interfaceInteraction: self.interfaceInteraction) { + if let inputContextPanelNode = inputContextPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, context: self.context, currentPanel: self.inputContextPanelNode, controllerInteraction: self.controllerInteraction, interfaceInteraction: self.interfaceInteraction) { if inputContextPanelNode !== self.inputContextPanelNode { dismissedInputContextPanelNode = self.inputContextPanelNode self.inputContextPanelNode = inputContextPanelNode @@ -789,7 +789,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { } var immediatelyLayoutOverlayContextPanelAndAnimateAppearance = false - if let overlayContextPanelNode = chatOverlayContextPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, account: self.account, currentPanel: self.overlayContextPanelNode, interfaceInteraction: self.interfaceInteraction) { + if let overlayContextPanelNode = chatOverlayContextPanelForChatPresentationIntefaceState(self.chatPresentationInterfaceState, context: self.context, currentPanel: self.overlayContextPanelNode, interfaceInteraction: self.interfaceInteraction) { if overlayContextPanelNode !== self.overlayContextPanelNode { dismissedOverlayContextPanelNode = self.overlayContextPanelNode self.overlayContextPanelNode = overlayContextPanelNode @@ -1315,7 +1315,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { let themeUpdated = self.chatPresentationInterfaceState.theme !== chatPresentationInterfaceState.theme if self.chatPresentationInterfaceState.chatWallpaper != chatPresentationInterfaceState.chatWallpaper || self.chatPresentationInterfaceState.chatWallpaperMode != chatPresentationInterfaceState.chatWallpaperMode { - self.backgroundNode.image = chatControllerBackgroundImage(wallpaper: chatPresentationInterfaceState.chatWallpaper, mode: chatPresentationInterfaceState.chatWallpaperMode, postbox: account.postbox) + self.backgroundNode.image = chatControllerBackgroundImage(wallpaper: chatPresentationInterfaceState.chatWallpaper, mode: chatPresentationInterfaceState.chatWallpaperMode, postbox: context.account.postbox) if chatPresentationInterfaceState.chatWallpaperMode.contains(.motion) { self.backgroundNode.parallaxEnabled = true @@ -1519,7 +1519,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { if case let .peer(id) = self.chatPresentationInterfaceState.chatLocation { peerId = id } - let inputNode = ChatMediaInputNode(account: self.account, peerId: peerId, controllerInteraction: self.controllerInteraction, theme: theme, strings: strings, gifPaneIsActiveUpdated: { [weak self] value in + let inputNode = ChatMediaInputNode(context: self.context, peerId: peerId, controllerInteraction: self.controllerInteraction, theme: theme, strings: strings, gifPaneIsActiveUpdated: { [weak self] value in if let strongSelf = self, let interfaceInteraction = strongSelf.interfaceInteraction { interfaceInteraction.updateInputModeAndDismissedButtonKeyboardMessageId { state in if case let .media(_, expanded) = state.inputMode { diff --git a/TelegramUI/ChatDocumentGalleryItem.swift b/TelegramUI/ChatDocumentGalleryItem.swift index a1a3711f9f..f3300518fb 100644 --- a/TelegramUI/ChatDocumentGalleryItem.swift +++ b/TelegramUI/ChatDocumentGalleryItem.swift @@ -6,28 +6,28 @@ import WebKit import TelegramCore class ChatDocumentGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let presentationData: PresentationData let message: Message let location: MessageHistoryEntryLocation? - init(account: Account, presentationData: PresentationData, message: Message, location: MessageHistoryEntryLocation?) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, message: Message, location: MessageHistoryEntryLocation?) { + self.context = context self.presentationData = presentationData self.message = message self.location = location } func node() -> GalleryItemNode { - let node = ChatDocumentGalleryItemNode(account: self.account, presentationData: self.presentationData) + let node = ChatDocumentGalleryItemNode(context: self.context, presentationData: self.presentationData) for media in self.message.media { if let file = media as? TelegramMediaFile { - node.setFile(account: account, fileReference: .message(message: MessageReference(self.message), media: file)) + node.setFile(context: context, fileReference: .message(message: MessageReference(self.message), media: file)) break } else if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { if let file = content.file { - node.setFile(account: account, fileReference: .message(message: MessageReference(self.message), media: file)) + node.setFile(context: context, fileReference: .message(message: MessageReference(self.message), media: file)) break } } @@ -90,7 +90,7 @@ class ChatDocumentGalleryItemNode: GalleryItemNode, WKNavigationDelegate { private let webView: UIView - private var accountAndFile: (Account, FileMediaReference)? + private var contextAndFile: (AccountContext, FileMediaReference)? private let dataDisposable = MetaDisposable() private var itemIsVisible = false @@ -103,7 +103,7 @@ class ChatDocumentGalleryItemNode: GalleryItemNode, WKNavigationDelegate { private let statusDisposable = MetaDisposable() private var status: MediaResourceStatus? - init(account: Account, presentationData: PresentationData) { + init(context: AccountContext, presentationData: PresentationData) { if #available(iOSApplicationExtension 11.0, *) { let preferences = WKPreferences() preferences.javaScriptEnabled = false @@ -120,7 +120,7 @@ class ChatDocumentGalleryItemNode: GalleryItemNode, WKNavigationDelegate { webView.scalesPageToFit = true self.webView = webView } - self.footerContentNode = ChatItemGalleryFooterContentNode(account: account, presentationData: presentationData) + self.footerContentNode = ChatItemGalleryFooterContentNode(context: context, presentationData: presentationData) self.statusNodeContainer = HighlightableButtonNode() self.statusNode = RadialStatusNode(backgroundNodeColor: UIColor(white: 0.0, alpha: 0.5)) @@ -162,9 +162,9 @@ class ChatDocumentGalleryItemNode: GalleryItemNode, WKNavigationDelegate { return .single(.dark) } - func setFile(account: Account, fileReference: FileMediaReference) { - let updateFile = self.accountAndFile?.1.media != fileReference.media - self.accountAndFile = (account, fileReference) + func setFile(context: AccountContext, fileReference: FileMediaReference) { + let updateFile = self.contextAndFile?.1.media != fileReference.media + self.contextAndFile = (context, fileReference) if updateFile { if fileReference.media.mimeType.hasPrefix("image/") { if let webView = self.webView as? WKWebView { @@ -172,17 +172,17 @@ class ChatDocumentGalleryItemNode: GalleryItemNode, WKNavigationDelegate { } } self.maybeLoadContent() - self.setupStatus(account: account, resource: fileReference.media.resource) + self.setupStatus(context: context, resource: fileReference.media.resource) } } - private func setupStatus(account: Account, resource: MediaResource) { - self.statusDisposable.set((account.postbox.mediaBox.resourceStatus(resource) - |> deliverOnMainQueue).start(next: { [weak self] status in - if let strongSelf = self { - let previousStatus = strongSelf.status - strongSelf.status = status - switch status { + private func setupStatus(context: AccountContext, resource: MediaResource) { + self.statusDisposable.set((context.account.postbox.mediaBox.resourceStatus(resource) + |> deliverOnMainQueue).start(next: { [weak self] status in + if let strongSelf = self { + let previousStatus = strongSelf.status + strongSelf.status = status + switch status { case .Remote: strongSelf.statusNode.isHidden = false strongSelf.statusNode.alpha = 1.0 @@ -216,19 +216,19 @@ class ChatDocumentGalleryItemNode: GalleryItemNode, WKNavigationDelegate { } }) } - } } - })) + } + })) } private func maybeLoadContent() { - if let (account, fileReference) = self.accountAndFile { + if let (context, fileReference) = self.contextAndFile { var pathExtension: String? if let fileName = fileReference.media.fileName { pathExtension = (fileName as NSString).pathExtension } - let data = account.postbox.mediaBox.resourceData(fileReference.media.resource, pathExtension: pathExtension, option: .complete(waitUntilFetchStatus: false)) - |> deliverOnMainQueue + let data = context.account.postbox.mediaBox.resourceData(fileReference.media.resource, pathExtension: pathExtension, option: .complete(waitUntilFetchStatus: false)) + |> deliverOnMainQueue self.dataDisposable.set(data.start(next: { [weak self] data in if let strongSelf = self { if data.complete { @@ -372,12 +372,12 @@ class ChatDocumentGalleryItemNode: GalleryItemNode, WKNavigationDelegate { } @objc func statusPressed() { - if let (account, fileReference) = self.accountAndFile, let status = self.status { + if let (context, fileReference) = self.contextAndFile, let status = self.status { switch status { case .Fetching: - account.postbox.mediaBox.cancelInteractiveResourceFetch(fileReference.media.resource) + context.account.postbox.mediaBox.cancelInteractiveResourceFetch(fileReference.media.resource) case .Remote: - self.fetchDisposable.set(fetchedMediaResource(postbox: account.postbox, reference: fileReference.resourceReference(fileReference.media.resource)).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: context.account.postbox, reference: fileReference.resourceReference(fileReference.media.resource)).start()) default: break } diff --git a/TelegramUI/ChatEmptyNode.swift b/TelegramUI/ChatEmptyNode.swift index 39ffcc8987..a422c8d46a 100644 --- a/TelegramUI/ChatEmptyNode.swift +++ b/TelegramUI/ChatEmptyNode.swift @@ -223,7 +223,7 @@ private final class ChatEmptyNodeGroupChatContent: ASDisplayNode, ChatEmptyNodeC self.subtitleNode.attributedText = NSAttributedString(string: interfaceState.strings.EmptyGroupInfo_Subtitle, font: messageFont, textColor: serviceColor.primaryText) let strings: [String] = [ - interfaceState.strings.EmptyGroupInfo_Line1("100,000").0, + interfaceState.strings.EmptyGroupInfo_Line1("200,000").0, interfaceState.strings.EmptyGroupInfo_Line2, interfaceState.strings.EmptyGroupInfo_Line3, interfaceState.strings.EmptyGroupInfo_Line4 diff --git a/TelegramUI/ChatExternalFileGalleryItem.swift b/TelegramUI/ChatExternalFileGalleryItem.swift index 9bcadbee48..bc7f4be3da 100644 --- a/TelegramUI/ChatExternalFileGalleryItem.swift +++ b/TelegramUI/ChatExternalFileGalleryItem.swift @@ -6,28 +6,28 @@ import WebKit import TelegramCore class ChatExternalFileGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let presentationData: PresentationData let message: Message let location: MessageHistoryEntryLocation? - init(account: Account, presentationData: PresentationData, message: Message, location: MessageHistoryEntryLocation?) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, message: Message, location: MessageHistoryEntryLocation?) { + self.context = context self.presentationData = presentationData self.message = message self.location = location } func node() -> GalleryItemNode { - let node = ChatExternalFileGalleryItemNode(account: self.account, presentationData: self.presentationData) + let node = ChatExternalFileGalleryItemNode(context: self.context, presentationData: self.presentationData) for media in self.message.media { if let file = media as? TelegramMediaFile { - node.setFile(account: account, fileReference: .message(message: MessageReference(self.message), media: file)) + node.setFile(context: context, fileReference: .message(message: MessageReference(self.message), media: file)) break } else if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { if let file = content.file { - node.setFile(account: account, fileReference: .message(message: MessageReference(self.message), media: file)) + node.setFile(context: context, fileReference: .message(message: MessageReference(self.message), media: file)) break } } @@ -64,7 +64,7 @@ class ChatExternalFileGalleryItemNode: GalleryItemNode { private let actionTitleNode: ImmediateTextNode private let actionButtonNode: HighlightableButtonNode - private var accountAndFile: (Account, FileMediaReference)? + private var contextAndFile: (AccountContext, FileMediaReference)? private let dataDisposable = MetaDisposable() private var itemIsVisible = false @@ -77,7 +77,7 @@ class ChatExternalFileGalleryItemNode: GalleryItemNode { private let statusDisposable = MetaDisposable() private var status: MediaResourceStatus? - init(account: Account, presentationData: PresentationData) { + init(context: AccountContext, presentationData: PresentationData) { self.containerNode = ASDisplayNode() self.containerNode.backgroundColor = .white @@ -91,7 +91,7 @@ class ChatExternalFileGalleryItemNode: GalleryItemNode { self.actionButtonNode = HighlightableButtonNode() self.containerNode.addSubnode(self.actionButtonNode) - self.footerContentNode = ChatItemGalleryFooterContentNode(account: account, presentationData: presentationData) + self.footerContentNode = ChatItemGalleryFooterContentNode(context: context, presentationData: presentationData) self.statusNodeContainer = HighlightableButtonNode() self.statusNode = RadialStatusNode(backgroundNodeColor: UIColor(white: 0.0, alpha: 0.5)) @@ -164,58 +164,58 @@ class ChatExternalFileGalleryItemNode: GalleryItemNode { return .single(.dark) } - func setFile(account: Account, fileReference: FileMediaReference) { - let updateFile = self.accountAndFile?.1.media != fileReference.media - self.accountAndFile = (account, fileReference) + func setFile(context: AccountContext, fileReference: FileMediaReference) { + let updateFile = self.contextAndFile?.1.media != fileReference.media + self.contextAndFile = (context, fileReference) if updateFile { self.fileNameNode.attributedText = NSAttributedString(string: fileReference.media.fileName ?? " ", font: Font.regular(17.0), textColor: .black) - self.setupStatus(account: account, resource: fileReference.media.resource) + self.setupStatus(context: context, resource: fileReference.media.resource) } } - private func setupStatus(account: Account, resource: MediaResource) { - self.statusDisposable.set((account.postbox.mediaBox.resourceStatus(resource) - |> deliverOnMainQueue).start(next: { [weak self] status in - if let strongSelf = self { - let previousStatus = strongSelf.status - strongSelf.status = status - switch status { - case .Remote: - strongSelf.statusNode.isHidden = false - strongSelf.statusNode.alpha = 1.0 - strongSelf.statusNodeContainer.isUserInteractionEnabled = true - strongSelf.statusNode.transitionToState(.download(.white), completion: {}) - case let .Fetching(isActive, progress): - strongSelf.statusNode.isHidden = false - strongSelf.statusNode.alpha = 1.0 - strongSelf.statusNodeContainer.isUserInteractionEnabled = true - let adjustedProgress = max(progress, 0.027) - strongSelf.statusNode.transitionToState(.progress(color: .white, lineWidth: nil, value: CGFloat(adjustedProgress), cancelEnabled: true), completion: {}) - case .Local: - if let previousStatus = previousStatus, case .Fetching = previousStatus { - strongSelf.statusNode.transitionToState(.progress(color: .white, lineWidth: nil, value: 1.0, cancelEnabled: true), completion: { - if let strongSelf = self { - strongSelf.statusNode.alpha = 0.0 - strongSelf.statusNodeContainer.isUserInteractionEnabled = false - strongSelf.statusNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, completion: { _ in - if let strongSelf = self { - strongSelf.statusNode.transitionToState(.none, animated: false, completion: {}) - } - }) - } - }) - } else if !strongSelf.statusNode.isHidden && !strongSelf.statusNode.alpha.isZero { - strongSelf.statusNode.alpha = 0.0 - strongSelf.statusNodeContainer.isUserInteractionEnabled = false - strongSelf.statusNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, completion: { _ in - if let strongSelf = self { - strongSelf.statusNode.transitionToState(.none, animated: false, completion: {}) - } - }) - } + private func setupStatus(context: AccountContext, resource: MediaResource) { + self.statusDisposable.set((context.account.postbox.mediaBox.resourceStatus(resource) + |> deliverOnMainQueue).start(next: { [weak self] status in + if let strongSelf = self { + let previousStatus = strongSelf.status + strongSelf.status = status + switch status { + case .Remote: + strongSelf.statusNode.isHidden = false + strongSelf.statusNode.alpha = 1.0 + strongSelf.statusNodeContainer.isUserInteractionEnabled = true + strongSelf.statusNode.transitionToState(.download(.white), completion: {}) + case let .Fetching(isActive, progress): + strongSelf.statusNode.isHidden = false + strongSelf.statusNode.alpha = 1.0 + strongSelf.statusNodeContainer.isUserInteractionEnabled = true + let adjustedProgress = max(progress, 0.027) + strongSelf.statusNode.transitionToState(.progress(color: .white, lineWidth: nil, value: CGFloat(adjustedProgress), cancelEnabled: true), completion: {}) + case .Local: + if let previousStatus = previousStatus, case .Fetching = previousStatus { + strongSelf.statusNode.transitionToState(.progress(color: .white, lineWidth: nil, value: 1.0, cancelEnabled: true), completion: { + if let strongSelf = self { + strongSelf.statusNode.alpha = 0.0 + strongSelf.statusNodeContainer.isUserInteractionEnabled = false + strongSelf.statusNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, completion: { _ in + if let strongSelf = self { + strongSelf.statusNode.transitionToState(.none, animated: false, completion: {}) + } + }) + } + }) + } else if !strongSelf.statusNode.isHidden && !strongSelf.statusNode.alpha.isZero { + strongSelf.statusNode.alpha = 0.0 + strongSelf.statusNodeContainer.isUserInteractionEnabled = false + strongSelf.statusNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, completion: { _ in + if let strongSelf = self { + strongSelf.statusNode.transitionToState(.none, animated: false, completion: {}) + } + }) } } - })) + } + })) } override func visibilityUpdated(isVisible: Bool) { @@ -306,12 +306,12 @@ class ChatExternalFileGalleryItemNode: GalleryItemNode { } @objc func statusPressed() { - if let (account, fileReference) = self.accountAndFile, let status = self.status { + if let (context, fileReference) = self.contextAndFile, let status = self.status { switch status { case .Fetching: - account.postbox.mediaBox.cancelInteractiveResourceFetch(fileReference.media.resource) + context.account.postbox.mediaBox.cancelInteractiveResourceFetch(fileReference.media.resource) case .Remote: - self.fetchDisposable.set(fetchedMediaResource(postbox: account.postbox, reference: fileReference.resourceReference(fileReference.media.resource)).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: context.account.postbox, reference: fileReference.resourceReference(fileReference.media.resource)).start()) default: break } @@ -319,9 +319,9 @@ class ChatExternalFileGalleryItemNode: GalleryItemNode { } @objc func actionButtonPressed() { - if let (account, _) = self.accountAndFile, let message = self.message, let status = self.status, case .Local = status { + if let (context, _) = self.contextAndFile, let message = self.message, let status = self.status, case .Local = status { let baseNavigationController = self.baseNavigationController() - (baseNavigationController?.topViewController as? ViewController)?.present(ShareController(account: account, subject: .messages([message]), showInChat: nil, externalShare: true, immediateExternalShare: true), in: .window(.root)) + (baseNavigationController?.topViewController as? ViewController)?.present(ShareController(context: context, subject: .messages([message]), showInChat: nil, externalShare: true, immediateExternalShare: true), in: .window(.root)) } } } diff --git a/TelegramUI/ChatHistoryGridNode.swift b/TelegramUI/ChatHistoryGridNode.swift index e563526438..e59b65809e 100644 --- a/TelegramUI/ChatHistoryGridNode.swift +++ b/TelegramUI/ChatHistoryGridNode.swift @@ -70,11 +70,11 @@ struct ChatHistoryGridViewTransition { let stationaryItems: GridNodeStationaryItems } -private func mappedInsertEntries(account: Account, peerId: PeerId, controllerInteraction: ChatControllerInteraction, entries: [ChatHistoryViewTransitionInsertEntry], theme: PresentationTheme, strings: PresentationStrings) -> [GridNodeInsertItem] { +private func mappedInsertEntries(context: AccountContext, peerId: PeerId, controllerInteraction: ChatControllerInteraction, entries: [ChatHistoryViewTransitionInsertEntry], theme: PresentationTheme, strings: PresentationStrings) -> [GridNodeInsertItem] { return entries.map { entry -> GridNodeInsertItem in switch entry.entry { case let .MessageEntry(message, _, _, _, _, _): - return GridNodeInsertItem(index: entry.index, item: GridMessageItem(theme: theme, strings: strings, account: account, message: message, controllerInteraction: controllerInteraction), previousIndex: entry.previousIndex) + return GridNodeInsertItem(index: entry.index, item: GridMessageItem(theme: theme, strings: strings, context: context, message: message, controllerInteraction: controllerInteraction), previousIndex: entry.previousIndex) case .MessageGroupEntry: return GridNodeInsertItem(index: entry.index, item: GridHoleItem(), previousIndex: entry.previousIndex) case .HoleEntry: @@ -89,11 +89,11 @@ private func mappedInsertEntries(account: Account, peerId: PeerId, controllerInt } } -private func mappedUpdateEntries(account: Account, peerId: PeerId, controllerInteraction: ChatControllerInteraction, entries: [ChatHistoryViewTransitionUpdateEntry], theme: PresentationTheme, strings: PresentationStrings) -> [GridNodeUpdateItem] { +private func mappedUpdateEntries(context: AccountContext, peerId: PeerId, controllerInteraction: ChatControllerInteraction, entries: [ChatHistoryViewTransitionUpdateEntry], theme: PresentationTheme, strings: PresentationStrings) -> [GridNodeUpdateItem] { return entries.map { entry -> GridNodeUpdateItem in switch entry.entry { case let .MessageEntry(message, _, _, _, _, _): - return GridNodeUpdateItem(index: entry.index, previousIndex: entry.previousIndex, item: GridMessageItem(theme: theme, strings: strings, account: account, message: message, controllerInteraction: controllerInteraction)) + return GridNodeUpdateItem(index: entry.index, previousIndex: entry.previousIndex, item: GridMessageItem(theme: theme, strings: strings, context: context, message: message, controllerInteraction: controllerInteraction)) case .MessageGroupEntry: return GridNodeUpdateItem(index: entry.index, previousIndex: entry.previousIndex, item: GridHoleItem()) case .HoleEntry: @@ -108,7 +108,7 @@ private func mappedUpdateEntries(account: Account, peerId: PeerId, controllerInt } } -private func mappedChatHistoryViewListTransition(account: Account, peerId: PeerId, controllerInteraction: ChatControllerInteraction, transition: ChatHistoryViewTransition, from: ChatHistoryView?, presentationData: ChatPresentationData) -> ChatHistoryGridViewTransition { +private func mappedChatHistoryViewListTransition(context: AccountContext, peerId: PeerId, controllerInteraction: ChatControllerInteraction, transition: ChatHistoryViewTransition, from: ChatHistoryView?, presentationData: ChatPresentationData) -> ChatHistoryGridViewTransition { var mappedScrollToItem: GridNodeScrollToItem? if let scrollToItem = transition.scrollToItem { let mappedPosition: GridNodeScrollToItemPosition @@ -190,7 +190,7 @@ private func mappedChatHistoryViewListTransition(account: Account, peerId: PeerI } } - return ChatHistoryGridViewTransition(historyView: transition.historyView, topOffsetWithinMonth: topOffsetWithinMonth, deleteItems: transition.deleteItems.map { $0.index }, insertItems: mappedInsertEntries(account: account, peerId: peerId, controllerInteraction: controllerInteraction, entries: transition.insertEntries, theme: presentationData.theme.theme, strings: presentationData.strings), updateItems: mappedUpdateEntries(account: account, peerId: peerId, controllerInteraction: controllerInteraction, entries: transition.updateEntries, theme: presentationData.theme.theme, strings: presentationData.strings), scrollToItem: mappedScrollToItem, stationaryItems: stationaryItems) + return ChatHistoryGridViewTransition(historyView: transition.historyView, topOffsetWithinMonth: topOffsetWithinMonth, deleteItems: transition.deleteItems.map { $0.index }, insertItems: mappedInsertEntries(context: context, peerId: peerId, controllerInteraction: controllerInteraction, entries: transition.insertEntries, theme: presentationData.theme.theme, strings: presentationData.strings), updateItems: mappedUpdateEntries(context: context, peerId: peerId, controllerInteraction: controllerInteraction, entries: transition.updateEntries, theme: presentationData.theme.theme, strings: presentationData.strings), scrollToItem: mappedScrollToItem, stationaryItems: stationaryItems) } private func gridNodeLayoutForContainerLayout(size: CGSize) -> GridNodeLayoutType { @@ -199,7 +199,7 @@ private func gridNodeLayoutForContainerLayout(size: CGSize) -> GridNodeLayoutTyp } public final class ChatHistoryGridNode: GridNode, ChatHistoryNode { - private let account: Account + private let context: AccountContext private let peerId: PeerId private let messageId: MessageId? private let tagMask: MessageTags? @@ -238,17 +238,18 @@ public final class ChatHistoryGridNode: GridNode, ChatHistoryNode { public private(set) var loadState: ChatHistoryNodeLoadState? private var loadStateUpdated: ((ChatHistoryNodeLoadState, Bool) -> Void)? private let controllerInteraction: ChatControllerInteraction - public init(account: Account, peerId: PeerId, messageId: MessageId?, tagMask: MessageTags?, controllerInteraction: ChatControllerInteraction) { - self.account = account + + public init(context: AccountContext, peerId: PeerId, messageId: MessageId?, tagMask: MessageTags?, controllerInteraction: ChatControllerInteraction) { + self.context = context self.peerId = peerId self.messageId = messageId self.tagMask = tagMask self.controllerInteraction = controllerInteraction - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init() - self.chatPresentationDataPromise.set(account.telegramApplicationContext.presentationData |> map { presentationData in + self.chatPresentationDataPromise.set(context.presentationData |> map { presentationData in return ChatPresentationData(theme: ChatPresentationThemeData(theme: presentationData.theme, wallpaper: presentationData.chatWallpaper), fontSize: presentationData.fontSize, strings: self.presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameDisplayOrder: presentationData.nameDisplayOrder, disableAnimations: presentationData.disableAnimations) }) @@ -259,7 +260,7 @@ public final class ChatHistoryGridNode: GridNode, ChatHistoryNode { let historyViewUpdate = self.chatHistoryLocation |> distinctUntilChanged |> mapToSignal { location in - return chatHistoryViewForLocation(location, account: account, chatLocation: .peer(peerId), fixedCombinedReadStates: nil, tagMask: tagMask, additionalData: [], orderStatistics: [.locationWithinMonth]) + return chatHistoryViewForLocation(location, account: context.account, chatLocation: .peer(peerId), fixedCombinedReadStates: nil, tagMask: tagMask, additionalData: [], orderStatistics: [.locationWithinMonth]) } let previousView = Atomic(value: nil) @@ -306,7 +307,7 @@ public final class ChatHistoryGridNode: GridNode, ChatHistoryNode { let processedView = ChatHistoryView(originalView: view, filteredEntries: chatHistoryEntriesForView(location: .peer(peerId), view: view, includeUnreadEntry: false, includeEmptyEntry: false, includeChatInfoEntry: false, includeSearchEntry: false, reverse: false, groupMessages: false, selectedMessages: nil, presentationData: chatPresentationData, historyAppearsCleared: false), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: false)) let previous = previousView.swap(processedView) - return preparedChatHistoryViewTransition(from: previous, to: processedView, reason: reason, reverse: false, account: account, chatLocation: .peer(peerId), controllerInteraction: controllerInteraction, scrollPosition: scrollPosition, initialData: nil, keyboardButtonsMessage: nil, cachedData: nil, cachedDataMessages: nil, readStateData: nil) |> map({ mappedChatHistoryViewListTransition(account: account, peerId: peerId, controllerInteraction: controllerInteraction, transition: $0, from: previous, presentationData: chatPresentationData) }) |> runOn(prepareOnMainQueue ? Queue.mainQueue() : messageViewQueue) + return preparedChatHistoryViewTransition(from: previous, to: processedView, reason: reason, reverse: false, chatLocation: .peer(peerId), controllerInteraction: controllerInteraction, scrollPosition: scrollPosition, initialData: nil, keyboardButtonsMessage: nil, cachedData: nil, cachedDataMessages: nil, readStateData: nil) |> map({ mappedChatHistoryViewListTransition(context: context, peerId: peerId, controllerInteraction: controllerInteraction, transition: $0, from: previous, presentationData: chatPresentationData) }) |> runOn(prepareOnMainQueue ? Queue.mainQueue() : messageViewQueue) } } @@ -452,7 +453,7 @@ public final class ChatHistoryGridNode: GridNode, ChatHistoryNode { strongSelf.historyView = transition.historyView if let range = visibleRange.loadedRange { - strongSelf.account.postbox.updateMessageHistoryViewVisibleRange(transition.historyView.originalView.id, earliestVisibleIndex: transition.historyView.filteredEntries[transition.historyView.filteredEntries.count - 1 - range.upperBound].index, latestVisibleIndex: transition.historyView.filteredEntries[transition.historyView.filteredEntries.count - 1 - range.lowerBound].index) + strongSelf.context.account.postbox.updateMessageHistoryViewVisibleRange(transition.historyView.originalView.id, earliestVisibleIndex: transition.historyView.filteredEntries[transition.historyView.filteredEntries.count - 1 - range.upperBound].index, latestVisibleIndex: transition.historyView.filteredEntries[transition.historyView.filteredEntries.count - 1 - range.lowerBound].index) } let loadState: ChatHistoryNodeLoadState diff --git a/TelegramUI/ChatHistoryListNode.swift b/TelegramUI/ChatHistoryListNode.swift index 5b0d89d1f8..479d27ff20 100644 --- a/TelegramUI/ChatHistoryListNode.swift +++ b/TelegramUI/ChatHistoryListNode.swift @@ -165,26 +165,26 @@ private func maxMessageIndexForEntries(_ view: ChatHistoryView, indexRange: (Int return (incoming, overall) } -private func mappedInsertEntries(account: Account, chatLocation: ChatLocation, associatedData: ChatMessageItemAssociatedData, controllerInteraction: ChatControllerInteraction, mode: ChatHistoryListMode, entries: [ChatHistoryViewTransitionInsertEntry]) -> [ListViewInsertItem] { +private func mappedInsertEntries(context: AccountContext, chatLocation: ChatLocation, associatedData: ChatMessageItemAssociatedData, controllerInteraction: ChatControllerInteraction, mode: ChatHistoryListMode, entries: [ChatHistoryViewTransitionInsertEntry]) -> [ListViewInsertItem] { return entries.map { entry -> ListViewInsertItem in switch entry.entry { case let .MessageEntry(message, presentationData, read, _, selection, isAdmin): let item: ListViewItem switch mode { case .bubbles: - item = ChatMessageItem(presentationData: presentationData, account: account, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, content: .message(message: message, read: read, selection: selection, isAdmin: isAdmin)) + item = ChatMessageItem(presentationData: presentationData, context: context, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, content: .message(message: message, read: read, selection: selection, isAdmin: isAdmin)) case let .list(search, _): - item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, account: account, chatLocation: chatLocation, controllerInteraction: controllerInteraction, message: message, selection: selection, displayHeader: search) + item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, context: context, chatLocation: chatLocation, controllerInteraction: controllerInteraction, message: message, selection: selection, displayHeader: search) } return ListViewInsertItem(index: entry.index, previousIndex: entry.previousIndex, item: item, directionHint: entry.directionHint) case let .MessageGroupEntry(_, messages, presentationData): let item: ListViewItem switch mode { case .bubbles: - item = ChatMessageItem(presentationData: presentationData, account: account, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, content: .group(messages: messages)) + item = ChatMessageItem(presentationData: presentationData, context: context, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, content: .group(messages: messages)) case let .list(search, _): assertionFailure() - item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, account: account, chatLocation: chatLocation, controllerInteraction: controllerInteraction, message: messages[0].0, selection: .none, displayHeader: search) + item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, context: context, chatLocation: chatLocation, controllerInteraction: controllerInteraction, message: messages[0].0, selection: .none, displayHeader: search) } return ListViewInsertItem(index: entry.index, previousIndex: entry.previousIndex, item: item, directionHint: entry.directionHint) case let .HoleEntry(_, presentationData): @@ -208,26 +208,26 @@ private func mappedInsertEntries(account: Account, chatLocation: ChatLocation, a } } -private func mappedUpdateEntries(account: Account, chatLocation: ChatLocation, associatedData: ChatMessageItemAssociatedData, controllerInteraction: ChatControllerInteraction, mode: ChatHistoryListMode, entries: [ChatHistoryViewTransitionUpdateEntry]) -> [ListViewUpdateItem] { +private func mappedUpdateEntries(context: AccountContext, chatLocation: ChatLocation, associatedData: ChatMessageItemAssociatedData, controllerInteraction: ChatControllerInteraction, mode: ChatHistoryListMode, entries: [ChatHistoryViewTransitionUpdateEntry]) -> [ListViewUpdateItem] { return entries.map { entry -> ListViewUpdateItem in switch entry.entry { case let .MessageEntry(message, presentationData, read, _, selection, isAdmin): let item: ListViewItem switch mode { case .bubbles: - item = ChatMessageItem(presentationData: presentationData, account: account, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, content: .message(message: message, read: read, selection: selection, isAdmin: isAdmin)) + item = ChatMessageItem(presentationData: presentationData, context: context, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, content: .message(message: message, read: read, selection: selection, isAdmin: isAdmin)) case let .list(search, _): - item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, account: account, chatLocation: chatLocation, controllerInteraction: controllerInteraction, message: message, selection: selection, displayHeader: search) + item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, context: context, chatLocation: chatLocation, controllerInteraction: controllerInteraction, message: message, selection: selection, displayHeader: search) } return ListViewUpdateItem(index: entry.index, previousIndex: entry.previousIndex, item: item, directionHint: entry.directionHint) case let .MessageGroupEntry(_, messages, presentationData): let item: ListViewItem switch mode { case .bubbles: - item = ChatMessageItem(presentationData: presentationData, account: account, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, content: .group(messages: messages)) + item = ChatMessageItem(presentationData: presentationData, context: context, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, content: .group(messages: messages)) case let .list(search, _): assertionFailure() - item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, account: account, chatLocation: chatLocation, controllerInteraction: controllerInteraction, message: messages[0].0, selection: .none, displayHeader: search) + item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, context: context, chatLocation: chatLocation, controllerInteraction: controllerInteraction, message: messages[0].0, selection: .none, displayHeader: search) } return ListViewUpdateItem(index: entry.index, previousIndex: entry.previousIndex, item: item, directionHint: entry.directionHint) case let .HoleEntry(_, presentationData): @@ -251,8 +251,8 @@ private func mappedUpdateEntries(account: Account, chatLocation: ChatLocation, a } } -private func mappedChatHistoryViewListTransition(account: Account, chatLocation: ChatLocation, associatedData: ChatMessageItemAssociatedData, controllerInteraction: ChatControllerInteraction, mode: ChatHistoryListMode, transition: ChatHistoryViewTransition) -> ChatHistoryListViewTransition { - return ChatHistoryListViewTransition(historyView: transition.historyView, deleteItems: transition.deleteItems, insertItems: mappedInsertEntries(account: account, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, mode: mode, entries: transition.insertEntries), updateItems: mappedUpdateEntries(account: account, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, mode: mode, entries: transition.updateEntries), options: transition.options, scrollToItem: transition.scrollToItem, stationaryItemRange: transition.stationaryItemRange, initialData: transition.initialData, keyboardButtonsMessage: transition.keyboardButtonsMessage, cachedData: transition.cachedData, cachedDataMessages: transition.cachedDataMessages, readStateData: transition.readStateData, scrolledToIndex: transition.scrolledToIndex, animateIn: transition.animateIn) +private func mappedChatHistoryViewListTransition(context: AccountContext, chatLocation: ChatLocation, associatedData: ChatMessageItemAssociatedData, controllerInteraction: ChatControllerInteraction, mode: ChatHistoryListMode, transition: ChatHistoryViewTransition) -> ChatHistoryListViewTransition { + return ChatHistoryListViewTransition(historyView: transition.historyView, deleteItems: transition.deleteItems, insertItems: mappedInsertEntries(context: context, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, mode: mode, entries: transition.insertEntries), updateItems: mappedUpdateEntries(context: context, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, mode: mode, entries: transition.updateEntries), options: transition.options, scrollToItem: transition.scrollToItem, stationaryItemRange: transition.stationaryItemRange, initialData: transition.initialData, keyboardButtonsMessage: transition.keyboardButtonsMessage, cachedData: transition.cachedData, cachedDataMessages: transition.cachedDataMessages, readStateData: transition.readStateData, scrolledToIndex: transition.scrolledToIndex, animateIn: transition.animateIn) } private final class ChatHistoryTransactionOpaqueState { @@ -293,7 +293,7 @@ private func extractAssociatedData(chatLocation: ChatLocation, view: MessageHist } public final class ChatHistoryListNode: ListView, ChatHistoryNode { - private let account: Account + private let context: AccountContext private let chatLocation: ChatLocation private let messageId: MessageId? private let tagMask: MessageTags? @@ -377,15 +377,15 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { private var loadedMessagesFromCachedDataDisposable: Disposable? - public init(account: Account, chatLocation: ChatLocation, tagMask: MessageTags?, messageId: MessageId?, controllerInteraction: ChatControllerInteraction, selectedMessages: Signal?, NoError>, mode: ChatHistoryListMode = .bubbles) { - self.account = account + public init(context: AccountContext, chatLocation: ChatLocation, tagMask: MessageTags?, messageId: MessageId?, controllerInteraction: ChatControllerInteraction, selectedMessages: Signal?, NoError>, mode: ChatHistoryListMode = .bubbles) { + self.context = context self.chatLocation = chatLocation self.messageId = messageId self.tagMask = tagMask self.controllerInteraction = controllerInteraction self.mode = mode - self.currentPresentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.currentPresentationData = context.currentPresentationData.with { $0 } self.chatPresentationDataPromise = Promise(ChatPresentationData(theme: ChatPresentationThemeData(theme: self.currentPresentationData.theme, wallpaper: self.currentPresentationData.chatWallpaper), fontSize: self.currentPresentationData.fontSize, strings: self.currentPresentationData.strings, dateTimeFormat: self.currentPresentationData.dateTimeFormat, nameDisplayOrder: self.currentPresentationData.nameDisplayOrder, disableAnimations: self.currentPresentationData.disableAnimations)) @@ -395,14 +395,14 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { //self.debugInfo = true - self.messageProcessingManager.process = { [weak account] messageIds in - account?.viewTracker.updateViewCountForMessageIds(messageIds: messageIds) + self.messageProcessingManager.process = { [weak context] messageIds in + context?.account.viewTracker.updateViewCountForMessageIds(messageIds: messageIds) } - self.unsupportedMessageProcessingManager.process = { [weak account] messageIds in - account?.viewTracker.updateUnsupportedMediaForMessageIds(messageIds: messageIds) + self.unsupportedMessageProcessingManager.process = { [weak context] messageIds in + context?.account.viewTracker.updateUnsupportedMediaForMessageIds(messageIds: messageIds) } - self.messageMentionProcessingManager.process = { [weak account] messageIds in - account?.viewTracker.updateMarkMentionsSeenForMessageIds(messageIds: messageIds) + self.messageMentionProcessingManager.process = { [weak context] messageIds in + context?.account.viewTracker.updateMarkMentionsSeenForMessageIds(messageIds: messageIds) } self.preloadPages = false @@ -437,7 +437,7 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { let historyViewUpdate = self.chatHistoryLocation |> distinctUntilChanged |> mapToSignal { location in - return chatHistoryViewForLocation(location, account: account, chatLocation: chatLocation, fixedCombinedReadStates: fixedCombinedReadStates.with { $0 }, tagMask: tagMask, additionalData: additionalData) + return chatHistoryViewForLocation(location, account: context.account, chatLocation: chatLocation, fixedCombinedReadStates: fixedCombinedReadStates.with { $0 }, tagMask: tagMask, additionalData: additionalData) |> beforeNext { viewUpdate in switch viewUpdate { case let .HistoryView(view, _, _, _, _): @@ -449,7 +449,7 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { } let previousView = Atomic(value: nil) - let automaticDownloadNetworkType = account.networkType + let automaticDownloadNetworkType = context.account.networkType |> map { type -> AutomaticDownloadNetworkType in switch type { case .none, .wifi: @@ -548,7 +548,7 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { } } - return preparedChatHistoryViewTransition(from: previous, to: processedView, reason: reason, reverse: reverse, account: account, chatLocation: chatLocation, controllerInteraction: controllerInteraction, scrollPosition: updatedScrollPosition, initialData: initialData?.initialData, keyboardButtonsMessage: view.topTaggedMessages.first, cachedData: initialData?.cachedData, cachedDataMessages: initialData?.cachedDataMessages, readStateData: initialData?.readStateData) |> map({ mappedChatHistoryViewListTransition(account: account, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, mode: mode, transition: $0) }) |> runOn(prepareOnMainQueue ? Queue.mainQueue() : messageViewQueue) + return preparedChatHistoryViewTransition(from: previous, to: processedView, reason: reason, reverse: reverse, chatLocation: chatLocation, controllerInteraction: controllerInteraction, scrollPosition: updatedScrollPosition, initialData: initialData?.initialData, keyboardButtonsMessage: view.topTaggedMessages.first, cachedData: initialData?.cachedData, cachedDataMessages: initialData?.cachedDataMessages, readStateData: initialData?.readStateData) |> map({ mappedChatHistoryViewListTransition(context: context, chatLocation: chatLocation, associatedData: associatedData, controllerInteraction: controllerInteraction, mode: mode, transition: $0) }) |> runOn(prepareOnMainQueue ? Queue.mainQueue() : messageViewQueue) } } @@ -563,30 +563,30 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { let previousMaxIncomingMessageIndexByNamespace = Atomic<[MessageId.Namespace: MessageIndex]>(value: [:]) let readHistory = combineLatest(self.maxVisibleIncomingMessageIndex.get(), self.canReadHistory.get()) - |> map { messageIndex, canRead in - if canRead { - var apply = false - let _ = previousMaxIncomingMessageIndexByNamespace.modify { dict in - let previousIndex = dict[messageIndex.id.namespace] - if previousIndex == nil || previousIndex! < messageIndex { - apply = true - var dict = dict - dict[messageIndex.id.namespace] = messageIndex - return dict - } + |> map { messageIndex, canRead in + if canRead { + var apply = false + let _ = previousMaxIncomingMessageIndexByNamespace.modify { dict in + let previousIndex = dict[messageIndex.id.namespace] + if previousIndex == nil || previousIndex! < messageIndex { + apply = true + var dict = dict + dict[messageIndex.id.namespace] = messageIndex return dict } - if apply { - switch chatLocation { - case .peer: - let _ = applyMaxReadIndexInteractively(postbox: account.postbox, stateManager: account.stateManager, index: messageIndex).start() - case let .group(groupId): - let _ = account.postbox.transaction({ transaction -> Void in - transaction.applyGroupFeedInteractiveReadMaxIndex(groupId: groupId, index: messageIndex) - }).start() - } + return dict + } + if apply { + switch chatLocation { + case .peer: + let _ = applyMaxReadIndexInteractively(postbox: context.account.postbox, stateManager: context.account.stateManager, index: messageIndex).start() + case let .group(groupId): + let _ = context.account.postbox.transaction({ transaction -> Void in + transaction.applyGroupFeedInteractiveReadMaxIndex(groupId: groupId, index: messageIndex) + }).start() } } + } } self.readHistoryDisposable.set(readHistory.start()) @@ -713,7 +713,7 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { } } - self.presentationDataDisposable = (account.telegramApplicationContext.presentationData + self.presentationDataDisposable = (context.presentationData |> deliverOnMainQueue).start(next: { [weak self] presentationData in if let strongSelf = self { let previousTheme = strongSelf.currentPresentationData.theme @@ -771,7 +771,7 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { } |> distinctUntilChanged(isEqual: { $0 == $1 }) |> mapToSignal { messageId -> Signal in if let messageId = messageId { - return getMessagesLoadIfNecessary([messageId], postbox: account.postbox, network: account.network, accountPeerId: account.peerId) |> map { _ -> Void in return Void() } + return getMessagesLoadIfNecessary([messageId], postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId) |> map { _ -> Void in return Void() } } else { return .complete() } @@ -1007,7 +1007,7 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { } if let range = visibleRange.loadedRange { - strongSelf.account.postbox.updateMessageHistoryViewVisibleRange(transition.historyView.originalView.id, earliestVisibleIndex: transition.historyView.filteredEntries[transition.historyView.filteredEntries.count - 1 - range.lastIndex].index, latestVisibleIndex: transition.historyView.filteredEntries[transition.historyView.filteredEntries.count - 1 - range.firstIndex].index) + strongSelf.context.account.postbox.updateMessageHistoryViewVisibleRange(transition.historyView.originalView.id, earliestVisibleIndex: transition.historyView.filteredEntries[transition.historyView.filteredEntries.count - 1 - range.lastIndex].index, latestVisibleIndex: transition.historyView.filteredEntries[transition.historyView.filteredEntries.count - 1 - range.firstIndex].index) if let visible = visibleRange.visibleRange { var visibleFirstIndex = visible.firstIndex @@ -1096,7 +1096,7 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { } } else if self.interactiveReadActionDisposable == nil { if case let .peer(peerId) = self.chatLocation { - self.interactiveReadActionDisposable = installInteractiveReadMessagesAction(postbox: self.account.postbox, stateManager: self.account.stateManager, peerId: peerId) + self.interactiveReadActionDisposable = installInteractiveReadMessagesAction(postbox: self.context.account.postbox, stateManager: self.context.account.stateManager, peerId: peerId) } } } @@ -1212,9 +1212,9 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { let item: ListViewItem switch self.mode { case .bubbles: - item = ChatMessageItem(presentationData: presentationData, account: self.account, chatLocation: self.chatLocation, associatedData: associatedData, controllerInteraction: self.controllerInteraction, content: .message(message: message, read: read, selection: selection, isAdmin: isAdmin)) + item = ChatMessageItem(presentationData: presentationData, context: self.context, chatLocation: self.chatLocation, associatedData: associatedData, controllerInteraction: self.controllerInteraction, content: .message(message: message, read: read, selection: selection, isAdmin: isAdmin)) case let .list(search, _): - item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, account: self.account, chatLocation: self.chatLocation, controllerInteraction: self.controllerInteraction, message: message, selection: selection, displayHeader: search) + item = ListMessageItem(theme: presentationData.theme.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, context: self.context, chatLocation: self.chatLocation, controllerInteraction: self.controllerInteraction, message: message, selection: selection, displayHeader: search) } let updateItem = ListViewUpdateItem(index: index, previousIndex: index, item: item, directionHint: nil) self.transaction(deleteIndices: [], insertIndicesAndItems: [], updateIndicesAndItems: [updateItem], options: [.AnimateInsertion], scrollToItem: nil, additionalScrollDistance: 0.0, updateSizeAndInsets: nil, stationaryItemRange: nil, updateOpaqueState: nil, completion: { _ in }) diff --git a/TelegramUI/ChatHistoryNode.swift b/TelegramUI/ChatHistoryNode.swift index 5c4020e821..b16e741a30 100644 --- a/TelegramUI/ChatHistoryNode.swift +++ b/TelegramUI/ChatHistoryNode.swift @@ -6,23 +6,6 @@ import Display public enum ChatHistoryNodeHistoryState: Equatable { case loading case loaded(isEmpty: Bool) - - public static func ==(lhs: ChatHistoryNodeHistoryState, rhs: ChatHistoryNodeHistoryState) -> Bool { - switch lhs { - case .loading: - if case .loading = rhs { - return true - } else { - return false - } - case let .loaded(isEmpty): - if case .loaded(isEmpty) = rhs { - return true - } else { - return false - } - } - } } public enum ChatHistoryNodeLoadState { diff --git a/TelegramUI/ChatHistorySearchContainerNode.swift b/TelegramUI/ChatHistorySearchContainerNode.swift index 7f74778c9d..510e38e02b 100644 --- a/TelegramUI/ChatHistorySearchContainerNode.swift +++ b/TelegramUI/ChatHistorySearchContainerNode.swift @@ -102,7 +102,7 @@ private func chatHistorySearchContainerPreparedTransition(from fromEntries: [Cha } final class ChatHistorySearchContainerNode: SearchDisplayControllerContentNode { - private let account: Account + private let context: AccountContext private let dimNode: ASDisplayNode private let listNode: ListView @@ -132,10 +132,10 @@ final class ChatHistorySearchContainerNode: SearchDisplayControllerContentNode { private var enqueuedTransitions: [(ChatHistorySearchContainerTransition, Bool)] = [] - init(account: Account, peerId: PeerId, tagMask: MessageTags, interfaceInteraction: ChatControllerInteraction) { - self.account = account + init(context: AccountContext, peerId: PeerId, tagMask: MessageTags, interfaceInteraction: ChatControllerInteraction) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.themeAndStringsPromise = Promise((self.presentationData.theme, self.presentationData.strings, self.presentationData.dateTimeFormat)) diff --git a/TelegramUI/ChatImageGalleryItem.swift b/TelegramUI/ChatImageGalleryItem.swift index 12ea0d1fad..297c5f34bf 100644 --- a/TelegramUI/ChatImageGalleryItem.swift +++ b/TelegramUI/ChatImageGalleryItem.swift @@ -69,15 +69,15 @@ final class ChatMediaGalleryThumbnailItem: GalleryThumbnailItem { } class ChatImageGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let presentationData: PresentationData let message: Message let location: MessageHistoryEntryLocation? let performAction: (GalleryControllerInteractionTapAction) -> Void let openActionOptions: (GalleryControllerInteractionTapAction) -> Void - init(account: Account, presentationData: PresentationData, message: Message, location: MessageHistoryEntryLocation?, performAction: @escaping (GalleryControllerInteractionTapAction) -> Void, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, message: Message, location: MessageHistoryEntryLocation?, performAction: @escaping (GalleryControllerInteractionTapAction) -> Void, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void) { + self.context = context self.presentationData = presentationData self.message = message self.location = location @@ -86,21 +86,21 @@ class ChatImageGalleryItem: GalleryItem { } func node() -> GalleryItemNode { - let node = ChatImageGalleryItemNode(account: self.account, presentationData: self.presentationData, performAction: self.performAction, openActionOptions: self.openActionOptions) + let node = ChatImageGalleryItemNode(context: self.context, presentationData: self.presentationData, performAction: self.performAction, openActionOptions: self.openActionOptions) for media in self.message.media { if let image = media as? TelegramMediaImage { node.setImage(imageReference: .message(message: MessageReference(self.message), media: image)) break } else if let file = media as? TelegramMediaFile, file.mimeType.hasPrefix("image/") { - node.setFile(account: account, fileReference: .message(message: MessageReference(self.message), media: file)) + node.setFile(context: self.context, fileReference: .message(message: MessageReference(self.message), media: file)) break } else if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { if let image = content.image { node.setImage(imageReference: .message(message: MessageReference(self.message), media: image)) break } else if let file = content.file, file.mimeType.hasPrefix("image/") { - node.setFile(account: account, fileReference: .message(message: MessageReference(self.message), media: file)) + node.setFile(context: self.context, fileReference: .message(message: MessageReference(self.message), media: file)) break } } @@ -134,7 +134,7 @@ class ChatImageGalleryItem: GalleryItem { } } if let mediaReference = mediaReference { - if let item = ChatMediaGalleryThumbnailItem(account: self.account, mediaReference: mediaReference) { + if let item = ChatMediaGalleryThumbnailItem(account: self.context.account, mediaReference: mediaReference) { return (Int64(id), item) } } @@ -144,7 +144,7 @@ class ChatImageGalleryItem: GalleryItem { } final class ChatImageGalleryItemNode: ZoomableContentGalleryItemNode { - private let account: Account + private let context: AccountContext private var message: Message? private let imageNode: TransformImageNode @@ -154,17 +154,17 @@ final class ChatImageGalleryItemNode: ZoomableContentGalleryItemNode { private let statusNode: RadialStatusNode private let footerContentNode: ChatItemGalleryFooterContentNode - private var accountAndMedia: (Account, AnyMediaReference)? + private var contextAndMedia: (AccountContext, AnyMediaReference)? private var fetchDisposable = MetaDisposable() private let statusDisposable = MetaDisposable() private var status: MediaResourceStatus? - init(account: Account, presentationData: PresentationData,performAction: @escaping (GalleryControllerInteractionTapAction) -> Void, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData,performAction: @escaping (GalleryControllerInteractionTapAction) -> Void, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void) { + self.context = context self.imageNode = TransformImageNode() - self.footerContentNode = ChatItemGalleryFooterContentNode(account: account, presentationData: presentationData) + self.footerContentNode = ChatItemGalleryFooterContentNode(context: context, presentationData: presentationData) self.footerContentNode.performAction = performAction self.footerContentNode.openActionOptions = openActionOptions @@ -212,24 +212,24 @@ final class ChatImageGalleryItemNode: ZoomableContentGalleryItemNode { } fileprivate func setImage(imageReference: ImageMediaReference) { - if self.accountAndMedia == nil || !self.accountAndMedia!.1.media.isEqual(to: imageReference.media) { + if self.contextAndMedia == nil || !self.contextAndMedia!.1.media.isEqual(to: imageReference.media) { if let largestSize = largestRepresentationForPhoto(imageReference.media) { let displaySize = largestSize.dimensions.fitted(CGSize(width: 1280.0, height: 1280.0)).dividedByScreenScale().integralFloor self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: displaySize, boundingSize: displaySize, intrinsicInsets: UIEdgeInsets()))() - self.imageNode.setSignal(chatMessagePhoto(postbox: account.postbox, photoReference: imageReference), dispatchOnDisplayLink: false) + self.imageNode.setSignal(chatMessagePhoto(postbox: context.account.postbox, photoReference: imageReference), dispatchOnDisplayLink: false) self.zoomableContent = (largestSize.dimensions, self.imageNode) - self.fetchDisposable.set(fetchedMediaResource(postbox: self.account.postbox, reference: imageReference.resourceReference(largestSize.resource)).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: self.context.account.postbox, reference: imageReference.resourceReference(largestSize.resource)).start()) self.setupStatus(resource: largestSize.resource) } else { self._ready.set(.single(Void())) } } - self.accountAndMedia = (account, imageReference.abstract) + self.contextAndMedia = (self.context, imageReference.abstract) } - func setFile(account: Account, fileReference: FileMediaReference) { - if self.accountAndMedia == nil || !self.accountAndMedia!.1.media.isEqual(to: fileReference.media) { + func setFile(context: AccountContext, fileReference: FileMediaReference) { + if self.contextAndMedia == nil || !self.contextAndMedia!.1.media.isEqual(to: fileReference.media) { if var largestSize = fileReference.media.dimensions { var displaySize = largestSize.dividedByScreenScale() if let previewDimensions = largestImageRepresentation(fileReference.media.previewRepresentations)?.dimensions { @@ -241,18 +241,18 @@ final class ChatImageGalleryItemNode: ZoomableContentGalleryItemNode { } } self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: displaySize, boundingSize: displaySize, intrinsicInsets: UIEdgeInsets()))() - self.imageNode.setSignal(chatMessageImageFile(account: account, fileReference: fileReference, thumbnail: false), dispatchOnDisplayLink: false) + self.imageNode.setSignal(chatMessageImageFile(account: context.account, fileReference: fileReference, thumbnail: false), dispatchOnDisplayLink: false) self.zoomableContent = (largestSize, self.imageNode) self.setupStatus(resource: fileReference.media.resource) } else { self._ready.set(.single(Void())) } } - self.accountAndMedia = (account, fileReference.abstract) + self.contextAndMedia = (context, fileReference.abstract) } private func setupStatus(resource: MediaResource) { - self.statusDisposable.set((account.postbox.mediaBox.resourceStatus(resource) + self.statusDisposable.set((self.context.account.postbox.mediaBox.resourceStatus(resource) |> deliverOnMainQueue).start(next: { [weak self] status in if let strongSelf = self { let previousStatus = strongSelf.status @@ -423,7 +423,7 @@ final class ChatImageGalleryItemNode: ZoomableContentGalleryItemNode { override func visibilityUpdated(isVisible: Bool) { super.visibilityUpdated(isVisible: isVisible) - if let (account, mediaReference) = self.accountAndMedia, let fileReference = mediaReference.concrete(TelegramMediaFile.self) { + if let (context, mediaReference) = self.contextAndMedia, let fileReference = mediaReference.concrete(TelegramMediaFile.self) { if isVisible { } else { self.fetchDisposable.set(nil) @@ -440,7 +440,7 @@ final class ChatImageGalleryItemNode: ZoomableContentGalleryItemNode { } @objc func statusPressed() { - if let (_, mediaReference) = self.accountAndMedia, let status = self.status { + if let (_, mediaReference) = self.contextAndMedia, let status = self.status { var resource: MediaResourceReference? var statsCategory: MediaResourceStatsCategory? if let fileReference = mediaReference.concrete(TelegramMediaFile.self) { @@ -453,9 +453,9 @@ final class ChatImageGalleryItemNode: ZoomableContentGalleryItemNode { if let resource = resource { switch status { case .Fetching: - self.account.postbox.mediaBox.cancelInteractiveResourceFetch(resource.resource) + self.context.account.postbox.mediaBox.cancelInteractiveResourceFetch(resource.resource) case .Remote: - self.fetchDisposable.set(fetchedMediaResource(postbox: self.account.postbox, reference: resource, statsCategory: statsCategory ?? .generic).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: self.context.account.postbox, reference: resource, statsCategory: statsCategory ?? .generic).start()) default: break } diff --git a/TelegramUI/ChatInfo.swift b/TelegramUI/ChatInfo.swift index 28efe73f69..529dcac1a0 100644 --- a/TelegramUI/ChatInfo.swift +++ b/TelegramUI/ChatInfo.swift @@ -3,6 +3,6 @@ import Postbox import TelegramCore import Display -func peerSharedMediaController(account: Account, peerId: PeerId) -> ViewController? { - return PeerMediaCollectionController(account: account, peerId: peerId) +func peerSharedMediaController(context: AccountContext, peerId: PeerId) -> ViewController? { + return PeerMediaCollectionController(context: context, peerId: peerId) } diff --git a/TelegramUI/ChatInputContextPanelNode.swift b/TelegramUI/ChatInputContextPanelNode.swift index 6611c02472..2088a0a970 100644 --- a/TelegramUI/ChatInputContextPanelNode.swift +++ b/TelegramUI/ChatInputContextPanelNode.swift @@ -9,13 +9,15 @@ enum ChatInputContextPanelPlacement { } class ChatInputContextPanelNode: ASDisplayNode { - let account: Account + let context: AccountContext var interfaceInteraction: ChatPanelInterfaceInteraction? var placement: ChatInputContextPanelPlacement = .overPanels var theme: PresentationTheme - init(account: Account, theme: PresentationTheme, strings: PresentationStrings) { - self.account = account + + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings) { + self.context = context self.theme = theme + super.init() } diff --git a/TelegramUI/ChatInputPanelNode.swift b/TelegramUI/ChatInputPanelNode.swift index 7f7c0135bd..ea98204380 100644 --- a/TelegramUI/ChatInputPanelNode.swift +++ b/TelegramUI/ChatInputPanelNode.swift @@ -5,7 +5,7 @@ import Postbox import TelegramCore class ChatInputPanelNode: ASDisplayNode { - var account: Account? + var context: AccountContext? var interfaceInteraction: ChatPanelInterfaceInteraction? func updateLayout(width: CGFloat, leftInset: CGFloat, rightInset: CGFloat, maxHeight: CGFloat, transition: ContainedViewLayoutTransition, interfaceState: ChatPresentationInterfaceState, metrics: LayoutMetrics) -> CGFloat { diff --git a/TelegramUI/ChatInterfaceInputContextPanels.swift b/TelegramUI/ChatInterfaceInputContextPanels.swift index a2e2ae2c99..e9e77e5d53 100644 --- a/TelegramUI/ChatInterfaceInputContextPanels.swift +++ b/TelegramUI/ChatInterfaceInputContextPanels.swift @@ -31,7 +31,7 @@ private func inputQueryResultPriority(_ result: ChatPresentationInputQueryResult } } -func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account, currentPanel: ChatInputContextPanelNode?, controllerInteraction: ChatControllerInteraction?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> ChatInputContextPanelNode? { +func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, currentPanel: ChatInputContextPanelNode?, controllerInteraction: ChatControllerInteraction?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> ChatInputContextPanelNode? { guard let _ = chatPresentationInterfaceState.renderedPeer?.peer else { return nil } @@ -172,7 +172,7 @@ func inputContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfa return nil } -func chatOverlayContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account, currentPanel: ChatInputContextPanelNode?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> ChatInputContextPanelNode? { +func chatOverlayContextPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, currentPanel: ChatInputContextPanelNode?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> ChatInputContextPanelNode? { guard let searchQuerySuggestionResult = chatPresentationInterfaceState.searchQuerySuggestionResult, let _ = chatPresentationInterfaceState.renderedPeer?.peer else { return nil } diff --git a/TelegramUI/ChatInterfaceInputContexts.swift b/TelegramUI/ChatInterfaceInputContexts.swift index db832b7402..40de2dfc70 100644 --- a/TelegramUI/ChatInterfaceInputContexts.swift +++ b/TelegramUI/ChatInterfaceInputContexts.swift @@ -194,7 +194,7 @@ func inputContextQueriesForChatPresentationIntefaceState(_ chatPresentationInter return result } -func inputTextPanelStateForChatPresentationInterfaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account) -> ChatTextInputPanelState { +func inputTextPanelStateForChatPresentationInterfaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext) -> ChatTextInputPanelState { var contextPlaceholder: NSAttributedString? loop: for (_, result) in chatPresentationInterfaceState.inputQueryResults { if case let .contextRequestResult(peer, _) = result, let botUser = peer as? TelegramUser, let botInfo = botUser.botInfo, let inlinePlaceholder = botInfo.inlinePlaceholder { diff --git a/TelegramUI/ChatInterfaceInputNodes.swift b/TelegramUI/ChatInterfaceInputNodes.swift index 419025cb45..80f8b540e7 100644 --- a/TelegramUI/ChatInterfaceInputNodes.swift +++ b/TelegramUI/ChatInterfaceInputNodes.swift @@ -3,7 +3,7 @@ import AsyncDisplayKit import TelegramCore import Postbox -func inputNodeForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account, currentNode: ChatInputNode?, interfaceInteraction: ChatPanelInterfaceInteraction?, inputMediaNode: ChatMediaInputNode?, controllerInteraction: ChatControllerInteraction, inputPanelNode: ChatInputPanelNode?) -> ChatInputNode? { +func inputNodeForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, currentNode: ChatInputNode?, interfaceInteraction: ChatPanelInterfaceInteraction?, inputMediaNode: ChatMediaInputNode?, controllerInteraction: ChatControllerInteraction, inputPanelNode: ChatInputPanelNode?) -> ChatInputNode? { if !(inputPanelNode is ChatTextInputPanelNode) { return nil } diff --git a/TelegramUI/ChatInterfaceStateAccessoryPanels.swift b/TelegramUI/ChatInterfaceStateAccessoryPanels.swift index 470a869735..5eea14c19a 100644 --- a/TelegramUI/ChatInterfaceStateAccessoryPanels.swift +++ b/TelegramUI/ChatInterfaceStateAccessoryPanels.swift @@ -2,7 +2,7 @@ import Foundation import AsyncDisplayKit import TelegramCore -func accessoryPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account, currentPanel: AccessoryPanelNode?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> AccessoryPanelNode? { +func accessoryPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, currentPanel: AccessoryPanelNode?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> AccessoryPanelNode? { if let _ = chatPresentationInterfaceState.interfaceState.selectionState { return nil } @@ -18,7 +18,7 @@ func accessoryPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceS previewPanelNode.updateThemeAndStrings(theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) return previewPanelNode } else { - let panelNode = WebpagePreviewAccessoryPanelNode(account: account, url: editingUrlPreview.0, webpage: editingUrlPreview.1, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panelNode = WebpagePreviewAccessoryPanelNode(context: context, url: editingUrlPreview.0, webpage: editingUrlPreview.1, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panelNode.interfaceInteraction = interfaceInteraction return panelNode } @@ -29,7 +29,7 @@ func accessoryPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceS editPanelNode.updateThemeAndStrings(theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) return editPanelNode } else { - let panelNode = EditAccessoryPanelNode(account: account, messageId: editMessage.messageId, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, nameDisplayOrder: chatPresentationInterfaceState.nameDisplayOrder) + let panelNode = EditAccessoryPanelNode(context: context, messageId: editMessage.messageId, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, nameDisplayOrder: chatPresentationInterfaceState.nameDisplayOrder) panelNode.interfaceInteraction = interfaceInteraction return panelNode } @@ -40,7 +40,7 @@ func accessoryPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceS previewPanelNode.updateThemeAndStrings(theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) return previewPanelNode } else { - let panelNode = WebpagePreviewAccessoryPanelNode(account: account, url: urlPreview.0, webpage: urlPreview.1, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panelNode = WebpagePreviewAccessoryPanelNode(context: context, url: urlPreview.0, webpage: urlPreview.1, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panelNode.interfaceInteraction = interfaceInteraction return panelNode } @@ -50,7 +50,7 @@ func accessoryPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceS forwardPanelNode.updateThemeAndStrings(theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) return forwardPanelNode } else { - let panelNode = ForwardAccessoryPanelNode(account: account, messageIds: forwardMessageIds, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) + let panelNode = ForwardAccessoryPanelNode(context: context, messageIds: forwardMessageIds, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) panelNode.interfaceInteraction = interfaceInteraction return panelNode } @@ -60,7 +60,7 @@ func accessoryPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceS replyPanelNode.updateThemeAndStrings(theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) return replyPanelNode } else { - let panelNode = ReplyAccessoryPanelNode(account: account, messageId: replyMessageId, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, nameDisplayOrder: chatPresentationInterfaceState.nameDisplayOrder) + let panelNode = ReplyAccessoryPanelNode(context: context, messageId: replyMessageId, theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings, nameDisplayOrder: chatPresentationInterfaceState.nameDisplayOrder) panelNode.interfaceInteraction = interfaceInteraction return panelNode } diff --git a/TelegramUI/ChatInterfaceStateContextMenus.swift b/TelegramUI/ChatInterfaceStateContextMenus.swift index 279a1f2554..493ba0e296 100644 --- a/TelegramUI/ChatInterfaceStateContextMenus.swift +++ b/TelegramUI/ChatInterfaceStateContextMenus.swift @@ -144,7 +144,7 @@ func updatedChatEditInterfaceMessagetState(state: ChatPresentationInterfaceState return updated } -func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account, messages: [Message], controllerInteraction: ChatControllerInteraction?, selectAll: Bool, interfaceInteraction: ChatPanelInterfaceInteraction?) -> Signal<[ChatMessageContextMenuAction], NoError> { +func contextMenuForChatPresentationIntefaceState(chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, messages: [Message], controllerInteraction: ChatControllerInteraction?, selectAll: Bool, interfaceInteraction: ChatPanelInterfaceInteraction?) -> Signal<[ChatMessageContextMenuAction], NoError> { guard let interfaceInteraction = interfaceInteraction, let controllerInteraction = controllerInteraction else { return .single([]) } diff --git a/TelegramUI/ChatInterfaceStateContextQueries.swift b/TelegramUI/ChatInterfaceStateContextQueries.swift index 49a10c319b..14bfdff424 100644 --- a/TelegramUI/ChatInterfaceStateContextQueries.swift +++ b/TelegramUI/ChatInterfaceStateContextQueries.swift @@ -11,7 +11,7 @@ enum ChatContextQueryUpdate { case update(ChatPresentationInputQuery, Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError>) } -func contextQueryResultStateForChatInterfacePresentationState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account, currentQueryStates: inout [ChatPresentationInputQueryKind: (ChatPresentationInputQuery, Disposable)]) -> [ChatPresentationInputQueryKind: ChatContextQueryUpdate] { +func contextQueryResultStateForChatInterfacePresentationState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, currentQueryStates: inout [ChatPresentationInputQueryKind: (ChatPresentationInputQuery, Disposable)]) -> [ChatPresentationInputQueryKind: ChatContextQueryUpdate] { guard let peer = chatPresentationInterfaceState.renderedPeer?.peer else { return [:] } @@ -283,7 +283,7 @@ private func updatedContextQueryResultStateForQuery(account: Account, peer: Peer } } -func searchQuerySuggestionResultStateForChatInterfacePresentationState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account, currentQuery: ChatPresentationInputQuery?) -> (ChatPresentationInputQuery?, Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError>)? { +func searchQuerySuggestionResultStateForChatInterfacePresentationState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, currentQuery: ChatPresentationInputQuery?) -> (ChatPresentationInputQuery?, Signal<(ChatPresentationInputQueryResult?) -> ChatPresentationInputQueryResult?, NoError>)? { var inputQuery: ChatPresentationInputQuery? if let search = chatPresentationInterfaceState.search { switch search.domain { @@ -337,7 +337,7 @@ func searchQuerySuggestionResultStateForChatInterfacePresentationState(_ chatPre private let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType([.link]).rawValue) -func urlPreviewStateForInputText(_ inputText: String?, account: Account, currentQuery: String?) -> (String?, Signal<(TelegramMediaWebpage?) -> TelegramMediaWebpage?, NoError>)? { +func urlPreviewStateForInputText(_ inputText: String?, context: AccountContext, currentQuery: String?) -> (String?, Signal<(TelegramMediaWebpage?) -> TelegramMediaWebpage?, NoError>)? { guard let text = inputText else { if currentQuery != nil { return (nil, .single({ _ in return nil })) diff --git a/TelegramUI/ChatInterfaceStateInputPanels.swift b/TelegramUI/ChatInterfaceStateInputPanels.swift index 95b8e2d628..1c23972046 100644 --- a/TelegramUI/ChatInterfaceStateInputPanels.swift +++ b/TelegramUI/ChatInterfaceStateInputPanels.swift @@ -2,7 +2,7 @@ import Foundation import AsyncDisplayKit import TelegramCore -func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account, currentPanel: ChatInputPanelNode?, textInputPanelNode: ChatTextInputPanelNode?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> ChatInputPanelNode? { +func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, currentPanel: ChatInputPanelNode?, textInputPanelNode: ChatTextInputPanelNode?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> ChatInputPanelNode? { if let renderedPeer = chatPresentationInterfaceState.renderedPeer, renderedPeer.peer?.restrictionText != nil { return nil } @@ -21,7 +21,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatSearchInputPanelNode(theme: chatPresentationInterfaceState.theme) - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -36,7 +36,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatMessageSelectionInputPanelNode(theme: chatPresentationInterfaceState.theme) - panel.account = account + panel.context = context panel.selectedMessages = selectionState.selectedIds panel.interfaceInteraction = interfaceInteraction return panel @@ -49,7 +49,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatUnblockInputPanelNode(theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -67,7 +67,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatFeedNavigationInputPanelNode(theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -82,7 +82,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = SecretChatHandshakeStatusInputPanelNode() - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -91,7 +91,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = DeleteChatInputPanelNode() - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -104,7 +104,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatRestrictedInputPanelNode() - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -116,7 +116,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = DeleteChatInputPanelNode() - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -132,7 +132,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatChannelSubscriberInputPanelNode() - panel.account = account + panel.context = context return panel } } @@ -143,7 +143,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatChannelSubscriberInputPanelNode() - panel.account = account + panel.context = context return panel } case .member: @@ -157,7 +157,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = DeleteChatInputPanelNode() - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -170,7 +170,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatRestrictedInputPanelNode() - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -192,7 +192,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatBotStartInputPanelNode(theme: chatPresentationInterfaceState.theme, strings: chatPresentationInterfaceState.strings) - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -203,7 +203,7 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState return currentPanel } else { let panel = ChatRecordingPreviewInputPanelNode(theme: chatPresentationInterfaceState.theme) - panel.account = account + panel.context = context panel.interfaceInteraction = interfaceInteraction return panel } @@ -224,14 +224,14 @@ func inputPanelForChatPresentationIntefaceState(_ chatPresentationInterfaceState } else { if let textInputPanelNode = textInputPanelNode { textInputPanelNode.interfaceInteraction = interfaceInteraction - textInputPanelNode.account = account + textInputPanelNode.context = context return textInputPanelNode } else { let panel = ChatTextInputPanelNode(theme: chatPresentationInterfaceState.theme, presentController: { [weak interfaceInteraction] controller in interfaceInteraction?.presentController(controller, nil) }) panel.interfaceInteraction = interfaceInteraction - panel.account = account + panel.context = context return panel } } diff --git a/TelegramUI/ChatInterfaceTitlePanelNodes.swift b/TelegramUI/ChatInterfaceTitlePanelNodes.swift index c940af820e..c87f6ddef6 100644 --- a/TelegramUI/ChatInterfaceTitlePanelNodes.swift +++ b/TelegramUI/ChatInterfaceTitlePanelNodes.swift @@ -1,7 +1,7 @@ import Foundation import TelegramCore -func titlePanelForChatPresentationInterfaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, account: Account, currentPanel: ChatTitleAccessoryPanelNode?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> ChatTitleAccessoryPanelNode? { +func titlePanelForChatPresentationInterfaceState(_ chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, currentPanel: ChatTitleAccessoryPanelNode?, interfaceInteraction: ChatPanelInterfaceInteraction?) -> ChatTitleAccessoryPanelNode? { if case .overlay = chatPresentationInterfaceState.mode { return nil } diff --git a/TelegramUI/ChatItemGalleryFooterContentNode.swift b/TelegramUI/ChatItemGalleryFooterContentNode.swift index 34cc0941f8..21edf6cce1 100644 --- a/TelegramUI/ChatItemGalleryFooterContentNode.swift +++ b/TelegramUI/ChatItemGalleryFooterContentNode.swift @@ -103,7 +103,7 @@ enum ChatItemGalleryFooterContentTapAction { } final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { - private let account: Account + private let context: AccountContext private var theme: PresentationTheme private var strings: PresentationStrings private var dateTimeFormat: PresentationDateTimeFormat @@ -201,8 +201,8 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { } } - init(account: Account, presentationData: PresentationData) { - self.account = account + init(context: AccountContext, presentationData: PresentationData) { + self.context = context self.theme = presentationData.theme self.strings = presentationData.strings self.dateTimeFormat = presentationData.dateTimeFormat @@ -544,17 +544,17 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { @objc func deleteButtonPressed() { if let currentMessage = self.currentMessage { - let _ = (self.account.postbox.transaction { transaction -> [Message] in + let _ = (self.context.account.postbox.transaction { transaction -> [Message] in return transaction.getMessageGroup(currentMessage.id) ?? [] } |> deliverOnMainQueue).start(next: { [weak self] messages in if let strongSelf = self, !messages.isEmpty { if messages.count == 1 { strongSelf.commitDeleteMessages(messages, ask: true) } else { - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.account.telegramApplicationContext.currentPresentationData.with { $0 } var generalMessageContentKind: MessageContentKind? for message in messages { - let currentKind = messageContentKind(message, strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: strongSelf.account.peerId) + let currentKind = messageContentKind(message, strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: strongSelf.context.account.peerId) if generalMessageContentKind == nil || generalMessageContentKind == currentKind { generalMessageContentKind = currentKind } else { @@ -613,13 +613,13 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { } private func commitDeleteMessages(_ messages: [Message], ask: Bool) { - self.messageContextDisposable.set((chatAvailableMessageActions(postbox: self.account.postbox, accountPeerId: self.account.peerId, messageIds: Set(messages.map { $0.id })) |> deliverOnMainQueue).start(next: { [weak self] actions in + self.messageContextDisposable.set((chatAvailableMessageActions(postbox: self.context.account.postbox, accountPeerId: self.context.account.peerId, messageIds: Set(messages.map { $0.id })) |> deliverOnMainQueue).start(next: { [weak self] actions in if let strongSelf = self, let controllerInteration = strongSelf.controllerInteraction, !actions.options.isEmpty { let actionSheet = ActionSheetController(presentationTheme: strongSelf.theme) var items: [ActionSheetItem] = [] var personalPeerName: String? var isChannel = false - var peerId: PeerId = messages[0].id.peerId + let peerId: PeerId = messages[0].id.peerId if let user = messages[0].peers[messages[0].id.peerId] as? TelegramUser { personalPeerName = user.compactDisplayTitle } else if let channel = messages[0].peers[messages[0].id.peerId] as? TelegramChannel, case .broadcast = channel.info { @@ -638,26 +638,26 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { items.append(ActionSheetButtonItem(title: globalTitle, color: .destructive, action: { [weak actionSheet] in actionSheet?.dismissAnimated() if let strongSelf = self { - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: messages.map { $0.id }, type: .forEveryone).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: messages.map { $0.id }, type: .forEveryone).start() strongSelf.controllerInteraction?.dismissController() } })) } if actions.options.contains(.deleteLocally) { var localOptionText = strongSelf.strings.Conversation_DeleteMessagesForMe - if strongSelf.account.peerId == peerId { + if strongSelf.context.account.peerId == peerId { localOptionText = strongSelf.strings.Conversation_Moderate_Delete } items.append(ActionSheetButtonItem(title: localOptionText, color: .destructive, action: { [weak actionSheet] in actionSheet?.dismissAnimated() if let strongSelf = self { - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: messages.map { $0.id }, type: .forLocalPeer).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: messages.map { $0.id }, type: .forLocalPeer).start() strongSelf.controllerInteraction?.dismissController() } })) } if !ask && items.count == 1 { - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: messages.map { $0.id }, type: .forEveryone).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: messages.map { $0.id }, type: .forEveryone).start() strongSelf.controllerInteraction?.dismissController() } else { actionSheet.setItemGroups([ActionSheetItemGroup(items: items), ActionSheetItemGroup(items: [ @@ -673,14 +673,14 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { @objc func actionButtonPressed() { if let currentMessage = self.currentMessage { - let _ = (self.account.postbox.transaction { transaction -> [Message] in + let _ = (self.context.account.postbox.transaction { transaction -> [Message] in return transaction.getMessageGroup(currentMessage.id) ?? [] } |> deliverOnMainQueue).start(next: { [weak self] messages in if let strongSelf = self, !messages.isEmpty { - let presentationData = strongSelf.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.account.peerId) + let currentKind = messageContentKind(message, strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: strongSelf.context.account.peerId) if generalMessageContentKind == nil || generalMessageContentKind == currentKind { generalMessageContentKind = currentKind } else { @@ -706,12 +706,12 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { } else if let webpage = m as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { if content.embedType == "iframe" { let item = OpenInItem.url(url: content.url) - if availableOpenInOptions(applicationContext: strongSelf.account.telegramApplicationContext, item: item).count > 1 { + if availableOpenInOptions(context: strongSelf.context, item: item).count > 1 { preferredAction = .custom(action: ShareControllerAction(title: presentationData.strings.Conversation_FileOpenIn, action: { [weak self] in if let strongSelf = self { - let openInController = OpenInActionSheetController(account: strongSelf.account, item: item, additionalAction: nil, openUrl: { [weak self] url in - if let strongSelf = self, let applicationContext = strongSelf.account.applicationContext as? TelegramApplicationContext { - openExternalUrl(account: strongSelf.account, url: url, forceExternal: true, presentationData: presentationData, applicationContext: applicationContext, navigationController: nil, dismissInput: {}) + let openInController = OpenInActionSheetController(context: strongSelf.context, item: item, additionalAction: nil, openUrl: { [weak self] url in + if let strongSelf = self { + openExternalUrl(context: strongSelf.context, url: url, forceExternal: true, presentationData: presentationData, navigationController: nil, dismissInput: {}) } }) strongSelf.controllerInteraction?.presentController(openInController, nil) @@ -720,7 +720,7 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { } else { preferredAction = .custom(action: ShareControllerAction(title: presentationData.strings.Web_OpenExternal, action: { [weak self] in if let strongSelf = self { - openExternalUrl(account: strongSelf.account, url: content.url, presentationData: presentationData, applicationContext: strongSelf.account.telegramApplicationContext, navigationController: nil, dismissInput: {}) + openExternalUrl(context: strongSelf.context, url: content.url, presentationData: presentationData, navigationController: nil, dismissInput: {}) } })) } @@ -739,7 +739,7 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { preferredAction = .custom(action: ShareControllerAction(title: presentationData.strings.Preview_SaveGif, action: { [weak self] in if let strongSelf = self { let message = messages[0] - let _ = addSavedGif(postbox: strongSelf.account.postbox, fileReference: .message(message: MessageReference(message), media: file)).start() + let _ = addSavedGif(postbox: strongSelf.context.account.postbox, fileReference: .message(message: MessageReference(message), media: file)).start() } })) } else if file.mimeType.hasPrefix("image/") || file.mimeType.hasPrefix("video/") { @@ -747,7 +747,7 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { } } } - let shareController = ShareController(account: strongSelf.account, subject: subject, preferredAction: preferredAction) + let shareController = ShareController(context: strongSelf.context, subject: subject, preferredAction: preferredAction) strongSelf.controllerInteraction?.presentController(shareController, nil) } else { var singleText = presentationData.strings.Media_ShareItem(1) @@ -768,7 +768,7 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { let shareAction: ([Message]) -> Void = { messages in if let strongSelf = self { - let shareController = ShareController(account: strongSelf.account, subject: .messages(messages), preferredAction: preferredAction) + let shareController = ShareController(context: strongSelf.context, subject: .messages(messages), preferredAction: preferredAction) strongSelf.controllerInteraction?.presentController(shareController, nil) } } @@ -797,7 +797,7 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { } }) } else if let (webPage, media) = self.currentWebPageAndMedia { - let presentationData = self.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = self.context.currentPresentationData.with { $0 } var preferredAction = ShareControllerPreferredAction.default var subject = ShareControllerSubject.media(.webPage(webPage: WebpageReference(webPage), media: media)) @@ -806,7 +806,7 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { if file.isAnimated { preferredAction = .custom(action: ShareControllerAction(title: presentationData.strings.Preview_SaveGif, action: { [weak self] in if let strongSelf = self { - let _ = addSavedGif(postbox: strongSelf.account.postbox, fileReference: .webPage(webPage: WebpageReference(webPage), media: file)).start() + let _ = addSavedGif(postbox: strongSelf.context.account.postbox, fileReference: .webPage(webPage: WebpageReference(webPage), media: file)).start() } })) } else if file.mimeType.hasPrefix("image/") || file.mimeType.hasPrefix("video/") { @@ -817,12 +817,12 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { subject = .url(content.url) let item = OpenInItem.url(url: content.url) - if availableOpenInOptions(applicationContext: self.account.telegramApplicationContext, item: item).count > 1 { + if availableOpenInOptions(context: self.context, item: item).count > 1 { preferredAction = .custom(action: ShareControllerAction(title: presentationData.strings.Conversation_FileOpenIn, action: { [weak self] in if let strongSelf = self { - let openInController = OpenInActionSheetController(account: strongSelf.account, item: item, additionalAction: nil, openUrl: { [weak self] url in - if let strongSelf = self, let applicationContext = strongSelf.account.applicationContext as? TelegramApplicationContext { - openExternalUrl(account: strongSelf.account, url: url, forceExternal: true, presentationData: presentationData, applicationContext: applicationContext, navigationController: nil, dismissInput: {}) + let openInController = OpenInActionSheetController(context: strongSelf.context, item: item, additionalAction: nil, openUrl: { [weak self] url in + if let strongSelf = self { + openExternalUrl(context: strongSelf.context, url: url, forceExternal: true, presentationData: presentationData, navigationController: nil, dismissInput: {}) } }) strongSelf.controllerInteraction?.presentController(openInController, nil) @@ -831,7 +831,7 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { } else { preferredAction = .custom(action: ShareControllerAction(title: presentationData.strings.Web_OpenExternal, action: { [weak self] in if let strongSelf = self { - openExternalUrl(account: strongSelf.account, url: content.url, presentationData: presentationData, applicationContext: strongSelf.account.telegramApplicationContext, navigationController: nil, dismissInput: {}) + openExternalUrl(context: strongSelf.context, url: content.url, presentationData: presentationData, navigationController: nil, dismissInput: {}) } })) } @@ -845,7 +845,7 @@ final class ChatItemGalleryFooterContentNode: GalleryFooterContentNode { } } } - let shareController = ShareController(account: self.account, subject: subject, preferredAction: preferredAction) + let shareController = ShareController(context: self.context, subject: subject, preferredAction: preferredAction) self.controllerInteraction?.presentController(shareController, nil) } } diff --git a/TelegramUI/ChatListController.swift b/TelegramUI/ChatListController.swift index e1936748e6..eb6a0e95d8 100644 --- a/TelegramUI/ChatListController.swift +++ b/TelegramUI/ChatListController.swift @@ -11,7 +11,7 @@ public func useSpecialTabBarIcons() -> Bool { public class ChatListController: TelegramController, KeyShortcutResponder, UIViewControllerPreviewingDelegate { private var validLayout: ContainerViewLayout? - private let account: Account + private let context: AccountContext private let controlsHistoryPreload: Bool public let groupId: PeerGroupId? @@ -48,18 +48,18 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie private var searchContentNode: NavigationBarSearchContentNode? - public init(account: Account, groupId: PeerGroupId?, controlsHistoryPreload: Bool) { - self.account = account + public init(context: AccountContext, groupId: PeerGroupId?, controlsHistoryPreload: Bool) { + self.context = context self.controlsHistoryPreload = controlsHistoryPreload self.groupId = groupId - self.presentationData = (account.telegramApplicationContext.currentPresentationData.with { $0 }) + self.presentationData = (context.currentPresentationData.with { $0 }) self.presentationDataValue.set(.single(self.presentationData)) self.titleView = NetworkStatusTitleView(theme: self.presentationData.theme) - super.init(account: account, navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData), mediaAccessoryPanelVisibility: .always, locationBroadcastPanelSource: .summary) + super.init(context: context, navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData), mediaAccessoryPanelVisibility: .always, locationBroadcastPanelSource: .summary) self.statusBar.statusBarStyle = self.presentationData.theme.rootController.statusBar.style.style @@ -134,7 +134,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie } } - let hasProxy = account.postbox.preferencesView(keys: [PreferencesKeys.proxySettings]) + let hasProxy = context.account.postbox.preferencesView(keys: [PreferencesKeys.proxySettings]) |> map { preferences -> (Bool, Bool) in if let settings = preferences.values[PreferencesKeys.proxySettings] as? ProxySettings { return (!settings.servers.isEmpty, settings.enabled) @@ -146,13 +146,13 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie return lhs == rhs }) - let passcode = account.postbox.combinedView(keys: [.accessChallengeData]) + let passcode = context.account.postbox.combinedView(keys: [.accessChallengeData]) |> map { view -> (Bool, Bool) in let data = (view.views[.accessChallengeData] as! AccessChallengeDataView).data return (data.isLockable, data.autolockDeadline == 0) } - self.titleDisposable = (combineLatest(account.networkState |> deliverOnMainQueue, hasProxy |> deliverOnMainQueue, passcode |> deliverOnMainQueue)).start(next: { [weak self] state, proxy, passcode in + self.titleDisposable = combineLatest(queue: .mainQueue(), context.account.networkState, hasProxy, passcode).start(next: { [weak self] state, proxy, passcode in if let strongSelf = self { let (hasProxy, connectsViaProxy) = proxy let (isPasscodeSet, isManuallyLocked) = passcode @@ -201,7 +201,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie } }) - self.badgeDisposable = (renderedTotalUnreadCount(postbox: account.postbox) |> deliverOnMainQueue).start(next: { [weak self] count in + self.badgeDisposable = (renderedTotalUnreadCount(postbox: context.account.postbox) |> deliverOnMainQueue).start(next: { [weak self] count in if let strongSelf = self { if count.0 == 0 { strongSelf.tabBarItem.badgeValue = "" @@ -217,7 +217,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie self.titleView.toggleIsLocked = { [weak self] in if let strongSelf = self { - let _ = (strongSelf.account.postbox.transaction({ transaction -> Void in + let _ = (strongSelf.context.account.postbox.transaction({ transaction -> Void in var data = transaction.getAccessChallengeData() if data.isLockable { if data.autolockDeadline != 0 { @@ -238,11 +238,11 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie self.titleView.openProxySettings = { [weak self] in if let strongSelf = self { - (strongSelf.navigationController as? NavigationController)?.pushViewController(proxySettingsController(account: account)) + (strongSelf.navigationController as? NavigationController)?.pushViewController(proxySettingsController(context: context)) } } - 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 @@ -320,7 +320,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie } override public func loadDisplayNode() { - self.displayNode = ChatListControllerNode(account: self.account, groupId: self.groupId, controlsHistoryPreload: self.controlsHistoryPreload, presentationData: self.presentationData, controller: self) + self.displayNode = ChatListControllerNode(context: self.context, groupId: self.groupId, controlsHistoryPreload: self.controlsHistoryPreload, presentationData: self.presentationData, controller: self) self.chatListDisplayNode.navigationBar = self.navigationBar @@ -342,7 +342,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie guard let strongSelf = self else { return } - let _ = (strongSelf.account.postbox.transaction { transaction -> RenderedPeer? in + let _ = (strongSelf.context.account.postbox.transaction { transaction -> RenderedPeer? in guard let peer = transaction.getPeer(peerId) else { return nil } @@ -382,7 +382,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie } else if let _ = chatPeer as? TelegramSecretChat { deleteTitle = strongSelf.presentationData.strings.ChatList_DeleteChat } - items.append(DeleteChatPeerActionSheetItem(account: strongSelf.account, peer: mainPeer, chatPeer: chatPeer, strings: strongSelf.presentationData.strings)) + items.append(DeleteChatPeerActionSheetItem(context: strongSelf.context, peer: mainPeer, chatPeer: chatPeer, strings: strongSelf.presentationData.strings)) if canClear { items.append(ActionSheetButtonItem(title: strongSelf.presentationData.strings.DialogList_ClearHistoryConfirmation, color: .accent, action: { [weak actionSheet] in actionSheet?.dismissAnimated() @@ -395,12 +395,12 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie state.pendingClearHistoryPeerIds.insert(peer.peerId) return state }) - strongSelf.present(UndoOverlayController(account: strongSelf.account, text: strongSelf.presentationData.strings.Undo_MessagesDeleted, action: { shouldCommit in + strongSelf.present(UndoOverlayController(context: strongSelf.context, text: strongSelf.presentationData.strings.Undo_MessagesDeleted, action: { shouldCommit in guard let strongSelf = self else { return } if shouldCommit { - let _ = clearHistoryInteractively(postbox: strongSelf.account.postbox, peerId: peerId).start(completed: { + let _ = clearHistoryInteractively(postbox: strongSelf.context.account.postbox, peerId: peerId).start(completed: { guard let strongSelf = self else { return } @@ -435,10 +435,10 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie if let strongSelf = self { strongSelf.chatListDisplayNode.chatListNode.setCurrentRemovingPeerId(peerId) - let _ = removePeerChat(postbox: strongSelf.account.postbox, peerId: peerId, reportChatSpam: false).start(completed: { + let _ = removePeerChat(postbox: strongSelf.context.account.postbox, peerId: peerId, reportChatSpam: false).start(completed: { self?.chatListDisplayNode.chatListNode.setCurrentRemovingPeerId(peerId) }) - let _ = requestUpdatePeerIsBlocked(account: strongSelf.account, peerId: peer.peerId, isBlocked: true).start() + let _ = requestUpdatePeerIsBlocked(account: strongSelf.context.account, peerId: peer.peerId, isBlocked: true).start() } })) } @@ -458,7 +458,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie if let strongSelf = self { if let navigationController = strongSelf.navigationController as? NavigationController { if isAd { - let _ = (ApplicationSpecificNotice.getProxyAdsAcknowledgment(postbox: strongSelf.account.postbox) + let _ = (ApplicationSpecificNotice.getProxyAdsAcknowledgment(postbox: strongSelf.context.account.postbox) |> deliverOnMainQueue).start(next: { value in guard let strongSelf = self else { return @@ -466,7 +466,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie if !value { strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: strongSelf.presentationData.theme), title: nil, text: strongSelf.presentationData.strings.DialogList_AdNoticeAlert, actions: [TextAlertAction(type: .defaultAction, title: strongSelf.presentationData.strings.Common_OK, action: { if let strongSelf = self { - let _ = ApplicationSpecificNotice.setProxyAdsAcknowledgment(postbox: strongSelf.account.postbox).start() + let _ = ApplicationSpecificNotice.setProxyAdsAcknowledgment(postbox: strongSelf.context.account.postbox).start() } })]), in: .window(.root)) } @@ -477,7 +477,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie if let layout = strongSelf.validLayout, case .regular = layout.metrics.widthClass { scrollToEndIfExists = true } - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(peerId), scrollToEndIfExists: scrollToEndIfExists, animated: animated, completion: { [weak self] in + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peerId), scrollToEndIfExists: scrollToEndIfExists, animated: animated, completion: { [weak self] in self?.chatListDisplayNode.chatListNode.clearHighlightAnimated(true) }) } @@ -491,7 +491,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie if let layout = strongSelf.validLayout, case .regular = layout.metrics.widthClass { scrollToEndIfExists = true } - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .group(groupId), scrollToEndIfExists: scrollToEndIfExists) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .group(groupId), scrollToEndIfExists: scrollToEndIfExists) strongSelf.chatListDisplayNode.chatListNode.clearHighlightAnimated(true) } } @@ -499,17 +499,17 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie self.chatListDisplayNode.chatListNode.updatePeerGrouping = { [weak self] peerId, group in if let strongSelf = self { - let _ = updatePeerGroupIdInteractively(postbox: strongSelf.account.postbox, peerId: peerId, groupId: group ? Namespaces.PeerGroup.feed : nil).start() + let _ = updatePeerGroupIdInteractively(postbox: strongSelf.context.account.postbox, peerId: peerId, groupId: group ? Namespaces.PeerGroup.feed : nil).start() } } self.chatListDisplayNode.requestOpenMessageFromSearch = { [weak self] peer, messageId in if let strongSelf = self { - strongSelf.openMessageFromSearchDisposable.set((storedMessageFromSearchPeer(account: strongSelf.account, peer: peer) + strongSelf.openMessageFromSearchDisposable.set((storedMessageFromSearchPeer(account: strongSelf.context.account, peer: peer) |> deliverOnMainQueue).start(next: { [weak strongSelf] actualPeerId in if let strongSelf = strongSelf { if let navigationController = strongSelf.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(actualPeerId), messageId: messageId, purposefulAction: { + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(actualPeerId), messageId: messageId, purposefulAction: { self?.deactivateSearch(animated: false) }) strongSelf.chatListDisplayNode.chatListNode.clearHighlightAnimated(true) @@ -521,7 +521,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie self.chatListDisplayNode.requestOpenPeerFromSearch = { [weak self] peer, dismissSearch in if let strongSelf = self { - let storedPeer = strongSelf.account.postbox.transaction { transaction -> Void in + let storedPeer = strongSelf.context.account.postbox.transaction { transaction -> Void in if transaction.getPeer(peer.id) == nil { updatePeers(transaction: transaction, peers: [peer], update: { previousPeer, updatedPeer in return updatedPeer @@ -534,7 +534,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie strongSelf.dismissSearchOnDisappear = true } if let navigationController = strongSelf.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(peer.id), purposefulAction: { [weak self] in + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peer.id), purposefulAction: { [weak self] in self?.deactivateSearch(animated: false) }) strongSelf.chatListDisplayNode.chatListNode.clearHighlightAnimated(true) @@ -555,7 +555,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie actionSheet?.dismissAnimated() if let strongSelf = self { - let _ = removeRecentPeer(account: strongSelf.account, peerId: peer.id).start() + let _ = removeRecentPeer(account: strongSelf.context.account, peerId: peer.id).start() let searchContainer = strongSelf.chatListDisplayNode.searchDisplayController?.contentNode as? ChatListSearchContainerNode searchContainer?.removePeerFromTopPeers(peer.id) } @@ -574,7 +574,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie self.chatListDisplayNode.requestAddContact = { [weak self] phoneNumber in if let strongSelf = self { strongSelf.chatListDisplayNode.view.endEditing(true) - openAddContact(account: strongSelf.account, phoneNumber: phoneNumber, present: { [weak self] controller, arguments in + openAddContact(context: strongSelf.context, phoneNumber: phoneNumber, present: { [weak self] controller, arguments in self?.present(controller, in: .window(.root), with: arguments) }, completed: { self?.deactivateSearch(animated: false) @@ -596,7 +596,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie } } - let account = self.account + let context = self.context let peerIdsAndOptions: Signal<(ChatListSelectionOptions, Set)?, NoError> = self.chatListDisplayNode.chatListNode.state |> map { state -> Set? in if !state.editing { @@ -607,7 +607,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie |> distinctUntilChanged |> mapToSignal { selectedPeerIds -> Signal<(ChatListSelectionOptions, Set)?, NoError> in if let selectedPeerIds = selectedPeerIds { - return chatListSelectionOptions(postbox: account.postbox, peerIds: selectedPeerIds) + return chatListSelectionOptions(postbox: context.account.postbox, peerIds: selectedPeerIds) |> map { options -> (ChatListSelectionOptions, Set)? in return (options, selectedPeerIds) } @@ -670,13 +670,12 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie } if let lockViewFrame = self.titleView.lockViewFrame, !self.didShowPasscodeLockTooltipController { - self.passcodeLockTooltipDisposable.set((combineLatest(ApplicationSpecificNotice.getPasscodeLockTips(postbox: self.account.postbox), account.postbox.combinedView(keys: [.accessChallengeData]) |> take(1)) - |> deliverOnMainQueue).start(next: { [weak self] tooltipValue, passcodeView in + self.passcodeLockTooltipDisposable.set(combineLatest(queue: .mainQueue(), ApplicationSpecificNotice.getPasscodeLockTips(postbox: self.context.account.postbox), self.context.account.postbox.combinedView(keys: [.accessChallengeData]) |> take(1)).start(next: { [weak self] tooltipValue, passcodeView in if let strongSelf = self { if !tooltipValue { let hasPasscode = (passcodeView.views[.accessChallengeData] as! AccessChallengeDataView).data.isLockable if hasPasscode { - let _ = ApplicationSpecificNotice.setPasscodeLockTips(postbox: strongSelf.account.postbox).start() + let _ = ApplicationSpecificNotice.setPasscodeLockTips(postbox: strongSelf.context.account.postbox).start() let tooltipController = TooltipController(text: strongSelf.presentationData.strings.DialogList_PasscodeLockHelp, dismissByTapOutside: true) strongSelf.present(tooltipController, in: .window(.root), with: TooltipControllerPresentationArguments(sourceViewAndRect: { [weak self] in @@ -697,8 +696,8 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie if !self.didSuggestLocalization { self.didSuggestLocalization = true - let network = self.account.network - let signal = self.account.postbox.transaction { transaction -> (String, SuggestedLocalizationEntry?) in + let network = self.context.account.network + let signal = self.context.account.postbox.transaction { transaction -> (String, SuggestedLocalizationEntry?) in let languageCode: String if let current = transaction.getPreferencesEntry(key: PreferencesKeys.localizationSettings) as? LocalizationSettings { let code = current.primaryComponent.languageCode @@ -730,14 +729,14 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie guard let strongSelf = self, let (currentLanguageCode, suggestedLocalization) = suggestedLocalization else { return } - if let controller = languageSuggestionController(account: strongSelf.account, suggestedLocalization: suggestedLocalization, currentLanguageCode: currentLanguageCode, openSelection: { [weak self] in + if let controller = languageSuggestionController(context: strongSelf.context, suggestedLocalization: suggestedLocalization, currentLanguageCode: currentLanguageCode, openSelection: { [weak self] in if let strongSelf = self { - let controller = LocalizationListController(account: strongSelf.account) + let controller = LocalizationListController(context: strongSelf.context) (strongSelf.navigationController as? NavigationController)?.pushViewController(controller) } }) { strongSelf.present(controller, in: .window(.root)) - _ = markSuggestedLocalizationAsSeenInteractively(postbox: strongSelf.account.postbox, languageCode: suggestedLocalization.languageCode).start() + _ = markSuggestedLocalizationAsSeenInteractively(postbox: strongSelf.context.account.postbox, languageCode: suggestedLocalization.languageCode).start() } })) } @@ -844,7 +843,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie } @objc func composePressed() { - (self.navigationController as? NavigationController)?.replaceAllButRootController(ComposeController(account: self.account), animated: true) + (self.navigationController as? NavigationController)?.replaceAllButRootController(ComposeController(context: self.context), animated: true) } public func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { @@ -880,7 +879,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie sourceRect = CGRect(x: sourceRect.minX, y: sourceRect.minY + bounds.minY, width: bounds.width, height: bounds.height) sourceRect.size.height -= UIScreenPixel - let chatController = ChatController(account: self.account, chatLocation: .peer(peerId), mode: .standard(previewing: true)) + let chatController = ChatController(context: self.context, chatLocation: .peer(peerId), mode: .standard(previewing: true)) chatController.canReadHistory.set(false) chatController.containerLayoutUpdated(ContainerViewLayout(size: contentSize, metrics: LayoutMetrics(), intrinsicInsets: UIEdgeInsets(), safeInsets: UIEdgeInsets(), statusBarHeight: nil, inputHeight: nil, standardInputHeight: 216.0, inputHeightIsInteractivellyChanging: false), transition: .immediate) return (chatController, sourceRect) @@ -889,7 +888,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie sourceRect = CGRect(x: sourceRect.minX, y: sourceRect.minY + bounds.minY, width: bounds.width, height: bounds.height) sourceRect.size.height -= UIScreenPixel - let chatController = ChatController(account: self.account, chatLocation: .peer(messageId.peerId), messageId: messageId, mode: .standard(previewing: true)) + let chatController = ChatController(context: self.context, chatLocation: .peer(messageId.peerId), messageId: messageId, mode: .standard(previewing: true)) chatController.canReadHistory.set(false) chatController.containerLayoutUpdated(ContainerViewLayout(size: contentSize, metrics: LayoutMetrics(), intrinsicInsets: UIEdgeInsets(), safeInsets: UIEdgeInsets(), statusBarHeight: nil, inputHeight: nil, standardInputHeight: 216.0, inputHeightIsInteractivellyChanging: false), transition: .immediate) return (chatController, sourceRect) @@ -922,7 +921,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie switch item.content { case let .peer(_, peer, _, _, _, _, _, _, _): if peer.peerId.namespace != Namespaces.Peer.SecretChat { - let chatController = ChatController(account: self.account, chatLocation: .peer(peer.peerId), mode: .standard(previewing: true)) + let chatController = ChatController(context: self.context, chatLocation: .peer(peer.peerId), mode: .standard(previewing: true)) chatController.canReadHistory.set(false) chatController.containerLayoutUpdated(ContainerViewLayout(size: contentSize, metrics: LayoutMetrics(), intrinsicInsets: UIEdgeInsets(), safeInsets: UIEdgeInsets(), statusBarHeight: nil, inputHeight: nil, standardInputHeight: 216.0, inputHeightIsInteractivellyChanging: false), transition: .immediate) return (chatController, sourceRect) @@ -930,7 +929,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie return nil } case let .groupReference(groupId, _, _, _): - let chatListController = ChatListController(account: self.account, groupId: groupId, controlsHistoryPreload: false) + let chatListController = ChatListController(context: self.context, groupId: groupId, controlsHistoryPreload: false) chatListController.containerLayoutUpdated(ContainerViewLayout(size: contentSize, metrics: LayoutMetrics(), intrinsicInsets: UIEdgeInsets(), safeInsets: UIEdgeInsets(), statusBarHeight: nil, inputHeight: nil, standardInputHeight: 216.0, inputHeightIsInteractivellyChanging: false), transition: .immediate) return (chatListController, sourceRect) } @@ -949,7 +948,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie chatController.canReadHistory.set(true) chatController.updatePresentationMode(.standard(previewing: false)) if let navigationController = self.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, chatController: chatController, account: self.account, chatLocation: chatController.chatLocation, animated: false) + navigateToChatController(navigationController: navigationController, chatController: chatController, context: self.context, chatLocation: chatController.chatLocation, animated: false) self.chatListDisplayNode.chatListNode.clearHighlightAnimated(true) } } @@ -1004,16 +1003,16 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie let peerIds = self.chatListDisplayNode.chatListNode.currentState.selectedPeerIds if left { let signal: Signal - let account = self.account + let context = self.context if !peerIds.isEmpty { - signal = self.account.postbox.transaction { transaction -> Void in + signal = self.context.account.postbox.transaction { transaction -> Void in for peerId in peerIds { - togglePeerUnreadMarkInteractively(transaction: transaction, viewTracker: account.viewTracker, peerId: peerId, setToValue: false) + togglePeerUnreadMarkInteractively(transaction: transaction, viewTracker: context.account.viewTracker, peerId: peerId, setToValue: false) } } } else { - signal = self.account.postbox.transaction { transaction -> Void in - markAllChatsAsReadInteractively(transaction: transaction, viewTracker: account.viewTracker) + signal = self.context.account.postbox.transaction { transaction -> Void in + markAllChatsAsReadInteractively(transaction: transaction, viewTracker: context.account.viewTracker) } } let _ = (signal @@ -1030,7 +1029,7 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie return } - let account = strongSelf.account + let context = strongSelf.context let presentationData = strongSelf.presentationData let progressSignal = Signal { subscriber in let controller = OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .loading(cancelled: nil)) @@ -1045,9 +1044,9 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie |> delay(0.8, queue: Queue.mainQueue()) let progressDisposable = progressSignal.start() - let signal: Signal = strongSelf.account.postbox.transaction { transaction -> Void in + let signal: Signal = strongSelf.context.account.postbox.transaction { transaction -> Void in for peerId in peerIds { - removePeerChat(transaction: transaction, mediaBox: account.postbox.mediaBox, peerId: peerId, reportChatSpam: false, deleteGloballyIfPossible: false) + removePeerChat(transaction: transaction, mediaBox: context.account.postbox.mediaBox, peerId: peerId, reportChatSpam: false, deleteGloballyIfPossible: false) } } |> afterDisposed { @@ -1111,13 +1110,13 @@ public class ChatListController: TelegramController, KeyShortcutResponder, UIVie } else { statusText = self.presentationData.strings.Undo_ChatDeleted } - self.present(UndoOverlayController(account: self.account, text: statusText, action: { [weak self] shouldCommit in + self.present(UndoOverlayController(context: self.context, text: statusText, action: { [weak self] shouldCommit in guard let strongSelf = self else { return } if shouldCommit { strongSelf.chatListDisplayNode.chatListNode.setCurrentRemovingPeerId(peerId) - let _ = removePeerChat(postbox: strongSelf.account.postbox, peerId: peerId, reportChatSpam: false, deleteGloballyIfPossible: deleteGloballyIfPossible).start(completed: { + let _ = removePeerChat(postbox: strongSelf.context.account.postbox, peerId: peerId, reportChatSpam: false, deleteGloballyIfPossible: deleteGloballyIfPossible).start(completed: { guard let strongSelf = self else { return } diff --git a/TelegramUI/ChatListControllerNode.swift b/TelegramUI/ChatListControllerNode.swift index 0865c9c27c..2e74705b43 100644 --- a/TelegramUI/ChatListControllerNode.swift +++ b/TelegramUI/ChatListControllerNode.swift @@ -17,7 +17,7 @@ private final class ChatListControllerNodeView: UITracingLayerView, PreviewingHo } final class ChatListControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private let groupId: PeerGroupId? private var presentationData: PresentationData @@ -46,12 +46,12 @@ final class ChatListControllerNode: ASDisplayNode { } } - init(account: Account, groupId: PeerGroupId?, controlsHistoryPreload: Bool, presentationData: PresentationData, controller: ChatListController) { - self.account = account + init(context: AccountContext, groupId: PeerGroupId?, controlsHistoryPreload: Bool, presentationData: PresentationData, controller: ChatListController) { + self.context = context self.groupId = groupId self.presentationData = presentationData - self.chatListNode = ChatListNode(account: account, groupId: groupId, controlsHistoryPreload: controlsHistoryPreload, mode: .chatList, theme: presentationData.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameSortOrder: presentationData.nameSortOrder, nameDisplayOrder: presentationData.nameDisplayOrder, disableAnimations: presentationData.disableAnimations) + self.chatListNode = ChatListNode(context: context, groupId: groupId, controlsHistoryPreload: controlsHistoryPreload, mode: .chatList, theme: presentationData.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameSortOrder: presentationData.nameSortOrder, nameDisplayOrder: presentationData.nameDisplayOrder, disableAnimations: presentationData.disableAnimations) self.controller = controller @@ -180,7 +180,7 @@ final class ChatListControllerNode: ASDisplayNode { return } - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ChatListSearchContainerNode(account: self.account, filter: [], groupId: self.groupId, openPeer: { [weak self] peer, dismissSearch in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ChatListSearchContainerNode(context: self.context, filter: [], groupId: self.groupId, openPeer: { [weak self] peer, dismissSearch in self?.requestOpenPeerFromSearch?(peer, dismissSearch) }, openRecentPeerOptions: { [weak self] peer in self?.requestOpenRecentPeerOptions?(peer) diff --git a/TelegramUI/ChatListItem.swift b/TelegramUI/ChatListItem.swift index aa26488a8f..215d45ca21 100644 --- a/TelegramUI/ChatListItem.swift +++ b/TelegramUI/ChatListItem.swift @@ -392,7 +392,7 @@ class ChatListItemNode: ItemListRevealOptionsItemNode { if peer.id == item.account.peerId { overrideImage = .savedMessagesIcon } - self.avatarNode.setPeer(account: item.account, peer: peer, overrideImage: overrideImage, emptyColor: item.presentationData.theme.list.mediaPlaceholderColor) + self.avatarNode.setPeer(account: item.account, theme: item.presentationData.theme, peer: peer, overrideImage: overrideImage, emptyColor: item.presentationData.theme.list.mediaPlaceholderColor) } } diff --git a/TelegramUI/ChatListNode.swift b/TelegramUI/ChatListNode.swift index fec39e304c..e025f41671 100644 --- a/TelegramUI/ChatListNode.swift +++ b/TelegramUI/ChatListNode.swift @@ -288,7 +288,7 @@ enum ChatListNodeEmtpyState: Equatable { final class ChatListNode: ListView { private let controlsHistoryPreload: Bool - private let account: Account + private let context: AccountContext private let mode: ChatListNodeMode private let _ready = ValuePromise() @@ -372,8 +372,8 @@ final class ChatListNode: ListView { let _ = self.currentRemovingPeerId.swap(peerId) } - init(account: Account, groupId: PeerGroupId?, controlsHistoryPreload: Bool, mode: ChatListNodeMode, theme: PresentationTheme, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, nameSortOrder: PresentationPersonNameOrder, nameDisplayOrder: PresentationPersonNameOrder, disableAnimations: Bool) { - self.account = account + init(context: AccountContext, groupId: PeerGroupId?, controlsHistoryPreload: Bool, mode: ChatListNodeMode, theme: PresentationTheme, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, nameSortOrder: PresentationPersonNameOrder, nameDisplayOrder: PresentationPersonNameOrder, disableAnimations: Bool) { + self.context = context self.controlsHistoryPreload = controlsHistoryPreload self.mode = mode @@ -426,7 +426,7 @@ final class ChatListNode: ListView { } } }, setItemPinned: { [weak self] itemId, _ in - let _ = (toggleItemPinned(postbox: account.postbox, itemId: itemId) |> deliverOnMainQueue).start(next: { result in + let _ = (toggleItemPinned(postbox: context.account.postbox, itemId: itemId) |> deliverOnMainQueue).start(next: { result in if let strongSelf = self { switch result { case .done: @@ -437,7 +437,7 @@ final class ChatListNode: ListView { } }) }, setPeerMuted: { [weak self] peerId, _ in - let _ = (togglePeerMuted(account: account, peerId: peerId) + let _ = (togglePeerMuted(account: context.account, peerId: peerId) |> deliverOnMainQueue).start(completed: { self?.updateState { state in var state = state @@ -449,12 +449,12 @@ final class ChatListNode: ListView { self?.deletePeerChat?(peerId) }, updatePeerGrouping: { [weak self] peerId, group in self?.updatePeerGrouping?(peerId, group) - }, togglePeerMarkedUnread: { [weak self, weak account] peerId, animated in - guard let account = account else { + }, togglePeerMarkedUnread: { [weak self, weak context] peerId, animated in + guard let context = context else { return } - let _ = (togglePeerUnreadMarkInteractively(postbox: account.postbox, viewTracker: account.viewTracker, peerId: peerId) + let _ = (togglePeerUnreadMarkInteractively(postbox: context.account.postbox, viewTracker: context.account.viewTracker, peerId: peerId) |> deliverOnMainQueue).start(completed: { self?.updateState { state in var state = state @@ -469,7 +469,7 @@ final class ChatListNode: ListView { let chatListViewUpdate = self.chatListLocation.get() |> distinctUntilChanged |> mapToSignal { location in - return chatListViewForLocation(groupId: groupId, location: location, account: account) + return chatListViewForLocation(groupId: groupId, location: location, account: context.account) } let previousState = Atomic(value: self.currentState) @@ -478,12 +478,12 @@ final class ChatListNode: ListView { let savedMessagesPeer: Signal if case let .peers(filter) = mode, filter == [.onlyWriteable] { - savedMessagesPeer = account.postbox.loadedPeerWithId(account.peerId) |> map(Optional.init) + savedMessagesPeer = context.account.postbox.loadedPeerWithId(context.account.peerId) |> map(Optional.init) } else { savedMessagesPeer = .single(nil) } - let currentPeerId: PeerId = account.peerId + let currentPeerId: PeerId = context.account.peerId let chatListNodeViewTransition = combineLatest(savedMessagesPeer, chatListViewUpdate, self.statePromise.get()) |> mapToQueue { (savedMessagesPeer, update, state) -> Signal in @@ -621,8 +621,8 @@ final class ChatListNode: ListView { searchMode = true } - return preparedChatListNodeViewTransition(from: previousView, to: processedView, reason: reason, disableAnimations: disableAnimations, account: account, scrollPosition: updatedScrollPosition, searchMode: searchMode) - |> map({ mappedChatListNodeViewListTransition(account: account, nodeInteraction: nodeInteraction, peerGroupId: groupId, mode: mode, transition: $0) }) + return preparedChatListNodeViewTransition(from: previousView, to: processedView, reason: reason, disableAnimations: disableAnimations, account: context.account, scrollPosition: updatedScrollPosition, searchMode: searchMode) + |> map({ mappedChatListNodeViewListTransition(account: context.account, nodeInteraction: nodeInteraction, peerGroupId: groupId, mode: mode, transition: $0) }) |> runOn(prepareOnMainQueue ? Queue.mainQueue() : viewProcessingQueue) } @@ -698,100 +698,100 @@ final class ChatListNode: ListView { self.currentLocation = initialLocation self.chatListLocation.set(initialLocation) - let postbox = account.postbox + let postbox = context.account.postbox let previousPeerCache = Atomic<[PeerId: Peer]>(value: [:]) let previousActivities = Atomic(value: nil) - self.activityStatusesDisposable = (account.allPeerInputActivities() - |> mapToSignal { activitiesByPeerId -> Signal<[PeerId: [(Peer, PeerInputActivity)]], NoError> in - var foundAllPeers = true - var cachedResult: [PeerId: [(Peer, PeerInputActivity)]] = [:] - previousPeerCache.with { dict -> Void in - for (chatPeerId, activities) in activitiesByPeerId { - var cachedChatResult: [(Peer, PeerInputActivity)] = [] - for (peerId, activity) in activities { - if let peer = dict[peerId] { - cachedChatResult.append((peer, activity)) - } else { - foundAllPeers = false - break - } - cachedResult[chatPeerId] = cachedChatResult + self.activityStatusesDisposable = (context.account.allPeerInputActivities() + |> mapToSignal { activitiesByPeerId -> Signal<[PeerId: [(Peer, PeerInputActivity)]], NoError> in + var foundAllPeers = true + var cachedResult: [PeerId: [(Peer, PeerInputActivity)]] = [:] + previousPeerCache.with { dict -> Void in + for (chatPeerId, activities) in activitiesByPeerId { + var cachedChatResult: [(Peer, PeerInputActivity)] = [] + for (peerId, activity) in activities { + if let peer = dict[peerId] { + cachedChatResult.append((peer, activity)) + } else { + foundAllPeers = false + break } - } - } - if foundAllPeers { - return .single(cachedResult) - } else { - return postbox.transaction { transaction -> [PeerId: [(Peer, PeerInputActivity)]] in - var result: [PeerId: [(Peer, PeerInputActivity)]] = [:] - var peerCache: [PeerId: Peer] = [:] - for (chatPeerId, activities) in activitiesByPeerId { - var chatResult: [(Peer, PeerInputActivity)] = [] - - for (peerId, activity) in activities { - if let peer = transaction.getPeer(peerId) { - chatResult.append((peer, activity)) - peerCache[peerId] = peer - } - } - - result[chatPeerId] = chatResult - } - let _ = previousPeerCache.swap(peerCache) - return result + cachedResult[chatPeerId] = cachedChatResult } } } - |> map { activities -> ChatListNodePeerInputActivities? in - return previousActivities.modify { current in - var updated = false - let currentList: [PeerId: [(Peer, PeerInputActivity)]] = current?.activities ?? [:] - if currentList.count != activities.count { - updated = true - } else { - outer: for (peerId, currentValue) in currentList { - if let value = activities[peerId] { - if currentValue.count != value.count { - updated = true - break outer - } else { - for i in 0 ..< currentValue.count { - if !arePeersEqual(currentValue[i].0, value[i].0) { - updated = true - break outer - } - if currentValue[i].1 != value[i].1 { - updated = true - break outer - } - } - } - } else { + if foundAllPeers { + return .single(cachedResult) + } else { + return postbox.transaction { transaction -> [PeerId: [(Peer, PeerInputActivity)]] in + var result: [PeerId: [(Peer, PeerInputActivity)]] = [:] + var peerCache: [PeerId: Peer] = [:] + for (chatPeerId, activities) in activitiesByPeerId { + var chatResult: [(Peer, PeerInputActivity)] = [] + + for (peerId, activity) in activities { + if let peer = transaction.getPeer(peerId) { + chatResult.append((peer, activity)) + peerCache[peerId] = peer + } + } + + result[chatPeerId] = chatResult + } + let _ = previousPeerCache.swap(peerCache) + return result + } + } + } + |> map { activities -> ChatListNodePeerInputActivities? in + return previousActivities.modify { current in + var updated = false + let currentList: [PeerId: [(Peer, PeerInputActivity)]] = current?.activities ?? [:] + if currentList.count != activities.count { + updated = true + } else { + outer: for (peerId, currentValue) in currentList { + if let value = activities[peerId] { + if currentValue.count != value.count { updated = true break outer + } else { + for i in 0 ..< currentValue.count { + if !arePeersEqual(currentValue[i].0, value[i].0) { + updated = true + break outer + } + if currentValue[i].1 != value[i].1 { + updated = true + break outer + } + } } - } - } - if updated { - if activities.isEmpty { - return nil } else { - return ChatListNodePeerInputActivities(activities: activities) + updated = true + break outer } - } else { - return current } } + if updated { + if activities.isEmpty { + return nil + } else { + return ChatListNodePeerInputActivities(activities: activities) + } + } else { + return current + } } - |> deliverOnMainQueue).start(next: { [weak self] activities in - if let strongSelf = self { - strongSelf.updateState { state in - var state = state - state.peerInputActivities = activities - return state - } + } + |> deliverOnMainQueue).start(next: { [weak self] activities in + if let strongSelf = self { + strongSelf.updateState { state in + var state = state + state.peerInputActivities = activities + return state } - }) + } + }) self.beganInteractiveDragging = { [weak self] in if let strongSelf = self { @@ -826,7 +826,7 @@ final class ChatListNode: ListView { } if let _ = fromEntry.index.pinningIndex { - return strongSelf.account.postbox.transaction { transaction -> Bool in + return strongSelf.context.account.postbox.transaction { transaction -> Bool in var itemIds = transaction.getPinnedItemIds() var itemId: PinnedItemId? @@ -879,7 +879,7 @@ final class ChatListNode: ListView { } self.scrollToTopOptionPromise.set(combineLatest( - renderedTotalUnreadCount(postbox: account.postbox) |> deliverOnMainQueue, + renderedTotalUnreadCount(postbox: self.context.account.postbox) |> deliverOnMainQueue, self.visibleUnreadCounts.get(), self.scrolledAtTop.get() ) |> map { badge, visibleUnreadCounts, scrolledAtTop -> ChatListGlobalScrollOption in @@ -1089,14 +1089,14 @@ final class ChatListNode: ListView { } private func relativeUnreadChatListIndex(position: ChatListRelativePosition) -> Signal { - return self.account.postbox.transaction { transaction -> ChatListIndex? in + return self.context.account.postbox.transaction { transaction -> ChatListIndex? in var filter = true if let inAppNotificationSettings = transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.inAppNotificationSettings) as? InAppNotificationSettings { switch inAppNotificationSettings.totalUnreadCountDisplayStyle { - case .raw: - filter = false - case .filtered: - filter = true + case .raw: + filter = false + case .filtered: + filter = true } } return transaction.getRelativeUnreadChatListIndex(filtered: filter, position: position) diff --git a/TelegramUI/ChatListSearchContainerNode.swift b/TelegramUI/ChatListSearchContainerNode.swift index 3eb0020766..90c918eba8 100644 --- a/TelegramUI/ChatListSearchContainerNode.swift +++ b/TelegramUI/ChatListSearchContainerNode.swift @@ -94,10 +94,10 @@ private enum ChatListRecentEntry: Comparable, Identifiable { } } - func item(account: Account, filter: ChatListNodePeersFilter, peerSelected: @escaping (Peer) -> Void, peerLongTapped: @escaping (Peer) -> Void, clearRecentlySearchedPeers: @escaping () -> Void, setPeerIdWithRevealedOptions: @escaping (PeerId?, PeerId?) -> Void, deletePeer: @escaping (PeerId) -> Void) -> ListViewItem { + func item(context: AccountContext, filter: ChatListNodePeersFilter, peerSelected: @escaping (Peer) -> Void, peerLongTapped: @escaping (Peer) -> Void, clearRecentlySearchedPeers: @escaping () -> Void, setPeerIdWithRevealedOptions: @escaping (PeerId?, PeerId?) -> Void, deletePeer: @escaping (PeerId) -> Void) -> ListViewItem { switch self { case let .topPeers(peers, theme, strings): - return ChatListRecentPeersListItem(theme: theme, strings: strings, account: account, peers: peers, peerSelected: { peer in + return ChatListRecentPeersListItem(theme: theme, strings: strings, account: context.account, peers: peers, peerSelected: { peer in peerSelected(peer) }, peerLongTapped: { peer in peerLongTapped(peer) @@ -146,7 +146,7 @@ private enum ChatListRecentEntry: Comparable, Identifiable { if let user = primaryPeer as? TelegramUser { if let _ = user.botInfo { status = .custom(strings.Bot_GenericBotStatus) - } else if user.id != account.peerId { + } else if user.id != context.account.peerId { let presence = peer.presence ?? TelegramUserPresence(status: .none, lastActivity: 0) status = .presence(presence, timeFormat) } else { @@ -181,7 +181,7 @@ private enum ChatListRecentEntry: Comparable, Identifiable { badge = ContactsPeerItemBadge(count: peer.unreadCount, type: isMuted ? .inactive : .active) } - return ContactsPeerItem(theme: theme, strings: strings, sortOrder: nameSortOrder, displayOrder: nameDisplayOrder, account: account, peerMode: .generalSearch, peer: .peer(peer: primaryPeer, chatPeer: chatPeer), status: status, badge: badge, enabled: enabled, selection: .none, editing: ContactsPeerItemEditing(editable: true, editing: false, revealed: hasRevealControls), index: nil, header: ChatListSearchItemHeader(type: .recentPeers, theme: theme, strings: strings, actionTitle: strings.WebSearch_RecentSectionClear.uppercased(), action: { + return ContactsPeerItem(theme: theme, strings: strings, sortOrder: nameSortOrder, displayOrder: nameDisplayOrder, account: context.account, peerMode: .generalSearch, peer: .peer(peer: primaryPeer, chatPeer: chatPeer), status: status, badge: badge, enabled: enabled, selection: .none, editing: ContactsPeerItemEditing(editable: true, editing: false, revealed: hasRevealControls), index: nil, header: ChatListSearchItemHeader(type: .recentPeers, theme: theme, strings: strings, actionTitle: strings.WebSearch_RecentSectionClear.uppercased(), action: { clearRecentlySearchedPeers() }), action: { _ in if let chatPeer = peer.peer.peers[peer.peer.peerId] { @@ -341,7 +341,7 @@ enum ChatListSearchEntry: Comparable, Identifiable { } } - func item(account: Account, enableHeaders: Bool, filter: ChatListNodePeersFilter, interaction: ChatListNodeInteraction) -> ListViewItem { + func item(context: AccountContext, enableHeaders: Bool, filter: ChatListNodePeersFilter, interaction: ChatListNodeInteraction) -> ListViewItem { switch self { case let .localPeer(peer, associatedPeer, unreadBadge, _, theme, strings, nameSortOrder, nameDisplayOrder): let primaryPeer: Peer @@ -395,7 +395,7 @@ enum ChatListSearchEntry: Comparable, Identifiable { header = ChatListSearchItemHeader(type: .localPeers, theme: theme, strings: strings, actionTitle: nil, action: nil) } - return ContactsPeerItem(theme: theme, strings: strings, sortOrder: nameSortOrder, displayOrder: nameDisplayOrder, account: account, peerMode: .generalSearch, peer: .peer(peer: primaryPeer, chatPeer: chatPeer), status: .none, badge: badge, enabled: enabled, selection: .none, editing: ContactsPeerItemEditing(editable: false, editing: false, revealed: false), index: nil, header: header, action: { _ in + return ContactsPeerItem(theme: theme, strings: strings, sortOrder: nameSortOrder, displayOrder: nameDisplayOrder, account: context.account, peerMode: .generalSearch, peer: .peer(peer: primaryPeer, chatPeer: chatPeer), status: .none, badge: badge, enabled: enabled, selection: .none, editing: ContactsPeerItemEditing(editable: false, editing: false, revealed: false), index: nil, header: header, action: { _ in interaction.peerSelected(peer) }) case let .globalPeer(peer, unreadBadge, _, theme, strings, nameSortOrder, nameDisplayOrder): @@ -439,11 +439,11 @@ enum ChatListSearchEntry: Comparable, Identifiable { header = ChatListSearchItemHeader(type: .globalPeers, theme: theme, strings: strings, actionTitle: nil, action: nil) } - return ContactsPeerItem(theme: theme, strings: strings, sortOrder: nameSortOrder, displayOrder: nameDisplayOrder, account: account, peerMode: .generalSearch, peer: .peer(peer: peer.peer, chatPeer: peer.peer), status: .addressName(suffixString), badge: badge, enabled: enabled, selection: .none, editing: ContactsPeerItemEditing(editable: false, editing: false, revealed: false), index: nil, header: header, action: { _ in + return ContactsPeerItem(theme: theme, strings: strings, sortOrder: nameSortOrder, displayOrder: nameDisplayOrder, account: context.account, peerMode: .generalSearch, peer: .peer(peer: peer.peer, chatPeer: peer.peer), status: .addressName(suffixString), badge: badge, enabled: enabled, selection: .none, editing: ContactsPeerItemEditing(editable: false, editing: false, revealed: false), index: nil, header: header, action: { _ in interaction.peerSelected(peer.peer) }) case let .message(message, readState, presentationData): - return ChatListItem(presentationData: presentationData, account: account, peerGroupId: nil, index: ChatListIndex(pinningIndex: nil, messageIndex: MessageIndex(message)), content: .peer(message: message, peer: RenderedPeer(message: message), combinedReadState: readState, notificationSettings: nil, summaryInfo: ChatListMessageTagSummaryInfo(), embeddedState: nil, inputActivities: nil, isAd: false, ignoreUnreadBadge: true), editing: false, hasActiveRevealControls: false, selected: false, header: enableHeaders ? ChatListSearchItemHeader(type: .messages, theme: presentationData.theme, strings: presentationData.strings, actionTitle: nil, action: nil) : nil, enableContextActions: false, interaction: interaction) + return ChatListItem(presentationData: presentationData, account: context.account, peerGroupId: nil, index: ChatListIndex(pinningIndex: nil, messageIndex: MessageIndex(message)), content: .peer(message: message, peer: RenderedPeer(message: message), combinedReadState: readState, notificationSettings: nil, summaryInfo: ChatListMessageTagSummaryInfo(), embeddedState: nil, inputActivities: nil, isAd: false, ignoreUnreadBadge: true), editing: false, hasActiveRevealControls: false, selected: false, header: enableHeaders ? ChatListSearchItemHeader(type: .messages, theme: presentationData.theme, strings: presentationData.strings, actionTitle: nil, action: nil) : nil, enableContextActions: false, interaction: interaction) case let .addContact(phoneNumber, theme, strings): return ContactsAddItem(theme: theme, strings: strings, phoneNumber: phoneNumber, header: ChatListSearchItemHeader(type: .phoneNumber, theme: theme, strings: strings, actionTitle: nil, action: nil), action: { interaction.addContact(phoneNumber) @@ -465,22 +465,22 @@ struct ChatListSearchContainerTransition { let displayingResults: Bool } -private func chatListSearchContainerPreparedRecentTransition(from fromEntries: [ChatListRecentEntry], to toEntries: [ChatListRecentEntry], account: Account, filter: ChatListNodePeersFilter, peerSelected: @escaping (Peer) -> Void, peerLongTapped: @escaping (Peer) -> Void, clearRecentlySearchedPeers: @escaping () -> Void, setPeerIdWithRevealedOptions: @escaping (PeerId?, PeerId?) -> Void, deletePeer: @escaping (PeerId) -> Void) -> ChatListSearchContainerRecentTransition { +private func chatListSearchContainerPreparedRecentTransition(from fromEntries: [ChatListRecentEntry], to toEntries: [ChatListRecentEntry], context: AccountContext, filter: ChatListNodePeersFilter, peerSelected: @escaping (Peer) -> Void, peerLongTapped: @escaping (Peer) -> Void, clearRecentlySearchedPeers: @escaping () -> Void, setPeerIdWithRevealedOptions: @escaping (PeerId?, PeerId?) -> Void, deletePeer: @escaping (PeerId) -> Void) -> ChatListSearchContainerRecentTransition { 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, filter: filter, peerSelected: peerSelected, peerLongTapped: peerLongTapped, clearRecentlySearchedPeers: clearRecentlySearchedPeers, setPeerIdWithRevealedOptions: setPeerIdWithRevealedOptions, deletePeer: deletePeer), directionHint: nil) } - let updates = updateIndices.map { ListViewUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(account: account, filter: filter, peerSelected: peerSelected, peerLongTapped: peerLongTapped, clearRecentlySearchedPeers: clearRecentlySearchedPeers, setPeerIdWithRevealedOptions: setPeerIdWithRevealedOptions, deletePeer: deletePeer), directionHint: nil) } + let insertions = indicesAndItems.map { ListViewInsertItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, filter: filter, peerSelected: peerSelected, peerLongTapped: peerLongTapped, clearRecentlySearchedPeers: clearRecentlySearchedPeers, setPeerIdWithRevealedOptions: setPeerIdWithRevealedOptions, deletePeer: deletePeer), directionHint: nil) } + let updates = updateIndices.map { ListViewUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, filter: filter, peerSelected: peerSelected, peerLongTapped: peerLongTapped, clearRecentlySearchedPeers: clearRecentlySearchedPeers, setPeerIdWithRevealedOptions: setPeerIdWithRevealedOptions, deletePeer: deletePeer), directionHint: nil) } return ChatListSearchContainerRecentTransition(deletions: deletions, insertions: insertions, updates: updates) } -func chatListSearchContainerPreparedTransition(from fromEntries: [ChatListSearchEntry], to toEntries: [ChatListSearchEntry], displayingResults: Bool, account: Account, enableHeaders: Bool, filter: ChatListNodePeersFilter, interaction: ChatListNodeInteraction) -> ChatListSearchContainerTransition { +func chatListSearchContainerPreparedTransition(from fromEntries: [ChatListSearchEntry], to toEntries: [ChatListSearchEntry], displayingResults: Bool, context: AccountContext, enableHeaders: Bool, filter: ChatListNodePeersFilter, interaction: ChatListNodeInteraction) -> ChatListSearchContainerTransition { 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, enableHeaders: enableHeaders, filter: filter, interaction: interaction), directionHint: nil) } - let updates = updateIndices.map { ListViewUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(account: account, enableHeaders: enableHeaders, filter: filter, interaction: interaction), directionHint: nil) } + let insertions = indicesAndItems.map { ListViewInsertItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, enableHeaders: enableHeaders, filter: filter, interaction: interaction), directionHint: nil) } + let updates = updateIndices.map { ListViewUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, enableHeaders: enableHeaders, filter: filter, interaction: interaction), directionHint: nil) } return ChatListSearchContainerTransition(deletions: deletions, insertions: insertions, updates: updates, displayingResults: displayingResults) } @@ -536,7 +536,7 @@ private struct ChatListSearchMessagesContext { } final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { - private let account: Account + private let context: AccountContext private let recentListNode: ListView private let listNode: ListView @@ -565,12 +565,12 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { private let filter: ChatListNodePeersFilter - init(account: Account, filter: ChatListNodePeersFilter, groupId: PeerGroupId?, openPeer: @escaping (Peer, Bool) -> Void, openRecentPeerOptions: @escaping (Peer) -> Void, openMessage: @escaping (Peer, MessageId) -> Void, addContact: ((String) -> Void)?) { - self.account = account + init(context: AccountContext, filter: ChatListNodePeersFilter, groupId: PeerGroupId?, openPeer: @escaping (Peer, Bool) -> Void, openRecentPeerOptions: @escaping (Peer) -> Void, openMessage: @escaping (Peer, MessageId) -> Void, addContact: ((String) -> Void)?) { + self.context = context self.filter = filter self.dimNode = ASDisplayNode() - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.presentationDataPromise = Promise(ChatListPresentationData(theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameSortOrder: self.presentationData.nameSortOrder, nameDisplayOrder: self.presentationData.nameDisplayOrder, disableAnimations: self.presentationData.disableAnimations)) self.recentListNode = ListView() @@ -635,17 +635,17 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { return .single(nil) } - let accountPeer = account.postbox.loadedPeerWithId(account.peerId) + let accountPeer = context.account.postbox.loadedPeerWithId(context.account.peerId) |> take(1) - let foundLocalPeers = account.postbox.searchPeers(query: query.lowercased(), groupId: groupId) + let foundLocalPeers = context.account.postbox.searchPeers(query: query.lowercased(), groupId: groupId) |> mapToSignal { local -> Signal<([PeerView], [RenderedPeer]), NoError> in - return combineLatest(local.map {account.postbox.peerView(id: $0.peerId)}) |> map { views in + return combineLatest(local.map { context.account.postbox.peerView(id: $0.peerId) }) |> map { views in return (views, local) } } |> mapToSignal{ viewsAndPeers -> Signal<(peers: [RenderedPeer], unread: [PeerId : UnreadSearchBadge]), NoError> in - return account.postbox.unreadMessageCountsView(items: viewsAndPeers.0.map {.peer($0.peerId)}) |> map { values in + return context.account.postbox.unreadMessageCountsView(items: viewsAndPeers.0.map {.peer($0.peerId)}) |> map { values in var unread:[PeerId: UnreadSearchBadge] = [:] for peerView in viewsAndPeers.0 { var isMuted: Bool = false @@ -669,7 +669,7 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { let foundRemotePeers: Signal<([FoundPeer], [FoundPeer], Bool), NoError> if groupId == nil { - foundRemotePeers = (.single(([], [], true)) |> then(searchPeers(account: account, query: query) |> map { ($0.0, $0.1, false) } + foundRemotePeers = (.single(([], [], true)) |> then(searchPeers(account: context.account, query: query) |> map { ($0.0, $0.1, false) } |> delay(0.2, queue: Queue.concurrentDefaultQueue()))) } else { foundRemotePeers = .single(([], [], false)) @@ -688,7 +688,7 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { if filter.contains(.doNotSearchMessages) { foundRemoteMessages = .single((([], [:], 0), false)) } else { - let searchSignal = searchMessages(account: account, location: location, query: query, state: nil, limit: 50) + let searchSignal = searchMessages(account: context.account, location: location, query: query, state: nil, limit: 50) |> map { result, updatedState -> ChatListSearchMessagesResult in return ChatListSearchMessagesResult(query: query, messages: result.messages.sorted(by: { MessageIndex($0) > MessageIndex($1) }), readStates: result.readStates, hasMore: !result.completed, state: updatedState) } @@ -697,7 +697,7 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { |> mapToSignal { searchContext -> Signal<(([Message], [PeerId: CombinedPeerReadState], Int32), Bool), NoError> in if let searchContext = searchContext { if let _ = searchContext.loadMoreIndex { - return searchMessages(account: account, location: location, query: query, state: searchContext.result.state, limit: 80) + return searchMessages(account: context.account, location: location, query: query, state: searchContext.result.state, limit: 80) |> map { result, updatedState -> ChatListSearchMessagesResult in return ChatListSearchMessagesResult(query: query, messages: result.messages.sorted(by: { MessageIndex($0) > MessageIndex($1) }), readStates: result.readStates, hasMore: !result.completed, state: updatedState) } @@ -776,7 +776,7 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { } for renderedPeer in foundLocalPeers.peers { - if let peer = renderedPeer.peers[renderedPeer.peerId], peer.id != account.peerId, filteredPeer(peer, accountPeer) { + if let peer = renderedPeer.peers[renderedPeer.peerId], peer.id != context.account.peerId, filteredPeer(peer, accountPeer) { if !existingPeerIds.contains(peer.id) { existingPeerIds.insert(peer.id) var associatedPeer: Peer? @@ -827,7 +827,7 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { let interaction = ChatListNodeInteraction(activateSearch: { }, peerSelected: { [weak self] peer in openPeer(peer, false) - let _ = addRecentlySearchedPeer(postbox: account.postbox, peerId: peer.id).start() + let _ = addRecentlySearchedPeer(postbox: context.account.postbox, peerId: peer.id).start() self?.listNode.clearHighlightAnimated(true) }, togglePeerSelected: { _ in }, messageSelected: { [weak self] peer, message, _ in @@ -857,7 +857,7 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { }) let previousRecentItems = Atomic<[ChatListRecentEntry]?>(value: nil) - let hasRecentPeers = recentPeers(account: account) + let hasRecentPeers = recentPeers(account: context.account) |> map { value -> Bool in switch value { case let .peers(peers): @@ -869,7 +869,7 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { |> distinctUntilChanged let previousRecentlySearchedPeerOrder = Atomic<[PeerId]>(value: []) - let fixedRecentlySearchedPeers = recentlySearchedPeers(postbox: account.postbox) + let fixedRecentlySearchedPeers = recentlySearchedPeers(postbox: context.account.postbox) |> map { peers -> [RecentlySearchedPeer] in var result: [RecentlySearchedPeer] = [] let _ = previousRecentlySearchedPeerOrder.modify { current in @@ -920,9 +920,9 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { } let previousEntries = previousRecentItems.swap(entries) - let transition = chatListSearchContainerPreparedRecentTransition(from: previousEntries ?? [], to: entries, account: account, filter: filter, peerSelected: { peer in + let transition = chatListSearchContainerPreparedRecentTransition(from: previousEntries ?? [], to: entries, context: context, filter: filter, peerSelected: { peer in openPeer(peer, true) - let _ = addRecentlySearchedPeer(postbox: account.postbox, peerId: peer.id).start() + let _ = addRecentlySearchedPeer(postbox: context.account.postbox, peerId: peer.id).start() self?.recentListNode.clearHighlightAnimated(true) }, peerLongTapped: { peer in openRecentPeerOptions(peer) @@ -932,7 +932,7 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { interaction.setPeerIdWithRevealedOptions(peerId, fromPeerId) }, deletePeer: { peerId in if let strongSelf = self { - let _ = removeRecentlySearchedPeer(postbox: strongSelf.account.postbox, peerId: peerId).start() + let _ = removeRecentlySearchedPeer(postbox: strongSelf.context.account.postbox, peerId: peerId).start() } }) return .single((transition, previousEntries == nil)) @@ -942,7 +942,7 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { recentItemsTransition = .single((ChatListSearchContainerRecentTransition(deletions: [], insertions: [], updates: []), true)) } - self.updatedRecentPeersDisposable.set(managedUpdatedRecentPeers(accountPeerId: account.peerId, postbox: account.postbox, network: account.network).start()) + self.updatedRecentPeersDisposable.set(managedUpdatedRecentPeers(accountPeerId: context.account.peerId, postbox: context.account.postbox, network: context.account.network).start()) self.recentDisposable.set((recentItemsTransition |> deliverOnMainQueue).start(next: { [weak self] (transition, firstTime) in if let strongSelf = self { @@ -958,12 +958,12 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { let previousEntries = previousSearchItems.swap(entriesAndFlags?.0) let firstTime = previousEntries == nil - let transition = chatListSearchContainerPreparedTransition(from: previousEntries ?? [], to: entriesAndFlags?.0 ?? [], displayingResults: entriesAndFlags?.0 != nil, account: account, enableHeaders: true, filter: filter, interaction: interaction) + let transition = chatListSearchContainerPreparedTransition(from: previousEntries ?? [], to: entriesAndFlags?.0 ?? [], displayingResults: entriesAndFlags?.0 != nil, context: context, enableHeaders: true, filter: filter, interaction: interaction) strongSelf.enqueueTransition(transition, firstTime: firstTime) } })) - 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 @@ -1183,7 +1183,8 @@ final class ChatListSearchContainerNode: SearchDisplayControllerContentNode { } private func clearRecentSearch() { - let _ = (clearRecentlySearchedPeers(postbox: self.account.postbox) |> deliverOnMainQueue).start() + let _ = (clearRecentlySearchedPeers(postbox: self.context.account.postbox) + |> deliverOnMainQueue).start() } func removePeerFromTopPeers(_ peerId: PeerId) { diff --git a/TelegramUI/ChatMediaInputNode.swift b/TelegramUI/ChatMediaInputNode.swift index ce06de5fd8..71076ffc9d 100644 --- a/TelegramUI/ChatMediaInputNode.swift +++ b/TelegramUI/ChatMediaInputNode.swift @@ -379,7 +379,7 @@ private final class CollectionListContainerNode: ASDisplayNode { } final class ChatMediaInputNode: ChatInputNode { - private let account: Account + private let context: AccountContext private let peerId: PeerId? private let controllerInteraction: ChatControllerInteraction private let gifPaneIsActiveUpdated: (Bool) -> Void @@ -424,8 +424,8 @@ final class ChatMediaInputNode: ChatInputNode { return self._ready.get() } - init(account: Account, peerId: PeerId?, controllerInteraction: ChatControllerInteraction, theme: PresentationTheme, strings: PresentationStrings, gifPaneIsActiveUpdated: @escaping (Bool) -> Void) { - self.account = account + init(context: AccountContext, peerId: PeerId?, controllerInteraction: ChatControllerInteraction, theme: PresentationTheme, strings: PresentationStrings, gifPaneIsActiveUpdated: @escaping (Bool) -> Void) { + self.context = context self.peerId = peerId self.controllerInteraction = controllerInteraction self.theme = theme @@ -456,14 +456,14 @@ final class ChatMediaInputNode: ChatInputNode { }, fixPaneScroll: { pane, state in fixPaneScrollImpl?(pane, state) }) - self.gifPane = ChatMediaInputGifPane(account: account, theme: theme, strings: strings, controllerInteraction: controllerInteraction, paneDidScroll: { pane, state, transition in + self.gifPane = ChatMediaInputGifPane(account: context.account, theme: theme, strings: strings, controllerInteraction: controllerInteraction, paneDidScroll: { pane, state, transition in paneDidScrollImpl?(pane, state, transition) }, fixPaneScroll: { pane, state in fixPaneScrollImpl?(pane, state) }) var getItemIsPreviewedImpl: ((StickerPackItem) -> Bool)? - self.trendingPane = ChatMediaInputTrendingPane(account: account, controllerInteraction: controllerInteraction, getItemIsPreviewed: { item in + self.trendingPane = ChatMediaInputTrendingPane(context: context, controllerInteraction: controllerInteraction, getItemIsPreviewed: { item in return getItemIsPreviewedImpl?(item) ?? false }) @@ -507,7 +507,7 @@ final class ChatMediaInputNode: ChatInputNode { } }, openSettings: { [weak self] in if let strongSelf = self { - strongSelf.controllerInteraction.navigationController()?.pushViewController(installedStickerPacksController(account: account, mode: .modal)) + strongSelf.controllerInteraction.navigationController()?.pushViewController(installedStickerPacksController(context: context, mode: .modal)) } }, toggleSearch: { [weak self] value in if let strongSelf = self { @@ -516,7 +516,7 @@ final class ChatMediaInputNode: ChatInputNode { if let current = strongSelf.stickerSearchContainerNode { stickerSearchContainerNode = current } else { - stickerSearchContainerNode = StickerPaneSearchContainerNode(account: strongSelf.account, theme: strongSelf.theme, strings: strongSelf.strings, controllerInteraction: strongSelf.controllerInteraction, inputNodeInteraction: strongSelf.inputNodeInteraction, cancel: { + stickerSearchContainerNode = StickerPaneSearchContainerNode(context: strongSelf.context, theme: strongSelf.theme, strings: strongSelf.strings, controllerInteraction: strongSelf.controllerInteraction, inputNodeInteraction: strongSelf.inputNodeInteraction, cancel: { self?.stickerSearchContainerNode?.deactivate() self?.inputNodeInteraction.toggleSearch(false) }) @@ -551,14 +551,14 @@ final class ChatMediaInputNode: ChatInputNode { return } - let _ = (account.postbox.transaction { transaction -> StickerPackCollectionInfo? in + let _ = (context.account.postbox.transaction { transaction -> StickerPackCollectionInfo? in return (transaction.getPeerCachedData(peerId: peerId) as? CachedChannelData)?.stickerPack } |> deliverOnMainQueue).start(next: { info in guard let strongSelf = self else { return } - strongSelf.controllerInteraction.presentController(groupStickerPackSetupController(account: account, peerId: peerId, currentPackInfo: info), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + strongSelf.controllerInteraction.presentController(groupStickerPackSetupController(context: context, peerId: peerId, currentPackInfo: info), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) }, dismissPeerSpecificSettings: { [weak self] in self?.dismissPeerSpecificPackSetup() @@ -584,7 +584,7 @@ final class ChatMediaInputNode: ChatInputNode { switch position { case .initial: var firstTime = true - return account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: nil, count: 50) + return context.account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: nil, count: 50) |> map { view -> (ItemCollectionsView, StickerPacksCollectionUpdate) in let update: StickerPacksCollectionUpdate if firstTime { @@ -597,7 +597,7 @@ final class ChatMediaInputNode: ChatInputNode { } case let .scroll(aroundIndex): var firstTime = true - return account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: aroundIndex, count: 300) + return context.account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: aroundIndex, count: 300) |> map { view -> (ItemCollectionsView, StickerPacksCollectionUpdate) in let update: StickerPacksCollectionUpdate if firstTime { @@ -610,7 +610,7 @@ final class ChatMediaInputNode: ChatInputNode { } case let .navigate(index, collectionId): var firstTime = true - return account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: index, count: 300) + return context.account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: index, count: 300) |> map { view -> (ItemCollectionsView, StickerPacksCollectionUpdate) in let update: StickerPacksCollectionUpdate if firstTime { @@ -629,7 +629,7 @@ final class ChatMediaInputNode: ChatInputNode { let inputNodeInteraction = self.inputNodeInteraction! let peerSpecificPack: Signal<(PeerSpecificPackData?, CanInstallPeerSpecificPack), NoError> if let peerId = peerId { - self.dismissedPeerSpecificStickerPack.set(account.postbox.transaction { transaction -> Bool in + self.dismissedPeerSpecificStickerPack.set(context.account.postbox.transaction { transaction -> Bool in guard let state = transaction.getPeerChatInterfaceState(peerId) as? ChatInterfaceState else { return false } @@ -639,7 +639,7 @@ final class ChatMediaInputNode: ChatInputNode { return false }) - peerSpecificPack = combineLatest(peerSpecificStickerPack(postbox: account.postbox, network: account.network, peerId: peerId), account.postbox.multiplePeersView([peerId]), self.dismissedPeerSpecificStickerPack.get()) + peerSpecificPack = combineLatest(peerSpecificStickerPack(postbox: context.account.postbox, network: context.account.network, peerId: peerId), context.account.postbox.multiplePeersView([peerId]), self.dismissedPeerSpecificStickerPack.get()) |> map { packData, peersView, dismissedPeerSpecificPack -> (PeerSpecificPackData?, CanInstallPeerSpecificPack) in if let peer = peersView.peers[peerId] { var canInstall: CanInstallPeerSpecificPack = .none @@ -681,7 +681,7 @@ final class ChatMediaInputNode: ChatInputNode { let panelEntries = chatMediaInputPanelEntries(view: view, savedStickers: savedStickers, recentStickers: recentStickers, peerSpecificPack: peerSpecificPack.0, canInstallPeerSpecificPack: peerSpecificPack.1, theme: theme) let gridEntries = chatMediaInputGridEntries(view: view, savedStickers: savedStickers, recentStickers: recentStickers, peerSpecificPack: peerSpecificPack.0, canInstallPeerSpecificPack: peerSpecificPack.1, strings: strings, theme: theme) let (previousPanelEntries, previousGridEntries) = previousEntries.swap((panelEntries, gridEntries)) - return (view, preparedChatMediaInputPanelEntryTransition(account: account, from: previousPanelEntries, to: panelEntries, inputNodeInteraction: inputNodeInteraction), previousPanelEntries.isEmpty, preparedChatMediaInputGridEntryTransition(account: account, view: view, from: previousGridEntries, to: gridEntries, update: update, interfaceInteraction: controllerInteraction, inputNodeInteraction: inputNodeInteraction), previousGridEntries.isEmpty) + return (view, preparedChatMediaInputPanelEntryTransition(account: context.account, from: previousPanelEntries, to: panelEntries, inputNodeInteraction: inputNodeInteraction), previousPanelEntries.isEmpty, preparedChatMediaInputGridEntryTransition(account: context.account, view: view, from: previousGridEntries, to: gridEntries, update: update, interfaceInteraction: controllerInteraction, inputNodeInteraction: inputNodeInteraction), previousGridEntries.isEmpty) } self.disposable.set((transitions @@ -789,7 +789,7 @@ final class ChatMediaInputNode: ChatInputNode { if let stickerSearchContainerNode = strongSelf.stickerSearchContainerNode { panes = [] if let (itemNode, item) = stickerSearchContainerNode.itemAt(point: point.offsetBy(dx: -stickerSearchContainerNode.frame.minX, dy: -stickerSearchContainerNode.frame.minY)) { - return strongSelf.account.postbox.transaction { transaction -> Bool in + return strongSelf.context.account.postbox.transaction { transaction -> Bool in return getIsStickerSaved(transaction: transaction, fileId: item.file.fileId) } |> deliverOnMainQueue @@ -805,9 +805,9 @@ final class ChatMediaInputNode: ChatInputNode { PeekControllerMenuItem(title: isStarred ? strongSelf.strings.Stickers_RemoveFromFavorites : strongSelf.strings.Stickers_AddToFavorites, color: isStarred ? .destructive : .accent, action: { if let strongSelf = self { if isStarred { - let _ = removeSavedSticker(postbox: strongSelf.account.postbox, mediaId: item.file.fileId).start() + let _ = removeSavedSticker(postbox: strongSelf.context.account.postbox, mediaId: item.file.fileId).start() } else { - let _ = addSavedSticker(postbox: strongSelf.account.postbox, network: strongSelf.account.network, file: item.file).start() + let _ = addSavedSticker(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, file: item.file).start() } } }), @@ -817,7 +817,7 @@ final class ChatMediaInputNode: ChatInputNode { switch attribute { case let .Sticker(_, packReference, _): if let packReference = packReference { - let controller = StickerPackPreviewController(account: strongSelf.account, stickerPack: packReference, parentNavigationController: strongSelf.controllerInteraction.navigationController()) + let controller = StickerPackPreviewController(context: strongSelf.context, stickerPack: packReference, parentNavigationController: strongSelf.controllerInteraction.navigationController()) controller.sendSticker = { file in if let strongSelf = self { strongSelf.controllerInteraction.sendSticker(file, false) @@ -836,7 +836,7 @@ final class ChatMediaInputNode: ChatInputNode { }), PeekControllerMenuItem(title: strongSelf.strings.Common_Cancel, color: .accent, action: {}) ] - return (itemNode, StickerPreviewPeekContent(account: strongSelf.account, item: item, menu: menuItems)) + return (itemNode, StickerPreviewPeekContent(account: strongSelf.context.account, item: item, menu: menuItems)) } else { return nil } @@ -849,7 +849,7 @@ final class ChatMediaInputNode: ChatInputNode { if pane.supernode != nil, pane.frame.contains(point) { if let pane = pane as? ChatMediaInputGifPane { if let file = pane.fileAt(point: point.offsetBy(dx: -pane.frame.minX, dy: -pane.frame.minY)) { - return .single((strongSelf, ChatContextResultPeekContent(account: strongSelf.account, contextResult: .internalReference(queryId: 0, id: "", type: "gif", title: nil, description: nil, image: nil, file: file.media, message: .auto(caption: "", entities: nil, replyMarkup: nil)), menu: [ + return .single((strongSelf, ChatContextResultPeekContent(account: strongSelf.context.account, contextResult: .internalReference(queryId: 0, id: "", type: "gif", title: nil, description: nil, image: nil, file: file.media, message: .auto(caption: "", entities: nil, replyMarkup: nil)), menu: [ PeekControllerMenuItem(title: strongSelf.strings.ShareMenu_Send, color: .accent, font: .bold, action: { if let strongSelf = self { strongSelf.controllerInteraction.sendGif(file) @@ -857,7 +857,7 @@ final class ChatMediaInputNode: ChatInputNode { }), PeekControllerMenuItem(title: strongSelf.strings.Common_Delete, color: .destructive, action: { if let strongSelf = self { - let _ = removeSavedGif(postbox: strongSelf.account.postbox, mediaId: file.media.fileId).start() + let _ = removeSavedGif(postbox: strongSelf.context.account.postbox, mediaId: file.media.fileId).start() } }) ]))) @@ -871,7 +871,7 @@ final class ChatMediaInputNode: ChatInputNode { } if let (itemNode, item) = itemNodeAndItem { - return strongSelf.account.postbox.transaction { transaction -> Bool in + return strongSelf.context.account.postbox.transaction { transaction -> Bool in return getIsStickerSaved(transaction: transaction, fileId: item.file.fileId) } |> deliverOnMainQueue @@ -887,9 +887,9 @@ final class ChatMediaInputNode: ChatInputNode { PeekControllerMenuItem(title: isStarred ? strongSelf.strings.Stickers_RemoveFromFavorites : strongSelf.strings.Stickers_AddToFavorites, color: isStarred ? .destructive : .accent, action: { if let strongSelf = self { if isStarred { - let _ = removeSavedSticker(postbox: strongSelf.account.postbox, mediaId: item.file.fileId).start() + let _ = removeSavedSticker(postbox: strongSelf.context.account.postbox, mediaId: item.file.fileId).start() } else { - let _ = addSavedSticker(postbox: strongSelf.account.postbox, network: strongSelf.account.network, file: item.file).start() + let _ = addSavedSticker(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, file: item.file).start() } } }), @@ -899,7 +899,7 @@ final class ChatMediaInputNode: ChatInputNode { switch attribute { case let .Sticker(_, packReference, _): if let packReference = packReference { - let controller = StickerPackPreviewController(account: strongSelf.account, stickerPack: packReference, parentNavigationController: strongSelf.controllerInteraction.navigationController()) + let controller = StickerPackPreviewController(context: strongSelf.context, stickerPack: packReference, parentNavigationController: strongSelf.controllerInteraction.navigationController()) controller.sendSticker = { file in if let strongSelf = self { strongSelf.controllerInteraction.sendSticker(file, false) @@ -918,7 +918,7 @@ final class ChatMediaInputNode: ChatInputNode { }), PeekControllerMenuItem(title: strongSelf.strings.Common_Cancel, color: .accent, action: {}) ] - return (itemNode, StickerPreviewPeekContent(account: strongSelf.account, item: .pack(item), menu: menuItems)) + return (itemNode, StickerPreviewPeekContent(account: strongSelf.context.account, item: .pack(item), menu: menuItems)) } else { return nil } @@ -1523,7 +1523,7 @@ final class ChatMediaInputNode: ChatInputNode { return } self.dismissedPeerSpecificStickerPack.set(.single(true)) - let _ = (self.account.postbox.transaction { transaction -> Void in + let _ = (self.context.account.postbox.transaction { transaction -> Void in transaction.updatePeerChatInterfaceState(peerId, update: { current in if let current = current as? ChatInterfaceState { return current.withUpdatedMessageActionsState({ $0.withUpdatedClosedPeerSpecificPackSetup(true) }) diff --git a/TelegramUI/ChatMediaInputPeerSpecificItem.swift b/TelegramUI/ChatMediaInputPeerSpecificItem.swift index cc8e9730d1..56c012b954 100644 --- a/TelegramUI/ChatMediaInputPeerSpecificItem.swift +++ b/TelegramUI/ChatMediaInputPeerSpecificItem.swift @@ -105,7 +105,7 @@ final class ChatMediaInputPeerSpecificItemNode: ListViewItemNode { self.highlightNode.image = PresentationResourcesChat.chatMediaInputPanelHighlightedIconImage(theme) } - self.avatarNode.setPeer(account: account, peer: peer) + self.avatarNode.setPeer(account: account, theme: theme, peer: peer) } func updateIsHighlighted() { diff --git a/TelegramUI/ChatMediaInputTrendingPane.swift b/TelegramUI/ChatMediaInputTrendingPane.swift index f647df4e28..04c2186e3d 100644 --- a/TelegramUI/ChatMediaInputTrendingPane.swift +++ b/TelegramUI/ChatMediaInputTrendingPane.swift @@ -101,7 +101,7 @@ private func trendingPaneEntries(trendingEntries: [FeaturedStickerPackItem], ins } final class ChatMediaInputTrendingPane: ChatMediaInputPane { - private let account: Account + private let context: AccountContext private let controllerInteraction: ChatControllerInteraction private let getItemIsPreviewed: (StickerPackItem) -> Bool @@ -121,8 +121,8 @@ final class ChatMediaInputTrendingPane: ChatMediaInputPane { var scrollingInitiated: (() -> Void)? - init(account: Account, controllerInteraction: ChatControllerInteraction, getItemIsPreviewed: @escaping (StickerPackItem) -> Bool) { - self.account = account + init(context: AccountContext, controllerInteraction: ChatControllerInteraction, getItemIsPreviewed: @escaping (StickerPackItem) -> Bool) { + self.context = context self.controllerInteraction = controllerInteraction self.getItemIsPreviewed = getItemIsPreviewed @@ -149,14 +149,14 @@ 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.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.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 @@ -166,7 +166,7 @@ final class ChatMediaInputTrendingPane: ChatMediaInputPane { return .complete() } |> deliverOnMainQueue).start(completed: { if let strongSelf = self { - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } strongSelf.controllerInteraction.presentController(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .success), nil) } }) @@ -174,7 +174,7 @@ final class ChatMediaInputTrendingPane: ChatMediaInputPane { }, openPack: { [weak self] info in if let strongSelf = self, let info = info as? StickerPackCollectionInfo { strongSelf.view.window?.endEditing(true) - let controller = StickerPackPreviewController(account: strongSelf.account, stickerPack: .id(id: info.id.id, accessHash: info.accessHash), parentNavigationController: strongSelf.controllerInteraction.navigationController()) + let controller = StickerPackPreviewController(context: strongSelf.context, stickerPack: .id(id: info.id.id, accessHash: info.accessHash), parentNavigationController: strongSelf.controllerInteraction.navigationController()) controller.sendSticker = { fileReference in if let strongSelf = self { strongSelf.controllerInteraction.sendSticker(fileReference, false) @@ -185,8 +185,8 @@ final class ChatMediaInputTrendingPane: ChatMediaInputPane { }, getItemIsPreviewed: self.getItemIsPreviewed) let previousEntries = Atomic<[TrendingPaneEntry]?>(value: nil) - let account = self.account - self.disposable = (combineLatest(account.viewTracker.featuredStickerPacks(), account.postbox.combinedView(keys: [.itemCollectionInfos(namespaces: [Namespaces.ItemCollection.CloudStickerPacks])]), account.telegramApplicationContext.presentationData) + let context = self.context + self.disposable = (combineLatest(context.account.viewTracker.featuredStickerPacks(), context.account.postbox.combinedView(keys: [.itemCollectionInfos(namespaces: [Namespaces.ItemCollection.CloudStickerPacks])]), context.presentationData) |> map { trendingEntries, view, presentationData -> TrendingPaneTransition in var installedPacks = Set() if let stickerPacksView = view.views[.itemCollectionInfos(namespaces: [Namespaces.ItemCollection.CloudStickerPacks])] as? ItemCollectionInfosView { diff --git a/TelegramUI/ChatMessageActionButtonsNode.swift b/TelegramUI/ChatMessageActionButtonsNode.swift index b352244ec1..b9d3311553 100644 --- a/TelegramUI/ChatMessageActionButtonsNode.swift +++ b/TelegramUI/ChatMessageActionButtonsNode.swift @@ -68,14 +68,14 @@ private final class ChatMessageActionButtonNode: ASDisplayNode { } } - class func asyncLayout(_ maybeNode: ChatMessageActionButtonNode?) -> (_ account: Account, _ theme: ChatPresentationThemeData, _ strings: PresentationStrings, _ message: Message, _ button: ReplyMarkupButton, _ constrainedWidth: CGFloat, _ position: MessageBubbleActionButtonPosition) -> (minimumWidth: CGFloat, layout: ((CGFloat) -> (CGSize, () -> ChatMessageActionButtonNode))) { + class func asyncLayout(_ maybeNode: ChatMessageActionButtonNode?) -> (_ context: AccountContext, _ theme: ChatPresentationThemeData, _ strings: PresentationStrings, _ message: Message, _ button: ReplyMarkupButton, _ constrainedWidth: CGFloat, _ position: MessageBubbleActionButtonPosition) -> (minimumWidth: CGFloat, layout: ((CGFloat) -> (CGSize, () -> ChatMessageActionButtonNode))) { let titleLayout = TextNode.asyncLayout(maybeNode?.titleNode) - return { account, theme, strings, message, button, constrainedWidth, position in + return { context, theme, strings, message, button, constrainedWidth, position in let sideInset: CGFloat = 8.0 let minimumSideInset: CGFloat = 4.0 - let incoming = message.effectivelyIncoming(account.peerId) + let incoming = message.effectivelyIncoming(context.account.peerId) var title = button.title if case .payment = button.action { @@ -196,10 +196,10 @@ final class ChatMessageActionButtonsNode: ASDisplayNode { } } - class func asyncLayout(_ maybeNode: ChatMessageActionButtonsNode?) -> (_ account: Account, _ theme: ChatPresentationThemeData, _ strings: PresentationStrings, _ replyMarkup: ReplyMarkupMessageAttribute, _ message: Message, _ constrainedWidth: CGFloat) -> (minWidth: CGFloat, layout: (CGFloat) -> (CGSize, (_ animated: Bool) -> ChatMessageActionButtonsNode)) { + class func asyncLayout(_ maybeNode: ChatMessageActionButtonsNode?) -> (_ context: AccountContext, _ theme: ChatPresentationThemeData, _ strings: PresentationStrings, _ replyMarkup: ReplyMarkupMessageAttribute, _ message: Message, _ constrainedWidth: CGFloat) -> (minWidth: CGFloat, layout: (CGFloat) -> (CGSize, (_ animated: Bool) -> ChatMessageActionButtonsNode)) { let currentButtonLayouts = maybeNode?.buttonNodes.map { ChatMessageActionButtonNode.asyncLayout($0) } ?? [] - return { account, theme, strings, replyMarkup, message, constrainedWidth in + return { context, theme, strings, replyMarkup, message, constrainedWidth in let buttonHeight: CGFloat = 42.0 let buttonSpacing: CGFloat = 4.0 @@ -232,9 +232,9 @@ final class ChatMessageActionButtonsNode: ASDisplayNode { let prepareButtonLayout: (minimumWidth: CGFloat, layout: ((CGFloat) -> (CGSize, () -> ChatMessageActionButtonNode))) if buttonIndex < currentButtonLayouts.count { - prepareButtonLayout = currentButtonLayouts[buttonIndex](account, theme, strings, message, button, maximumButtonWidth, buttonPosition) + prepareButtonLayout = currentButtonLayouts[buttonIndex](context, theme, strings, message, button, maximumButtonWidth, buttonPosition) } else { - prepareButtonLayout = ChatMessageActionButtonNode.asyncLayout(nil)(account, theme, strings, message, button, maximumButtonWidth, buttonPosition) + prepareButtonLayout = ChatMessageActionButtonNode.asyncLayout(nil)(context, theme, strings, message, button, maximumButtonWidth, buttonPosition) } maximumRowButtonWidth = max(maximumRowButtonWidth, prepareButtonLayout.minimumWidth) diff --git a/TelegramUI/ChatMessageActionItemNode.swift b/TelegramUI/ChatMessageActionItemNode.swift index 36cb26a9f3..16b4f4a9fe 100644 --- a/TelegramUI/ChatMessageActionItemNode.swift +++ b/TelegramUI/ChatMessageActionItemNode.swift @@ -515,7 +515,7 @@ class ChatMessageActionBubbleContentNode: ChatMessageBubbleContentNode { let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: true, headerSpacing: 0.0, hidesBackground: .always, forceFullCorners: false, forceAlignment: .center) return (contentProperties, nil, CGFloat.greatestFiniteMagnitude, { constrainedSize, position in - let attributedString = attributedServiceMessageString(theme: item.presentationData.theme, strings: item.presentationData.strings, nameDisplayOrder: item.presentationData.nameDisplayOrder, message: item.message, accountPeerId: item.account.peerId) + let attributedString = attributedServiceMessageString(theme: item.presentationData.theme, strings: item.presentationData.strings, nameDisplayOrder: item.presentationData.nameDisplayOrder, message: item.message, accountPeerId: item.context.account.peerId) var image: TelegramMediaImage? for media in item.message.media { diff --git a/TelegramUI/ChatMessageAnimatedStickerItemNode.swift b/TelegramUI/ChatMessageAnimatedStickerItemNode.swift index b6cf563994..5f7c66a216 100644 --- a/TelegramUI/ChatMessageAnimatedStickerItemNode.swift +++ b/TelegramUI/ChatMessageAnimatedStickerItemNode.swift @@ -142,7 +142,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { for media in item.message.media { if let telegramFile = media as? TelegramMediaFile { if self.telegramFile != telegramFile { - let signal = chatMessageAnimatedStickerDatas(postbox: item.account.postbox, fileReference: FileMediaReference.message(message: MessageReference(item.message), media: telegramFile), synchronousLoad: false) + let signal = chatMessageAnimatedStickerDatas(postbox: item.context.account.postbox, fileReference: FileMediaReference.message(message: MessageReference(item.message), media: telegramFile), synchronousLoad: false) |> mapToSignal { data, completed -> Signal in if completed, let data = data { return .single(data) @@ -152,7 +152,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { } self.telegramFile = telegramFile self.animationNode.setSignal(signal) - self.fetchDisposable.set(freeMediaFileInteractiveFetched(account: item.account, fileReference: .message(message: MessageReference(item.message), media: telegramFile)).start()) + self.fetchDisposable.set(freeMediaFileInteractiveFetched(account: item.context.account, fileReference: .message(message: MessageReference(item.message), media: telegramFile)).start()) self.animationNode.play() } @@ -175,7 +175,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { let currentItem = self.item return { item, params, mergedTop, mergedBottom, dateHeaderAtBottom in - let incoming = item.message.effectivelyIncoming(item.account.peerId) + let incoming = item.message.effectivelyIncoming(item.context.account.peerId) var imageSize: CGSize = CGSize(width: 162.0, height: 162.0) if let telegramFile = telegramFile { if let dimensions = telegramFile.dimensions { @@ -190,7 +190,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { switch item.chatLocation { case let .peer(peerId): - if peerId != item.account.peerId { + if peerId != item.context.account.peerId { if peerId.isGroupOrChannel && item.message.author != nil { var isBroadcastChannel = false if let peer = item.message.peers[item.message.id.peerId] as? TelegramChannel, case .broadcast = peer.info { @@ -215,14 +215,14 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { } var needShareButton = false - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { for attribute in item.content.firstMessage.attributes { if let _ = attribute as? SourceReferenceMessageAttribute { needShareButton = true break } } - } else if item.message.effectivelyIncoming(item.account.peerId) { + } else if item.message.effectivelyIncoming(item.context.account.peerId) { if let peer = item.message.peers[item.message.id.peerId] { if let channel = peer as? TelegramChannel { if case .broadcast = channel.info { @@ -270,7 +270,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { let imageApply = imageLayout(arguments) let statusType: ChatMessageDateAndStatusType - if item.message.effectivelyIncoming(item.account.peerId) { + if item.message.effectivelyIncoming(item.context.account.peerId) { statusType = .FreeIncoming } else { if item.message.flags.contains(.Failed) { @@ -305,7 +305,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { for attribute in item.message.attributes { if let replyAttribute = attribute as? ReplyMessageAttribute, let replyMessage = item.message.associatedMessages[replyAttribute.messageId] { let availableWidth = max(60.0, params.width - params.leftInset - params.rightInset - imageSize.width - 20.0 - layoutConstants.bubble.edgeInset * 2.0 - avatarInset - layoutConstants.bubble.contentInsets.left) - replyInfoApply = makeReplyInfoLayout(item.presentationData, item.presentationData.strings, item.account, .standalone, replyMessage, CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude)) + replyInfoApply = makeReplyInfoLayout(item.presentationData, item.presentationData.strings, item.context, .standalone, replyMessage, CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude)) if let currentReplyBackgroundNode = currentReplyBackgroundNode { updatedReplyBackgroundNode = currentReplyBackgroundNode @@ -327,7 +327,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { updatedShareButtonNode = currentShareButtonNode if item.presentationData.theme !== currentItem?.presentationData.theme { let graphics = PresentationResourcesChat.additionalGraphics(item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper) - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { updatedShareButtonBackground = graphics.chatBubbleNavigateButtonImage } else { updatedShareButtonBackground = graphics.chatBubbleShareButtonImage @@ -337,7 +337,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { let buttonNode = HighlightableButtonNode() let buttonIcon: UIImage? let graphics = PresentationResourcesChat.additionalGraphics(item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper) - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { buttonIcon = graphics.chatBubbleNavigateButtonImage } else { buttonIcon = graphics.chatBubbleShareButtonImage @@ -422,7 +422,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { if let avatarNode = self.accessoryItemNode as? ChatMessageAvatarAccessoryItemNode, avatarNode.frame.contains(location) { if let item = self.item, let author = item.content.firstMessage.author { let navigate: ChatControllerInteractionNavigateToPeer - if item.content.firstMessage.id.peerId == item.account.peerId { + if item.content.firstMessage.id.peerId == item.context.account.peerId { navigate = .chat(textInputState: nil, messageId: nil) } else { navigate = .info @@ -465,7 +465,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { @objc func shareButtonPressed() { if let item = self.item { - if item.content.firstMessage.id.peerId == item.account.peerId { + if item.content.firstMessage.id.peerId == item.context.account.peerId { for attribute in item.content.firstMessage.attributes { if let attribute = attribute as? SourceReferenceMessageAttribute { item.controllerInteraction.navigateToMessage(item.content.firstMessage.id, attribute.messageId) @@ -559,7 +559,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { var incoming = true selected = selectionState.selectedIds.contains(item.message.id) - incoming = item.message.effectivelyIncoming(item.account.peerId) + incoming = item.message.effectivelyIncoming(item.context.account.peerId) let offset: CGFloat = incoming ? 42.0 : 0.0 diff --git a/TelegramUI/ChatMessageAttachedContentNode.swift b/TelegramUI/ChatMessageAttachedContentNode.swift index b65a87a027..2e7a8a32f0 100644 --- a/TelegramUI/ChatMessageAttachedContentNode.swift +++ b/TelegramUI/ChatMessageAttachedContentNode.swift @@ -220,7 +220,7 @@ final class ChatMessageAttachedContentNode: ASDisplayNode { private var additionalImageBadgeNode: ChatMessageInteractiveMediaBadge? private var linkHighlightingNode: LinkHighlightingNode? - private var account: Account? + private var context: AccountContext? private var message: Message? private var media: Media? private var theme: ChatPresentationThemeData? @@ -262,7 +262,7 @@ final class ChatMessageAttachedContentNode: ASDisplayNode { self.addSubnode(self.statusNode) } - func asyncLayout() -> (_ presentationData: ChatPresentationData, _ automaticDownloadSettings: AutomaticMediaDownloadSettings, _ associatedData: ChatMessageItemAssociatedData, _ account: Account, _ controllerInteraction: ChatControllerInteraction, _ message: Message, _ messageRead: Bool, _ title: String?, _ subtitle: NSAttributedString?, _ text: String?, _ entities: [MessageTextEntity]?, _ media: (Media, ChatMessageAttachedContentNodeMediaFlags)?, _ actionIcon: ChatMessageAttachedContentActionIcon?, _ actionTitle: String?, _ displayLine: Bool, _ layoutConstants: ChatMessageItemLayoutConstants, _ constrainedSize: CGSize) -> (CGFloat, (CGSize, ChatMessageBubbleContentPosition) -> (CGFloat, (CGFloat) -> (CGSize, (ListViewItemUpdateAnimation, Bool) -> Void))) { + func asyncLayout() -> (_ presentationData: ChatPresentationData, _ automaticDownloadSettings: AutomaticMediaDownloadSettings, _ associatedData: ChatMessageItemAssociatedData, _ context: AccountContext, _ controllerInteraction: ChatControllerInteraction, _ message: Message, _ messageRead: Bool, _ title: String?, _ subtitle: NSAttributedString?, _ text: String?, _ entities: [MessageTextEntity]?, _ media: (Media, ChatMessageAttachedContentNodeMediaFlags)?, _ actionIcon: ChatMessageAttachedContentActionIcon?, _ actionTitle: String?, _ displayLine: Bool, _ layoutConstants: ChatMessageItemLayoutConstants, _ constrainedSize: CGSize) -> (CGFloat, (CGSize, ChatMessageBubbleContentPosition) -> (CGFloat, (CGFloat) -> (CGSize, (ListViewItemUpdateAnimation, Bool) -> Void))) { let textAsyncLayout = TextNode.asyncLayout(self.textNode) let currentImage = self.media as? TelegramMediaImage let imageLayout = self.inlineImageNode.asyncLayout() @@ -275,8 +275,8 @@ final class ChatMessageAttachedContentNode: ASDisplayNode { let currentAdditionalImageBadgeNode = self.additionalImageBadgeNode - return { presentationData, automaticDownloadSettings, associatedData, account, controllerInteraction, message, messageRead, title, subtitle, text, entities, mediaAndFlags, actionIcon, actionTitle, displayLine, layoutConstants, constrainedSize in - let incoming = message.effectivelyIncoming(account.peerId) + return { presentationData, automaticDownloadSettings, associatedData, context, controllerInteraction, message, messageRead, title, subtitle, text, entities, mediaAndFlags, actionIcon, actionTitle, displayLine, layoutConstants, constrainedSize in + let incoming = message.effectivelyIncoming(context.account.peerId) var horizontalInsets = UIEdgeInsets(top: 0.0, left: 12.0, bottom: 0.0, right: 12.0) if displayLine { @@ -376,24 +376,24 @@ final class ChatMessageAttachedContentNode: ASDisplayNode { if let file = media as? TelegramMediaFile { if file.isInstantVideo { let automaticDownload = shouldDownloadMediaAutomatically(settings: automaticDownloadSettings, peerType: associatedData.automaticDownloadPeerType, networkType: associatedData.automaticDownloadNetworkType, media: file) - let (videoLayout, apply) = contentInstantVideoLayout(ChatMessageBubbleContentItem(account: account, controllerInteraction: controllerInteraction, message: message, read: messageRead, presentationData: presentationData, associatedData: associatedData), constrainedSize.width - horizontalInsets.left - horizontalInsets.right, CGSize(width: 180.0, height: 180.0), .bubble, automaticDownload) + let (videoLayout, apply) = contentInstantVideoLayout(ChatMessageBubbleContentItem(context: context, controllerInteraction: controllerInteraction, message: message, read: messageRead, presentationData: presentationData, associatedData: associatedData), constrainedSize.width - horizontalInsets.left - horizontalInsets.right, CGSize(width: 180.0, height: 180.0), .bubble, automaticDownload) initialWidth = videoLayout.contentSize.width + videoLayout.overflowLeft + videoLayout.overflowRight contentInstantVideoSizeAndApply = (videoLayout, apply) } else if file.isVideo { let automaticDownload = shouldDownloadMediaAutomatically(settings: automaticDownloadSettings, peerType: associatedData.automaticDownloadPeerType, networkType: associatedData.automaticDownloadNetworkType, media: file) - let (_, initialImageWidth, refineLayout) = contentImageLayout(account, presentationData.theme.theme, presentationData.strings, message, file, automaticDownload, associatedData.automaticDownloadPeerType, automaticDownloadSettings.autoplayGifs, .constrained(CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)), layoutConstants) + let (_, initialImageWidth, refineLayout) = contentImageLayout(context, presentationData.theme.theme, presentationData.strings, message, file, automaticDownload, associatedData.automaticDownloadPeerType, automaticDownloadSettings.autoplayGifs, .constrained(CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)), layoutConstants) initialWidth = initialImageWidth + horizontalInsets.left + horizontalInsets.right refineContentImageLayout = refineLayout } else if file.isSticker, let _ = file.dimensions { let automaticDownload = shouldDownloadMediaAutomatically(settings: automaticDownloadSettings, peerType: associatedData.automaticDownloadPeerType, networkType: associatedData.automaticDownloadNetworkType, media: file) - let (_, initialImageWidth, refineLayout) = contentImageLayout(account, presentationData.theme.theme, presentationData.strings, message, file, automaticDownload, associatedData.automaticDownloadPeerType, automaticDownloadSettings.autoplayGifs, .constrained(CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)), layoutConstants) + let (_, initialImageWidth, refineLayout) = contentImageLayout(context, presentationData.theme.theme, presentationData.strings, message, file, automaticDownload, associatedData.automaticDownloadPeerType, automaticDownloadSettings.autoplayGifs, .constrained(CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)), layoutConstants) initialWidth = initialImageWidth + horizontalInsets.left + horizontalInsets.right refineContentImageLayout = refineLayout } else { let automaticDownload = shouldDownloadMediaAutomatically(settings: automaticDownloadSettings, peerType: associatedData.automaticDownloadPeerType, networkType: associatedData.automaticDownloadNetworkType, media: file) let statusType: ChatMessageDateAndStatusType - if message.effectivelyIncoming(account.peerId) { + if message.effectivelyIncoming(context.account.peerId) { statusType = .BubbleIncoming } else { if message.flags.contains(.Failed) { @@ -405,25 +405,25 @@ final class ChatMessageAttachedContentNode: ASDisplayNode { } } - let (_, refineLayout) = contentFileLayout(account, presentationData, message, file, automaticDownload, message.effectivelyIncoming(account.peerId), false, statusType, CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)) + let (_, refineLayout) = contentFileLayout(context, presentationData, message, file, automaticDownload, message.effectivelyIncoming(context.account.peerId), false, statusType, CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)) refineContentFileLayout = refineLayout } } else if let image = media as? TelegramMediaImage { if !flags.contains(.preferMediaInline) { let automaticDownload = shouldDownloadMediaAutomatically(settings: automaticDownloadSettings, peerType: associatedData.automaticDownloadPeerType, networkType: associatedData.automaticDownloadNetworkType, media: image) - let (_, initialImageWidth, refineLayout) = contentImageLayout(account, presentationData.theme.theme, presentationData.strings, message, image, automaticDownload, associatedData.automaticDownloadPeerType, automaticDownloadSettings.autoplayGifs, .constrained(CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)), layoutConstants) + let (_, initialImageWidth, refineLayout) = contentImageLayout(context, presentationData.theme.theme, presentationData.strings, message, image, automaticDownload, associatedData.automaticDownloadPeerType, automaticDownloadSettings.autoplayGifs, .constrained(CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)), layoutConstants) initialWidth = initialImageWidth + horizontalInsets.left + horizontalInsets.right refineContentImageLayout = refineLayout } else if let dimensions = largestImageRepresentation(image.representations)?.dimensions { inlineImageDimensions = dimensions if image != currentImage { - updateInlineImageSignal = chatWebpageSnippetPhoto(account: account, photoReference: .message(message: MessageReference(message), media: image)) + updateInlineImageSignal = chatWebpageSnippetPhoto(account: context.account, photoReference: .message(message: MessageReference(message), media: image)) } } } else if let image = media as? TelegramMediaWebFile { let automaticDownload = shouldDownloadMediaAutomatically(settings: automaticDownloadSettings, peerType: associatedData.automaticDownloadPeerType, networkType: associatedData.automaticDownloadNetworkType, media: image) - let (_, initialImageWidth, refineLayout) = contentImageLayout(account, presentationData.theme.theme, presentationData.strings, message, image, automaticDownload, associatedData.automaticDownloadPeerType, automaticDownloadSettings.autoplayGifs, .constrained(CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)), layoutConstants) + let (_, initialImageWidth, refineLayout) = contentImageLayout(context, presentationData.theme.theme, presentationData.strings, message, image, automaticDownload, associatedData.automaticDownloadPeerType, automaticDownloadSettings.autoplayGifs, .constrained(CGSize(width: constrainedSize.width - horizontalInsets.left - horizontalInsets.right, height: constrainedSize.height)), layoutConstants) initialWidth = initialImageWidth + horizontalInsets.left + horizontalInsets.right refineContentImageLayout = refineLayout } @@ -467,7 +467,7 @@ final class ChatMessageAttachedContentNode: ASDisplayNode { if !skipStandardStatus { let statusType: ChatMessageDateAndStatusType - if message.effectivelyIncoming(account.peerId) { + if message.effectivelyIncoming(context.account.peerId) { if imageMode { statusType = .ImageIncoming } else { @@ -691,7 +691,7 @@ final class ChatMessageAttachedContentNode: ASDisplayNode { return (adjustedBoundingSize, { [weak self] animation, synchronousLoads in if let strongSelf = self { - strongSelf.account = account + strongSelf.context = context strongSelf.message = message strongSelf.media = mediaAndFlags?.0 strongSelf.theme = presentationData.theme @@ -932,7 +932,7 @@ final class ChatMessageAttachedContentNode: ASDisplayNode { } func updateTouchesAtPoint(_ point: CGPoint?) { - if let account = self.account, let message = self.message, let theme = self.theme { + if let context = self.context, let message = self.message, let theme = self.theme { var rects: [CGRect]? if let point = point { let textNodeFrame = self.textNode.frame @@ -958,7 +958,7 @@ final class ChatMessageAttachedContentNode: ASDisplayNode { if let current = self.linkHighlightingNode { linkHighlightingNode = current } else { - linkHighlightingNode = LinkHighlightingNode(color: message.effectivelyIncoming(account.peerId) ? theme.theme.chat.bubble.incomingLinkHighlightColor : theme.theme.chat.bubble.outgoingLinkHighlightColor) + linkHighlightingNode = LinkHighlightingNode(color: message.effectivelyIncoming(context.account.peerId) ? theme.theme.chat.bubble.incomingLinkHighlightColor : theme.theme.chat.bubble.outgoingLinkHighlightColor) self.linkHighlightingNode = linkHighlightingNode self.insertSubnode(linkHighlightingNode, belowSubnode: self.textNode) } diff --git a/TelegramUI/ChatMessageAvatarAccessoryItem.swift b/TelegramUI/ChatMessageAvatarAccessoryItem.swift index afa368eea0..665a2b6924 100644 --- a/TelegramUI/ChatMessageAvatarAccessoryItem.swift +++ b/TelegramUI/ChatMessageAvatarAccessoryItem.swift @@ -6,15 +6,15 @@ import TelegramCore private let avatarFont: UIFont = UIFont(name: ".SFCompactRounded-Semibold", size: 16.0)! final class ChatMessageAvatarAccessoryItem: ListViewAccessoryItem { - private let account: Account + private let context: AccountContext private let peerId: PeerId private let peer: Peer? private let messageReference: MessageReference? private let messageTimestamp: Int32 private let emptyColor: UIColor - init(account: Account, peerId: PeerId, peer: Peer?, messageReference: MessageReference?, messageTimestamp: Int32, emptyColor: UIColor) { - self.account = account + init(context: AccountContext, peerId: PeerId, peer: Peer?, messageReference: MessageReference?, messageTimestamp: Int32, emptyColor: UIColor) { + self.context = context self.peerId = peerId self.peer = peer self.messageReference = messageReference @@ -34,7 +34,7 @@ final class ChatMessageAvatarAccessoryItem: ListViewAccessoryItem { let node = ChatMessageAvatarAccessoryItemNode() node.frame = CGRect(origin: CGPoint(), size: CGSize(width: 38.0, height: 38.0)) if let peer = self.peer { - node.setPeer(account: account, peer: peer, authorOfMessage: self.messageReference, emptyColor: self.emptyColor) + node.setPeer(account: self.context.account, theme: self.context.currentPresentationData.with({ $0 }).theme, peer: peer, authorOfMessage: self.messageReference, emptyColor: self.emptyColor) } return node } @@ -56,7 +56,7 @@ final class ChatMessageAvatarAccessoryItemNode: ListViewAccessoryItemNode { self.addSubnode(self.avatarNode) } - func setPeer(account: Account, peer: Peer, authorOfMessage: MessageReference?, emptyColor: UIColor) { - self.avatarNode.setPeer(account: account, peer: peer, authorOfMessage: authorOfMessage, emptyColor: emptyColor) + func setPeer(account: Account, theme: PresentationTheme, peer: Peer, authorOfMessage: MessageReference?, emptyColor: UIColor) { + self.avatarNode.setPeer(account: account, theme: theme, peer: peer, authorOfMessage: authorOfMessage, emptyColor: emptyColor) } } diff --git a/TelegramUI/ChatMessageBubbleContentNode.swift b/TelegramUI/ChatMessageBubbleContentNode.swift index d221333897..8c7a54189c 100644 --- a/TelegramUI/ChatMessageBubbleContentNode.swift +++ b/TelegramUI/ChatMessageBubbleContentNode.swift @@ -77,15 +77,15 @@ enum ChatMessageBubbleContentTapAction { } final class ChatMessageBubbleContentItem { - let account: Account + let context: AccountContext let controllerInteraction: ChatControllerInteraction let message: Message let read: Bool let presentationData: ChatPresentationData let associatedData: ChatMessageItemAssociatedData - init(account: Account, controllerInteraction: ChatControllerInteraction, message: Message, read: Bool, presentationData: ChatPresentationData, associatedData: ChatMessageItemAssociatedData) { - self.account = account + init(context: AccountContext, controllerInteraction: ChatControllerInteraction, message: Message, read: Bool, presentationData: ChatPresentationData, associatedData: ChatMessageItemAssociatedData) { + self.context = context self.controllerInteraction = controllerInteraction self.message = message self.read = read diff --git a/TelegramUI/ChatMessageBubbleItemNode.swift b/TelegramUI/ChatMessageBubbleItemNode.swift index 1a7da18ff6..9fa742ed51 100644 --- a/TelegramUI/ChatMessageBubbleItemNode.swift +++ b/TelegramUI/ChatMessageBubbleItemNode.swift @@ -314,7 +314,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { let content = item.content let firstMessage = content.firstMessage - let incoming = item.content.effectivelyIncoming(item.account.peerId) + let incoming = item.content.effectivelyIncoming(item.context.account.peerId) var effectiveAuthor: Peer? var ignoreForward = false @@ -326,7 +326,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { var allowFullWidth = false switch item.chatLocation { case let .peer(peerId): - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { if let forwardInfo = item.content.firstMessage.forwardInfo { ignoreForward = true effectiveAuthor = forwardInfo.author @@ -337,7 +337,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { displayAuthorInfo = !mergedTop.merged && incoming && peerId.isGroupOrChannel && effectiveAuthor != nil } - if peerId != item.account.peerId { + if peerId != item.context.account.peerId { if peerId.isGroupOrChannel && effectiveAuthor != nil { var isBroadcastChannel = false if let peer = firstMessage.peers[firstMessage.id.peerId] as? TelegramChannel, case .broadcast = peer.info { @@ -346,7 +346,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { } if !isBroadcastChannel { - hasAvatar = item.content.firstMessage.effectivelyIncoming(item.account.peerId) + hasAvatar = item.content.firstMessage.effectivelyIncoming(item.context.account.peerId) } } } else if incoming { @@ -376,14 +376,14 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { var needShareButton = false if item.message.flags.contains(.Failed) { needShareButton = false - } else if item.message.id.peerId == item.account.peerId { + } else if item.message.id.peerId == item.context.account.peerId { for attribute in item.content.firstMessage.attributes { if let _ = attribute as? SourceReferenceMessageAttribute { needShareButton = true break } } - } else if item.message.effectivelyIncoming(item.account.peerId) { + } else if item.message.effectivelyIncoming(item.context.account.peerId) { if let peer = item.message.peers[item.message.id.peerId] { if let channel = peer as? TelegramChannel { if case .broadcast = channel.info { @@ -564,7 +564,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { prepareContentPosition = .linear(top: topPosition, bottom: refinedBottomPosition) } - let contentItem = ChatMessageBubbleContentItem(account: item.account, controllerInteraction: item.controllerInteraction, message: message, read: read, presentationData: item.presentationData, associatedData: item.associatedData) + let contentItem = ChatMessageBubbleContentItem(context: item.context, controllerInteraction: item.controllerInteraction, message: message, read: read, presentationData: item.presentationData, associatedData: item.associatedData) var itemSelection: Bool? if case .mosaic = prepareContentPosition { @@ -710,7 +710,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { let dateText = stringForMessageTimestampStatus(message: message, dateTimeFormat: item.presentationData.dateTimeFormat, nameDisplayOrder: item.presentationData.nameDisplayOrder, strings: item.presentationData.strings) let statusType: ChatMessageDateAndStatusType - if message.effectivelyIncoming(item.account.peerId) { + if message.effectivelyIncoming(item.context.account.peerId) { statusType = .ImageIncoming } else { if message.flags.contains(.Failed) { @@ -817,7 +817,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { } else { headerSize.height += 2.0 } - let sizeAndApply = replyInfoLayout(item.presentationData, item.presentationData.strings, item.account, .bubble(incoming: incoming), replyMessage, CGSize(width: maximumNodeWidth - layoutConstants.text.bubbleInsets.left - layoutConstants.text.bubbleInsets.right, height: CGFloat.greatestFiniteMagnitude)) + let sizeAndApply = replyInfoLayout(item.presentationData, item.presentationData.strings, item.context, .bubble(incoming: incoming), replyMessage, CGSize(width: maximumNodeWidth - layoutConstants.text.bubbleInsets.left - layoutConstants.text.bubbleInsets.right, height: CGFloat.greatestFiniteMagnitude)) replyInfoSizeApply = (sizeAndApply.0, { sizeAndApply.1() }) replyInfoOriginY = headerSize.height @@ -866,7 +866,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { var actionButtonsFinalize: ((CGFloat) -> (CGSize, (_ animated: Bool) -> ChatMessageActionButtonsNode))? if let replyMarkup = replyMarkup { - let (minWidth, buttonsLayout) = actionButtonsLayout(item.account, item.presentationData.theme, item.presentationData.strings, replyMarkup, item.message, maximumNodeWidth) + let (minWidth, buttonsLayout) = actionButtonsLayout(item.context, item.presentationData.theme, item.presentationData.strings, replyMarkup, item.message, maximumNodeWidth) maxContentWidth = max(maxContentWidth, minWidth) actionButtonsFinalize = buttonsLayout } @@ -1099,7 +1099,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { updatedShareButtonNode = currentShareButtonNode if item.presentationData.theme !== currentItem?.presentationData.theme { let graphics = PresentationResourcesChat.additionalGraphics(item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper) - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { updatedShareButtonBackground = graphics.chatBubbleNavigateButtonImage } else { updatedShareButtonBackground = graphics.chatBubbleShareButtonImage @@ -1109,7 +1109,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { let buttonNode = HighlightableButtonNode() let buttonIcon: UIImage? let graphics = PresentationResourcesChat.additionalGraphics(item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper) - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { buttonIcon = graphics.chatBubbleNavigateButtonImage } else { buttonIcon = graphics.chatBubbleShareButtonImage @@ -1536,7 +1536,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { if let avatarNode = self.accessoryItemNode as? ChatMessageAvatarAccessoryItemNode, avatarNode.frame.contains(location) { if let item = self.item, let author = item.content.firstMessage.author { let navigate: ChatControllerInteractionNavigateToPeer - if item.content.firstMessage.id.peerId == item.account.peerId { + if item.content.firstMessage.id.peerId == item.context.account.peerId { navigate = .chat(textInputState: nil, messageId: nil) } else { navigate = .info @@ -1863,7 +1863,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { selected = allSelected } - incoming = item.message.effectivelyIncoming(item.account.peerId) + incoming = item.message.effectivelyIncoming(item.context.account.peerId) let offset: CGFloat = incoming ? 42.0 : 0.0 @@ -1966,7 +1966,7 @@ class ChatMessageBubbleItemNode: ChatMessageItemView { @objc func shareButtonPressed() { if let item = self.item { - if item.content.firstMessage.id.peerId == item.account.peerId { + if item.content.firstMessage.id.peerId == item.context.account.peerId { for attribute in item.content.firstMessage.attributes { if let attribute = attribute as? SourceReferenceMessageAttribute { item.controllerInteraction.navigateToMessage(item.content.firstMessage.id, attribute.messageId) diff --git a/TelegramUI/ChatMessageCallBubbleContentNode.swift b/TelegramUI/ChatMessageCallBubbleContentNode.swift index 4a12e251ee..f3594cb12c 100644 --- a/TelegramUI/ChatMessageCallBubbleContentNode.swift +++ b/TelegramUI/ChatMessageCallBubbleContentNode.swift @@ -63,7 +63,7 @@ class ChatMessageCallBubbleContentNode: ChatMessageBubbleContentNode { return (contentProperties, nil, CGFloat.greatestFiniteMagnitude, { constrainedSize, position in let message = item.message - let incoming = item.message.effectivelyIncoming(item.account.peerId) + let incoming = item.message.effectivelyIncoming(item.context.account.peerId) let horizontalInset = layoutConstants.text.bubbleInsets.left + layoutConstants.text.bubbleInsets.right let textConstrainedSize = CGSize(width: constrainedSize.width - horizontalInset, height: constrainedSize.height) @@ -142,7 +142,7 @@ class ChatMessageCallBubbleContentNode: ChatMessageBubbleContentNode { } var attributedLabel: NSAttributedString? - attributedLabel = NSAttributedString(string: statusText, font: labelFont, textColor: message.effectivelyIncoming(item.account.peerId) ? bubbleTheme.incomingFileDurationColor : bubbleTheme.outgoingFileDurationColor) + attributedLabel = NSAttributedString(string: statusText, font: labelFont, textColor: message.effectivelyIncoming(item.context.account.peerId) ? bubbleTheme.incomingFileDurationColor : bubbleTheme.outgoingFileDurationColor) let (titleLayout, titleApply) = makeTitleLayout(TextNodeLayoutArguments(attributedString: attributedTitle, backgroundColor: nil, maximumNumberOfLines: 0, truncationType: .end, constrainedSize: textConstrainedSize, alignment: .natural, cutout: nil, insets: UIEdgeInsets())) let (labelLayout, labelApply) = makeLabelLayout(TextNodeLayoutArguments(attributedString: attributedLabel, backgroundColor: nil, maximumNumberOfLines: 0, truncationType: .end, constrainedSize: textConstrainedSize, alignment: .natural, cutout: nil, insets: UIEdgeInsets())) diff --git a/TelegramUI/ChatMessageContactBubbleContentNode.swift b/TelegramUI/ChatMessageContactBubbleContentNode.swift index 2b01bd1754..3a62f8fbf5 100644 --- a/TelegramUI/ChatMessageContactBubbleContentNode.swift +++ b/TelegramUI/ChatMessageContactBubbleContentNode.swift @@ -120,8 +120,8 @@ class ChatMessageContactBubbleContentNode: ChatMessageBubbleContentNode { updatedContactInfo = info - titleString = NSAttributedString(string: displayName, font: titleFont, textColor: item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingAccentTextColor : item.presentationData.theme.theme.chat.bubble.outgoingAccentTextColor) - textString = NSAttributedString(string: info, font: textFont, textColor: item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingPrimaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingPrimaryTextColor) + titleString = NSAttributedString(string: displayName, font: titleFont, textColor: item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingAccentTextColor : item.presentationData.theme.theme.chat.bubble.outgoingAccentTextColor) + textString = NSAttributedString(string: info, font: textFont, textColor: item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingPrimaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingPrimaryTextColor) } else { updatedContactInfo = nil } @@ -156,7 +156,7 @@ class ChatMessageContactBubbleContentNode: ChatMessageBubbleContentNode { let statusType: ChatMessageDateAndStatusType? switch position { case .linear(_, .None): - if item.message.effectivelyIncoming(item.account.peerId) { + if item.message.effectivelyIncoming(item.context.account.peerId) { statusType = .BubbleIncoming } else { if item.message.flags.contains(.Failed) { @@ -185,7 +185,7 @@ class ChatMessageContactBubbleContentNode: ChatMessageBubbleContentNode { let titleColor: UIColor let titleHighlightedColor: UIColor let avatarPlaceholderColor: UIColor - if item.message.effectivelyIncoming(item.account.peerId) { + if item.message.effectivelyIncoming(item.context.account.peerId) { buttonImage = PresentationResourcesChat.chatMessageAttachedContentButtonIncoming(item.presentationData.theme.theme)! buttonHighlightedImage = PresentationResourcesChat.chatMessageAttachedContentHighlightedButtonIncoming(item.presentationData.theme.theme)! titleColor = item.presentationData.theme.theme.chat.bubble.incomingAccentTextColor @@ -289,7 +289,7 @@ class ChatMessageContactBubbleContentNode: ChatMessageBubbleContentNode { } if let peerId = selectedContact?.peerId, let peer = item.message.peers[peerId] { - strongSelf.avatarNode.setPeer(account: item.account, peer: peer, emptyColor: avatarPlaceholderColor) + strongSelf.avatarNode.setPeer(account: item.context.account, theme: item.presentationData.theme.theme, peer: peer, emptyColor: avatarPlaceholderColor) } else { strongSelf.avatarNode.setCustomLetters(customLetters) } diff --git a/TelegramUI/ChatMessageEventLogPreviousDescriptionContentNode.swift b/TelegramUI/ChatMessageEventLogPreviousDescriptionContentNode.swift index 74a7a300cb..5272725de9 100644 --- a/TelegramUI/ChatMessageEventLogPreviousDescriptionContentNode.swift +++ b/TelegramUI/ChatMessageEventLogPreviousDescriptionContentNode.swift @@ -42,7 +42,7 @@ final class ChatMessageEventLogPreviousDescriptionContentNode: ChatMessageBubble } let mediaAndFlags: (Media, ChatMessageAttachedContentNodeMediaFlags)? = nil - let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.account, item.controllerInteraction, item.message, true, title, nil, text, messageEntities, mediaAndFlags, nil, nil, true, layoutConstants, constrainedSize) + let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.context, item.controllerInteraction, item.message, true, title, nil, text, messageEntities, mediaAndFlags, nil, nil, true, layoutConstants, constrainedSize) let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: false, headerSpacing: 8.0, hidesBackground: .never, forceFullCorners: false, forceAlignment: .none) diff --git a/TelegramUI/ChatMessageEventLogPreviousLinkContentNode.swift b/TelegramUI/ChatMessageEventLogPreviousLinkContentNode.swift index eb8385c302..2a1415937b 100644 --- a/TelegramUI/ChatMessageEventLogPreviousLinkContentNode.swift +++ b/TelegramUI/ChatMessageEventLogPreviousLinkContentNode.swift @@ -37,7 +37,7 @@ final class ChatMessageEventLogPreviousLinkContentNode: ChatMessageBubbleContent let text: String = item.message.text let mediaAndFlags: (Media, ChatMessageAttachedContentNodeMediaFlags)? = nil - let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.account, item.controllerInteraction, item.message, true, title, nil, text, messageEntities, mediaAndFlags, nil, nil, true, layoutConstants, constrainedSize) + let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.context, item.controllerInteraction, item.message, true, title, nil, text, messageEntities, mediaAndFlags, nil, nil, true, layoutConstants, constrainedSize) let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: false, headerSpacing: 8.0, hidesBackground: .never, forceFullCorners: false, forceAlignment: .none) diff --git a/TelegramUI/ChatMessageEventLogPreviousMessageContentNode.swift b/TelegramUI/ChatMessageEventLogPreviousMessageContentNode.swift index 68e5a0e9bd..abe7dd4ddb 100644 --- a/TelegramUI/ChatMessageEventLogPreviousMessageContentNode.swift +++ b/TelegramUI/ChatMessageEventLogPreviousMessageContentNode.swift @@ -42,7 +42,7 @@ final class ChatMessageEventLogPreviousMessageContentNode: ChatMessageBubbleCont } let mediaAndFlags: (Media, ChatMessageAttachedContentNodeMediaFlags)? = nil - let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.account, item.controllerInteraction, item.message, true, title, nil, text, messageEntities, mediaAndFlags, nil, nil, true, layoutConstants, constrainedSize) + let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.context, item.controllerInteraction, item.message, true, title, nil, text, messageEntities, mediaAndFlags, nil, nil, true, layoutConstants, constrainedSize) let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: false, headerSpacing: 8.0, hidesBackground: .never, forceFullCorners: false, forceAlignment: .none) diff --git a/TelegramUI/ChatMessageFileBubbleContentNode.swift b/TelegramUI/ChatMessageFileBubbleContentNode.swift index 4d15ebe0c4..3e4debaf2d 100644 --- a/TelegramUI/ChatMessageFileBubbleContentNode.swift +++ b/TelegramUI/ChatMessageFileBubbleContentNode.swift @@ -47,7 +47,7 @@ class ChatMessageFileBubbleContentNode: ChatMessageBubbleContentNode { } } - let incoming = item.message.effectivelyIncoming(item.account.peerId) + let incoming = item.message.effectivelyIncoming(item.context.account.peerId) let statusType: ChatMessageDateAndStatusType? switch preparePosition { case .linear(_, .None): @@ -69,7 +69,7 @@ class ChatMessageFileBubbleContentNode: ChatMessageBubbleContentNode { var automaticDownload = false automaticDownload = shouldDownloadMediaAutomatically(settings: item.controllerInteraction.automaticMediaDownloadSettings, peerType: item.associatedData.automaticDownloadPeerType, networkType: item.associatedData.automaticDownloadNetworkType, media: selectedFile!) - let (initialWidth, refineLayout) = interactiveFileLayout(item.account, item.presentationData, item.message, selectedFile!, automaticDownload, item.message.effectivelyIncoming(item.account.peerId), item.associatedData.isRecentActions, statusType, CGSize(width: constrainedSize.width - layoutConstants.file.bubbleInsets.left - layoutConstants.file.bubbleInsets.right, height: constrainedSize.height)) + let (initialWidth, refineLayout) = interactiveFileLayout(item.context, item.presentationData, item.message, selectedFile!, automaticDownload, item.message.effectivelyIncoming(item.context.account.peerId), item.associatedData.isRecentActions, statusType, CGSize(width: constrainedSize.width - layoutConstants.file.bubbleInsets.left - layoutConstants.file.bubbleInsets.right, height: constrainedSize.height)) let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: false, headerSpacing: 0.0, hidesBackground: .never, forceFullCorners: false, forceAlignment: .none) diff --git a/TelegramUI/ChatMessageGameBubbleContentNode.swift b/TelegramUI/ChatMessageGameBubbleContentNode.swift index c9edbc381a..e2e204302f 100644 --- a/TelegramUI/ChatMessageGameBubbleContentNode.swift +++ b/TelegramUI/ChatMessageGameBubbleContentNode.swift @@ -69,7 +69,7 @@ final class ChatMessageGameBubbleContentNode: ChatMessageBubbleContentNode { } } - let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.account, item.controllerInteraction, item.message, item.read, title, nil, item.message.text.isEmpty ? text : item.message.text, item.message.text.isEmpty ? nil : messageEntities, mediaAndFlags, nil, nil, true, layoutConstants, constrainedSize) + let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.context, item.controllerInteraction, item.message, item.read, title, nil, item.message.text.isEmpty ? text : item.message.text, item.message.text.isEmpty ? nil : messageEntities, mediaAndFlags, nil, nil, true, layoutConstants, constrainedSize) let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: false, headerSpacing: 8.0, hidesBackground: .never, forceFullCorners: false, forceAlignment: .none) diff --git a/TelegramUI/ChatMessageInstantVideoItemNode.swift b/TelegramUI/ChatMessageInstantVideoItemNode.swift index 47a9b7537c..ed9da659c1 100644 --- a/TelegramUI/ChatMessageInstantVideoItemNode.swift +++ b/TelegramUI/ChatMessageInstantVideoItemNode.swift @@ -98,14 +98,14 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { return { item, params, mergedTop, mergedBottom, dateHeaderAtBottom in let baseWidth = params.width - params.leftInset - params.rightInset - let incoming = item.message.effectivelyIncoming(item.account.peerId) + let incoming = item.message.effectivelyIncoming(item.context.account.peerId) let avatarInset: CGFloat var hasAvatar = false switch item.chatLocation { case let .peer(peerId): - if peerId != item.account.peerId { + if peerId != item.context.account.peerId { if peerId.isGroupOrChannel && item.message.author != nil { var isBroadcastChannel = false if let peer = item.message.peers[item.message.id.peerId] as? TelegramChannel, case .broadcast = peer.info { @@ -130,14 +130,14 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { } var needShareButton = false - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { for attribute in item.content.firstMessage.attributes { if let _ = attribute as? SourceReferenceMessageAttribute { needShareButton = true break } } - } else if item.message.effectivelyIncoming(item.account.peerId) { + } else if item.message.effectivelyIncoming(item.context.account.peerId) { if let peer = item.message.peers[item.message.id.peerId] { if let channel = peer as? TelegramChannel { if case .broadcast = channel.info { @@ -182,7 +182,7 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { } } - let (videoLayout, videoApply) = makeVideoLayout(ChatMessageBubbleContentItem(account: item.account, controllerInteraction: item.controllerInteraction, message: item.message, read: item.read, presentationData: item.presentationData, associatedData: item.associatedData), params.width - params.leftInset - params.rightInset - avatarInset, displaySize, .free, automaticDownload) + let (videoLayout, videoApply) = makeVideoLayout(ChatMessageBubbleContentItem(context: item.context, controllerInteraction: item.controllerInteraction, message: item.message, read: item.read, presentationData: item.presentationData, associatedData: item.associatedData), params.width - params.leftInset - params.rightInset - avatarInset, displaySize, .free, automaticDownload) let videoFrame = CGRect(origin: CGPoint(x: (incoming ? (params.leftInset + layoutConstants.bubble.edgeInset + avatarInset + layoutConstants.bubble.contentInsets.left) : (params.width - params.rightInset - videoLayout.contentSize.width - layoutConstants.bubble.edgeInset - layoutConstants.bubble.contentInsets.left)), y: 0.0), size: videoLayout.contentSize) @@ -215,7 +215,7 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { } } if let replyAttribute = attribute as? ReplyMessageAttribute, let replyMessage = item.message.associatedMessages[replyAttribute.messageId] { - replyInfoApply = makeReplyInfoLayout(item.presentationData, item.presentationData.strings, item.account, .standalone, replyMessage, CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude)) + replyInfoApply = makeReplyInfoLayout(item.presentationData, item.presentationData.strings, item.context, .standalone, replyMessage, CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude)) } else if let attribute = attribute as? InlineBotMessageAttribute { if let peerId = attribute.peerId, let bot = item.message.peers[peerId] as? TelegramUser { inlineBotNameString = bot.username @@ -246,7 +246,7 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { updatedShareButtonNode = currentShareButtonNode if item.presentationData.theme !== currentItem?.presentationData.theme { let graphics = PresentationResourcesChat.additionalGraphics(item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper) - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { updatedShareButtonBackground = graphics.chatBubbleNavigateButtonImage } else { updatedShareButtonBackground = graphics.chatBubbleShareButtonImage @@ -256,7 +256,7 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { let buttonNode = HighlightableButtonNode() let buttonIcon: UIImage? let graphics = PresentationResourcesChat.additionalGraphics(item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper) - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { buttonIcon = graphics.chatBubbleNavigateButtonImage } else { buttonIcon = graphics.chatBubbleShareButtonImage @@ -304,7 +304,7 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { var maxContentWidth = videoLayout.contentSize.width var actionButtonsFinalize: ((CGFloat) -> (CGSize, (_ animated: Bool) -> ChatMessageActionButtonsNode))? if let replyMarkup = replyMarkup { - let (minWidth, buttonsLayout) = actionButtonsLayout(item.account, item.presentationData.theme, item.presentationData.strings, replyMarkup, item.message, maxContentWidth) + let (minWidth, buttonsLayout) = actionButtonsLayout(item.context, item.presentationData.theme, item.presentationData.strings, replyMarkup, item.message, maxContentWidth) maxContentWidth = max(maxContentWidth, minWidth) actionButtonsFinalize = buttonsLayout } @@ -481,7 +481,7 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { if let avatarNode = self.accessoryItemNode as? ChatMessageAvatarAccessoryItemNode, avatarNode.frame.contains(location) { if let item = self.item, let author = item.content.firstMessage.author { let navigate: ChatControllerInteractionNavigateToPeer - if item.content.firstMessage.id.peerId == item.account.peerId { + if item.content.firstMessage.id.peerId == item.context.account.peerId { navigate = .chat(textInputState: nil, messageId: nil) } else { navigate = .info @@ -529,7 +529,7 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { @objc func shareButtonPressed() { if let item = self.item { - if item.content.firstMessage.id.peerId == item.account.peerId { + if item.content.firstMessage.id.peerId == item.context.account.peerId { for attribute in item.content.firstMessage.attributes { if let attribute = attribute as? SourceReferenceMessageAttribute { item.controllerInteraction.navigateToMessage(item.content.firstMessage.id, attribute.messageId) @@ -625,7 +625,7 @@ class ChatMessageInstantVideoItemNode: ChatMessageItemView { var incoming = true selected = selectionState.selectedIds.contains(item.message.id) - incoming = item.message.effectivelyIncoming(item.account.peerId) + incoming = item.message.effectivelyIncoming(item.context.account.peerId) let offset: CGFloat = incoming ? 42.0 : 0.0 diff --git a/TelegramUI/ChatMessageInteractiveFileNode.swift b/TelegramUI/ChatMessageInteractiveFileNode.swift index e8bf43a6ec..3422402377 100644 --- a/TelegramUI/ChatMessageInteractiveFileNode.swift +++ b/TelegramUI/ChatMessageInteractiveFileNode.swift @@ -41,7 +41,7 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { var activateLocalContent: () -> Void = { } var requestUpdateLayout: (Bool) -> Void = { _ in } - private var account: Account? + private var context: AccountContext? private var message: Message? private var themeAndStrings: (ChatPresentationThemeData, PresentationStrings)? private var file: TelegramMediaFile? @@ -129,9 +129,9 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { if let resourceStatus = self.resourceStatus { switch resourceStatus.mediaStatus { case let .fetchStatus(fetchStatus): - if let account = self.account, let message = self.message, message.flags.isSending { - let _ = account.postbox.transaction({ transaction -> Void in - deleteMessages(transaction: transaction, mediaBox: account.postbox.mediaBox, ids: [message.id]) + if let context = self.context, let message = self.message, message.flags.isSending { + let _ = context.account.postbox.transaction({ transaction -> Void in + deleteMessages(transaction: transaction, mediaBox: context.account.postbox.mediaBox, ids: [message.id]) }).start() } else { switch fetchStatus { @@ -148,8 +148,8 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { } } case .playbackStatus: - if let account = self.account, let applicationContext = account.applicationContext as? TelegramApplicationContext, let message = self.message, let type = peerMessageMediaPlayerType(message) { - applicationContext.mediaManager?.playlistControl(.playback(.togglePlayPause), type: type) + if let context = context, let message = self.message, let type = peerMessageMediaPlayerType(message) { + context.mediaManager.playlistControl(.playback(.togglePlayPause), type: type) } } } @@ -165,7 +165,7 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { } } - func asyncLayout() -> (_ account: Account, _ presentationData: ChatPresentationData, _ message: Message, _ file: TelegramMediaFile, _ automaticDownload: Bool, _ incoming: Bool, _ isRecentActions: Bool, _ dateAndStatusType: ChatMessageDateAndStatusType?, _ constrainedSize: CGSize) -> (CGFloat, (CGSize) -> (CGFloat, (CGFloat) -> (CGSize, () -> Void))) { + func asyncLayout() -> (_ context: AccountContext, _ presentationData: ChatPresentationData, _ message: Message, _ file: TelegramMediaFile, _ automaticDownload: Bool, _ incoming: Bool, _ isRecentActions: Bool, _ dateAndStatusType: ChatMessageDateAndStatusType?, _ constrainedSize: CGSize) -> (CGFloat, (CGSize) -> (CGFloat, (CGFloat) -> (CGSize, () -> Void))) { let currentFile = self.file let titleAsyncLayout = TextNode.asyncLayout(self.titleNode) @@ -176,7 +176,7 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { let currentMessage = self.message let currentTheme = self.themeAndStrings?.0 - return { account, presentationData, message, file, automaticDownload, incoming, isRecentActions, dateAndStatusType, constrainedSize in + return { context, presentationData, message, file, automaticDownload, incoming, isRecentActions, dateAndStatusType, constrainedSize in return (CGFloat.greatestFiniteMagnitude, { constrainedSize in var updateImageSignal: Signal<(TransformImageArguments) -> DrawingContext?, NoError>? var updatedStatusSignal: Signal? @@ -199,21 +199,21 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { if mediaUpdated { if largestImageRepresentation(file.previewRepresentations) != nil || file.immediateThumbnailData != nil { - updateImageSignal = chatMessageImageFile(account: account, fileReference: .message(message: MessageReference(message), media: file), thumbnail: true) + updateImageSignal = chatMessageImageFile(account: context.account, fileReference: .message(message: MessageReference(message), media: file), thumbnail: true) } updatedFetchControls = FetchControls(fetch: { [weak self] in if let strongSelf = self { - strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: account, message: message, file: file, userInitiated: true).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: file, userInitiated: true).start()) } }, cancel: { - messageMediaFileCancelInteractiveFetch(account: account, messageId: message.id, file: file) + messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: file) }) } if statusUpdated { - updatedStatusSignal = messageFileMediaResourceStatus(account: account, file: file, message: message, isRecentActions: isRecentActions) - updatedPlaybackStatusSignal = messageFileMediaPlaybackStatus(account: account, file: file, message: message, isRecentActions: isRecentActions) + updatedStatusSignal = messageFileMediaResourceStatus(account: context.account, file: file, message: message, isRecentActions: isRecentActions) + updatedPlaybackStatusSignal = messageFileMediaPlaybackStatus(account: context.account, file: file, message: message, isRecentActions: isRecentActions) } var statusSize: CGSize? @@ -469,7 +469,7 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { return (fittedLayoutSize, { [weak self] in if let strongSelf = self { - strongSelf.account = account + strongSelf.context = context strongSelf.themeAndStrings = (presentationData.theme, presentationData.strings) strongSelf.message = message strongSelf.file = file @@ -510,8 +510,8 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { let waveformScrubbingNode = MediaPlayerScrubbingNode(content: .custom(backgroundNode: strongSelf.waveformNode, foregroundContentNode: strongSelf.waveformForegroundNode)) waveformScrubbingNode.hitTestSlop = UIEdgeInsetsMake(-10.0, 0.0, -10.0, 0.0) waveformScrubbingNode.seek = { timestamp in - if let strongSelf = self, let account = strongSelf.account, let message = strongSelf.message, let type = peerMessageMediaPlayerType(message) { - account.telegramApplicationContext.mediaManager?.playlistControl(.seek(timestamp), type: type) + if let strongSelf = self, let context = strongSelf.context, let message = strongSelf.message, let type = peerMessageMediaPlayerType(message) { + context.mediaManager.playlistControl(.seek(timestamp), type: type) } } waveformScrubbingNode.status = strongSelf.playbackStatus.get() @@ -625,7 +625,7 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { guard let message = self.message else { return } - guard let account = self.account else { + guard let context = self.context else { return } guard let presentationData = self.themeAndStrings?.0 else { @@ -637,7 +637,7 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { guard let file = self.file else { return } - let incoming = message.effectivelyIncoming(account.peerId) + let incoming = message.effectivelyIncoming(context.account.peerId) let bubbleTheme = presentationData.theme.chat.bubble var isAudio = false @@ -821,12 +821,12 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { self.fetchingCompactTextNode.frame = CGRect(origin: self.descriptionNode.frame.origin, size: fetchingCompactSize) } - static func asyncLayout(_ node: ChatMessageInteractiveFileNode?) -> (_ account: Account, _ presentationData: ChatPresentationData, _ message: Message, _ file: TelegramMediaFile, _ automaticDownload: Bool, _ incoming: Bool, _ isRecentActions: Bool, _ dateAndStatusType: ChatMessageDateAndStatusType?, _ constrainedSize: CGSize) -> (CGFloat, (CGSize) -> (CGFloat, (CGFloat) -> (CGSize, () -> ChatMessageInteractiveFileNode))) { + static func asyncLayout(_ node: ChatMessageInteractiveFileNode?) -> (_ context: AccountContext, _ presentationData: ChatPresentationData, _ message: Message, _ file: TelegramMediaFile, _ automaticDownload: Bool, _ incoming: Bool, _ isRecentActions: Bool, _ dateAndStatusType: ChatMessageDateAndStatusType?, _ constrainedSize: CGSize) -> (CGFloat, (CGSize) -> (CGFloat, (CGFloat) -> (CGSize, () -> ChatMessageInteractiveFileNode))) { let currentAsyncLayout = node?.asyncLayout() - return { account, presentationData, message, file, automaticDownload, incoming, isRecentActions, dateAndStatusType, constrainedSize in + return { context, presentationData, message, file, automaticDownload, incoming, isRecentActions, dateAndStatusType, constrainedSize in var fileNode: ChatMessageInteractiveFileNode - var fileLayout: (_ account: Account, _ presentationData: ChatPresentationData, _ message: Message, _ file: TelegramMediaFile, _ automaticDownload: Bool, _ incoming: Bool, _ isRecentActions: Bool, _ dateAndStatusType: ChatMessageDateAndStatusType?, _ constrainedSize: CGSize) -> (CGFloat, (CGSize) -> (CGFloat, (CGFloat) -> (CGSize, () -> Void))) + var fileLayout: (_ context: AccountContext, _ presentationData: ChatPresentationData, _ message: Message, _ file: TelegramMediaFile, _ automaticDownload: Bool, _ incoming: Bool, _ isRecentActions: Bool, _ dateAndStatusType: ChatMessageDateAndStatusType?, _ constrainedSize: CGSize) -> (CGFloat, (CGSize) -> (CGFloat, (CGFloat) -> (CGSize, () -> Void))) if let node = node, let currentAsyncLayout = currentAsyncLayout { fileNode = node @@ -836,7 +836,7 @@ final class ChatMessageInteractiveFileNode: ASDisplayNode { fileLayout = fileNode.asyncLayout() } - let (initialWidth, continueLayout) = fileLayout(account, presentationData, message, file, automaticDownload, incoming, isRecentActions, dateAndStatusType, constrainedSize) + let (initialWidth, continueLayout) = fileLayout(context, presentationData, message, file, automaticDownload, incoming, isRecentActions, dateAndStatusType, constrainedSize) return (initialWidth, { constrainedSize in let (finalWidth, finalLayout) = continueLayout(constrainedSize) diff --git a/TelegramUI/ChatMessageInteractiveInstantVideoNode.swift b/TelegramUI/ChatMessageInteractiveInstantVideoNode.swift index 4fabdd384d..6c92f801ce 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.account, file: updatedFile, message: item.message, isRecentActions: item.associatedData.isRecentActions), item.account.pendingMessageManager.pendingMessageStatus(item.message.id)) + updatedPlaybackStatus = combineLatest(messageFileMediaResourceStatus(account: item.context.account, 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 @@ -200,7 +200,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { let arguments = TransformImageArguments(corners: ImageCorners(radius: videoFrame.size.width / 2.0), imageSize: videoFrame.size, boundingSize: videoFrame.size, intrinsicInsets: UIEdgeInsets()) let statusType: ChatMessageDateAndStatusType - if item.message.effectivelyIncoming(item.account.peerId) { + if item.message.effectivelyIncoming(item.context.account.peerId) { switch statusDisplayType { case .free: statusType = .FreeIncoming @@ -306,7 +306,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { if let updatedFile = updatedFile, updatedMedia { if let resource = updatedFile.previewRepresentations.first?.resource { - strongSelf.fetchedThumbnailDisposable.set(fetchedMediaResource(postbox: item.account.postbox, reference: FileMediaReference.message(message: MessageReference(item.message), media: updatedFile).resourceReference(resource)).start()) + strongSelf.fetchedThumbnailDisposable.set(fetchedMediaResource(postbox: item.context.account.postbox, reference: FileMediaReference.message(message: MessageReference(item.message), media: updatedFile).resourceReference(resource)).start()) } else { strongSelf.fetchedThumbnailDisposable.set(nil) } @@ -336,7 +336,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { durationFillColor = serviceColor.fill case .bubble: durationFillColor = .clear - if item.message.effectivelyIncoming(item.account.peerId) { + if item.message.effectivelyIncoming(item.context.account.peerId) { durationTextColor = theme.theme.chat.bubble.incomingSecondaryTextColor } else { durationTextColor = theme.theme.chat.bubble.outgoingSecondaryTextColor @@ -359,33 +359,30 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { videoNode?.removeFromSupernode() }) } - if let mediaManager = item.account.telegramApplicationContext.mediaManager { - let videoNode = UniversalVideoNode(postbox: item.account.postbox, audioSession: mediaManager.audioSession, manager: mediaManager.universalVideoManager, decoration: ChatBubbleInstantVideoDecoration(diameter: displaySize.width + 2.0, backgroundImage: instantVideoBackgroundImage, tapped: { - if let strongSelf = self { - if let item = strongSelf.item { - if strongSelf.infoBackgroundNode.alpha.isZero { - item.account.telegramApplicationContext.mediaManager?.playlistControl(.playback(.togglePlayPause), type: .voice) - } else { - //let _ = item.controllerInteraction.openMessage(item.message) - } + let mediaManager = item.context.mediaManager + let videoNode = UniversalVideoNode(postbox: item.context.account.postbox, audioSession: mediaManager.audioSession, manager: mediaManager.universalVideoManager, decoration: ChatBubbleInstantVideoDecoration(diameter: displaySize.width + 2.0, backgroundImage: instantVideoBackgroundImage, tapped: { + if let strongSelf = self { + if let item = strongSelf.item { + if strongSelf.infoBackgroundNode.alpha.isZero { + item.context.account.telegramApplicationContext.mediaManager?.playlistControl(.playback(.togglePlayPause), type: .voice) + } else { + //let _ = item.controllerInteraction.openMessage(item.message) } } - }), content: NativeVideoContent(id: .message(item.message.id, item.message.stableId, telegramFile.fileId), fileReference: .message(message: MessageReference(item.message), media: telegramFile), streamVideo: false, enableSound: false, fetchAutomatically: false), priority: .embedded, autoplay: true) - let previousVideoNode = strongSelf.videoNode - strongSelf.videoNode = videoNode - strongSelf.insertSubnode(videoNode, belowSubnode: previousVideoNode ?? strongSelf.dateAndStatusNode) - videoNode.canAttachContent = strongSelf.shouldAcquireVideoContext - - if isSecretMedia { - let updatedSecretPlaceholderSignal = chatSecretMessageVideo(account: item.account, videoReference: .message(message: MessageReference(item.message), media: telegramFile)) - strongSelf.secretVideoPlaceholder.setSignal(updatedSecretPlaceholderSignal) - if strongSelf.secretVideoPlaceholder.supernode == nil { - strongSelf.insertSubnode(strongSelf.secretVideoPlaceholderBackground, belowSubnode: videoNode) - strongSelf.insertSubnode(strongSelf.secretVideoPlaceholder, belowSubnode: videoNode) - } } - } else { - strongSelf.secretVideoPlaceholder.removeFromSupernode() + }), content: NativeVideoContent(id: .message(item.message.id, item.message.stableId, telegramFile.fileId), fileReference: .message(message: MessageReference(item.message), media: telegramFile), streamVideo: false, enableSound: false, fetchAutomatically: false), priority: .embedded, autoplay: true) + let previousVideoNode = strongSelf.videoNode + strongSelf.videoNode = videoNode + strongSelf.insertSubnode(videoNode, belowSubnode: previousVideoNode ?? strongSelf.dateAndStatusNode) + videoNode.canAttachContent = strongSelf.shouldAcquireVideoContext + + if isSecretMedia { + let updatedSecretPlaceholderSignal = chatSecretMessageVideo(account: item.context.account, videoReference: .message(message: MessageReference(item.message), media: telegramFile)) + strongSelf.secretVideoPlaceholder.setSignal(updatedSecretPlaceholderSignal) + if strongSelf.secretVideoPlaceholder.supernode == nil { + strongSelf.insertSubnode(strongSelf.secretVideoPlaceholderBackground, belowSubnode: videoNode) + strongSelf.insertSubnode(strongSelf.secretVideoPlaceholder, belowSubnode: videoNode) + } } } @@ -410,7 +407,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { strongSelf.updateStatus() if let telegramFile = updatedFile, previousAutomaticDownload != automaticDownload, automaticDownload { - strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: item.account, message: item.message, file: telegramFile, userInitiated: false).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: item.context.account, message: item.message, file: telegramFile, userInitiated: false).start()) } } }) @@ -548,7 +545,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { } playbackStatusNode.frame = videoFrame.insetBy(dx: 1.5, dy: 1.5) - let status = messageFileMediaPlaybackStatus(account: item.account, file: file, message: item.message, isRecentActions: item.associatedData.isRecentActions) + let status = messageFileMediaPlaybackStatus(account: item.context.account, file: file, message: item.message, isRecentActions: item.associatedData.isRecentActions) playbackStatusNode.status = status self.durationNode?.status = status |> map(Optional.init) @@ -606,7 +603,7 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { return } if self.infoBackgroundNode.alpha.isZero { - item.account.telegramApplicationContext.mediaManager?.playlistControl(.playback(.togglePlayPause), type: .voice) + item.context.mediaManager.playlistControl(.playback(.togglePlayPause), type: .voice) } else { let _ = item.controllerInteraction.openMessage(item.message, .default) } @@ -636,11 +633,11 @@ class ChatMessageInteractiveInstantVideoNode: ASDisplayNode { case .Fetching: if item.message.flags.isSending { let messageId = item.message.id - let _ = item.account.postbox.transaction({ transaction -> Void in - deleteMessages(transaction: transaction, mediaBox: item.account.postbox.mediaBox, ids: [messageId]) + let _ = item.context.account.postbox.transaction({ transaction -> Void in + deleteMessages(transaction: transaction, mediaBox: item.context.account.postbox.mediaBox, ids: [messageId]) }).start() } else { - messageMediaFileCancelInteractiveFetch(account: item.account, messageId: item.message.id, file: file) + messageMediaFileCancelInteractiveFetch(account: item.context.account, messageId: item.message.id, file: file) } case .Remote: self.videoNode?.fetchControl(.fetch) diff --git a/TelegramUI/ChatMessageInteractiveMediaLabelNode.swift b/TelegramUI/ChatMessageInteractiveMediaLabelNode.swift deleted file mode 100644 index 0f227dab93..0000000000 --- a/TelegramUI/ChatMessageInteractiveMediaLabelNode.swift +++ /dev/null @@ -1,24 +0,0 @@ -import Foundation -import AsyncDisplayKit -import Display - -final class ChatMessageInteractiveMediaLabelNode: ASDisplayNode { - private let backgroundNode: ASImageNode - private let textNode: TextNode - - override init() { - self.backgroundNode = ASImageNode() - self.backgroundNode.isLayerBacked = true - self.backgroundNode.displayWithoutProcessing = true - self.backgroundNode.displaysAsynchronously = false - - self.textNode = TextNode() - - super.init() - - self.addSubnode(self.backgroundNode) - self.addSubnode(self.textNode) - } - - -} diff --git a/TelegramUI/ChatMessageInteractiveMediaNode.swift b/TelegramUI/ChatMessageInteractiveMediaNode.swift index f8433e14c4..5d4cbfb5c9 100644 --- a/TelegramUI/ChatMessageInteractiveMediaNode.swift +++ b/TelegramUI/ChatMessageInteractiveMediaNode.swift @@ -26,10 +26,9 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { private var videoNode: UniversalVideoNode? private var statusNode: RadialStatusNode? private var badgeNode: ChatMessageInteractiveMediaBadge? - private var labelNode: ChatMessageInteractiveMediaLabelNode? private var tapRecognizer: UITapGestureRecognizer? - private var account: Account? + private var context: AccountContext? private var message: Message? private var media: Media? private var themeAndStrings: (PresentationTheme, PresentationStrings)? @@ -100,15 +99,15 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { switch fetchStatus { case .Fetching: - if let account = self.account, let message = self.message, message.flags.isSending { - let _ = account.postbox.transaction({ transaction -> Void in - deleteMessages(transaction: transaction, mediaBox: account.postbox.mediaBox, ids: [message.id]) + if let context = self.context, let message = self.message, message.flags.isSending { + let _ = context.account.postbox.transaction({ transaction -> Void in + deleteMessages(transaction: transaction, mediaBox: context.account.postbox.mediaBox, ids: [message.id]) }).start() - } else if let media = media, let account = self.account, let message = message { + } else if let media = media, let context = self.context, let message = message { if let media = media as? TelegramMediaFile { - messageMediaFileCancelInteractiveFetch(account: account, messageId: message.id, file: media) + messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: media) } else if let media = media as? TelegramMediaImage, let resource = largestImageRepresentation(media.representations)?.resource { - messageMediaImageCancelInteractiveFetch(account: account, messageId: message.id, image: media, resource: resource) + messageMediaImageCancelInteractiveFetch(account: context.account, messageId: message.id, image: media, resource: resource) } } if let cancel = self.fetchControls.with({ return $0?.cancel }) { @@ -141,7 +140,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { } } - func asyncLayout() -> (_ account: Account, _ theme: PresentationTheme, _ strings: PresentationStrings, _ message: Message, _ media: Media, _ automaticDownload: Bool, _ peerType: AutomaticMediaDownloadPeerType, _ automaticPlayback: Bool, _ sizeCalculation: InteractiveMediaNodeSizeCalculation, _ layoutConstants: ChatMessageItemLayoutConstants) -> (CGSize, CGFloat, (CGSize, ImageCorners) -> (CGFloat, (CGFloat) -> (CGSize, (ContainedViewLayoutTransition, Bool) -> Void))) { + func asyncLayout() -> (_ context: AccountContext, _ theme: PresentationTheme, _ strings: PresentationStrings, _ message: Message, _ media: Media, _ automaticDownload: Bool, _ peerType: AutomaticMediaDownloadPeerType, _ automaticPlayback: Bool, _ sizeCalculation: InteractiveMediaNodeSizeCalculation, _ layoutConstants: ChatMessageItemLayoutConstants) -> (CGSize, CGFloat, (CGSize, ImageCorners) -> (CGFloat, (CGFloat) -> (CGSize, (ContainedViewLayoutTransition, Bool) -> Void))) { let currentMessage = self.message let currentMedia = self.media let imageLayout = self.imageNode.asyncLayout() @@ -150,7 +149,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { let hasCurrentVideoNode = currentVideoNode != nil let previousAutomaticDownload = self.automaticDownload - return { [weak self] account, theme, strings, message, media, automaticDownload, peerType, automaticPlayback, sizeCalculation, layoutConstants in + return { [weak self] context, theme, strings, message, media, automaticDownload, peerType, automaticPlayback, sizeCalculation, layoutConstants in var nativeSize: CGSize let isSecretMedia = message.containsSecretMedia @@ -280,7 +279,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { } if isSecretMedia { updateImageSignal = { synchronousLoad in - return chatSecretPhoto(account: account, photoReference: .message(message: MessageReference(message), media: image)) + return chatSecretPhoto(account: context.account, photoReference: .message(message: MessageReference(message), media: image)) } } else { let tinyThumbnailData: TinyThumbnailData? @@ -290,22 +289,22 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { tinyThumbnailData = nil } updateImageSignal = { synchronousLoad in - return chatMessagePhoto(postbox: account.postbox, photoReference: .message(message: MessageReference(message), media: image), synchronousLoad: synchronousLoad, tinyThumbnailData: tinyThumbnailData) + return chatMessagePhoto(postbox: context.account.postbox, photoReference: .message(message: MessageReference(message), media: image), synchronousLoad: synchronousLoad, tinyThumbnailData: tinyThumbnailData) } } updatedFetchControls = FetchControls(fetch: { manual in if let strongSelf = self { if !manual { - strongSelf.fetchDisposable.set(chatMessagePhotoInteractiveFetched(account: account, photoReference: .message(message: MessageReference(message), media: image), storeToDownloadsPeerType: storeToDownloadsPeerType).start()) + strongSelf.fetchDisposable.set(chatMessagePhotoInteractiveFetched(account: context.account, photoReference: .message(message: MessageReference(message), media: image), storeToDownloadsPeerType: storeToDownloadsPeerType).start()) } else if let resource = largestRepresentationForPhoto(image)?.resource { - strongSelf.fetchDisposable.set(messageMediaImageInteractiveFetched(account: account, message: message, image: image, resource: resource, storeToDownloadsPeerType: storeToDownloadsPeerType).start()) + strongSelf.fetchDisposable.set(messageMediaImageInteractiveFetched(account: context.account, message: message, image: image, resource: resource, storeToDownloadsPeerType: storeToDownloadsPeerType).start()) } } }, cancel: { - chatMessagePhotoCancelInteractiveFetch(account: account, photoReference: .message(message: MessageReference(message), media: image)) + chatMessagePhotoCancelInteractiveFetch(account: context.account, photoReference: .message(message: MessageReference(message), media: image)) if let resource = largestRepresentationForPhoto(image)?.resource { - messageMediaImageCancelInteractiveFetch(account: account, messageId: message.id, image: image, resource: resource) + messageMediaImageCancelInteractiveFetch(account: context.account, messageId: message.id, image: image, resource: resource) } }) } else if let image = media as? TelegramMediaWebFile { @@ -313,29 +312,29 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { replaceVideoNode = true } updateImageSignal = { synchronousLoad in - return chatWebFileImage(account: account, file: image) + return chatWebFileImage(account: context.account, file: image) } updatedFetchControls = FetchControls(fetch: { _ in if let strongSelf = self { - strongSelf.fetchDisposable.set(chatMessageWebFileInteractiveFetched(account: account, image: image).start()) + strongSelf.fetchDisposable.set(chatMessageWebFileInteractiveFetched(account: context.account, image: image).start()) } }, cancel: { - chatMessageWebFileCancelInteractiveFetch(account: account, image: image) + chatMessageWebFileCancelInteractiveFetch(account: context.account, image: image) }) } else if let file = media as? TelegramMediaFile { if isSecretMedia { updateImageSignal = { synchronousLoad in - return chatSecretMessageVideo(account: account, videoReference: .message(message: MessageReference(message), media: file)) + return chatSecretMessageVideo(account: context.account, videoReference: .message(message: MessageReference(message), media: file)) } } else { if file.isSticker { updateImageSignal = { synchronousLoad in - return chatMessageSticker(account: account, file: file, small: false) + return chatMessageSticker(account: context.account, file: file, small: false) } } else { updateImageSignal = { synchronousLoad in - return mediaGridMessageVideo(postbox: account.postbox, videoReference: .message(message: MessageReference(message), media: file), onlyFullSize: currentMedia?.id?.namespace == Namespaces.Media.LocalFile) + return mediaGridMessageVideo(postbox: context.account.postbox, videoReference: .message(message: MessageReference(message), media: file), onlyFullSize: currentMedia?.id?.namespace == Namespaces.Media.LocalFile) } } } @@ -358,16 +357,16 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { updatedFetchControls = FetchControls(fetch: { manual in if let strongSelf = self { if file.isAnimated { - strongSelf.fetchDisposable.set(fetchedMediaResource(postbox: account.postbox, reference: AnyMediaReference.message(message: MessageReference(message), media: file).resourceReference(file.resource), statsCategory: statsCategoryForFileWithAttributes(file.attributes)).start()) + 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: account, message: message, file: file, userInitiated: manual).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: file, userInitiated: manual).start()) } } }, cancel: { if file.isAnimated { - account.postbox.mediaBox.cancelInteractiveResourceFetch(file.resource) + context.account.postbox.mediaBox.cancelInteractiveResourceFetch(file.resource) } else { - messageMediaFileCancelInteractiveFetch(account: account, messageId: message.id, file: file) + messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: file) } }) } @@ -376,7 +375,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { if statusUpdated { if let image = media as? TelegramMediaImage { if message.flags.isSending { - updatedStatusSignal = combineLatest(chatMessagePhotoStatus(account: account, messageId: message.id, photoReference: .message(message: MessageReference(message), media: image)), account.pendingMessageManager.pendingMessageStatus(message.id)) + updatedStatusSignal = combineLatest(chatMessagePhotoStatus(account: context.account, 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) @@ -386,10 +385,10 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { } } } else { - updatedStatusSignal = chatMessagePhotoStatus(account: account, messageId: message.id, photoReference: .message(message: MessageReference(message), media: image)) + updatedStatusSignal = chatMessagePhotoStatus(account: context.account, messageId: message.id, photoReference: .message(message: MessageReference(message), media: image)) } } else if let file = media as? TelegramMediaFile { - updatedStatusSignal = combineLatest(messageMediaFileStatus(account: account, messageId: message.id, file: file), account.pendingMessageManager.pendingMessageStatus(message.id)) + updatedStatusSignal = combineLatest(messageMediaFileStatus(account: context.account, messageId: message.id, file: file), account.pendingMessageManager.pendingMessageStatus(message.id)) |> map { resourceStatus, pendingStatus -> MediaResourceStatus in if let pendingStatus = pendingStatus { let adjustedProgress = max(pendingStatus.progress, 0.027) @@ -401,7 +400,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { } } - let arguments = TransformImageArguments(corners: corners, imageSize: drawingSize, boundingSize: boundingSize, intrinsicInsets: UIEdgeInsets(), resizeMode: isInlinePlayableVideo ? .fill(.black) : .blurBackground, emptyColor: message.effectivelyIncoming(account.peerId) ? theme.chat.bubble.incomingMediaPlaceholderColor : theme.chat.bubble.outgoingMediaPlaceholderColor) + let arguments = TransformImageArguments(corners: corners, imageSize: drawingSize, boundingSize: boundingSize, intrinsicInsets: UIEdgeInsets(), resizeMode: isInlinePlayableVideo ? .fill(.black) : .blurBackground, emptyColor: message.effectivelyIncoming(context.account.peerId) ? theme.chat.bubble.incomingMediaPlaceholderColor : theme.chat.bubble.outgoingMediaPlaceholderColor) let imageFrame = CGRect(origin: CGPoint(x: -arguments.insets.left, y: -arguments.insets.top), size: arguments.drawingSize) @@ -409,7 +408,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { return (boundingSize, { transition, synchronousLoads in if let strongSelf = self { - strongSelf.account = account + strongSelf.context = context strongSelf.message = message strongSelf.media = media strongSelf.themeAndStrings = (theme, strings) @@ -443,9 +442,10 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { strongSelf.videoNode = nil } - if replaceVideoNode, let updatedVideoFile = updateVideoFile, let mediaManager = account.telegramApplicationContext.mediaManager { + if replaceVideoNode, let updatedVideoFile = updateVideoFile { + let mediaManager = context.mediaManager let cornerRadius: CGFloat = arguments.corners.topLeft.radius - let videoNode = UniversalVideoNode(postbox: account.postbox, audioSession: mediaManager.audioSession, manager: mediaManager.universalVideoManager, decoration: ChatBubbleVideoDecoration(cornerRadius: cornerRadius, nativeSize: nativeSize, backgroudColor: arguments.emptyColor ?? .black), content: NativeVideoContent(id: .message(message.id, message.stableId, updatedVideoFile.fileId), fileReference: .message(message: MessageReference(message), media: updatedVideoFile), enableSound: false, fetchAutomatically: false), priority: .embedded) + let videoNode = UniversalVideoNode(postbox: context.account.postbox, audioSession: mediaManager.audioSession, manager: mediaManager.universalVideoManager, decoration: ChatBubbleVideoDecoration(cornerRadius: cornerRadius, nativeSize: nativeSize, backgroudColor: arguments.emptyColor ?? .black), content: NativeVideoContent(id: .message(message.id, message.stableId, updatedVideoFile.fileId), fileReference: .message(message: MessageReference(message), media: updatedVideoFile), enableSound: false, fetchAutomatically: false), priority: .embedded) videoNode.isUserInteractionEnabled = false strongSelf.videoNode = videoNode @@ -497,10 +497,10 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { if let _ = media as? TelegramMediaImage { updatedFetchControls.fetch(false) } else if let image = media as? TelegramMediaWebFile { - strongSelf.fetchDisposable.set(chatMessageWebFileInteractiveFetched(account: account, image: image).start()) + 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: account, message: message, file: file, userInitiated: false).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: file, userInitiated: false).start()) } } } @@ -792,12 +792,12 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { } } - static func asyncLayout(_ node: ChatMessageInteractiveMediaNode?) -> (_ account: Account, _ theme: PresentationTheme, _ strings: PresentationStrings, _ message: Message, _ media: Media, _ automaticDownload: Bool, _ peerType: AutomaticMediaDownloadPeerType, _ automaticPlayback: Bool, _ sizeCalculation: InteractiveMediaNodeSizeCalculation, _ layoutConstants: ChatMessageItemLayoutConstants) -> (CGSize, CGFloat, (CGSize, ImageCorners) -> (CGFloat, (CGFloat) -> (CGSize, (ContainedViewLayoutTransition, Bool) -> ChatMessageInteractiveMediaNode))) { + static func asyncLayout(_ node: ChatMessageInteractiveMediaNode?) -> (_ context: AccountContext, _ theme: PresentationTheme, _ strings: PresentationStrings, _ message: Message, _ media: Media, _ automaticDownload: Bool, _ peerType: AutomaticMediaDownloadPeerType, _ automaticPlayback: Bool, _ sizeCalculation: InteractiveMediaNodeSizeCalculation, _ layoutConstants: ChatMessageItemLayoutConstants) -> (CGSize, CGFloat, (CGSize, ImageCorners) -> (CGFloat, (CGFloat) -> (CGSize, (ContainedViewLayoutTransition, Bool) -> ChatMessageInteractiveMediaNode))) { let currentAsyncLayout = node?.asyncLayout() - return { account, theme, strings, message, media, automaticDownload, peerType, automaticPlayback, sizeCalculation, layoutConstants in + return { context, theme, strings, message, media, automaticDownload, peerType, automaticPlayback, sizeCalculation, layoutConstants in var imageNode: ChatMessageInteractiveMediaNode - var imageLayout: (_ account: Account, _ theme: PresentationTheme, _ strings: PresentationStrings, _ message: Message, _ media: Media, _ automaticDownload: Bool, _ peerType: AutomaticMediaDownloadPeerType, _ automaticPlayback: Bool, _ sizeCalculation: InteractiveMediaNodeSizeCalculation, _ layoutConstants: ChatMessageItemLayoutConstants) -> (CGSize, CGFloat, (CGSize, ImageCorners) -> (CGFloat, (CGFloat) -> (CGSize, (ContainedViewLayoutTransition, Bool) -> Void))) + var imageLayout: (_ context: AccountContext, _ theme: PresentationTheme, _ strings: PresentationStrings, _ message: Message, _ media: Media, _ automaticDownload: Bool, _ peerType: AutomaticMediaDownloadPeerType, _ automaticPlayback: Bool, _ sizeCalculation: InteractiveMediaNodeSizeCalculation, _ layoutConstants: ChatMessageItemLayoutConstants) -> (CGSize, CGFloat, (CGSize, ImageCorners) -> (CGFloat, (CGFloat) -> (CGSize, (ContainedViewLayoutTransition, Bool) -> Void))) if let node = node, let currentAsyncLayout = currentAsyncLayout { imageNode = node @@ -807,7 +807,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode { imageLayout = imageNode.asyncLayout() } - let (unboundSize, initialWidth, continueLayout) = imageLayout(account, theme, strings, message, media, automaticDownload, peerType, automaticPlayback, sizeCalculation, layoutConstants) + let (unboundSize, initialWidth, continueLayout) = imageLayout(context, theme, strings, message, media, automaticDownload, peerType, automaticPlayback, sizeCalculation, layoutConstants) return (unboundSize, initialWidth, { constrainedSize, corners in let (finalWidth, finalLayout) = continueLayout(constrainedSize, corners) diff --git a/TelegramUI/ChatMessageInvoiceBubbleContentNode.swift b/TelegramUI/ChatMessageInvoiceBubbleContentNode.swift index bb6d65f238..13dbad350f 100644 --- a/TelegramUI/ChatMessageInvoiceBubbleContentNode.swift +++ b/TelegramUI/ChatMessageInvoiceBubbleContentNode.swift @@ -70,7 +70,7 @@ final class ChatMessageInvoiceBubbleContentNode: ChatMessageBubbleContentNode { } } - let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, automaticDownloadSettings, item.associatedData, item.account, item.controllerInteraction, item.message, item.read, title, subtitle, text, nil, mediaAndFlags, nil, nil, false, layoutConstants, constrainedSize) + let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, automaticDownloadSettings, item.associatedData, item.context, item.controllerInteraction, item.message, item.read, title, subtitle, text, nil, mediaAndFlags, nil, nil, false, layoutConstants, constrainedSize) let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: false, headerSpacing: 8.0, hidesBackground: .never, forceFullCorners: false, forceAlignment: .none) diff --git a/TelegramUI/ChatMessageItem.swift b/TelegramUI/ChatMessageItem.swift index ec61b0dccd..98578d542c 100644 --- a/TelegramUI/ChatMessageItem.swift +++ b/TelegramUI/ChatMessageItem.swift @@ -214,7 +214,7 @@ public final class ChatMessageItemAssociatedData: Equatable { public final class ChatMessageItem: ListViewItem, CustomStringConvertible { let presentationData: ChatPresentationData - let account: Account + let context: AccountContext let chatLocation: ChatLocation let associatedData: ChatMessageItemAssociatedData let controllerInteraction: ChatControllerInteraction @@ -244,9 +244,9 @@ public final class ChatMessageItem: ListViewItem, CustomStringConvertible { } } - public init(presentationData: ChatPresentationData, account: Account, chatLocation: ChatLocation, associatedData: ChatMessageItemAssociatedData, controllerInteraction: ChatControllerInteraction, content: ChatMessageItemContent, disableDate: Bool = false, additionalContent: ChatMessageItemAdditionalContent? = nil) { + public init(presentationData: ChatPresentationData, context: AccountContext, chatLocation: ChatLocation, associatedData: ChatMessageItemAssociatedData, controllerInteraction: ChatControllerInteraction, content: ChatMessageItemContent, disableDate: Bool = false, additionalContent: ChatMessageItemAdditionalContent? = nil) { self.presentationData = presentationData - self.account = account + self.context = context self.chatLocation = chatLocation self.associatedData = associatedData self.controllerInteraction = controllerInteraction @@ -255,14 +255,14 @@ public final class ChatMessageItem: ListViewItem, CustomStringConvertible { self.additionalContent = additionalContent var accessoryItem: ListViewAccessoryItem? - let incoming = content.effectivelyIncoming(self.account.peerId) + let incoming = content.effectivelyIncoming(self.context.account.peerId) var effectiveAuthor: Peer? let displayAuthorInfo: Bool switch chatLocation { case let .peer(peerId): - if peerId == account.peerId { + if peerId == context.account.peerId { if let forwardInfo = content.firstMessage.forwardInfo { effectiveAuthor = forwardInfo.author } @@ -307,7 +307,7 @@ public final class ChatMessageItem: ListViewItem, CustomStringConvertible { } if !hasActionMedia && !isBroadcastChannel { if let effectiveAuthor = effectiveAuthor { - accessoryItem = ChatMessageAvatarAccessoryItem(account: account, peerId: effectiveAuthor.id, peer: effectiveAuthor, messageReference: MessageReference(message), messageTimestamp: content.index.timestamp, emptyColor: presentationData.theme.theme.chat.bubble.incoming.withoutWallpaper.fill) + accessoryItem = ChatMessageAvatarAccessoryItem(context: context, peerId: effectiveAuthor.id, peer: effectiveAuthor, messageReference: MessageReference(message), messageTimestamp: content.index.timestamp, emptyColor: presentationData.theme.theme.chat.bubble.incoming.withoutWallpaper.fill) } } } @@ -381,7 +381,7 @@ public final class ChatMessageItem: ListViewItem, CustomStringConvertible { if top.header.id != self.header.id { mergedBottom = .none } else { - mergedBottom = messagesShouldBeMerged(accountPeerId: self.account.peerId, message, top.message) + mergedBottom = messagesShouldBeMerged(accountPeerId: self.context.account.peerId, message, top.message) } } if let bottom = bottom as? ChatMessageItem { @@ -389,7 +389,7 @@ public final class ChatMessageItem: ListViewItem, CustomStringConvertible { mergedTop = .none dateAtBottom = true } else { - mergedTop = messagesShouldBeMerged(accountPeerId: self.account.peerId, bottom.message, message) + mergedTop = messagesShouldBeMerged(accountPeerId: self.context.account.peerId, bottom.message, message) } } else if let bottom = bottom as? ChatUnreadItem { if bottom.header.id != self.header.id { diff --git a/TelegramUI/ChatMessageMapBubbleContentNode.swift b/TelegramUI/ChatMessageMapBubbleContentNode.swift index a6f5968f14..a5705f58d6 100644 --- a/TelegramUI/ChatMessageMapBubbleContentNode.swift +++ b/TelegramUI/ChatMessageMapBubbleContentNode.swift @@ -93,12 +93,12 @@ class ChatMessageMapBubbleContentNode: ChatMessageBubbleContentNode { imageSize = CGSize(width: fitWidth, height: floor(fitWidth * 0.5)) if let venue = selectedMedia.venue { - titleString = NSAttributedString(string: venue.title, font: titleFont, textColor: item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingPrimaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingPrimaryTextColor) + titleString = NSAttributedString(string: venue.title, font: titleFont, textColor: item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingPrimaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingPrimaryTextColor) if let address = venue.address, !address.isEmpty { - textString = NSAttributedString(string: address, font: textFont, textColor: item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingSecondaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingSecondaryTextColor) + textString = NSAttributedString(string: address, font: textFont, textColor: item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingSecondaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingSecondaryTextColor) } } else { - textString = NSAttributedString(string: " ", font: textFont, textColor: item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingSecondaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingSecondaryTextColor) + textString = NSAttributedString(string: " ", font: textFont, textColor: item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingSecondaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingSecondaryTextColor) } } else { let fitWidth: CGFloat = min(constrainedSize.width, layoutConstants.image.maxDimensions.width) @@ -107,7 +107,7 @@ class ChatMessageMapBubbleContentNode: ChatMessageBubbleContentNode { } if selectedMedia.liveBroadcastingTimeout != nil { - titleString = NSAttributedString(string: item.presentationData.strings.Message_LiveLocation, font: liveTitleFont, textColor: item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingPrimaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingPrimaryTextColor) + titleString = NSAttributedString(string: item.presentationData.strings.Message_LiveLocation, font: liveTitleFont, textColor: item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingPrimaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingPrimaryTextColor) } } else { imageSize = CGSize(width: 75.0, height: 75.0) @@ -122,7 +122,7 @@ class ChatMessageMapBubbleContentNode: ChatMessageBubbleContentNode { } } if updated { - updateImageSignal = chatMapSnapshotImage(account: item.account, resource: MapSnapshotMediaResource(latitude: selectedMedia.latitude, longitude: selectedMedia.longitude, width: Int32(imageSize.width), height: Int32(imageSize.height))) + updateImageSignal = chatMapSnapshotImage(account: item.context.account, resource: MapSnapshotMediaResource(latitude: selectedMedia.latitude, longitude: selectedMedia.longitude, width: Int32(imageSize.width), height: Int32(imageSize.height))) } } @@ -143,7 +143,7 @@ class ChatMessageMapBubbleContentNode: ChatMessageBubbleContentNode { pinLiveLocationActive = activeLiveBroadcastingTimeout != nil } } - let (pinSize, pinApply) = makePinLayout(item.account, item.presentationData.theme.theme, pinPeer, pinLiveLocationActive) + let (pinSize, pinApply) = makePinLayout(item.context.account, item.presentationData.theme.theme, pinPeer, pinLiveLocationActive) return (contentProperties, nil, maximumWidth, { constrainedSize, position in let imageCorners: ImageCorners @@ -194,7 +194,7 @@ class ChatMessageMapBubbleContentNode: ChatMessageBubbleContentNode { switch position { case .linear(_, .None): if selectedMedia?.venue != nil || activeLiveBroadcastingTimeout != nil { - if item.message.effectivelyIncoming(item.account.peerId) { + if item.message.effectivelyIncoming(item.context.account.peerId) { statusType = .BubbleIncoming } else { if item.message.flags.contains(.Failed) { @@ -206,7 +206,7 @@ class ChatMessageMapBubbleContentNode: ChatMessageBubbleContentNode { } } } else { - if item.message.effectivelyIncoming(item.account.peerId) { + if item.message.effectivelyIncoming(item.context.account.peerId) { statusType = .ImageIncoming } else { if item.message.flags.contains(.Failed) { @@ -239,7 +239,7 @@ class ChatMessageMapBubbleContentNode: ChatMessageBubbleContentNode { } return (contentWidth, { boundingWidth in - let arguments = TransformImageArguments(corners: imageCorners, imageSize: imageSize, boundingSize: imageSize, intrinsicInsets: UIEdgeInsets(), emptyColor: item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingMediaPlaceholderColor : item.presentationData.theme.theme.chat.bubble.outgoingMediaPlaceholderColor) + let arguments = TransformImageArguments(corners: imageCorners, imageSize: imageSize, boundingSize: imageSize, intrinsicInsets: UIEdgeInsets(), emptyColor: item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingMediaPlaceholderColor : item.presentationData.theme.theme.chat.bubble.outgoingMediaPlaceholderColor) let imageLayoutSize = CGSize(width: imageSize.width + bubbleInsets.left + bubbleInsets.right, height: imageSize.height + bubbleInsets.top + bubbleInsets.bottom) @@ -339,8 +339,8 @@ class ChatMessageMapBubbleContentNode: ChatMessageBubbleContentNode { let timerSize = CGSize(width: 28.0, height: 28.0) strongSelf.liveTimerNode?.frame = CGRect(origin: CGPoint(x: floor(imageFrame.maxX - 10.0 - timerSize.width), y: floor(imageFrame.maxY + 11.0)), size: timerSize) - let timerForegroundColor: UIColor = item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingAccentControlColor : item.presentationData.theme.theme.chat.bubble.outgoingAccentControlColor - let timerTextColor: UIColor = item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingSecondaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingSecondaryTextColor + let timerForegroundColor: UIColor = item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingAccentControlColor : item.presentationData.theme.theme.chat.bubble.outgoingAccentControlColor + let timerTextColor: UIColor = item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingSecondaryTextColor : item.presentationData.theme.theme.chat.bubble.outgoingSecondaryTextColor strongSelf.liveTimerNode?.update(backgroundColor: timerForegroundColor.withAlphaComponent(0.4), foregroundColor: timerForegroundColor, textColor: timerTextColor, beginTimestamp: Double(item.message.timestamp), timeout: Double(activeLiveBroadcastingTimeout), strings: item.presentationData.strings) if strongSelf.liveTextNode == nil { diff --git a/TelegramUI/ChatMessageMediaBubbleContentNode.swift b/TelegramUI/ChatMessageMediaBubbleContentNode.swift index c4cf5f0d1b..fb4e8e79c4 100644 --- a/TelegramUI/ChatMessageMediaBubbleContentNode.swift +++ b/TelegramUI/ChatMessageMediaBubbleContentNode.swift @@ -86,7 +86,7 @@ class ChatMessageMediaBubbleContentNode: ChatMessageBubbleContentNode { sizeCalculation = .unconstrained } - let (unboundSize, initialWidth, refineLayout) = interactiveImageLayout(item.account, item.presentationData.theme.theme, item.presentationData.strings, item.message, selectedMedia!, automaticDownload, item.associatedData.automaticDownloadPeerType, item.controllerInteraction.automaticMediaDownloadSettings.autoplayGifs, sizeCalculation, layoutConstants) + let (unboundSize, initialWidth, refineLayout) = interactiveImageLayout(item.context, item.presentationData.theme.theme, item.presentationData.strings, item.message, selectedMedia!, automaticDownload, item.associatedData.automaticDownloadPeerType, item.controllerInteraction.automaticMediaDownloadSettings.autoplayGifs, sizeCalculation, layoutConstants) var forceFullCorners = false if let media = selectedMedia as? TelegramMediaFile, media.isAnimated { @@ -134,7 +134,7 @@ class ChatMessageMediaBubbleContentNode: ChatMessageBubbleContentNode { let statusType: ChatMessageDateAndStatusType? switch position { case .linear(_, .None): - if item.message.effectivelyIncoming(item.account.peerId) { + if item.message.effectivelyIncoming(item.context.account.peerId) { statusType = .ImageIncoming } else { if item.message.flags.contains(.Failed) { diff --git a/TelegramUI/ChatMessagePollBubbleContentNode.swift b/TelegramUI/ChatMessagePollBubbleContentNode.swift index ac202eea03..7414a3a77b 100644 --- a/TelegramUI/ChatMessagePollBubbleContentNode.swift +++ b/TelegramUI/ChatMessagePollBubbleContentNode.swift @@ -570,7 +570,7 @@ class ChatMessagePollBubbleContentNode: ChatMessageBubbleContentNode { return (contentProperties, nil, CGFloat.greatestFiniteMagnitude, { constrainedSize, position in let message = item.message - let incoming = item.message.effectivelyIncoming(item.account.peerId) + let incoming = item.message.effectivelyIncoming(item.context.account.peerId) let horizontalInset = layoutConstants.text.bubbleInsets.left + layoutConstants.text.bubbleInsets.right let textConstrainedSize = CGSize(width: constrainedSize.width - horizontalInset, height: constrainedSize.height) @@ -732,7 +732,7 @@ class ChatMessagePollBubbleContentNode: ChatMessageBubbleContentNode { } else if poll.isClosed { optionResult = ChatMessagePollOptionResult(normalized: 0, percent: 0) } - let result = makeLayout(item.account.peerId, item.presentationData, item.message, option, optionResult, constrainedSize.width - layoutConstants.bubble.borderInset * 2.0) + let result = makeLayout(item.context.account.peerId, item.presentationData, item.message, option, optionResult, constrainedSize.width - layoutConstants.bubble.borderInset * 2.0) boundingSize.width = max(boundingSize.width, result.minimumWidth + layoutConstants.bubble.borderInset * 2.0) pollOptionsFinalizeLayouts.append(result.1) } diff --git a/TelegramUI/ChatMessageReplyInfoNode.swift b/TelegramUI/ChatMessageReplyInfoNode.swift index 15be0c3cae..5822536b80 100644 --- a/TelegramUI/ChatMessageReplyInfoNode.swift +++ b/TelegramUI/ChatMessageReplyInfoNode.swift @@ -39,18 +39,18 @@ class ChatMessageReplyInfoNode: ASDisplayNode { self.contentNode.addSubnode(self.lineNode) } - class func asyncLayout(_ maybeNode: ChatMessageReplyInfoNode?) -> (_ theme: ChatPresentationData, _ strings: PresentationStrings, _ account: Account, _ type: ChatMessageReplyInfoType, _ message: Message, _ constrainedSize: CGSize) -> (CGSize, () -> ChatMessageReplyInfoNode) { + class func asyncLayout(_ maybeNode: ChatMessageReplyInfoNode?) -> (_ theme: ChatPresentationData, _ strings: PresentationStrings, _ context: AccountContext, _ type: ChatMessageReplyInfoType, _ message: Message, _ constrainedSize: CGSize) -> (CGSize, () -> ChatMessageReplyInfoNode) { let titleNodeLayout = TextNode.asyncLayout(maybeNode?.titleNode) let textNodeLayout = TextNode.asyncLayout(maybeNode?.textNode) let imageNodeLayout = TransformImageNode.asyncLayout(maybeNode?.imageNode) let previousMediaReference = maybeNode?.previousMediaReference - return { presentationData, strings, account, type, message, constrainedSize in + return { presentationData, strings, context, type, message, constrainedSize in let titleString = message.author?.displayTitle(strings: strings, displayOrder: presentationData.nameDisplayOrder) ?? strings.User_DeletedAccount - let (textString, isMedia) = descriptionStringForMessage(message, strings: strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: account.peerId) + let (textString, isMedia) = descriptionStringForMessage(message, strings: strings, nameDisplayOrder: presentationData.nameDisplayOrder, accountPeerId: context.account.peerId) - let placeholderColor: UIColor = message.effectivelyIncoming(account.peerId) ? presentationData.theme.theme.chat.bubble.incomingMediaPlaceholderColor : presentationData.theme.theme.chat.bubble.outgoingMediaPlaceholderColor + let placeholderColor: UIColor = message.effectivelyIncoming(context.account.peerId) ? presentationData.theme.theme.chat.bubble.incomingMediaPlaceholderColor : presentationData.theme.theme.chat.bubble.outgoingMediaPlaceholderColor let titleColor: UIColor let lineImage: UIImage? let textColor: UIColor @@ -125,12 +125,12 @@ class ChatMessageReplyInfoNode: ASDisplayNode { var updateImageSignal: Signal<(TransformImageArguments) -> DrawingContext?, NoError>? if let updatedMediaReference = updatedMediaReference, mediaUpdated && imageDimensions != nil { if let imageReference = updatedMediaReference.concrete(TelegramMediaImage.self) { - updateImageSignal = chatMessagePhotoThumbnail(account: account, photoReference: imageReference) + updateImageSignal = chatMessagePhotoThumbnail(account: context.account, photoReference: imageReference) } else if let fileReference = updatedMediaReference.concrete(TelegramMediaFile.self) { if fileReference.media.isVideo { - updateImageSignal = chatMessageVideoThumbnail(account: account, fileReference: fileReference) + updateImageSignal = chatMessageVideoThumbnail(account: context.account, fileReference: fileReference) } else if let iconImageRepresentation = smallestImageRepresentation(fileReference.media.previewRepresentations) { - updateImageSignal = chatWebpageSnippetFile(account: account, fileReference: fileReference, representation: iconImageRepresentation) + updateImageSignal = chatWebpageSnippetFile(account: context.account, fileReference: fileReference, representation: iconImageRepresentation) } } } diff --git a/TelegramUI/ChatMessageSelectionInputPanelNode.swift b/TelegramUI/ChatMessageSelectionInputPanelNode.swift index 94d7b70b19..48e3d2a8dc 100644 --- a/TelegramUI/ChatMessageSelectionInputPanelNode.swift +++ b/TelegramUI/ChatMessageSelectionInputPanelNode.swift @@ -30,16 +30,16 @@ final class ChatMessageSelectionInputPanelNode: ChatInputPanelNode { let _ = self.updateLayout(width: width, leftInset: leftInset, rightInset: rightInset, maxHeight: maxHeight, transition: .immediate, interfaceState: interfaceState, metrics: metrics) } self.canDeleteMessagesDisposable.set(nil) - } else if let account = self.account { - self.canDeleteMessagesDisposable.set((chatAvailableMessageActions(postbox: account.postbox, accountPeerId: account.peerId, messageIds: self.selectedMessages) - |> deliverOnMainQueue).start(next: { [weak self] actions in - if let strongSelf = self { - strongSelf.actions = actions - if let (width, leftInset, rightInset, maxHeight, metrics) = strongSelf.validLayout, let interfaceState = strongSelf.presentationInterfaceState { - let _ = strongSelf.updateLayout(width: width, leftInset: leftInset, rightInset: rightInset, maxHeight: maxHeight, transition: .immediate, interfaceState: interfaceState, metrics: metrics) - } + } else if let context = self.context { + self.canDeleteMessagesDisposable.set((chatAvailableMessageActions(postbox: context.account.postbox, accountPeerId: context.account.peerId, messageIds: self.selectedMessages) + |> deliverOnMainQueue).start(next: { [weak self] actions in + if let strongSelf = self { + strongSelf.actions = actions + if let (width, leftInset, rightInset, maxHeight, metrics) = strongSelf.validLayout, let interfaceState = strongSelf.presentationInterfaceState { + let _ = strongSelf.updateLayout(width: width, leftInset: leftInset, rightInset: rightInset, maxHeight: maxHeight, transition: .immediate, interfaceState: interfaceState, metrics: metrics) } - })) + } + })) } } } diff --git a/TelegramUI/ChatMessageStickerItemNode.swift b/TelegramUI/ChatMessageStickerItemNode.swift index 41a359c175..0490264b05 100644 --- a/TelegramUI/ChatMessageStickerItemNode.swift +++ b/TelegramUI/ChatMessageStickerItemNode.swift @@ -89,10 +89,10 @@ class ChatMessageStickerItemNode: ChatMessageItemView { if let telegramFile = media as? TelegramMediaFile { if self.telegramFile != telegramFile { - let signal = chatMessageSticker(account: item.account, file: telegramFile, small: false, onlyFullSize: self.telegramFile != nil) + let signal = chatMessageSticker(account: item.context.account, file: telegramFile, small: false, onlyFullSize: self.telegramFile != nil) self.telegramFile = telegramFile self.imageNode.setSignal(signal) - self.fetchDisposable.set(freeMediaFileInteractiveFetched(account: item.account, fileReference: .message(message: MessageReference(item.message), media: telegramFile)).start()) + self.fetchDisposable.set(freeMediaFileInteractiveFetched(account: item.context.account, fileReference: .message(message: MessageReference(item.message), media: telegramFile)).start()) } break @@ -115,7 +115,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { let currentItem = self.item return { item, params, mergedTop, mergedBottom, dateHeaderAtBottom in - let incoming = item.message.effectivelyIncoming(item.account.peerId) + let incoming = item.message.effectivelyIncoming(item.context.account.peerId) var imageSize: CGSize = CGSize(width: 100.0, height: 100.0) if let telegramFile = telegramFile { if let dimensions = telegramFile.dimensions { @@ -130,7 +130,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { switch item.chatLocation { case let .peer(peerId): - if peerId != item.account.peerId { + if peerId != item.context.account.peerId { if peerId.isGroupOrChannel && item.message.author != nil { var isBroadcastChannel = false if let peer = item.message.peers[item.message.id.peerId] as? TelegramChannel, case .broadcast = peer.info { @@ -157,14 +157,14 @@ class ChatMessageStickerItemNode: ChatMessageItemView { var needShareButton = false if item.message.flags.contains(.Failed) { needShareButton = false - } else if item.message.id.peerId == item.account.peerId { + } else if item.message.id.peerId == item.context.account.peerId { for attribute in item.content.firstMessage.attributes { if let _ = attribute as? SourceReferenceMessageAttribute { needShareButton = true break } } - } else if item.message.effectivelyIncoming(item.account.peerId) { + } else if item.message.effectivelyIncoming(item.context.account.peerId) { if let peer = item.message.peers[item.message.id.peerId] { if let channel = peer as? TelegramChannel { if case .broadcast = channel.info { @@ -216,7 +216,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { let imageApply = imageLayout(arguments) let statusType: ChatMessageDateAndStatusType - if item.message.effectivelyIncoming(item.account.peerId) { + if item.message.effectivelyIncoming(item.context.account.peerId) { statusType = .FreeIncoming } else { if item.message.flags.contains(.Failed) { @@ -272,7 +272,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { } if let replyAttribute = attribute as? ReplyMessageAttribute, let replyMessage = item.message.associatedMessages[replyAttribute.messageId] { - replyInfoApply = makeReplyInfoLayout(item.presentationData, item.presentationData.strings, item.account, .standalone, replyMessage, CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude)) + replyInfoApply = makeReplyInfoLayout(item.presentationData, item.presentationData.strings, item.context, .standalone, replyMessage, CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude)) } else if let attribute = attribute as? ReplyMarkupMessageAttribute, attribute.flags.contains(.inline), !attribute.rows.isEmpty { replyMarkup = attribute } @@ -297,7 +297,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { updatedShareButtonNode = currentShareButtonNode if item.presentationData.theme !== currentItem?.presentationData.theme { let graphics = PresentationResourcesChat.additionalGraphics(item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper) - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { updatedShareButtonBackground = graphics.chatBubbleNavigateButtonImage } else { updatedShareButtonBackground = graphics.chatBubbleShareButtonImage @@ -307,7 +307,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { let buttonNode = HighlightableButtonNode() let buttonIcon: UIImage? let graphics = PresentationResourcesChat.additionalGraphics(item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper) - if item.message.id.peerId == item.account.peerId { + if item.message.id.peerId == item.context.account.peerId { buttonIcon = graphics.chatBubbleNavigateButtonImage } else { buttonIcon = graphics.chatBubbleShareButtonImage @@ -321,7 +321,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { var maxContentWidth = imageSize.width var actionButtonsFinalize: ((CGFloat) -> (CGSize, (_ animated: Bool) -> ChatMessageActionButtonsNode))? if let replyMarkup = replyMarkup { - let (minWidth, buttonsLayout) = actionButtonsLayout(item.account, item.presentationData.theme, item.presentationData.strings, replyMarkup, item.message, maxContentWidth) + let (minWidth, buttonsLayout) = actionButtonsLayout(item.context, item.presentationData.theme, item.presentationData.strings, replyMarkup, item.message, maxContentWidth) maxContentWidth = max(maxContentWidth, minWidth) actionButtonsFinalize = buttonsLayout } @@ -503,7 +503,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { if let avatarNode = self.accessoryItemNode as? ChatMessageAvatarAccessoryItemNode, avatarNode.frame.contains(location) { if let item = self.item, let author = item.content.firstMessage.author { let navigate: ChatControllerInteractionNavigateToPeer - if item.content.firstMessage.id.peerId == item.account.peerId { + if item.content.firstMessage.id.peerId == item.context.account.peerId { navigate = .chat(textInputState: nil, messageId: nil) } else { navigate = .info @@ -570,7 +570,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { @objc func shareButtonPressed() { if let item = self.item { - if item.content.firstMessage.id.peerId == item.account.peerId { + if item.content.firstMessage.id.peerId == item.context.account.peerId { for attribute in item.content.firstMessage.attributes { if let attribute = attribute as? SourceReferenceMessageAttribute { item.controllerInteraction.navigateToMessage(item.content.firstMessage.id, attribute.messageId) @@ -664,7 +664,7 @@ class ChatMessageStickerItemNode: ChatMessageItemView { var incoming = true selected = selectionState.selectedIds.contains(item.message.id) - incoming = item.message.effectivelyIncoming(item.account.peerId) + incoming = item.message.effectivelyIncoming(item.context.account.peerId) let offset: CGFloat = incoming ? 42.0 : 0.0 diff --git a/TelegramUI/ChatMessageTextBubbleContentNode.swift b/TelegramUI/ChatMessageTextBubbleContentNode.swift index 0c7b455b1d..9fb7934e86 100644 --- a/TelegramUI/ChatMessageTextBubbleContentNode.swift +++ b/TelegramUI/ChatMessageTextBubbleContentNode.swift @@ -66,7 +66,7 @@ class ChatMessageTextBubbleContentNode: ChatMessageBubbleContentNode { return (contentProperties, nil, CGFloat.greatestFiniteMagnitude, { constrainedSize, position in let message = item.message - let incoming = item.message.effectivelyIncoming(item.account.peerId) + let incoming = item.message.effectivelyIncoming(item.context.account.peerId) let horizontalInset = layoutConstants.text.bubbleInsets.left + layoutConstants.text.bubbleInsets.right let textConstrainedSize = CGSize(width: constrainedSize.width - horizontalInset, height: constrainedSize.height) @@ -344,7 +344,7 @@ class ChatMessageTextBubbleContentNode: ChatMessageBubbleContentNode { if let current = self.linkHighlightingNode { linkHighlightingNode = current } else { - linkHighlightingNode = LinkHighlightingNode(color: item.message.effectivelyIncoming(item.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingLinkHighlightColor : item.presentationData.theme.theme.chat.bubble.outgoingLinkHighlightColor) + linkHighlightingNode = LinkHighlightingNode(color: item.message.effectivelyIncoming(item.context.account.peerId) ? item.presentationData.theme.theme.chat.bubble.incomingLinkHighlightColor : item.presentationData.theme.theme.chat.bubble.outgoingLinkHighlightColor) self.linkHighlightingNode = linkHighlightingNode self.insertSubnode(linkHighlightingNode, belowSubnode: self.textNode) } diff --git a/TelegramUI/ChatMessageUnsupportedBubbleContentNode.swift b/TelegramUI/ChatMessageUnsupportedBubbleContentNode.swift index 7b66733627..eee80175a6 100644 --- a/TelegramUI/ChatMessageUnsupportedBubbleContentNode.swift +++ b/TelegramUI/ChatMessageUnsupportedBubbleContentNode.swift @@ -33,7 +33,7 @@ final class ChatMessageUnsupportedBubbleContentNode: ChatMessageBubbleContentNod return (contentProperties, nil, CGFloat.greatestFiniteMagnitude, { constrainedSize, position in let message = item.message - let incoming = message.effectivelyIncoming(item.account.peerId) + let incoming = message.effectivelyIncoming(item.context.account.peerId) let presentationData = item.presentationData let insets = UIEdgeInsets(top: 0.0, left: 12.0, bottom: 9.0, right: 12.0) diff --git a/TelegramUI/ChatMessageWebpageBubbleContentNode.swift b/TelegramUI/ChatMessageWebpageBubbleContentNode.swift index c5854249d3..ac35dda701 100644 --- a/TelegramUI/ChatMessageWebpageBubbleContentNode.swift +++ b/TelegramUI/ChatMessageWebpageBubbleContentNode.swift @@ -282,7 +282,7 @@ final class ChatMessageWebpageBubbleContentNode: ChatMessageBubbleContentNode { } } - let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.account, item.controllerInteraction, item.message, item.read, title, subtitle, text, entities, mediaAndFlags, actionIcon, actionTitle, true, layoutConstants, constrainedSize) + let (initialWidth, continueLayout) = contentNodeLayout(item.presentationData, item.controllerInteraction.automaticMediaDownloadSettings, item.associatedData, item.context, item.controllerInteraction, item.message, item.read, title, subtitle, text, entities, mediaAndFlags, actionIcon, actionTitle, true, layoutConstants, constrainedSize) let contentProperties = ChatMessageBubbleContentProperties(hidesSimpleAuthorHeader: false, headerSpacing: 8.0, hidesBackground: .never, forceFullCorners: false, forceAlignment: .none) diff --git a/TelegramUI/ChatPinnedMessageTitlePanelNode.swift b/TelegramUI/ChatPinnedMessageTitlePanelNode.swift index 6075cb5035..909a90e163 100644 --- a/TelegramUI/ChatPinnedMessageTitlePanelNode.swift +++ b/TelegramUI/ChatPinnedMessageTitlePanelNode.swift @@ -6,7 +6,7 @@ import TelegramCore import SwiftSignalKit final class ChatPinnedMessageTitlePanelNode: ChatTitleAccessoryPanelNode { - private let account: Account + private let context: AccountContext private let tapButton: HighlightTrackingButtonNode private let closeButton: HighlightableButtonNode private let lineNode: ASImageNode @@ -22,8 +22,8 @@ final class ChatPinnedMessageTitlePanelNode: ChatTitleAccessoryPanelNode { private let queue = Queue() - init(account: Account) { - self.account = account + init(context: AccountContext) { + self.context = context self.tapButton = HighlightTrackingButtonNode() @@ -115,7 +115,7 @@ final class ChatPinnedMessageTitlePanelNode: ChatTitleAccessoryPanelNode { self.currentMessage = interfaceState.pinnedMessage if let currentMessage = currentMessage, let currentLayout = self.currentLayout { - self.enqueueTransition(width: currentLayout.0, leftInset: currentLayout.1, rightInset: currentLayout.2, transition: .immediate, message: currentMessage, theme: interfaceState.theme, strings: interfaceState.strings, nameDisplayOrder: interfaceState.nameDisplayOrder, accountPeerId: self.account.peerId, firstTime: previousMessageWasNil) + self.enqueueTransition(width: currentLayout.0, leftInset: currentLayout.1, rightInset: currentLayout.2, transition: .immediate, message: currentMessage, theme: interfaceState.theme, strings: interfaceState.strings, nameDisplayOrder: interfaceState.nameDisplayOrder, accountPeerId: self.context.account.peerId, firstTime: previousMessageWasNil) } } @@ -147,7 +147,7 @@ final class ChatPinnedMessageTitlePanelNode: ChatTitleAccessoryPanelNode { let imageNodeLayout = self.imageNode.asyncLayout() let previousMediaReference = self.previousMediaReference - let account = self.account + let context = self.context let targetQueue: Queue if firstTime { @@ -204,12 +204,12 @@ final class ChatPinnedMessageTitlePanelNode: ChatTitleAccessoryPanelNode { if mediaUpdated { if let updatedMediaReference = updatedMediaReference, imageDimensions != nil { if let imageReference = updatedMediaReference.concrete(TelegramMediaImage.self) { - updateImageSignal = chatMessagePhotoThumbnail(account: account, photoReference: imageReference) + updateImageSignal = chatMessagePhotoThumbnail(account: context.account, photoReference: imageReference) } else if let fileReference = updatedMediaReference.concrete(TelegramMediaFile.self) { if fileReference.media.isVideo { - updateImageSignal = chatMessageVideoThumbnail(account: account, fileReference: fileReference) + updateImageSignal = chatMessageVideoThumbnail(account: context.account, fileReference: fileReference) } else if let iconImageRepresentation = smallestImageRepresentation(fileReference.media.previewRepresentations) { - updateImageSignal = chatWebpageSnippetFile(account: account, fileReference: fileReference, representation: iconImageRepresentation) + updateImageSignal = chatWebpageSnippetFile(account: context.account, fileReference: fileReference, representation: iconImageRepresentation) } } } else { diff --git a/TelegramUI/ChatRecentActionsController.swift b/TelegramUI/ChatRecentActionsController.swift index 3a23dd5eda..4c5dd97486 100644 --- a/TelegramUI/ChatRecentActionsController.swift +++ b/TelegramUI/ChatRecentActionsController.swift @@ -9,7 +9,7 @@ final class ChatRecentActionsController: TelegramController { return self.displayNode as! ChatRecentActionsControllerNode } - private let account: Account + private let context: AccountContext private let peer: Peer private var presentationData: PresentationData private var presentationDataDisposable: Disposable? @@ -19,15 +19,15 @@ final class ChatRecentActionsController: TelegramController { private let titleView: ChatRecentActionsTitleView - init(account: Account, peer: Peer) { - self.account = account + init(context: AccountContext, peer: Peer) { + self.context = context self.peer = peer - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.titleView = ChatRecentActionsTitleView(color: self.presentationData.theme.rootController.navigationBar.primaryTextColor) - super.init(account: account, navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData), mediaAccessoryPanelVisibility: .specific(size: .compact), locationBroadcastPanelSource: .none) + super.init(context: context, navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData), mediaAccessoryPanelVisibility: .specific(size: .compact), locationBroadcastPanelSource: .none) self.statusBar.statusBarStyle = self.presentationData.theme.rootController.statusBar.style.style @@ -104,7 +104,7 @@ final class ChatRecentActionsController: TelegramController { self?.openFilterSetup() } - 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 @@ -135,7 +135,7 @@ final class ChatRecentActionsController: TelegramController { } override func loadDisplayNode() { - self.displayNode = ChatRecentActionsControllerNode(account: self.account, peer: self.peer, presentationData: self.presentationData, interaction: self.interaction, pushController: { [weak self] c in + self.displayNode = ChatRecentActionsControllerNode(context: self.context, peer: self.peer, presentationData: self.presentationData, interaction: self.interaction, pushController: { [weak self] c in (self?.navigationController as? NavigationController)?.pushViewController(c) }, presentController: { [weak self] c, a in self?.present(c, in: .window(.root), with: a, blockInteraction: true) diff --git a/TelegramUI/ChatRecentActionsControllerNode.swift b/TelegramUI/ChatRecentActionsControllerNode.swift index 43213a4b79..71a89849bb 100644 --- a/TelegramUI/ChatRecentActionsControllerNode.swift +++ b/TelegramUI/ChatRecentActionsControllerNode.swift @@ -17,7 +17,7 @@ private final class ChatRecentActionsListOpaqueState { } final class ChatRecentActionsControllerNode: ViewControllerTracingNode { - private let account: Account + private let context: AccountContext private let peer: Peer private var presentationData: PresentationData @@ -58,7 +58,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { } private(set) var filter: ChannelAdminEventLogFilter = ChannelAdminEventLogFilter() - private let context: ChannelAdminEventLogContext + private let eventLogContext: ChannelAdminEventLogContext private var enqueuedTransitions: [(ChatRecentActionsHistoryTransition, Bool)] = [] @@ -68,8 +68,8 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { private var adminsState: ChannelMemberListState? private let banDisposables = DisposableDict() - init(account: Account, peer: Peer, presentationData: PresentationData, interaction: ChatRecentActionsInteraction, pushController: @escaping (ViewController) -> Void, presentController: @escaping (ViewController, Any?) -> Void, getNavigationController: @escaping () -> NavigationController?) { - self.account = account + init(context: AccountContext, peer: Peer, presentationData: PresentationData, interaction: ChatRecentActionsInteraction, pushController: @escaping (ViewController) -> Void, presentController: @escaping (ViewController, Any?) -> Void, getNavigationController: @escaping () -> NavigationController?) { + self.context = context self.peer = peer self.presentationData = presentationData self.interaction = interaction @@ -77,7 +77,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { self.presentController = presentController self.getNavigationController = getNavigationController - self.automaticMediaDownloadSettings = (account.applicationContext as! TelegramApplicationContext).currentAutomaticMediaDownloadSettings.with { $0 } + self.automaticMediaDownloadSettings = context.currentAutomaticMediaDownloadSettings.with { $0 } self.backgroundNode = ASDisplayNode() self.backgroundNode.isLayerBacked = true @@ -99,11 +99,11 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { self.chatPresentationDataPromise = Promise(ChatPresentationData(theme: ChatPresentationThemeData(theme: self.presentationData.theme, wallpaper: self.presentationData.chatWallpaper), fontSize: self.presentationData.fontSize, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, disableAnimations: self.presentationData.disableAnimations)) - self.context = ChannelAdminEventLogContext(postbox: self.account.postbox, network: self.account.network, peerId: self.peer.id) + self.eventLogContext = ChannelAdminEventLogContext(postbox: self.context.account.postbox, network: self.context.account.network, peerId: self.peer.id) super.init() - self.backgroundNode.contents = chatControllerBackgroundImage(wallpaper: self.state.chatWallpaper, postbox: account.postbox)?.cgImage + self.backgroundNode.contents = chatControllerBackgroundImage(wallpaper: self.state.chatWallpaper, postbox: context.account.postbox)?.cgImage self.addSubnode(self.backgroundNode) self.addSubnode(self.listNode) @@ -115,7 +115,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { self.panelButtonNode.addTarget(self, action: #selector(self.infoButtonPressed), forControlEvents: .touchUpInside) - let (adminsDisposable, _) = self.account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.admins(postbox: self.account.postbox, network: self.account.network, accountPeerId: account.peerId, peerId: self.peer.id, searchQuery: nil, updated: { [weak self] state in + let (adminsDisposable, _) = self.context.peerChannelMemberCategoriesContextsManager.admins(postbox: self.context.account.postbox, network: self.context.account.network, accountPeerId: context.account.peerId, peerId: self.peer.id, searchQuery: nil, updated: { [weak self] state in self?.adminsState = state }) self.adminsDisposable = adminsDisposable @@ -130,7 +130,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { switch entry.entry.event.action { case let .changeStickerPack(_, new): if let new = new { - strongSelf.presentController(StickerPackPreviewController(account: strongSelf.account, stickerPack: new, parentNavigationController: strongSelf.getNavigationController()), nil) + strongSelf.presentController(StickerPackPreviewController(context: strongSelf.context, stickerPack: new, parentNavigationController: strongSelf.getNavigationController()), nil) return true } default: @@ -140,7 +140,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { break } } - return openChatMessage(account: account, message: message, standalone: true, reverseMessageGalleryOrder: false, navigationController: navigationController, dismissInput: { + return openChatMessage(context: context, message: message, standalone: true, reverseMessageGalleryOrder: false, navigationController: navigationController, dismissInput: { //self?.chatDisplayNode.dismissInput() }, present: { c, a in self?.presentController(c, a) @@ -182,11 +182,11 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { self?.openUrl(url) }, shareCurrentLocation: {}, shareAccountContact: {}, sendBotCommand: { _, _ in }, openInstantPage: { [weak self] message in if let strongSelf = self, let navigationController = strongSelf.getNavigationController() { - openChatInstantPage(account: strongSelf.account, message: message, navigationController: navigationController) + openChatInstantPage(context: strongSelf.context, message: message, navigationController: navigationController) } }, openWallpaper: { [weak self] message in if let strongSelf = self{ - openChatWallpaper(account: strongSelf.account, message: message, present: { [weak self] c, a in + openChatWallpaper(context: strongSelf.context, message: message, present: { [weak self] c, a in self?.presentController(c, a) }) } @@ -196,23 +196,23 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { } let resolveSignal: Signal if let peerName = peerName { - resolveSignal = resolvePeerByName(account: strongSelf.account, name: peerName) + resolveSignal = resolvePeerByName(account: strongSelf.context.account, name: peerName) |> mapToSignal { peerId -> Signal in if let peerId = peerId { - return account.postbox.loadedPeerWithId(peerId) - |> map(Optional.init) + return context.account.postbox.loadedPeerWithId(peerId) + |> map(Optional.init) } else { return .single(nil) } } } else { - resolveSignal = account.postbox.loadedPeerWithId(strongSelf.peer.id) - |> map(Optional.init) + resolveSignal = context.account.postbox.loadedPeerWithId(strongSelf.peer.id) + |> map(Optional.init) } strongSelf.resolvePeerByNameDisposable.set((resolveSignal |> deliverOnMainQueue).start(next: { peer in if let strongSelf = self, !hashtag.isEmpty { - let searchController = HashtagSearchController(account: strongSelf.account, peer: peer, query: hashtag) + let searchController = HashtagSearchController(context: strongSelf.context, peer: peer, query: hashtag) strongSelf.pushController(searchController) } })) @@ -225,7 +225,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { switch action { case let .url(url): var cleanUrl = url - let canOpenIn = availableOpenInOptions(applicationContext: strongSelf.account.telegramApplicationContext, item: .url(url: url)).count > 1 + let canOpenIn = availableOpenInOptions(context: strongSelf.context, item: .url(url: url)).count > 1 var canAddToReadingList = true let mailtoString = "mailto:" let telString = "tel:" @@ -333,7 +333,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { ActionSheetButtonItem(title: strongSelf.presentationData.strings.Conversation_LinkDialogOpen, color: .accent, action: { [weak actionSheet] in actionSheet?.dismissAnimated() if let strongSelf = self { - let searchController = HashtagSearchController(account: strongSelf.account, peer: strongSelf.peer, query: hashtag) + let searchController = HashtagSearchController(context: strongSelf.context, peer: strongSelf.peer, query: hashtag) strongSelf.pushController(searchController) } }), @@ -360,7 +360,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { }, requestSelectMessagePollOption: { _, _ in }, openAppStorePage: { [weak self] in if let strongSelf = self { - strongSelf.account.telegramApplicationContext.applicationBindings.openAppStorePage() + strongSelf.context.applicationBindings.openAppStorePage() } }, requestMessageUpdate: { _ in }, cancelInteractiveKeyboardGestures: { @@ -374,16 +374,16 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { if let visible = displayedRange.visibleRange { let indexRange = (state.entries.count - 1 - visible.lastIndex, state.entries.count - 1 - visible.firstIndex) if indexRange.0 < 5 { - strongSelf.context.loadMoreEntries() + strongSelf.eventLogContext.loadMoreEntries() } } } } } - self.context.loadMoreEntries() + self.eventLogContext.loadMoreEntries() - let historyViewUpdate = self.context.get() + let historyViewUpdate = self.eventLogContext.get() let previousView = Atomic<[ChatRecentActionsEntry]?>(value: nil) @@ -400,7 +400,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { } - return .single(chatRecentActionsHistoryPreparedTransition(from: previous ?? [], to: processedView, type: update.2, canLoadEarlier: update.1, displayingResults: update.3, account: account, peer: peer, controllerInteraction: controllerInteraction)) + return .single(chatRecentActionsHistoryPreparedTransition(from: previous ?? [], to: processedView, type: update.2, canLoadEarlier: update.1, displayingResults: update.3, context: context, peer: peer, controllerInteraction: controllerInteraction)) } let appliedTransition = historyViewTransition |> deliverOnMainQueue |> mapToQueue { [weak self] transition -> Signal in @@ -413,31 +413,30 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { self.historyDisposable = appliedTransition.start() - if let mediaManager = self.account.telegramApplicationContext.mediaManager { - self.galleryHiddenMesageAndMediaDisposable.set(mediaManager.galleryHiddenMediaManager.hiddenIds().start(next: { [weak self] ids in - if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { - var messageIdAndMedia: [MessageId: [Media]] = [:] - - for id in ids { - if case let .chat(messageId, media) = id { - messageIdAndMedia[messageId] = [media] - } + let mediaManager = self.context.mediaManager + self.galleryHiddenMesageAndMediaDisposable.set(mediaManager.galleryHiddenMediaManager.hiddenIds().start(next: { [weak self] ids in + if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { + var messageIdAndMedia: [MessageId: [Media]] = [:] + + for id in ids { + if case let .chat(messageId, media) = id { + messageIdAndMedia[messageId] = [media] } - - //if controllerInteraction.hiddenMedia != messageIdAndMedia { - controllerInteraction.hiddenMedia = messageIdAndMedia - - strongSelf.listNode.forEachItemNode { itemNode in - if let itemNode = itemNode as? ChatMessageItemView { - itemNode.updateHiddenMedia() - } - } - //} } - })) - } + + //if controllerInteraction.hiddenMedia != messageIdAndMedia { + controllerInteraction.hiddenMedia = messageIdAndMedia + + strongSelf.listNode.forEachItemNode { itemNode in + if let itemNode = itemNode as? ChatMessageItemView { + itemNode.updateHiddenMedia() + } + } + //} + } + })) - 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 @@ -608,12 +607,12 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { func updateSearchQuery(_ query: String) { self.filter = self.filter.withQuery(query.isEmpty ? nil : query) - self.context.setFilter(self.filter) + self.eventLogContext.setFilter(self.filter) } func updateFilter(events: AdminLogEventsFlags, adminPeerIds: [PeerId]?) { self.filter = self.filter.withEvents(events).withAdminPeerIds(adminPeerIds) - self.context.setFilter(self.filter) + self.eventLogContext.setFilter(self.filter) } private func openPeer(peerId: PeerId, peer: Peer?) { @@ -621,11 +620,11 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { if let peer = peer { peerSignal = .single(peer) } else { - peerSignal = self.account.postbox.loadedPeerWithId(peerId) |> map(Optional.init) + peerSignal = self.context.account.postbox.loadedPeerWithId(peerId) |> map(Optional.init) } self.navigationActionDisposable.set((peerSignal |> take(1) |> deliverOnMainQueue).start(next: { [weak self] peer in if let strongSelf = self, let peer = peer { - if let infoController = peerInfoController(account: strongSelf.account, peer: peer) { + if let infoController = peerInfoController(context: strongSelf.context, peer: peer) { strongSelf.pushController(infoController) } } @@ -633,20 +632,20 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { } private func openPeerMention(_ name: String) { - let postbox = self.account.postbox - self.navigationActionDisposable.set((resolvePeerByName(account: self.account, name: name, ageLimit: 10) - |> take(1) - |> mapToSignal { peerId -> Signal in - if let peerId = peerId { - return postbox.loadedPeerWithId(peerId) |> map(Optional.init) - } else { - return .single(nil) - } + let postbox = self.context.account.postbox + self.navigationActionDisposable.set((resolvePeerByName(account: self.context.account, name: name, ageLimit: 10) + |> take(1) + |> mapToSignal { peerId -> Signal in + if let peerId = peerId { + return postbox.loadedPeerWithId(peerId) |> map(Optional.init) + } else { + return .single(nil) } - |> deliverOnMainQueue).start(next: { [weak self] peer in + } + |> deliverOnMainQueue).start(next: { [weak self] peer in if let strongSelf = self { if let peer = peer { - if let infoController = peerInfoController(account: strongSelf.account, peer: peer) { + if let infoController = peerInfoController(context: strongSelf.context, peer: peer) { strongSelf.pushController(infoController) } } @@ -663,7 +662,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { } if let author = message.author, let adminsState = self.adminsState { - var canBan = author.id != self.account.peerId + var canBan = author.id != self.context.account.peerId if let channel = self.peer as? TelegramChannel { if !channel.hasPermission(.banMembers) { canBan = false @@ -676,7 +675,7 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { canBan = false case let .member(_, _, adminInfo, _): if let adminInfo = adminInfo { - if adminInfo.promotedBy != self.account.peerId { + if adminInfo.promotedBy != self.context.account.peerId { canBan = false } } @@ -687,10 +686,10 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { if canBan { actions.append(ContextMenuAction(content: .text(self.presentationData.strings.Conversation_ContextMenuBan), action: { [weak self] in if let strongSelf = self { - strongSelf.banDisposables.set((fetchChannelParticipant(account: strongSelf.account, peerId: strongSelf.peer.id, participantId: author.id) + strongSelf.banDisposables.set((fetchChannelParticipant(account: strongSelf.context.account, peerId: strongSelf.peer.id, participantId: author.id) |> deliverOnMainQueue).start(next: { participant in if let strongSelf = self { - strongSelf.presentController(channelBannedMemberController(account: strongSelf.account, peerId: strongSelf.peer.id, memberId: author.id, initialParticipant: participant, updated: { _ in }, upgradedToSupergroup: { _, f in f() }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + strongSelf.presentController(channelBannedMemberController(context: strongSelf.context, peerId: strongSelf.peer.id, memberId: author.id, initialParticipant: participant, updated: { _ in }, upgradedToSupergroup: { _, f in f() }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } }), forKey: author.id) } @@ -732,12 +731,12 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { } private func openUrl(_ url: String) { - self.navigationActionDisposable.set((resolveUrl(account: self.account, url: url) |> deliverOnMainQueue).start(next: { [weak self] result in + self.navigationActionDisposable.set((resolveUrl(account: self.context.account, url: url) |> deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { switch result { case let .externalUrl(url): if let navigationController = strongSelf.getNavigationController() { - openExternalUrl(account: strongSelf.account, url: url, presentationData: strongSelf.presentationData, applicationContext: strongSelf.account.telegramApplicationContext, navigationController: navigationController, dismissInput: { + openExternalUrl(context: strongSelf.context, url: url, presentationData: strongSelf.presentationData, navigationController: navigationController, dismissInput: { self?.view.endEditing(true) }) } @@ -752,22 +751,22 @@ final class ChatRecentActionsControllerNode: ViewControllerTracingNode { break case let .channelMessage(peerId, messageId): if let navigationController = strongSelf.getNavigationController() { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(peerId), messageId: messageId) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peerId), messageId: messageId) } case let .stickerPack(name): - strongSelf.presentController(StickerPackPreviewController(account: strongSelf.account, stickerPack: .name(name), parentNavigationController: strongSelf.getNavigationController()), nil) + strongSelf.presentController(StickerPackPreviewController(context: strongSelf.context, stickerPack: .name(name), parentNavigationController: strongSelf.getNavigationController()), nil) case let .instantView(webpage, anchor): - strongSelf.pushController(InstantPageController(account: strongSelf.account, webPage: webpage, anchor: anchor)) + strongSelf.pushController(InstantPageController(context: strongSelf.context, webPage: webpage, anchor: anchor)) case let .join(link): - strongSelf.presentController(JoinLinkPreviewController(account: strongSelf.account, link: link, navigateToPeer: { peerId in + strongSelf.presentController(JoinLinkPreviewController(context: strongSelf.context, link: link, navigateToPeer: { peerId in if let strongSelf = self { strongSelf.openPeer(peerId: peerId, peer: nil) } }), nil) case let .localization(identifier): - strongSelf.presentController(LanguageLinkPreviewController(account: strongSelf.account, identifier: identifier), nil) + strongSelf.presentController(LanguageLinkPreviewController(context: strongSelf.context, identifier: identifier), nil) case .proxy, .confirmationCode, .cancelAccountReset, .share: - openResolvedUrl(result, account: strongSelf.account, navigationController: strongSelf.getNavigationController(), openPeer: { peerId, _ in + openResolvedUrl(result, context: strongSelf.context, navigationController: strongSelf.getNavigationController(), openPeer: { peerId, _ in if let strongSelf = self { strongSelf.openPeer(peerId: peerId, peer: nil) } diff --git a/TelegramUI/ChatRecentActionsFilterController.swift b/TelegramUI/ChatRecentActionsFilterController.swift index 429a5137be..f12cfe55fe 100644 --- a/TelegramUI/ChatRecentActionsFilterController.swift +++ b/TelegramUI/ChatRecentActionsFilterController.swift @@ -356,7 +356,7 @@ private func channelRecentActionsFilterControllerEntries(presentationData: Prese return entries } -public func channelRecentActionsFilterController(account: Account, peer: Peer, events: AdminLogEventsFlags, adminPeerIds: [PeerId]?, apply: @escaping (_ events: AdminLogEventsFlags, _ adminPeerIds: [PeerId]?) -> Void) -> ViewController { +public func channelRecentActionsFilterController(context: AccountContext, peer: Peer, events: AdminLogEventsFlags, adminPeerIds: [PeerId]?, apply: @escaping (_ events: AdminLogEventsFlags, _ adminPeerIds: [PeerId]?) -> Void) -> ViewController { let statePromise = ValuePromise(ChatRecentActionsFilterControllerState(events: events, adminPeerIds: adminPeerIds), ignoreRepeated: true) let stateValue = Atomic(value: ChatRecentActionsFilterControllerState(events: events, adminPeerIds: adminPeerIds)) let updateState: ((ChatRecentActionsFilterControllerState) -> ChatRecentActionsFilterControllerState) -> Void = { f in @@ -367,11 +367,11 @@ public func channelRecentActionsFilterController(account: Account, peer: Peer, e let adminsPromise = Promise<[RenderedChannelParticipant]?>(nil) - let presentationDataSignal = (account.applicationContext as! TelegramApplicationContext).presentationData + let presentationDataSignal = context.presentationData let actionsDisposable = DisposableSet() - let arguments = ChatRecentActionsFilterControllerArguments(account: account, toggleAllActions: { + let arguments = ChatRecentActionsFilterControllerArguments(account: context.account, toggleAllActions: { updateState { current in if current.events.isEmpty { return current.withUpdatedEvents(.all) @@ -433,7 +433,7 @@ public func channelRecentActionsFilterController(account: Account, peer: Peer, e adminsPromise.set(.single(nil)) - let (membersDisposable, _) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.admins(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peer.id) { membersState in + let (membersDisposable, _) = context.peerChannelMemberCategoriesContextsManager.admins(postbox: context.account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peer.id) { membersState in if case .loading = membersState.loadingState, membersState.list.isEmpty { adminsPromise.set(.single(nil)) } else { @@ -467,7 +467,7 @@ public func channelRecentActionsFilterController(account: Account, peer: Peer, e var sortedAdmins: [RenderedChannelParticipant]? if let admins = admins { - sortedAdmins = admins.filter { $0.peer.id == account.peerId } + admins.filter({ $0.peer.id != account.peerId }) + sortedAdmins = admins.filter { $0.peer.id == context.account.peerId } + admins.filter({ $0.peer.id != context.account.peerId }) } else { sortedAdmins = nil } @@ -476,7 +476,7 @@ public func channelRecentActionsFilterController(account: Account, peer: Peer, e previousPeers = sortedAdmins let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.ChatAdmins_Title), leftNavigationButton: leftNavigationButton, rightNavigationButton: rightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: true) - let listState = ItemListNodeState(entries: channelRecentActionsFilterControllerEntries(presentationData: presentationData, accountPeerId: account.peerId, peer: peer, state: state, participants: sortedAdmins), style: .blocks, animateChanges: previous != nil && admins != nil && previous!.count >= sortedAdmins!.count) + let listState = ItemListNodeState(entries: channelRecentActionsFilterControllerEntries(presentationData: presentationData, accountPeerId: context.account.peerId, peer: peer, state: state, participants: sortedAdmins), style: .blocks, animateChanges: previous != nil && admins != nil && previous!.count >= sortedAdmins!.count) return (controllerState, (listState, arguments)) } @@ -484,7 +484,7 @@ public func channelRecentActionsFilterController(account: Account, peer: Peer, e actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) dismissImpl = { [weak controller] in controller?.dismiss() } diff --git a/TelegramUI/ChatRecentActionsHistoryTransition.swift b/TelegramUI/ChatRecentActionsHistoryTransition.swift index e2e8807c9f..ae90ae1114 100644 --- a/TelegramUI/ChatRecentActionsHistoryTransition.swift +++ b/TelegramUI/ChatRecentActionsHistoryTransition.swift @@ -101,7 +101,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { return self.id } - func item(account: Account, peer: Peer, controllerInteraction: ChatControllerInteraction) -> ListViewItem { + func item(context: AccountContext, peer: Peer, controllerInteraction: ChatControllerInteraction) -> ListViewItem { switch self.entry.event.action { case let .changeTitle(_, new): var peers = SimpleDictionary() @@ -114,7 +114,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action = TelegramMediaActionType.titleUpdated(title: new) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .changeAbout(prev, new): var peers = SimpleDictionary() var author: Peer? @@ -145,14 +145,14 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: 1), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case .content: let peers = SimpleDictionary() let attributes: [MessageAttribute] = [] let prevMessage = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: prev, attributes: [], media: [], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: new, attributes: attributes, media: [], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false), additionalContent: !prev.isEmpty ? .eventLogPreviousDescription(prevMessage) : nil) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false), additionalContent: !prev.isEmpty ? .eventLogPreviousDescription(prevMessage) : nil) } case let .changeUsername(prev, new): var peers = SimpleDictionary() @@ -183,7 +183,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } let action: TelegramMediaActionType = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: 1), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case .content: var previousAttributes: [MessageAttribute] = [] var attributes: [MessageAttribute] = [] @@ -202,7 +202,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let prevMessage = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: 1), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: prevText, attributes: previousAttributes, media: [], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: text, attributes: attributes, media: [], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false), additionalContent: !prev.isEmpty ? .eventLogPreviousLink(prevMessage) : nil) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false), additionalContent: !prev.isEmpty ? .eventLogPreviousLink(prevMessage) : nil) } case let .changePhoto(_, new): var peers = SimpleDictionary() @@ -220,7 +220,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action = TelegramMediaActionType.photoUpdated(image: photo) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .toggleInvites(value): var peers = SimpleDictionary() var author: Peer? @@ -247,7 +247,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .toggleSignatures(value): var peers = SimpleDictionary() var author: Peer? @@ -274,7 +274,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .updatePinned(message): switch self.id.contentIndex { case .header: @@ -296,7 +296,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: 1), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case .content: if let message = message { var peers = SimpleDictionary() @@ -314,7 +314,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } } let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: message.author, text: message.text, attributes: attributes, media: message.media, peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) } else { var peers = SimpleDictionary() var author: Peer? @@ -336,7 +336,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: 0), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) } } case let .editMessage(prev, message): @@ -381,7 +381,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: 1), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case .content: var peers = SimpleDictionary() var attributes: [MessageAttribute] = [] @@ -398,7 +398,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } } let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: message.author, text: message.text, attributes: attributes, media: message.media, peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: filterOriginalMessageFlags(message), read: true, selection: .none, isAdmin: false), additionalContent: !prev.text.isEmpty || !message.text.isEmpty ? .eventLogPreviousMessage(filterOriginalMessageFlags(prev)) : nil) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: filterOriginalMessageFlags(message), read: true, selection: .none, isAdmin: false), additionalContent: !prev.text.isEmpty || !message.text.isEmpty ? .eventLogPreviousMessage(filterOriginalMessageFlags(prev)) : nil) } case let .deleteMessage(message): switch self.id.contentIndex { @@ -424,7 +424,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: 1), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case .content: var peers = SimpleDictionary() var attributes: [MessageAttribute] = [] @@ -448,7 +448,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } } let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: message.author, text: message.text, attributes: attributes, media: message.media, peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) } case .participantJoin, .participantLeave: var peers = SimpleDictionary() @@ -466,7 +466,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { action = TelegramMediaActionType.removedMembers(peerIds: [self.entry.event.peerId]) } let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .participantInvite(participant): var peers = SimpleDictionary() var author: Peer? @@ -483,7 +483,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action: TelegramMediaActionType action = TelegramMediaActionType.addedMembers(peerIds: [participant.peer.id]) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .participantToggleBan(prev, new): var peers = SimpleDictionary() var attributes: [MessageAttribute] = [] @@ -613,7 +613,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } } let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: text, attributes: attributes, media: [], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .participantToggleAdmin(prev, new): var peers = SimpleDictionary() var attributes: [MessageAttribute] = [] @@ -694,7 +694,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } } let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: text, attributes: attributes, media: [], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .changeStickerPack(_, new): var peers = SimpleDictionary() var author: Peer? @@ -723,7 +723,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .togglePreHistoryHidden(value): var peers = SimpleDictionary() var author: Peer? @@ -753,7 +753,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .updateDefaultBannedRights(prev, new): var peers = SimpleDictionary() var attributes: [MessageAttribute] = [] @@ -811,7 +811,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } } let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: text, attributes: attributes, media: [], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case let .pollStopped(message): switch self.id.contentIndex { case .header: @@ -839,7 +839,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { let action = TelegramMediaActionType.customText(text: text, entities: entities) let message = Message(stableId: 0, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: 1), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: author, text: "", attributes: [], media: [TelegramMediaAction(action: action)], peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: message, read: true, selection: .none, isAdmin: false)) case .content: var peers = SimpleDictionary() var attributes: [MessageAttribute] = [] @@ -856,7 +856,7 @@ struct ChatRecentActionsEntry: Comparable, Identifiable { } } let message = Message(stableId: self.entry.stableId, stableVersion: 0, id: MessageId(peerId: peer.id, namespace: Namespaces.Message.Cloud, id: Int32(bitPattern: self.entry.stableId)), globallyUniqueId: self.entry.event.id, groupingKey: nil, groupInfo: nil, timestamp: self.entry.event.date, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, author: message.author, text: message.text, attributes: attributes, media: message.media, peers: peers, associatedMessages: SimpleDictionary(), associatedMessageIds: []) - return ChatMessageItem(presentationData: self.presentationData, account: account, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: filterOriginalMessageFlags(message), read: true, selection: .none, isAdmin: false), additionalContent: nil) + return ChatMessageItem(presentationData: self.presentationData, context: context, chatLocation: .peer(peer.id), associatedData: ChatMessageItemAssociatedData(automaticDownloadPeerType: .channel, automaticDownloadNetworkType: .cellular, isRecentActions: true), controllerInteraction: controllerInteraction, content: .message(message: filterOriginalMessageFlags(message), read: true, selection: .none, isAdmin: false), additionalContent: nil) } } } @@ -886,12 +886,12 @@ struct ChatRecentActionsHistoryTransition { let isEmpty: Bool } -func chatRecentActionsHistoryPreparedTransition(from fromEntries: [ChatRecentActionsEntry], to toEntries: [ChatRecentActionsEntry], type: ChannelAdminEventLogUpdateType, canLoadEarlier: Bool, displayingResults: Bool, account: Account, peer: Peer, controllerInteraction: ChatControllerInteraction) -> ChatRecentActionsHistoryTransition { +func chatRecentActionsHistoryPreparedTransition(from fromEntries: [ChatRecentActionsEntry], to toEntries: [ChatRecentActionsEntry], type: ChannelAdminEventLogUpdateType, canLoadEarlier: Bool, displayingResults: Bool, context: AccountContext, peer: Peer, controllerInteraction: ChatControllerInteraction) -> ChatRecentActionsHistoryTransition { 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, peer: peer, controllerInteraction: controllerInteraction), directionHint: nil) } - let updates = updateIndices.map { ListViewUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(account: account, peer: peer, controllerInteraction: controllerInteraction), directionHint: nil) } + let insertions = indicesAndItems.map { ListViewInsertItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, peer: peer, controllerInteraction: controllerInteraction), directionHint: nil) } + let updates = updateIndices.map { ListViewUpdateItem(index: $0.0, previousIndex: $0.2, item: $0.1.item(context: context, peer: peer, controllerInteraction: controllerInteraction), directionHint: nil) } return ChatRecentActionsHistoryTransition(filteredEntries: toEntries, type: type, deletions: deletions, insertions: insertions, updates: updates, canLoadEarlier: canLoadEarlier, displayingResults: displayingResults, isEmpty: toEntries.isEmpty) } diff --git a/TelegramUI/ChatRecordingPreviewInputPanelNode.swift b/TelegramUI/ChatRecordingPreviewInputPanelNode.swift index 5fd2fa9635..3a85a878a3 100644 --- a/TelegramUI/ChatRecordingPreviewInputPanelNode.swift +++ b/TelegramUI/ChatRecordingPreviewInputPanelNode.swift @@ -109,8 +109,9 @@ final class ChatRecordingPreviewInputPanelNode: ChatInputPanelNode { if self.mediaPlayer != nil { self.mediaPlayer?.pause() } - if let account = self.account, let mediaManager = account.telegramApplicationContext.mediaManager { - let mediaPlayer = MediaPlayer(audioSessionManager: mediaManager.audioSession, postbox: account.postbox, resourceReference: .standalone(resource: recordedMediaPreview.resource), streamable: false, video: false, preferSoftwareDecoding: false, enableSound: true, fetchAutomatically: true) + if let context = self.context { + let mediaManager = context.mediaManager + let mediaPlayer = MediaPlayer(audioSessionManager: mediaManager.audioSession, postbox: context.account.postbox, resourceReference: .standalone(resource: recordedMediaPreview.resource), streamable: false, video: false, preferSoftwareDecoding: false, enableSound: true, fetchAutomatically: true) self.mediaPlayer = mediaPlayer self.durationLabel.defaultDuration = Double(recordedMediaPreview.duration) self.durationLabel.status = mediaPlayer.status diff --git a/TelegramUI/ChatSecretAutoremoveTimerActionSheet.swift b/TelegramUI/ChatSecretAutoremoveTimerActionSheet.swift index 64ff4fc060..96435b70e6 100644 --- a/TelegramUI/ChatSecretAutoremoveTimerActionSheet.swift +++ b/TelegramUI/ChatSecretAutoremoveTimerActionSheet.swift @@ -14,14 +14,14 @@ final class ChatSecretAutoremoveTimerActionSheetController: ActionSheetControlle 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.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/ChatTextInputPanelNode.swift b/TelegramUI/ChatTextInputPanelNode.swift index 02e509839d..89d543f06c 100644 --- a/TelegramUI/ChatTextInputPanelNode.swift +++ b/TelegramUI/ChatTextInputPanelNode.swift @@ -255,9 +255,9 @@ class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDelegate { } } - override var account: Account? { + override var context: AccountContext? { didSet { - self.actionButtons.micButton.account = self.account + self.actionButtons.micButton.account = self.context.account } } diff --git a/TelegramUI/CommandChatInputContextPanelNode.swift b/TelegramUI/CommandChatInputContextPanelNode.swift index 5e304831a9..686633ccdb 100644 --- a/TelegramUI/CommandChatInputContextPanelNode.swift +++ b/TelegramUI/CommandChatInputContextPanelNode.swift @@ -59,15 +59,13 @@ private func preparedTransition(from fromEntries: [CommandChatInputContextPanelE } final class CommandChatInputContextPanelNode: ChatInputContextPanelNode { - private let listView: ListView private var currentEntries: [CommandChatInputContextPanelEntry]? private var enqueuedTransitions: [(CommandChatInputContextPanelTransition, 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 @@ -75,7 +73,7 @@ final class CommandChatInputContextPanelNode: 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 @@ -101,7 +99,7 @@ final class CommandChatInputContextPanelNode: ChatInputContextPanelNode { private func prepareTransition(from: [CommandChatInputContextPanelEntry]? , to: [CommandChatInputContextPanelEntry]) { let firstTime = self.currentEntries == nil - let transition = preparedTransition(from: from ?? [], to: to, account: self.account, commandSelected: { [weak self] command, sendImmediately in + let transition = preparedTransition(from: from ?? [], to: to, account: self.context.account, commandSelected: { [weak self] command, sendImmediately in if let strongSelf = self, let interfaceInteraction = strongSelf.interfaceInteraction { if sendImmediately { interfaceInteraction.sendBotCommand(command.peer, "/" + command.command.text) diff --git a/TelegramUI/CommandChatInputPanelItem.swift b/TelegramUI/CommandChatInputPanelItem.swift index cb410f59ce..cc6b1da27b 100644 --- a/TelegramUI/CommandChatInputPanelItem.swift +++ b/TelegramUI/CommandChatInputPanelItem.swift @@ -156,7 +156,7 @@ final class CommandChatInputPanelItemNode: ListViewItemNode { strongSelf.arrowNode.setImage(iconImage, for: []) - strongSelf.avatarNode.setPeer(account: item.account, peer: item.command.peer, emptyColor: item.theme.list.mediaPlaceholderColor) + strongSelf.avatarNode.setPeer(account: item.account, theme: item.theme, peer: item.command.peer, emptyColor: item.theme.list.mediaPlaceholderColor) let _ = textApply() diff --git a/TelegramUI/ComposeController.swift b/TelegramUI/ComposeController.swift index 99b453bb83..b3eda898a2 100644 --- a/TelegramUI/ComposeController.swift +++ b/TelegramUI/ComposeController.swift @@ -6,7 +6,7 @@ import SwiftSignalKit import TelegramCore public class ComposeController: ViewController { - private let account: Account + private let context: AccountContext private var contactsNode: ComposeControllerNode { return self.displayNode as! ComposeControllerNode @@ -26,10 +26,10 @@ public class ComposeController: ViewController { private var searchContentNode: NavigationBarSearchContentNode? - public init(account: Account) { - self.account = account + public init(context: AccountContext) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -48,7 +48,7 @@ public class ComposeController: 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 @@ -86,7 +86,7 @@ public class ComposeController: ViewController { } override public func loadDisplayNode() { - self.displayNode = ComposeControllerNode(account: self.account) + self.displayNode = ComposeControllerNode(context: self.context) self._ready.set(self.contactsNode.contactListNode.ready) self.contactsNode.navigationBar = self.navigationBar @@ -111,7 +111,7 @@ public class ComposeController: ViewController { self.contactsNode.openCreateNewGroup = { [weak self] in if let strongSelf = self { - let controller = ContactMultiselectionController(account: strongSelf.account, mode: .groupCreation, options: []) + let controller = ContactMultiselectionController(context: strongSelf.context, mode: .groupCreation, options: []) (strongSelf.navigationController as? NavigationController)?.pushViewController(controller) strongSelf.createActionDisposable.set((controller.result |> deliverOnMainQueue).start(next: { [weak controller] peerIds in @@ -131,7 +131,7 @@ public class ComposeController: ViewController { self.contactsNode.openCreateNewSecretChat = { [weak self] in if let strongSelf = self { - let controller = ContactSelectionController(account: strongSelf.account, title: { $0.Compose_NewEncryptedChatTitle }) + let controller = ContactSelectionController(context: strongSelf.context, title: { $0.Compose_NewEncryptedChatTitle }) strongSelf.createActionDisposable.set((controller.result |> take(1) |> deliverOnMainQueue).start(next: { [weak controller] peer in @@ -159,13 +159,13 @@ public class ComposeController: ViewController { self.contactsNode.openCreateNewChannel = { [weak self] in if let strongSelf = self { - (strongSelf.navigationController as? NavigationController)?.pushViewController(legacyChannelIntroController(account: strongSelf.account, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings)) + (strongSelf.navigationController as? NavigationController)?.pushViewController(legacyChannelIntroController(context: strongSelf.context, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings)) } } self.contactsNode.contactListNode.suppressPermissionWarning = { [weak self] in if let strongSelf = self { - presentContactsWarningSuppression(account: strongSelf.account, present: { c, a in + presentContactsWarningSuppression(context: strongSelf.context, present: { c, a in strongSelf.present(c, in: .window(.root), with: a) }) } @@ -228,6 +228,6 @@ public class ComposeController: ViewController { } private func openPeer(peerId: PeerId) { - (self.navigationController as? NavigationController)?.replaceTopController(ChatController(account: self.account, chatLocation: .peer(peerId)), animated: true) + (self.navigationController as? NavigationController)?.replaceTopController(ChatController(context: self.context, chatLocation: .peer(peerId)), animated: true) } } diff --git a/TelegramUI/ComposeControllerNode.swift b/TelegramUI/ComposeControllerNode.swift index 636392d247..e4ddab20d9 100644 --- a/TelegramUI/ComposeControllerNode.swift +++ b/TelegramUI/ComposeControllerNode.swift @@ -8,7 +8,7 @@ import SwiftSignalKit final class ComposeControllerNode: ASDisplayNode { let contactListNode: ContactListNode - private let account: Account + private let context: AccountContext private var searchDisplayController: SearchDisplayController? private var containerLayout: (ContainerViewLayout, CGFloat)? @@ -25,16 +25,16 @@ final class ComposeControllerNode: ASDisplayNode { private var presentationData: PresentationData private var presentationDataDisposable: Disposable? - init(account: Account) { - self.account = account + init(context: AccountContext) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } var openCreateNewGroupImpl: (() -> Void)? var openCreateNewSecretChatImpl: (() -> Void)? var openCreateNewChannelImpl: (() -> Void)? - self.contactListNode = ContactListNode(account: account, presentation: .single(.natural(options: [ + self.contactListNode = ContactListNode(context: context, presentation: .single(.natural(options: [ ContactListAdditionalOption(title: self.presentationData.strings.Compose_NewGroup, icon: .generic(UIImage(bundleImageName: "Contact List/CreateGroupActionIcon")!), action: { openCreateNewGroupImpl?() }), @@ -66,7 +66,7 @@ final class ComposeControllerNode: ASDisplayNode { self?.openCreateNewChannel?() } - 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 @@ -111,7 +111,7 @@ final class ComposeControllerNode: ASDisplayNode { return } - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(account: self.account, onlyWriteable: false, categories: [.cloudContacts, .global], openPeer: { [weak self] peer in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(context: self.context, onlyWriteable: false, categories: [.cloudContacts, .global], openPeer: { [weak self] peer in if let requestOpenPeerFromSearch = self?.requestOpenPeerFromSearch, case let .peer(peer, _) = peer { requestOpenPeerFromSearch(peer.id) } diff --git a/TelegramUI/ConfirmPhoneNumberController.swift b/TelegramUI/ConfirmPhoneNumberController.swift index 4fb3ab7bdb..cf7ea8e1b1 100644 --- a/TelegramUI/ConfirmPhoneNumberController.swift +++ b/TelegramUI/ConfirmPhoneNumberController.swift @@ -154,11 +154,11 @@ protocol ConfirmPhoneNumberCodeController: class { private final class ConfirmPhoneNumberCodeControllerImpl: ItemListController, ConfirmPhoneNumberCodeController { private let applyCodeImpl: (Int) -> Void - init(account: Account, state: Signal<(ItemListControllerState, (ItemListNodeState, ConfirmPhoneNumberCodeEntry.ItemGenerationArguments)), NoError>, applyCodeImpl: @escaping (Int) -> Void) { + init(context: AccountContext, state: Signal<(ItemListControllerState, (ItemListNodeState, ConfirmPhoneNumberCodeEntry.ItemGenerationArguments)), NoError>, applyCodeImpl: @escaping (Int) -> Void) { self.applyCodeImpl = applyCodeImpl - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - super.init(theme: presentationData.theme, strings: presentationData.strings, updatedPresentationData: account.telegramApplicationContext.presentationData |> map { ($0.theme, $0.strings) }, state: state, tabBarItem: nil) + let presentationData = context.currentPresentationData.with { $0 } + super.init(theme: presentationData.theme, strings: presentationData.strings, updatedPresentationData: context.presentationData |> map { ($0.theme, $0.strings) }, state: state, tabBarItem: nil) } required init(coder aDecoder: NSCoder) { @@ -170,7 +170,7 @@ private final class ConfirmPhoneNumberCodeControllerImpl: ItemListController ViewController { +func confirmPhoneNumberCodeController(context: AccountContext, phoneNumber: String, codeData: CancelAccountResetData) -> ViewController { let initialState = ConfirmPhoneNumberCodeControllerState(codeText: "", checking: false) let statePromise = ValuePromise(initialState, ignoreRepeated: true) @@ -205,7 +205,7 @@ func confirmPhoneNumberCodeController(account: Account, phoneNumber: String, cod |> take(1) |> mapToSignal { _ -> Signal in return Signal { subscriber in - return requestNextCancelAccountResetOption(network: account.network, phoneNumber: phoneNumber, phoneCodeHash: data.hash).start(next: { next in + return requestNextCancelAccountResetOption(network: context.account.network, phoneNumber: phoneNumber, phoneCodeHash: data.hash).start(next: { next in currentDataPromise?.set(.single(next)) }, error: { error in @@ -231,14 +231,14 @@ func confirmPhoneNumberCodeController(account: Account, phoneNumber: String, cod } } if let code = code { - confirmPhoneDisposable.set((requestCancelAccountReset(network: account.network, phoneCodeHash: codeData.hash, phoneCode: code) + confirmPhoneDisposable.set((requestCancelAccountReset(network: context.account.network, phoneCodeHash: codeData.hash, phoneCode: code) |> deliverOnMainQueue).start(error: { error in updateState { state in var state = state state.checking = false return state } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let alertText: String switch error { case .generic: @@ -257,7 +257,7 @@ func confirmPhoneNumberCodeController(account: Account, phoneNumber: String, cod state.checking = false return state } - 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.CancelResetAccount_Success(formatPhoneNumber(phoneNumber)).0, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) dismissImpl?() })) @@ -281,7 +281,7 @@ func confirmPhoneNumberCodeController(account: Account, phoneNumber: String, cod checkCode() }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, currentDataPromise.get() |> deliverOnMainQueue, timeout.get() |> deliverOnMainQueue) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, currentDataPromise.get() |> deliverOnMainQueue, timeout.get() |> deliverOnMainQueue) |> deliverOnMainQueue |> map { presentationData, state, data, timeout -> (ItemListControllerState, (ItemListNodeState, ConfirmPhoneNumberCodeEntry.ItemGenerationArguments)) in let leftNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Cancel), style: .regular, enabled: true, action: { @@ -309,7 +309,7 @@ func confirmPhoneNumberCodeController(account: Account, phoneNumber: String, cod actionsDisposable.dispose() } - let controller = ConfirmPhoneNumberCodeControllerImpl(account: account, state: signal, applyCodeImpl: { code in + let controller = ConfirmPhoneNumberCodeControllerImpl(context: context, state: signal, applyCodeImpl: { code in updateState { state in var state = state state.codeText = "\(code)" diff --git a/TelegramUI/ContactListNode.swift b/TelegramUI/ContactListNode.swift index 4e9f91aa09..8925722cc8 100644 --- a/TelegramUI/ContactListNode.swift +++ b/TelegramUI/ContactListNode.swift @@ -732,7 +732,7 @@ enum ContactListFilter { } final class ContactListNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private var presentation: ContactListPresentation? private let filters: [ContactListFilter] @@ -769,11 +769,11 @@ final class ContactListNode: ASDisplayNode { if value != self.enableUpdatesValue { self.enableUpdatesValue = value if value { - self.contactPeersViewPromise.set(self.account.postbox.contactPeersView(accountPeerId: self.account.peerId, includePresences: true) |> mapToThrottled { next -> Signal in + self.contactPeersViewPromise.set(self.context.account.postbox.contactPeersView(accountPeerId: self.account.peerId, includePresences: true) |> mapToThrottled { next -> Signal in return .single(next) |> then(.complete() |> delay(5.0, queue: Queue.concurrentDefaultQueue())) }) } else { - self.contactPeersViewPromise.set(self.account.postbox.contactPeersView(accountPeerId: self.account.peerId, includePresences: true) |> take(1)) + self.contactPeersViewPromise.set(self.context.account.postbox.contactPeersView(accountPeerId: self.account.peerId, includePresences: true) |> take(1)) } } } @@ -798,12 +798,12 @@ final class ContactListNode: ASDisplayNode { private var authorizationNode: PermissionContentNode private let displayPermissionPlaceholder: Bool - init(account: Account, presentation: Signal, filters: [ContactListFilter] = [.excludeSelf], selectionState: ContactListNodeGroupSelectionState? = nil, displayPermissionPlaceholder: Bool = true, displaySortOptions: Bool = false) { - self.account = account + init(context: AccountContext, presentation: Signal, filters: [ContactListFilter] = [.excludeSelf], selectionState: ContactListNodeGroupSelectionState? = nil, displayPermissionPlaceholder: Bool = true, displaySortOptions: Bool = false) { + self.context = context self.filters = filters self.displayPermissionPlaceholder = displayPermissionPlaceholder - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.listNode = ListView() self.listNode.dynamicBounceEnabled = !self.presentationData.disableAnimations @@ -814,13 +814,14 @@ final class ContactListNode: ASDisplayNode { let contactsAuthorization = Promise() contactsAuthorization.set(.single(.allowed) - |> then(DeviceAccess.authorizationStatus(account: account, subject: .contacts))) + |> then(DeviceAccess.authorizationStatus(account: context.account, subject: .contacts))) let warningKey = PostboxViewKey.noticeEntry(ApplicationSpecificNotice.contactsPermissionWarningKey()) let preferencesKey = PostboxViewKey.preferences(keys: Set([ApplicationSpecificPreferencesKeys.contactSynchronizationSettings])) let contactsWarningSuppressed = Promise<(Bool, Bool)>() contactsWarningSuppressed.set(.single((false, false)) - |> then(account.postbox.combinedView(keys: [warningKey, preferencesKey]) + |> then( + context.account.postbox.combinedView(keys: [warningKey, preferencesKey]) |> map { combined -> (Bool, Bool) in let synchronizeDeviceContacts: Bool = ((combined.views[preferencesKey] as? PreferencesView)?.values[ApplicationSpecificPreferencesKeys.contactSynchronizationSettings] as? ContactSynchronizationSettings)?.synchronizeDeviceContacts ?? true let suppressed: Bool @@ -831,7 +832,8 @@ final class ContactListNode: ASDisplayNode { suppressed = false } return (suppressed, !synchronizeDeviceContacts) - })) + } + )) var authorizeImpl: (() -> Void)? var openPrivacyPolicyImpl: (() -> Void)? @@ -913,7 +915,7 @@ final class ContactListNode: ASDisplayNode { } } - let account = self.account + let context = self.context var firstTime: Int32 = 1 let selectionStateSignal = self.selectionStatePromise.get() let transition: Signal @@ -931,7 +933,7 @@ final class ContactListNode: ASDisplayNode { |> mapToSignal { query in let foundLocalContacts: Signal<([Peer], [PeerId : PeerPresence]), NoError> if searchChatList { - let foundChatListPeers = account.postbox.searchPeers(query: query.lowercased(), groupId: nil) + let foundChatListPeers = context.account.postbox.searchPeers(query: query.lowercased(), groupId: nil) foundLocalContacts = foundChatListPeers |> mapToSignal { peers -> Signal<([Peer], [PeerId : PeerPresence]), NoError> in var resultPeers: [Peer] = [] @@ -954,17 +956,17 @@ final class ContactListNode: ASDisplayNode { } } } else { - foundLocalContacts = account.postbox.searchContacts(query: query.lowercased()) + foundLocalContacts = context.account.postbox.searchContacts(query: query.lowercased()) } let foundRemoteContacts: Signal<([FoundPeer], [FoundPeer]), NoError> = .single(([], [])) |> then( - searchPeers(account: account, query: query) + searchPeers(account: context.account, query: query) |> map { ($0.0, $0.1) } |> delay(0.2, queue: Queue.concurrentDefaultQueue()) ) let foundDeviceContacts: Signal<[DeviceContactStableId: DeviceContactBasicData], NoError> if searchDeviceContacts { - foundDeviceContacts = account.telegramApplicationContext.contactDataManager.search(query: query) + foundDeviceContacts = context.contactDataManager.search(query: query) } else { foundDeviceContacts = .single([:]) } @@ -979,7 +981,7 @@ final class ContactListNode: ASDisplayNode { for filter in filters { switch filter { case .excludeSelf: - existingPeerIds.insert(account.peerId) + existingPeerIds.insert(context.account.peerId) case let .exclude(peerIds): existingPeerIds = existingPeerIds.union(peerIds) case let .disable(peerIds): @@ -1032,7 +1034,7 @@ final class ContactListNode: ASDisplayNode { let entries = contactListNodeEntries(accountPeer: nil, peers: peers, presences: localPeersAndStatuses.1, presentation: presentation, selectionState: selectionState, theme: themeAndStrings.0, strings: themeAndStrings.1, dateTimeFormat: themeAndStrings.2, sortOrder: themeAndStrings.3, displayOrder: themeAndStrings.4, disabledPeerIds: disabledPeerIds, authorizationStatus: .allowed, warningSuppressed: (true, true), displaySortOptions: false) let previous = previousEntries.swap(entries) - return .single(preparedContactListNodeTransition(account: account, from: previous ?? [], to: entries, interaction: interaction, firstTime: previous == nil, isEmpty: false, generateIndexSections: generateSections, animation: .none)) + return .single(preparedContactListNodeTransition(account: context.account, from: previous ?? [], to: entries, interaction: interaction, firstTime: previous == nil, isEmpty: false, generateIndexSections: generateSections, animation: .none)) } if OSAtomicCompareAndSwap32(1, 0, &firstTime) { @@ -1052,7 +1054,7 @@ final class ContactListNode: ASDisplayNode { for filter in filters { switch filter { case .excludeSelf: - existingPeerIds.insert(account.peerId) + existingPeerIds.insert(context.account.peerId) case let .exclude(peerIds): existingPeerIds = existingPeerIds.union(peerIds) case let .disable(peerIds): @@ -1103,7 +1105,7 @@ final class ContactListNode: ASDisplayNode { animation = .none } - return .single(preparedContactListNodeTransition(account: account, from: previous ?? [], to: entries, interaction: interaction, firstTime: previous == nil, isEmpty: isEmpty, generateIndexSections: generateSections, animation: animation)) + return .single(preparedContactListNodeTransition(account: context.account, from: previous ?? [], to: entries, interaction: interaction, firstTime: previous == nil, isEmpty: isEmpty, generateIndexSections: generateSections, animation: animation)) } if OSAtomicCompareAndSwap32(1, 0, &firstTime) { @@ -1119,7 +1121,7 @@ final class ContactListNode: ASDisplayNode { self?.enqueueTransition(transition) })) - 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 @@ -1179,14 +1181,14 @@ final class ContactListNode: ASDisplayNode { } authorizeImpl = { - let _ = (DeviceAccess.authorizationStatus(account: account, subject: .contacts) + let _ = (DeviceAccess.authorizationStatus(account: context.account, subject: .contacts) |> take(1) |> deliverOnMainQueue).start(next: { status in switch status { case .notDetermined: DeviceAccess.authorizeAccess(to: .contacts) case .denied, .restricted: - account.telegramApplicationContext.applicationBindings.openSettings() + context.applicationBindings.openSettings() default: break } diff --git a/TelegramUI/ContactMultiselectionController.swift b/TelegramUI/ContactMultiselectionController.swift index 54573b618b..422a1c9acd 100644 --- a/TelegramUI/ContactMultiselectionController.swift +++ b/TelegramUI/ContactMultiselectionController.swift @@ -12,7 +12,7 @@ enum ContactMultiselectionControllerMode { } class ContactMultiselectionController: ViewController { - private let account: Account + private let context: AccountContext private let mode: ContactMultiselectionControllerMode private let titleView: CounterContollerTitleView @@ -62,12 +62,12 @@ class ContactMultiselectionController: ViewController { private let options: [ContactListAdditionalOption] private let filters: [ContactListFilter] - init(account: Account, mode: ContactMultiselectionControllerMode, options: [ContactListAdditionalOption], filters: [ContactListFilter] = [.excludeSelf]) { - self.account = account + init(context: AccountContext, mode: ContactMultiselectionControllerMode, options: [ContactListAdditionalOption], filters: [ContactListFilter] = [.excludeSelf]) { + self.context = context self.mode = mode self.options = options self.filters = filters - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.titleView = CounterContollerTitleView(theme: self.presentationData.theme) @@ -84,7 +84,7 @@ class ContactMultiselectionController: 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 @@ -98,7 +98,7 @@ class ContactMultiselectionController: ViewController { } }) - self.limitsConfigurationDisposable = (account.postbox.transaction { transaction -> LimitsConfiguration in + self.limitsConfigurationDisposable = (context.account.postbox.transaction { transaction -> LimitsConfiguration in return currentLimitsConfiguration(transaction: transaction) } |> deliverOnMainQueue).start(next: { [weak self] value in if let strongSelf = self { @@ -154,7 +154,7 @@ class ContactMultiselectionController: ViewController { } override func loadDisplayNode() { - self.displayNode = ContactMultiselectionControllerNode(account: self.account, mode: self.mode, options: self.options, filters: filters) + self.displayNode = ContactMultiselectionControllerNode(context: self.context, mode: self.mode, options: self.options, filters: filters) self._listReady.set(self.contactsNode.contactListNode.ready) self.contactsNode.dismiss = { [weak self] in diff --git a/TelegramUI/ContactMultiselectionControllerNode.swift b/TelegramUI/ContactMultiselectionControllerNode.swift index 41f9b83fc5..8767ecdb8a 100644 --- a/TelegramUI/ContactMultiselectionControllerNode.swift +++ b/TelegramUI/ContactMultiselectionControllerNode.swift @@ -27,7 +27,7 @@ final class ContactMultiselectionControllerNode: ASDisplayNode { let tokenListNode: EditableTokenListNode var searchResultsNode: ContactListNode? - private let account: Account + private let context: AccountContext private var containerLayout: (ContainerViewLayout, CGFloat, CGFloat)? @@ -44,9 +44,9 @@ final class ContactMultiselectionControllerNode: ASDisplayNode { private var presentationData: PresentationData private var presentationDataDisposable: Disposable? - init(account: Account, mode: ContactMultiselectionControllerMode, options: [ContactListAdditionalOption], filters: [ContactListFilter]) { + init(context: AccountContext, mode: ContactMultiselectionControllerMode, options: [ContactListAdditionalOption], filters: [ContactListFilter]) { self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } let placeholder: String switch mode { @@ -56,7 +56,7 @@ final class ContactMultiselectionControllerNode: ASDisplayNode { placeholder = self.presentationData.strings.Compose_TokenListPlaceholder } - self.contactListNode = ContactListNode(account: account, presentation: .single(.natural(options: options)), filters: filters, selectionState: ContactListNodeGroupSelectionState()) + self.contactListNode = ContactListNode(context: context, presentation: .single(.natural(options: options)), filters: filters, selectionState: ContactListNodeGroupSelectionState()) self.tokenListNode = EditableTokenListNode(theme: EditableTokenListNodeTheme(backgroundColor: self.presentationData.theme.rootController.navigationBar.backgroundColor, separatorColor: self.presentationData.theme.rootController.navigationBar.separatorColor, placeholderTextColor: self.presentationData.theme.list.itemPlaceholderTextColor, primaryTextColor: self.presentationData.theme.list.itemPrimaryTextColor, selectedTextColor: self.presentationData.theme.list.itemAccentColor, keyboardColor: self.presentationData.theme.chatList.searchBarKeyboardColor), placeholder: placeholder) super.init() @@ -99,7 +99,7 @@ final class ContactMultiselectionControllerNode: ASDisplayNode { if case let .peerSelection(value) = mode { searchChatList = value } - let searchResultsNode = ContactListNode(account: account, presentation: .single(.search(signal: searchText.get(), searchChatList: searchChatList, searchDeviceContacts: false)), filters: filters, selectionState: selectionState) + let searchResultsNode = ContactListNode(context: context, presentation: .single(.search(signal: searchText.get(), searchChatList: searchChatList, searchDeviceContacts: false)), filters: filters, selectionState: selectionState) searchResultsNode.openPeer = { peer in self?.tokenListNode.setText("") self?.openPeer?(peer) @@ -129,7 +129,7 @@ final class ContactMultiselectionControllerNode: ASDisplayNode { } } - 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/ContactSelectionController.swift b/TelegramUI/ContactSelectionController.swift index ab502e8a34..90d27ae0e7 100644 --- a/TelegramUI/ContactSelectionController.swift +++ b/TelegramUI/ContactSelectionController.swift @@ -6,7 +6,7 @@ import SwiftSignalKit import TelegramCore class ContactSelectionController: ViewController { - private let account: Account + private let context: AccountContext private let autoDismiss: Bool private var contactsNode: ContactSelectionControllerNode { @@ -61,15 +61,15 @@ class ContactSelectionController: ViewController { } } - init(account: Account, autoDismiss: Bool = true, title: @escaping (PresentationStrings) -> String, options: [ContactListAdditionalOption] = [], displayDeviceContacts: Bool = false, confirmation: @escaping (ContactListPeer) -> Signal = { _ in .single(true) }) { - self.account = account + init(context: AccountContext, autoDismiss: Bool = true, title: @escaping (PresentationStrings) -> String, options: [ContactListAdditionalOption] = [], displayDeviceContacts: Bool = false, confirmation: @escaping (ContactListPeer) -> Signal = { _ in .single(true) }) { + self.context = context self.autoDismiss = autoDismiss self.titleProducer = title self.options = options self.displayDeviceContacts = displayDeviceContacts self.confirmation = confirmation - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -133,7 +133,7 @@ class ContactSelectionController: ViewController { } override func loadDisplayNode() { - self.displayNode = ContactSelectionControllerNode(account: self.account, options: self.options, displayDeviceContacts: self.displayDeviceContacts) + self.displayNode = ContactSelectionControllerNode(context: self.context, options: self.options, displayDeviceContacts: self.displayDeviceContacts) self._ready.set(self.contactsNode.contactListNode.ready) self.contactsNode.navigationBar = self.navigationBar @@ -156,7 +156,7 @@ class ContactSelectionController: ViewController { self.contactsNode.contactListNode.suppressPermissionWarning = { [weak self] in if let strongSelf = self { - presentContactsWarningSuppression(account: strongSelf.account, present: { c, a in + presentContactsWarningSuppression(context: strongSelf.context, present: { c, a in strongSelf.present(c, in: .window(.root), with: a) }) } diff --git a/TelegramUI/ContactSelectionControllerNode.swift b/TelegramUI/ContactSelectionControllerNode.swift index 1aed27debc..ad16986ca8 100644 --- a/TelegramUI/ContactSelectionControllerNode.swift +++ b/TelegramUI/ContactSelectionControllerNode.swift @@ -20,7 +20,7 @@ final class ContactSelectionControllerNode: ASDisplayNode { let contactListNode: ContactListNode private let dimNode: ASDisplayNode - private let account: Account + private let context: AccountContext private var searchDisplayController: SearchDisplayController? private var containerLayout: (ContainerViewLayout, CGFloat)? @@ -34,12 +34,12 @@ final class ContactSelectionControllerNode: ASDisplayNode { var presentationData: PresentationData var presentationDataDisposable: Disposable? - init(account: Account, options: [ContactListAdditionalOption], displayDeviceContacts: Bool) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, options: [ContactListAdditionalOption], displayDeviceContacts: Bool) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.displayDeviceContacts = displayDeviceContacts - self.contactListNode = ContactListNode(account: account, presentation: .single(.natural(options: options))) + self.contactListNode = ContactListNode(context: context, presentation: .single(.natural(options: options))) self.dimNode = ASDisplayNode() @@ -53,7 +53,7 @@ final class ContactSelectionControllerNode: ASDisplayNode { self.addSubnode(self.contactListNode) - 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 @@ -115,7 +115,7 @@ final class ContactSelectionControllerNode: ASDisplayNode { } else { categories.insert(.global) } - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(account: self.account, onlyWriteable: false, categories: categories, openPeer: { [weak self] peer in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(context: self.context, onlyWriteable: false, categories: categories, openPeer: { [weak self] peer in self?.requestOpenPeerFromSearch?(peer) }), cancel: { [weak self] in if let requestDeactivateSearch = self?.requestDeactivateSearch { diff --git a/TelegramUI/ContactsController.swift b/TelegramUI/ContactsController.swift index 6a2ac19d46..d48e087de1 100644 --- a/TelegramUI/ContactsController.swift +++ b/TelegramUI/ContactsController.swift @@ -50,7 +50,7 @@ private func fixListNodeScrolling(_ listNode: ListView, searchNode: NavigationBa } public class ContactsController: ViewController { - private let account: Account + private let context: AccountContext private var contactsNode: ContactsControllerNode { return self.displayNode as! ContactsControllerNode @@ -70,10 +70,10 @@ public class ContactsController: ViewController { private var searchContentNode: NavigationBarSearchContentNode? - public init(account: Account) { - self.account = account + public init(context: AccountContext) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -104,7 +104,7 @@ public class ContactsController: 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 @@ -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: account, subject: .contacts), account.postbox.combinedView(keys: [warningKey, preferencesKey]) + self.authorizationDisposable = (combineLatest(DeviceAccess.authorizationStatus(account: context.account, 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 @@ -144,7 +144,7 @@ public class ContactsController: ViewController { } }) } else { - self.sortOrderPromise.set(account.postbox.combinedView(keys: [preferencesKey]) + self.sortOrderPromise.set(context.account.postbox.combinedView(keys: [preferencesKey]) |> map { combined -> ContactsSortOrder in let settings = ((combined.views[preferencesKey] as? PreferencesView)?.values[ApplicationSpecificPreferencesKeys.contactSynchronizationSettings] as? ContactSynchronizationSettings) return settings?.sortOrder ?? .presence @@ -179,7 +179,7 @@ public class ContactsController: ViewController { } override public func loadDisplayNode() { - self.displayNode = ContactsControllerNode(account: self.account, sortOrder: sortOrderPromise.get() |> distinctUntilChanged, present: { [weak self] c, a in + self.displayNode = ContactsControllerNode(context: self.context, sortOrder: sortOrderPromise.get() |> distinctUntilChanged, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a) }) self._ready.set(self.contactsNode.contactListNode.ready) @@ -196,13 +196,13 @@ public class ContactsController: ViewController { self.contactsNode.contactListNode.openPrivacyPolicy = { [weak self] in if let strongSelf = self { - openExternalUrl(account: strongSelf.account, context: .generic, url: "https://telegram.org/privacy", forceExternal: true, presentationData: strongSelf.presentationData, applicationContext: strongSelf.account.telegramApplicationContext, navigationController: strongSelf.navigationController as? NavigationController, dismissInput: {}) + openExternalUrl(context: strongSelf.context, urlContext: .generic, url: "https://telegram.org/privacy", forceExternal: true, presentationData: strongSelf.presentationData, navigationController: strongSelf.navigationController as? NavigationController, dismissInput: {}) } } self.contactsNode.contactListNode.suppressPermissionWarning = { [weak self] in if let strongSelf = self { - presentContactsWarningSuppression(account: strongSelf.account, present: { c, a in + presentContactsWarningSuppression(context: strongSelf.context, present: { c, a in strongSelf.present(c, in: .window(.root), with: a) }) } @@ -217,15 +217,15 @@ public class ContactsController: ViewController { strongSelf.contactsNode.contactListNode.listNode.clearHighlightAnimated(true) switch peer { case let .peer(peer, _): - (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(account: strongSelf.account, chatLocation: .peer(peer.id))) + (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(context: strongSelf.context, chatLocation: .peer(peer.id))) case let .deviceContact(id, _): - let _ = (strongSelf.account.telegramApplicationContext.contactDataManager.extendedData(stableId: id) + let _ = (strongSelf.context.contactDataManager.extendedData(stableId: id) |> take(1) |> deliverOnMainQueue).start(next: { value in guard let strongSelf = self, let value = value else { return } - (strongSelf.navigationController as? NavigationController)?.pushViewController(deviceContactInfoController(account: strongSelf.account, subject: .vcard(nil, id, value))) + (strongSelf.navigationController as? NavigationController)?.pushViewController(deviceContactInfoController(context: strongSelf.context, subject: .vcard(nil, id, value))) }) } } @@ -233,7 +233,7 @@ public class ContactsController: ViewController { self.contactsNode.openInvite = { [weak self] in if let strongSelf = self { - (strongSelf.navigationController as? NavigationController)?.pushViewController(InviteContactsController(account: strongSelf.account)) + (strongSelf.navigationController as? NavigationController)?.pushViewController(InviteContactsController(context: strongSelf.context)) } } @@ -307,7 +307,7 @@ public class ContactsController: ViewController { let updateSortOrder: (ContactsSortOrder) -> Void = { [weak self] sortOrder in if let strongSelf = self { strongSelf.sortOrderPromise.set(.single(sortOrder)) - let _ = updateContactSettingsInteractively(postbox: strongSelf.account.postbox) { current -> ContactSynchronizationSettings in + let _ = updateContactSettingsInteractively(postbox: strongSelf.context.account.postbox) { current -> ContactSynchronizationSettings in var updated = current updated.sortOrder = sortOrder return updated @@ -335,7 +335,7 @@ public class ContactsController: ViewController { } @objc func addPressed() { - let _ = (DeviceAccess.authorizationStatus(account: self.account, subject: .contacts) + let _ = (DeviceAccess.authorizationStatus(account: self.context.account, subject: .contacts) |> take(1) |> deliverOnMainQueue).start(next: { [weak self] status in guard let strongSelf = self else { @@ -345,20 +345,20 @@ public class ContactsController: ViewController { switch status { case .allowed: let contactData = DeviceContactExtendedData(basicData: DeviceContactBasicData(firstName: "", lastName: "", phoneNumbers: [DeviceContactPhoneNumberData(label: "_$!!$_", value: "")]), middleName: "", prefix: "", suffix: "", organization: "", jobTitle: "", department: "", emailAddresses: [], urls: [], addresses: [], birthdayDate: nil, socialProfiles: [], instantMessagingProfiles: []) - strongSelf.present(deviceContactInfoController(account: strongSelf.account, subject: .create(peer: nil, contactData: contactData, completion: { peer, stableId, contactData in + strongSelf.present(deviceContactInfoController(context: strongSelf.context, subject: .create(peer: nil, contactData: contactData, completion: { peer, stableId, contactData in guard let strongSelf = self else { return } if let peer = peer { - if let infoController = peerInfoController(account: strongSelf.account, peer: peer) { + if let infoController = peerInfoController(context: strongSelf.context, peer: peer) { (strongSelf.navigationController as? NavigationController)?.pushViewController(infoController) } } else { - (strongSelf.navigationController as? NavigationController)?.pushViewController(deviceContactInfoController(account: strongSelf.account, subject: .vcard(nil, stableId, contactData))) + (strongSelf.navigationController as? NavigationController)?.pushViewController(deviceContactInfoController(context: strongSelf.context, subject: .vcard(nil, stableId, contactData))) } })), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) case .notDetermined: - DeviceAccess.authorizeAccess(to: .contacts, account: strongSelf.account) + DeviceAccess.authorizeAccess(to: .contacts, account: strongSelf.context.account) 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: { diff --git a/TelegramUI/ContactsControllerNode.swift b/TelegramUI/ContactsControllerNode.swift index 2e0d409c13..6daa4fe2ff 100644 --- a/TelegramUI/ContactsControllerNode.swift +++ b/TelegramUI/ContactsControllerNode.swift @@ -8,7 +8,7 @@ import SwiftSignalKit final class ContactsControllerNode: ASDisplayNode { let contactListNode: ContactListNode - private let account: Account + private let context: AccountContext private var searchDisplayController: SearchDisplayController? private var containerLayout: (ContainerViewLayout, CGFloat)? @@ -22,10 +22,10 @@ final class ContactsControllerNode: ASDisplayNode { private var presentationData: PresentationData private var presentationDataDisposable: Disposable? - init(account: Account, sortOrder: Signal, present: @escaping (ViewController, Any?) -> Void) { - self.account = account + init(context: AccountContext, sortOrder: Signal, present: @escaping (ViewController, Any?) -> Void) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } var inviteImpl: (() -> Void)? let options = [ContactListAdditionalOption(title: presentationData.strings.Contacts_InviteFriends, icon: .generic(UIImage(bundleImageName: "Contact List/AddMemberIcon")!), action: { @@ -42,7 +42,7 @@ final class ContactsControllerNode: ASDisplayNode { } } - self.contactListNode = ContactListNode(account: account, presentation: presentation, displaySortOptions: true) + self.contactListNode = ContactListNode(context: context, presentation: presentation, displaySortOptions: true) super.init() @@ -54,7 +54,7 @@ final class ContactsControllerNode: ASDisplayNode { self.addSubnode(self.contactListNode) - 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 @@ -84,7 +84,7 @@ final class ContactsControllerNode: ASDisplayNode { default: let presentationData = strongSelf.presentationData 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() })]), nil) } }) @@ -123,7 +123,7 @@ final class ContactsControllerNode: ASDisplayNode { return } - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(account: self.account, onlyWriteable: false, categories: [.cloudContacts, .global, .deviceContacts], openPeer: { [weak self] peer in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(context: self.context, onlyWriteable: false, categories: [.cloudContacts, .global, .deviceContacts], openPeer: { [weak self] peer in if let requestOpenPeerFromSearch = self?.requestOpenPeerFromSearch { requestOpenPeerFromSearch(peer) } diff --git a/TelegramUI/ContactsPeerItem.swift b/TelegramUI/ContactsPeerItem.swift index 38c768f1d5..82e48d3d93 100644 --- a/TelegramUI/ContactsPeerItem.swift +++ b/TelegramUI/ContactsPeerItem.swift @@ -629,7 +629,7 @@ class ContactsPeerItemNode: ItemListRevealOptionsItemNode { if peer.id == item.account.peerId, case .generalSearch = item.peerMode { overrideImage = .savedMessagesIcon } - strongSelf.avatarNode.setPeer(account: item.account, peer: peer, overrideImage: overrideImage, emptyColor: item.theme.list.mediaPlaceholderColor, synchronousLoad: synchronousLoads) + strongSelf.avatarNode.setPeer(account: item.account, theme: item.theme, peer: peer, overrideImage: overrideImage, emptyColor: item.theme.list.mediaPlaceholderColor, synchronousLoad: synchronousLoads) } case let .deviceContact(_, contact): let letters: [String] diff --git a/TelegramUI/ContactsSearchContainerNode.swift b/TelegramUI/ContactsSearchContainerNode.swift index 9d0778dd8e..ee865658a4 100644 --- a/TelegramUI/ContactsSearchContainerNode.swift +++ b/TelegramUI/ContactsSearchContainerNode.swift @@ -123,7 +123,7 @@ struct ContactsSearchCategories: OptionSet { } final class ContactsSearchContainerNode: SearchDisplayControllerContentNode { - private let account: Account + private let context: AccountContext private let openPeer: (ContactListPeer) -> Void private let dimNode: ASDisplayNode @@ -138,11 +138,11 @@ final class ContactsSearchContainerNode: SearchDisplayControllerContentNode { private var containerViewLayout: (ContainerViewLayout, CGFloat)? private var enqueuedTransitions: [ContactListSearchContainerTransition] = [] - init(account: Account, onlyWriteable: Bool, categories: ContactsSearchCategories, filters: [ContactListFilter] = [.excludeSelf], openPeer: @escaping (ContactListPeer) -> Void) { + init(context: AccountContext, onlyWriteable: Bool, categories: ContactsSearchCategories, filters: [ContactListFilter] = [.excludeSelf], openPeer: @escaping (ContactListPeer) -> Void) { self.account = account self.openPeer = openPeer - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.themeAndStringsPromise = Promise((self.presentationData.theme, self.presentationData.strings)) @@ -187,7 +187,7 @@ final class ContactsSearchContainerNode: SearchDisplayControllerContentNode { let searchDeviceContacts = categories.contains(.deviceContacts) let foundDeviceContacts: Signal<[DeviceContactStableId: DeviceContactBasicData]?, NoError> if searchDeviceContacts { - foundDeviceContacts = account.telegramApplicationContext.contactDataManager.search(query: query) + foundDeviceContacts = context.contactDataManager.search(query: query) |> map(Optional.init) } else { foundDeviceContacts = .single([:]) @@ -202,7 +202,7 @@ final class ContactsSearchContainerNode: SearchDisplayControllerContentNode { for filter in filters { switch filter { case .excludeSelf: - existingPeerIds.insert(account.peerId) + existingPeerIds.insert(context.account.peerId) case let .exclude(peerIds): existingPeerIds = existingPeerIds.union(peerIds) case let .disable(peerIds): @@ -292,7 +292,7 @@ final class ContactsSearchContainerNode: SearchDisplayControllerContentNode { if let strongSelf = self { let previousItems = previousSearchItems.swap(items ?? []) - let transition = contactListSearchContainerPreparedRecentTransition(from: previousItems, to: items ?? [], isSearching: items != nil, account: account, nameSortOrder: strongSelf.presentationData.nameSortOrder, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder, timeFormat: strongSelf.presentationData.dateTimeFormat, openPeer: { peer in self?.listNode.clearHighlightAnimated(true) + let transition = contactListSearchContainerPreparedRecentTransition(from: previousItems, to: items ?? [], isSearching: items != nil, account: context.account, nameSortOrder: strongSelf.presentationData.nameSortOrder, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder, timeFormat: strongSelf.presentationData.dateTimeFormat, openPeer: { peer in self?.listNode.clearHighlightAnimated(true) self?.openPeer(peer) }) diff --git a/TelegramUI/ConvertToSupergroupController.swift b/TelegramUI/ConvertToSupergroupController.swift index 63cb758982..b3893bea39 100644 --- a/TelegramUI/ConvertToSupergroupController.swift +++ b/TelegramUI/ConvertToSupergroupController.swift @@ -112,7 +112,7 @@ private func convertToSupergroupEntries(presentationData: PresentationData) -> [ return entries } -public func convertToSupergroupController(account: Account, peerId: PeerId) -> ViewController { +public func convertToSupergroupController(context: AccountContext, peerId: PeerId) -> ViewController { var replaceControllerImpl: ((ViewController) -> Void)? var presentControllerImpl: ((ViewController, Any?) -> Void)? @@ -128,7 +128,7 @@ public func convertToSupergroupController(account: Account, peerId: PeerId) -> V actionsDisposable.add(convertDisposable) let arguments = ConvertToSupergroupArguments(convert: { - 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.Group_UpgradeConfirmation, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: { var alreadyConverting = false @@ -140,15 +140,15 @@ public func convertToSupergroupController(account: Account, peerId: PeerId) -> V } if !alreadyConverting { - convertDisposable.set((convertGroupToSupergroup(account: account, peerId: peerId) + convertDisposable.set((convertGroupToSupergroup(account: context.account, peerId: peerId) |> deliverOnMainQueue).start(next: { createdPeerId in - replaceControllerImpl?(ChatController(account: account, chatLocation: .peer(createdPeerId))) + replaceControllerImpl?(ChatController(account: context.account, chatLocation: .peer(createdPeerId))) })) } })]), nil) }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get()) |> deliverOnMainQueue |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, ConvertToSupergroupEntry.ItemGenerationArguments)) in @@ -166,7 +166,7 @@ public func convertToSupergroupController(account: Account, peerId: PeerId) -> V actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) replaceControllerImpl = { [weak controller] c in if let controller = controller { (controller.navigationController as? NavigationController)?.replaceAllButRootController(c, animated: true) diff --git a/TelegramUI/CreateChannelController.swift b/TelegramUI/CreateChannelController.swift index 18b123fa02..f09de7cb20 100644 --- a/TelegramUI/CreateChannelController.swift +++ b/TelegramUI/CreateChannelController.swift @@ -185,7 +185,7 @@ private func CreateChannelEntries(presentationData: PresentationData, state: Cre return entries } -public func createChannelController(account: Account) -> ViewController { +public func createChannelController(context: AccountContext) -> ViewController { let initialState = CreateChannelState(creating: false, editingName: ItemListAvatarAndNameInfoItemName.title(title: "", type: .channel), editingDescriptionText: "", avatar: nil) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) @@ -203,7 +203,7 @@ public func createChannelController(account: Account) -> ViewController { let uploadedAvatar = Promise() - let arguments = CreateChannelArguments(account: account, updateEditingName: { editingName in + let arguments = CreateChannelArguments(account: context.account, updateEditingName: { editingName in updateState { current in var current = current switch editingName { @@ -233,7 +233,7 @@ public func createChannelController(account: Account) -> ViewController { } endEditingImpl?() - actionsDisposable.add((createChannel(account: account, title: title, description: description.isEmpty ? nil : description) |> deliverOnMainQueue |> afterDisposed { + actionsDisposable.add((createChannel(account: context.account, title: title, description: description.isEmpty ? nil : description) |> deliverOnMainQueue |> afterDisposed { Queue.mainQueue().async { updateState { current in var current = current @@ -247,12 +247,12 @@ public func createChannelController(account: Account) -> ViewController { return $0.avatar } if let _ = updatingAvatar { - let _ = updatePeerPhoto(postbox: account.postbox, network: account.network, stateManager: account.stateManager, accountPeerId: account.peerId, peerId: peerId, photo: uploadedAvatar.get(), mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) + 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: context.account.postbox, resource: resource, representations: representations) }).start() } - let controller = channelVisibilityController(account: account, peerId: peerId, mode: .initialSetup, upgradedToSupergroup: { _, f in f() }) + let controller = channelVisibilityController(context: context, peerId: peerId, mode: .initialSetup, upgradedToSupergroup: { _, f in f() }) replaceControllerImpl?(controller) } }, error: { _ in @@ -267,9 +267,9 @@ public func createChannelController(account: Account) -> ViewController { } let _ = (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 = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: .custom, theme: presentationData.theme) legacyController.statusBar.statusBarStyle = .Ignore @@ -335,7 +335,7 @@ public func createChannelController(account: Account) -> ViewController { }) }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get()) |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, CreateChannelEntry.ItemGenerationArguments)) in let rightNavigationButton: ItemListNavigationButton @@ -355,7 +355,7 @@ public func createChannelController(account: Account) -> ViewController { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) replaceControllerImpl = { [weak controller] value in (controller?.navigationController as? NavigationController)?.replaceAllButRootController(value, animated: true) } diff --git a/TelegramUI/CreateGroupController.swift b/TelegramUI/CreateGroupController.swift index 479d8b7ef5..bc6a87eb38 100644 --- a/TelegramUI/CreateGroupController.swift +++ b/TelegramUI/CreateGroupController.swift @@ -219,7 +219,7 @@ private func createGroupEntries(presentationData: PresentationData, state: Creat return entries } -public func createGroupController(account: Account, peerIds: [PeerId]) -> ViewController { +public func createGroupController(context: AccountContext, peerIds: [PeerId]) -> ViewController { let initialState = CreateGroupState(creating: false, editingName: .title(title: "", type: .group), avatar: nil) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) @@ -237,7 +237,7 @@ public func createGroupController(account: Account, peerIds: [PeerId]) -> ViewCo let uploadedAvatar = Promise() - let arguments = CreateGroupArguments(account: account, updateEditingName: { editingName in + let arguments = CreateGroupArguments(account: context.account, updateEditingName: { editingName in updateState { current in var current = current current.editingName = editingName @@ -255,7 +255,7 @@ public func createGroupController(account: Account, peerIds: [PeerId]) -> ViewCo return current } endEditingImpl?() - actionsDisposable.add((createGroup(account: account, title: title, peerIds: peerIds) + actionsDisposable.add((createGroup(account: context.account, title: title, peerIds: peerIds) |> deliverOnMainQueue |> afterDisposed { Queue.mainQueue().async { @@ -271,11 +271,11 @@ public func createGroupController(account: Account, peerIds: [PeerId]) -> ViewCo return $0.avatar } if let _ = updatingAvatar { - let _ = updatePeerPhoto(postbox: account.postbox, network: account.network, stateManager: account.stateManager, accountPeerId: account.peerId, peerId: peerId, photo: uploadedAvatar.get(), mapResourceToAvatarSizes: { resource, representations in + 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) }).start() } - let controller = ChatController(account: account, chatLocation: .peer(peerId)) + let controller = ChatController(context: context, chatLocation: .peer(peerId)) replaceControllerImpl?(controller) } })) @@ -287,10 +287,11 @@ public func createGroupController(account: Account, peerIds: [PeerId]) -> ViewCo return state.editingName.composedTitle } - let _ = (account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in + let _ = (context.account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in return (transaction.getPeer(account.peerId), currentSearchBotsConfiguration(transaction: transaction)) - } |> deliverOnMainQueue).start(next: { peer, searchBotsConfiguration in - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + } + |> deliverOnMainQueue).start(next: { peer, searchBotsConfiguration in + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: .custom, theme: presentationData.theme) legacyController.statusBar.statusBarStyle = .Ignore @@ -308,9 +309,9 @@ public func createGroupController(account: Account, peerIds: [PeerId]) -> ViewCo 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) @@ -322,7 +323,7 @@ public func createGroupController(account: Account, peerIds: [PeerId]) -> ViewCo 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) })) @@ -356,7 +357,7 @@ public func createGroupController(account: Account, peerIds: [PeerId]) -> ViewCo }) }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), account.postbox.multiplePeersView(peerIds)) + let signal = combineLatest(context.presentationData, statePromise.get(), context.account.postbox.multiplePeersView(peerIds)) |> map { presentationData, state, view -> (ItemListControllerState, (ItemListNodeState, CreateGroupEntry.ItemGenerationArguments)) in let rightNavigationButton: ItemListNavigationButton @@ -377,7 +378,7 @@ public func createGroupController(account: Account, peerIds: [PeerId]) -> ViewCo actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) replaceControllerImpl = { [weak controller] value in (controller?.navigationController as? NavigationController)?.replaceAllButRootController(value, animated: true) } diff --git a/TelegramUI/CreatePasswordController.swift b/TelegramUI/CreatePasswordController.swift index 40a50b3ddf..c77f0c38dd 100644 --- a/TelegramUI/CreatePasswordController.swift +++ b/TelegramUI/CreatePasswordController.swift @@ -218,7 +218,7 @@ enum CreatePasswordState: Equatable { case pendingVerification(emailPattern: String) } -func createPasswordController(account: Account, context: CreatePasswordContext, state: CreatePasswordState, completion: @escaping (String, String, Bool) -> Void, updatePasswordEmailConfirmation: @escaping ((String, String)?) -> Void, processPasswordEmailConfirmation: Bool = true) -> ViewController { +func createPasswordController(context: AccountContext, context: 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 @@ -244,7 +244,7 @@ func createPasswordController(account: Account, context: CreatePasswordContext, return s } if let state = state { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } if state.passwordText.isEmpty { } else if state.passwordText != state.passwordConfirmationText { presentControllerImpl?(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.TwoStepAuth_SetupPasswordConfirmFailed, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) @@ -265,7 +265,7 @@ func createPasswordController(account: Account, context: CreatePasswordContext, state.saving = true return state } - saveDisposable.set((updateTwoStepVerificationPassword(network: account.network, currentPassword: currentPassword, updatedPassword: .password(password: state.passwordText, hint: state.hintText, email: email)) + saveDisposable.set((updateTwoStepVerificationPassword(network: context.account.network, currentPassword: currentPassword, updatedPassword: .password(password: state.passwordText, hint: state.hintText, email: email)) |> deliverOnMainQueue).start(next: { update in switch update { case .none: @@ -347,7 +347,7 @@ func createPasswordController(account: Account, context: CreatePasswordContext, return state } - saveDisposable.set((updateTwoStepVerificationPassword(network: account.network, currentPassword: currentPassword, updatedPassword: .none) + saveDisposable.set((updateTwoStepVerificationPassword(network: context.account.network, currentPassword: currentPassword, updatedPassword: .none) |> deliverOnMainQueue).start(next: { _ in updateState { state in var state = state @@ -365,7 +365,7 @@ func createPasswordController(account: Account, context: CreatePasswordContext, })) }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get()) |> deliverOnMainQueue |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, CreatePasswordEntry.ItemGenerationArguments)) in let leftNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Cancel), style: .regular, enabled: true, action: { @@ -406,7 +406,7 @@ func createPasswordController(account: Account, context: CreatePasswordContext, actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) dismissImpl = { [weak controller] in controller?.view.endEditing(true) controller?.dismiss() diff --git a/TelegramUI/CreatePollController.swift b/TelegramUI/CreatePollController.swift index b86e141627..e176531b3d 100644 --- a/TelegramUI/CreatePollController.swift +++ b/TelegramUI/CreatePollController.swift @@ -192,7 +192,7 @@ private func createPollControllerEntries(presentationData: PresentationData, sta return entries } -public func createPollController(account: Account, peerId: PeerId, completion: @escaping (EnqueueMessage) -> Void) -> ViewController { +public func createPollController(context: AccountContext, peerId: PeerId, completion: @escaping (EnqueueMessage) -> Void) -> ViewController { let statePromise = ValuePromise(CreatePollControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: CreatePollControllerState()) let updateState: ((CreatePollControllerState) -> CreatePollControllerState) -> Void = { f in @@ -299,7 +299,7 @@ public func createPollController(account: Account, peerId: PeerId, completion: @ let previousOptionIds = Atomic<[Int]?>(value: nil) let limitsKey = PostboxViewKey.preferences(keys: Set([PreferencesKeys.limitsConfiguration])) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, account.postbox.combinedView(keys: [limitsKey])) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, 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 @@ -381,7 +381,7 @@ public func createPollController(account: Account, peerId: PeerId, completion: @ actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, a in controller?.present(c, in: .window(.root), with: a) } diff --git a/TelegramUI/DataAndStorageSettingsController.swift b/TelegramUI/DataAndStorageSettingsController.swift index f13c270080..8436267174 100644 --- a/TelegramUI/DataAndStorageSettingsController.swift +++ b/TelegramUI/DataAndStorageSettingsController.swift @@ -417,7 +417,7 @@ private func dataAndStorageControllerEntries(state: DataAndStorageControllerStat return entries } -func dataAndStorageController(account: Account) -> ViewController { +func dataAndStorageController(context: AccountContext) -> ViewController { let initialState = DataAndStorageControllerState() let statePromise = ValuePromise(initialState, ignoreRepeated: true) @@ -427,7 +427,7 @@ func dataAndStorageController(account: Account) -> ViewController { let actionsDisposable = DisposableSet() let dataAndStorageDataPromise = Promise() - dataAndStorageDataPromise.set(account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings, ApplicationSpecificPreferencesKeys.generatedMediaStoreSettings, ApplicationSpecificPreferencesKeys.voiceCallSettings, + dataAndStorageDataPromise.set(context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings, ApplicationSpecificPreferencesKeys.generatedMediaStoreSettings, ApplicationSpecificPreferencesKeys.voiceCallSettings, PreferencesKeys.proxySettings]) |> map { view -> DataAndStorageData in let automaticMediaDownloadSettings: AutomaticMediaDownloadSettings @@ -460,28 +460,28 @@ func dataAndStorageController(account: Account) -> ViewController { }) let arguments = DataAndStorageControllerArguments(openStorageUsage: { - pushControllerImpl?(storageUsageController(account: account)) + pushControllerImpl?(storageUsageController(context: context)) }, openNetworkUsage: { - pushControllerImpl?(networkUsageStatsController(account: account)) + pushControllerImpl?(networkUsageStatsController(context: context)) }, openProxy: { - pushControllerImpl?(proxySettingsController(account: account)) + pushControllerImpl?(proxySettingsController(context: context)) }, toggleAutomaticDownloadMaster: { value in - let _ = updateMediaDownloadSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.masterEnabled = value return settings }).start() }, openAutomaticDownloadCategory: { category in - pushControllerImpl?(autodownloadMediaCategoryController(account: account, category: category)) + pushControllerImpl?(autodownloadMediaCategoryController(context: context, category: category)) }, resetAutomaticDownload: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) actionSheet.setItemGroups([ActionSheetItemGroup(items: [ ActionSheetTextItem(title: presentationData.strings.AutoDownloadSettings_ResetHelp), ActionSheetButtonItem(title: presentationData.strings.AutoDownloadSettings_Reset, color: .destructive, action: { [weak actionSheet] in actionSheet?.dismissAnimated() - let _ = updateMediaDownloadSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings let defaultSettings = AutomaticMediaDownloadSettings.defaultSettings settings.masterEnabled = defaultSettings.masterEnabled @@ -496,28 +496,28 @@ func dataAndStorageController(account: Account) -> ViewController { ])]) presentControllerImpl?(actionSheet, nil) }, openVoiceUseLessData: { - pushControllerImpl?(voiceCallDataSavingController(account: account)) + pushControllerImpl?(voiceCallDataSavingController(context: context)) }, openSaveIncomingPhotos: { - pushControllerImpl?(saveIncomingMediaController(account: account)) + pushControllerImpl?(saveIncomingMediaController(context: context)) }, toggleSaveEditedPhotos: { value in - let _ = updateGeneratedMediaStoreSettingsInteractively(postbox: account.postbox, { current in + let _ = updateGeneratedMediaStoreSettingsInteractively(postbox: context.account.postbox, { current in return current.withUpdatedStoreEditedPhotos(value) }).start() }, toggleAutoplayGifs: { value in - let _ = updateMediaDownloadSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.autoplayGifs = value return settings }).start() }, toggleDownloadInBackground: { value in - let _ = updateMediaDownloadSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.downloadInBackground = value return settings }).start() }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), dataAndStorageDataPromise.get()) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, statePromise.get(), dataAndStorageDataPromise.get()) |> deliverOnMainQueue |> map { presentationData, state, dataAndStorageData -> (ItemListControllerState, (ItemListNodeState, DataAndStorageEntry.ItemGenerationArguments)) in let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.ChatSettings_Title), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: false) @@ -528,7 +528,7 @@ func dataAndStorageController(account: Account) -> ViewController { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] c in if let controller = controller { diff --git a/TelegramUI/DataPrivacySettingsController.swift b/TelegramUI/DataPrivacySettingsController.swift index c2b28344f7..bfed57fa65 100644 --- a/TelegramUI/DataPrivacySettingsController.swift +++ b/TelegramUI/DataPrivacySettingsController.swift @@ -275,7 +275,7 @@ private func dataPrivacyControllerEntries(presentationData: PresentationData, st return entries } -public func dataPrivacyController(account: Account) -> ViewController { +public func dataPrivacyController(context: AccountContext) -> ViewController { let statePromise = ValuePromise(DataPrivacyControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: DataPrivacyControllerState()) let updateState: ((DataPrivacyControllerState) -> DataPrivacyControllerState) -> Void = { f in @@ -292,8 +292,8 @@ public func dataPrivacyController(account: Account) -> ViewController { let clearPaymentInfoDisposable = MetaDisposable() actionsDisposable.add(clearPaymentInfoDisposable) - let arguments = DataPrivacyControllerArguments(account: account, clearPaymentInfo: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let arguments = DataPrivacyControllerArguments(account: context.account, clearPaymentInfo: { + let presentationData = context.currentPresentationData.with { $0 } let controller = ActionSheetController(presentationTheme: presentationData.theme) let dismissAction: () -> Void = { [weak controller] in controller?.dismissAnimated() @@ -348,14 +348,14 @@ public func dataPrivacyController(account: Account) -> ViewController { info.insert(.shippingInfo) } - clearPaymentInfoDisposable.set((clearBotPaymentInfo(network: account.network, info: info) + clearPaymentInfoDisposable.set((clearBotPaymentInfo(network: context.account.network, info: info) |> deliverOnMainQueue).start(completed: { updateState { state in var state = state state.clearingPaymentInfo = false return state } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .success)) })) } @@ -368,7 +368,7 @@ public func dataPrivacyController(account: Account) -> ViewController { ]) presentControllerImpl?(controller) }, updateSecretChatLinkPreviews: { value in - let _ = ApplicationSpecificNotice.setSecretChatLinkPreviews(postbox: account.postbox, value: value).start() + let _ = ApplicationSpecificNotice.setSecretChatLinkPreviews(postbox: context.account.postbox, value: value).start() }, deleteContacts: { var canBegin = false updateState { state in @@ -378,7 +378,7 @@ public func dataPrivacyController(account: Account) -> ViewController { return state } if canBegin { - 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.Privacy_ContactsResetConfirmation, actions: [TextAlertAction(type: .destructiveAction, title: presentationData.strings.Common_Delete, action: { var begin = false updateState { state in @@ -394,26 +394,26 @@ public func dataPrivacyController(account: Account) -> ViewController { return } - let _ = updateContactSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateContactSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.synchronizeDeviceContacts = false return settings }) - actionsDisposable.add(((deleteAllContacts(postbox: account.postbox, network: account.network) |> then(resetSavedContacts(network: account.network))) + actionsDisposable.add(((deleteAllContacts(postbox: context.account.postbox, network: context.account.network) |> then(resetSavedContacts(network: context.account.network))) |> deliverOnMainQueue).start(completed: { updateState { state in var state = state state.deletingContacts = false return state } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .success)) })) }), TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {})])) } }, updateSyncContacts: { value in - let _ = updateContactSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateContactSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.synchronizeDeviceContacts = value return settings @@ -425,10 +425,10 @@ public func dataPrivacyController(account: Account) -> ViewController { state.updatedSuggestFrequentContacts = value return state } - let _ = updateRecentPeersEnabled(postbox: account.postbox, network: account.network, enabled: value).start() + let _ = updateRecentPeersEnabled(postbox: context.account.postbox, network: context.account.network, enabled: value).start() } if !value { - 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.Privacy_TopPeersWarning, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: { apply() })])) @@ -436,7 +436,7 @@ public func dataPrivacyController(account: Account) -> ViewController { apply() } }, deleteCloudDrafts: { - 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() @@ -454,14 +454,14 @@ public func dataPrivacyController(account: Account) -> ViewController { return state } if clear { - clearPaymentInfoDisposable.set((clearCloudDraftsInteractively(postbox: account.postbox, network: account.network, accountPeerId: account.peerId) + clearPaymentInfoDisposable.set((clearCloudDraftsInteractively(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId) |> deliverOnMainQueue).start(completed: { updateState { state in var state = state state.deletingCloudDrafts = false return state } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .success)) })) } @@ -477,9 +477,9 @@ public func dataPrivacyController(account: Account) -> ViewController { let preferencesKey = PostboxViewKey.preferences(keys: Set([ApplicationSpecificPreferencesKeys.contactSynchronizationSettings])) - actionsDisposable.add(managedUpdatedRecentPeers(accountPeerId: account.peerId, postbox: account.postbox, network: account.network).start()) + actionsDisposable.add(managedUpdatedRecentPeers(accountPeerId: context.account.peerId, postbox: context.account.postbox, network: context.account.network).start()) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, account.postbox.combinedView(keys: [.noticeEntry(ApplicationSpecificNotice.secretChatLinkPreviewsKey()), preferencesKey]), recentPeers(account: account)) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, 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) }) @@ -511,7 +511,7 @@ public func dataPrivacyController(account: Account) -> ViewController { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c in controller?.present(c, in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } diff --git a/TelegramUI/DateSelectionActionSheetController.swift b/TelegramUI/DateSelectionActionSheetController.swift index 2fc588dc45..4e1bfd8673 100644 --- a/TelegramUI/DateSelectionActionSheetController.swift +++ b/TelegramUI/DateSelectionActionSheetController.swift @@ -14,14 +14,14 @@ final class DateSelectionActionSheetController: ActionSheetController { return self._ready } - init(account: Account, title: String?, currentValue: Int32, minimumDate: Date? = nil, maximumDate: Date? = nil, emptyTitle: String? = nil, applyValue: @escaping (Int32?) -> Void) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, title: String?, currentValue: Int32, minimumDate: Date? = nil, maximumDate: Date? = nil, emptyTitle: String? = nil, 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.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/DebugAccountsController.swift b/TelegramUI/DebugAccountsController.swift index 8f0f8a472a..09cb5330af 100644 --- a/TelegramUI/DebugAccountsController.swift +++ b/TelegramUI/DebugAccountsController.swift @@ -95,17 +95,17 @@ private func debugAccountsControllerEntries(view: AccountRecordsView, presentati return entries } -public func debugAccountsController(account: Account, accountManager: AccountManager) -> ViewController { +public func debugAccountsController(context: AccountContext, accountManager: AccountManager) -> ViewController { var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? - let arguments = DebugAccountsControllerArguments(account: account, presentController: { controller, arguments in + let arguments = DebugAccountsControllerArguments(context: context, presentController: { controller, arguments in presentControllerImpl?(controller, arguments) }, switchAccount: { id in let _ = accountManager.transaction({ transaction -> Void in transaction.setCurrentId(id) }).start() }, loginNewAccount: { - 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() @@ -132,7 +132,7 @@ public func debugAccountsController(account: Account, accountManager: AccountMan presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, accountManager.accountRecords()) + let signal = combineLatest(context.presentationData, accountManager.accountRecords()) |> map { presentationData, view -> (ItemListControllerState, (ItemListNodeState, DebugAccountsControllerEntry.ItemGenerationArguments)) in let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text("Accounts"), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) let listState = ItemListNodeState(entries: debugAccountsControllerEntries(view: view, presentationData: presentationData), style: .blocks) @@ -140,7 +140,7 @@ public func debugAccountsController(account: Account, accountManager: AccountMan return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, a in controller?.present(c, in: .window(.root), with: a) } diff --git a/TelegramUI/DebugController.swift b/TelegramUI/DebugController.swift index 61f4a69e4e..6bfe088d99 100644 --- a/TelegramUI/DebugController.swift +++ b/TelegramUI/DebugController.swift @@ -264,11 +264,11 @@ private func debugControllerEntries(presentationData: PresentationData, loggingS return entries } -public func debugController(account: Account, accountManager: AccountManager) -> ViewController { +public func debugController(context: AccountContext, accountManager: AccountManager) -> ViewController { var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? var pushControllerImpl: ((ViewController) -> Void)? - let arguments = DebugControllerArguments(account: account, accountManager: accountManager, presentController: { controller, arguments in + let arguments = DebugControllerArguments(account: context.account, accountManager: accountManager, presentController: { controller, arguments in presentControllerImpl?(controller, arguments) }, pushController: { controller in pushControllerImpl?(controller) @@ -283,7 +283,7 @@ public func debugController(account: Account, accountManager: AccountManager) -> hasLegacyAppData = FileManager.default.fileExists(atPath: statusPath) } - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, accountManager.sharedData(keys: Set([SharedDataKeys.loggingSettings])), account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.mediaInputSettings, ApplicationSpecificPreferencesKeys.experimentalUISettings])) + let signal = combineLatest(context.presentationData, accountManager.sharedData(keys: Set([SharedDataKeys.loggingSettings])), context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.mediaInputSettings, ApplicationSpecificPreferencesKeys.experimentalUISettings])) |> map { presentationData, sharedData, preferencesView -> (ItemListControllerState, (ItemListNodeState, DebugControllerEntry.ItemGenerationArguments)) in let loggingSettings: LoggingSettings if let value = sharedData.entries [SharedDataKeys.loggingSettings] as? LoggingSettings { @@ -307,7 +307,7 @@ public func debugController(account: Account, accountManager: AccountManager) -> return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, a in controller?.present(c, in: .window(.root), with: a) } diff --git a/TelegramUI/DeleteChatPeerActionSheetItem.swift b/TelegramUI/DeleteChatPeerActionSheetItem.swift index 4f5bae2139..5a58fee3b8 100644 --- a/TelegramUI/DeleteChatPeerActionSheetItem.swift +++ b/TelegramUI/DeleteChatPeerActionSheetItem.swift @@ -4,20 +4,20 @@ import Postbox import TelegramCore final class DeleteChatPeerActionSheetItem: ActionSheetItem { - let account: Account + let context: AccountContext let peer: Peer let chatPeer: Peer let strings: PresentationStrings - init(account: Account, peer: Peer, chatPeer: Peer, strings: PresentationStrings) { - self.account = account + init(context: AccountContext, peer: Peer, chatPeer: Peer, strings: PresentationStrings) { + self.context = context self.peer = peer self.chatPeer = chatPeer self.strings = strings } func node(theme: ActionSheetControllerTheme) -> ActionSheetItemNode { - return DeleteChatPeerActionSheetItemNode(theme: theme, strings: self.strings, account: self.account, peer: self.peer, chatPeer: self.chatPeer) + return DeleteChatPeerActionSheetItemNode(theme: theme, strings: self.strings, context: self.context, peer: self.peer, chatPeer: self.chatPeer) } func updateNode(_ node: ActionSheetItemNode) { @@ -33,7 +33,7 @@ private final class DeleteChatPeerActionSheetItemNode: ActionSheetItemNode { private let avatarNode: AvatarNode private let textNode: ImmediateTextNode - init(theme: ActionSheetControllerTheme, strings: PresentationStrings, account: Account, peer: Peer, chatPeer: Peer) { + init(theme: ActionSheetControllerTheme, strings: PresentationStrings, context: AccountContext, peer: Peer, chatPeer: Peer) { self.theme = theme self.strings = strings @@ -48,7 +48,7 @@ private final class DeleteChatPeerActionSheetItemNode: ActionSheetItemNode { self.addSubnode(self.avatarNode) self.addSubnode(self.textNode) - self.avatarNode.setPeer(account: account, peer: peer) + self.avatarNode.setPeer(account: context.account, theme: (context.currentPresentationData.with { $0 }).theme, peer: peer) let text: (String, [(Int, NSRange)]) if chatPeer is TelegramGroup || chatPeer is TelegramChannel { diff --git a/TelegramUI/DeviceContactInfoController.swift b/TelegramUI/DeviceContactInfoController.swift index d1fedfb796..408af46ff6 100644 --- a/TelegramUI/DeviceContactInfoController.swift +++ b/TelegramUI/DeviceContactInfoController.swift @@ -711,7 +711,7 @@ private final class DeviceContactInfoController: ItemListController Void)? = nil, cancelled: (() -> Void)? = nil) -> ViewController { +public func deviceContactInfoController(context: AccountContext, subject: DeviceContactInfoSubject, completed: (() -> Void)? = nil, cancelled: (() -> Void)? = nil) -> ViewController { var initialState = DeviceContactInfoState() if case let .create(peer, contactData, _) = subject { var peerPhoneNumber: String? @@ -1176,8 +1176,8 @@ private func addContactToExisting(account: Account, parentController: ViewContro }) } -func addContactOptionsController(account: Account, peer: Peer?, contactData: DeviceContactExtendedData) -> ActionSheetController { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } +func addContactOptionsController(context: AccountContext, peer: Peer?, contactData: DeviceContactExtendedData) -> ActionSheetController { + let presentationData = context.currentPresentationData.with { $0 } let controller = ActionSheetController(presentationTheme: presentationData.theme) let dismissAction: () -> Void = { [weak controller] in controller?.dismissAnimated() @@ -1186,7 +1186,7 @@ func addContactOptionsController(account: Account, peer: Peer?, contactData: Dev controller.setItemGroups([ ActionSheetItemGroup(items: [ ActionSheetButtonItem(title: presentationData.strings.Profile_CreateNewContact, action: { [weak controller] in - controller?.present(deviceContactInfoController(account: account, subject: .create(peer: peer, contactData: contactData, completion: { peer, stableId, contactData in + controller?.present(deviceContactInfoController(context: context, subject: .create(peer: peer, contactData: contactData, completion: { peer, stableId, contactData in if let peer = peer { @@ -1200,7 +1200,7 @@ func addContactOptionsController(account: Account, peer: Peer?, contactData: Dev guard let controller = controller else { return } - addContactToExisting(account: account, parentController: controller, contactData: contactData, completion: { peer, contactId, contactData in + addContactToExisting(account: context.account, parentController: controller, contactData: contactData, completion: { peer, contactId, contactData in }) dismissAction() diff --git a/TelegramUI/EditAccessoryPanelNode.swift b/TelegramUI/EditAccessoryPanelNode.swift index 04c91d8202..31bb324ff6 100644 --- a/TelegramUI/EditAccessoryPanelNode.swift +++ b/TelegramUI/EditAccessoryPanelNode.swift @@ -48,13 +48,13 @@ final class EditAccessoryPanelNode: AccessoryPanelNode { } } - private let account: Account + private let context: AccountContext var theme: PresentationTheme var strings: PresentationStrings var nameDisplayOrder: PresentationPersonNameOrder - init(account: Account, messageId: MessageId, theme: PresentationTheme, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder) { - self.account = account + init(context: AccountContext, messageId: MessageId, theme: PresentationTheme, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder) { + self.context = context self.messageId = messageId self.theme = theme self.strings = strings @@ -103,7 +103,7 @@ final class EditAccessoryPanelNode: AccessoryPanelNode { self.addSubnode(self.activityIndicator) self.addSubnode(self.statusNode) self.addSubnode(self.tapNode) - self.messageDisposable.set((account.postbox.messageAtId(messageId) + self.messageDisposable.set((context.account.postbox.messageAtId(messageId) |> deliverOnMainQueue).start(next: { [weak self] message in self?.updateMessage(message) })) @@ -129,7 +129,7 @@ final class EditAccessoryPanelNode: AccessoryPanelNode { if let currentEditMediaReference = self.currentEditMediaReference { effectiveMessage = effectiveMessage.withUpdatedMedia([currentEditMediaReference.media]) } - (text, _) = descriptionStringForMessage(effectiveMessage, strings: self.strings, nameDisplayOrder: self.nameDisplayOrder, accountPeerId: self.account.peerId) + (text, _) = descriptionStringForMessage(effectiveMessage, strings: self.strings, nameDisplayOrder: self.nameDisplayOrder, accountPeerId: self.context.account.peerId) } var updatedMediaReference: AnyMediaReference? @@ -179,12 +179,12 @@ final class EditAccessoryPanelNode: AccessoryPanelNode { if mediaUpdated { if let updatedMediaReference = updatedMediaReference, imageDimensions != nil { if let imageReference = updatedMediaReference.concrete(TelegramMediaImage.self) { - updateImageSignal = chatMessagePhotoThumbnail(account: self.account, photoReference: imageReference) + updateImageSignal = chatMessagePhotoThumbnail(account: self.context.account, photoReference: imageReference) } else if let fileReference = updatedMediaReference.concrete(TelegramMediaFile.self) { if fileReference.media.isVideo { - updateImageSignal = chatMessageVideoThumbnail(account: self.account, fileReference: fileReference) + updateImageSignal = chatMessageVideoThumbnail(account: self.context.account, fileReference: fileReference) } else if let iconImageRepresentation = smallestImageRepresentation(fileReference.media.previewRepresentations) { - updateImageSignal = chatWebpageSnippetFile(account: account, fileReference: fileReference, representation: iconImageRepresentation) + updateImageSignal = chatWebpageSnippetFile(account: self.context.account, fileReference: fileReference, representation: iconImageRepresentation) } } } else { @@ -198,7 +198,7 @@ final class EditAccessoryPanelNode: AccessoryPanelNode { if let currentEditMediaReference = self.currentEditMediaReference { effectiveMessage = effectiveMessage.withUpdatedMedia([currentEditMediaReference.media]) } - switch messageContentKind(effectiveMessage, strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: self.account.peerId) { + switch messageContentKind(effectiveMessage, strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: self.context.account.peerId) { case .text: isMedia = false default: diff --git a/TelegramUI/EditSettingsController.swift b/TelegramUI/EditSettingsController.swift index d9b66d2357..42ea62a8ff 100644 --- a/TelegramUI/EditSettingsController.swift +++ b/TelegramUI/EditSettingsController.swift @@ -280,7 +280,7 @@ private func editSettingsEntries(presentationData: PresentationData, state: Edit return entries } -func editSettingsController(account: Account, currentName: ItemListAvatarAndNameInfoItemName, currentBioText: String, accountManager: AccountManager) -> ViewController { +func editSettingsController(context: AccountContext, currentName: ItemListAvatarAndNameInfoItemName, currentBioText: String, accountManager: AccountManager) -> ViewController { let initialState = EditSettingsState(editingName: currentName, editingBioText: currentBioText) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) @@ -313,7 +313,7 @@ func editSettingsController(account: Account, currentName: ItemListAvatarAndName var updateHiddenAvatarImpl: (() -> Void)? var changeProfilePhotoImpl: (() -> Void)? - let arguments = EditSettingsItemArguments(account: account, accountManager: accountManager, avatarAndNameInfoContext: avatarAndNameInfoContext, avatarTapAction: { + let arguments = EditSettingsItemArguments(account: context.account, accountManager: accountManager, avatarAndNameInfoContext: avatarAndNameInfoContext, avatarTapAction: { var updating = false updateState { updating = $0.updatingAvatar != nil @@ -355,11 +355,11 @@ func editSettingsController(account: Account, currentName: ItemListAvatarAndName } var updateNameSignal: Signal = .complete() if let updateName = updateName, case let .personName(firstName, lastName) = updateName { - updateNameSignal = updateAccountPeerName(account: account, firstName: firstName, lastName: lastName) + updateNameSignal = updateAccountPeerName(account: context.account, firstName: firstName, lastName: lastName) } var updateBioSignal: Signal = .complete() if let updateBio = updateBio { - updateBioSignal = updateAbout(account: account, about: updateBio) + updateBioSignal = updateAbout(account: context.account, about: updateBio) |> `catch` { _ -> Signal in return .complete() } @@ -368,26 +368,26 @@ func editSettingsController(account: Account, currentName: ItemListAvatarAndName dismissImpl?() })) }, addAccount: { - let isTestingEnvironment = account.testingEnvironment + let isTestingEnvironment = context.account.testingEnvironment let _ = accountManager.transaction({ transaction -> Void in let id = transaction.createRecord([AccountEnvironmentAttribute(environment: isTestingEnvironment ? .test : .production)]) transaction.setCurrentId(id) }).start() }, logout: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let alertController = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: presentationData.strings.Settings_LogoutConfirmationTitle, text: presentationData.strings.Settings_LogoutConfirmationText, actions: [ TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Cancel, action: { }), TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: { - let _ = logoutFromAccount(id: account.id, accountManager: accountManager).start() + let _ = logoutFromAccount(id: context.account.id, accountManager: accountManager).start() }) ]) presentControllerImpl?(alertController, nil) }) - let peerView = account.viewTracker.peerView(account.peerId) + let peerView = context.account.viewTracker.peerView(context.account.peerId) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), peerView) + let signal = combineLatest(context.presentationData, statePromise.get(), peerView) |> map { presentationData, state, view -> (ItemListControllerState, (ItemListNodeState, SettingsEntry.ItemGenerationArguments)) in let rightNavigationButton: ItemListNavigationButton if state.updatingName != nil || state.updatingBioText { @@ -406,7 +406,7 @@ func editSettingsController(account: Account, currentName: ItemListAvatarAndName actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal, tabBarItem: nil) + let controller = ItemListController(context: context, state: signal, tabBarItem: nil) pushControllerImpl = { [weak controller] value in (controller?.navigationController as? NavigationController)?.pushViewController(value) } @@ -441,12 +441,12 @@ func editSettingsController(account: Account, currentName: ItemListAvatarAndName } } changeProfilePhotoImpl = { [weak controller] in - let _ = (account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in - return (transaction.getPeer(account.peerId), currentSearchBotsConfiguration(transaction: transaction)) + let _ = (context.account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in + return (transaction.getPeer(context.account.peerId), currentSearchBotsConfiguration(transaction: transaction)) } |> deliverOnMainQueue).start(next: { peer, searchBotsConfiguration in controller?.view.endEditing(true) - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: .custom, theme: presentationData.theme) legacyController.statusBar.statusBarStyle = .Ignore @@ -468,13 +468,13 @@ func editSettingsController(account: Account, currentName: ItemListAvatarAndName 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) updateState { $0.withUpdatedUpdatingAvatar(.image(representation, true)) } - updateAvatarDisposable.set((updateAccountPhoto(account: account, resource: resource, mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) + updateAvatarDisposable.set((updateAccountPhoto(account: context.account, resource: resource, mapResourceToAvatarSizes: { resource, representations in + return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations) }) |> deliverOnMainQueue).start(next: { result in switch result { case .complete: @@ -491,7 +491,7 @@ func editSettingsController(account: Account, currentName: ItemListAvatarAndName let mixin = TGMediaAvatarMenuMixin(context: legacyController.context, parentController: emptyController, hasSearchButton: true, hasDeleteButton: hasPhotos, hasViewButton: hasPhotos, personalPhoto: true, 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: nil, completion: { result in + let controller = WebSearchController(context: context, peer: peer, configuration: searchBotsConfiguration, mode: .avatar(initialQuery: nil, completion: { result in assetsController?.dismiss() completedImpl(result) })) @@ -511,8 +511,8 @@ func editSettingsController(account: Account, currentName: ItemListAvatarAndName return $0.withUpdatedUpdatingAvatar(.none) } } - updateAvatarDisposable.set((updateAccountPhoto(account: account, resource: nil, mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) + updateAvatarDisposable.set((updateAccountPhoto(account: context.account, resource: nil, mapResourceToAvatarSizes: { resource, representations in + return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations) }) |> deliverOnMainQueue).start(next: { result in switch result { case .complete: @@ -527,11 +527,11 @@ func editSettingsController(account: Account, currentName: ItemListAvatarAndName mixin.didFinishWithView = { let _ = currentAvatarMixin.swap(nil) - let _ = (account.postbox.loadedPeerWithId(account.peerId) + let _ = (context.account.postbox.loadedPeerWithId(context.account.peerId) |> take(1) |> deliverOnMainQueue).start(next: { peer in if peer.smallProfileImage != nil { - let galleryController = AvatarGalleryController(account: account, peer: peer, replaceRootController: { controller, ready in + let galleryController = AvatarGalleryController(account: context.account, peer: peer, replaceRootController: { controller, ready in }) /*hiddenAvatarRepresentationDisposable.set((galleryController.hiddenMedia |> deliverOnMainQueue).start(next: { entry in avatarAndNameInfoContext.hiddenAvatarRepresentation = entry?.representations.first diff --git a/TelegramUI/EmojisChatInputContextPanelNode.swift b/TelegramUI/EmojisChatInputContextPanelNode.swift index cff19074b7..0ad03897c9 100644 --- a/TelegramUI/EmojisChatInputContextPanelNode.swift +++ b/TelegramUI/EmojisChatInputContextPanelNode.swift @@ -60,8 +60,7 @@ final class EmojisChatInputContextPanelNode: ChatInputContextPanelNode { private var enqueuedTransitions: [(EmojisChatInputContextPanelTransition, 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 @@ -69,7 +68,7 @@ final class EmojisChatInputContextPanelNode: 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 @@ -96,7 +95,7 @@ final class EmojisChatInputContextPanelNode: ChatInputContextPanelNode { private func prepareTransition(from: [EmojisChatInputContextPanelEntry]? , to: [EmojisChatInputContextPanelEntry]) { let firstTime = self.currentEntries == 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 if let strongSelf = self, let interfaceInteraction = strongSelf.interfaceInteraction { interfaceInteraction.updateTextInputStateAndMode { textInputState, inputMode in var hashtagQueryRange: NSRange? diff --git a/TelegramUI/FeaturedStickerPacksController.swift b/TelegramUI/FeaturedStickerPacksController.swift index d080aaa9b2..f44cb1caea 100644 --- a/TelegramUI/FeaturedStickerPacksController.swift +++ b/TelegramUI/FeaturedStickerPacksController.swift @@ -152,13 +152,8 @@ private func featuredStickerPacksControllerEntries(presentationData: Presentatio return entries } -public func featuredStickerPacksController(account: Account) -> ViewController { +public func featuredStickerPacksController(context: AccountContext) -> ViewController { let statePromise = ValuePromise(FeaturedStickerPacksControllerState(), ignoreRepeated: true) - //let stateValue = Atomic(value: FeaturedStickerPacksControllerState()) - /*let updateState: ((FeaturedStickerPacksControllerState) -> FeaturedStickerPacksControllerState) -> Void = { f in - statePromise.set(stateValue.modify { f($0) }) - }*/ - var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? let actionsDisposable = DisposableSet() @@ -168,17 +163,17 @@ public func featuredStickerPacksController(account: Account) -> ViewController { var presentStickerPackController: ((StickerPackCollectionInfo) -> Void)? - let arguments = FeaturedStickerPacksControllerArguments(account: account, openStickerPack: { info in + let arguments = FeaturedStickerPacksControllerArguments(account: context.account, openStickerPack: { info in presentStickerPackController?(info) }, addPack: { info in - let _ = (loadedStickerPack(postbox: account.postbox, network: account.network, reference: .id(id: info.id.id, accessHash: info.accessHash), forceActualized: false) + let _ = (loadedStickerPack(postbox: context.account.postbox, network: 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: account.postbox, info: info, items: items) + return addStickerPackInteractively(postbox: context.account.postbox, info: info, items: items) } case .fetching: break @@ -190,15 +185,15 @@ public func featuredStickerPacksController(account: Account) -> ViewController { }) let stickerPacks = Promise() - stickerPacks.set(account.postbox.combinedView(keys: [.itemCollectionInfos(namespaces: [Namespaces.ItemCollection.CloudStickerPacks])])) + stickerPacks.set(context.account.postbox.combinedView(keys: [.itemCollectionInfos(namespaces: [Namespaces.ItemCollection.CloudStickerPacks])])) let featured = Promise<[FeaturedStickerPackItem]>() - featured.set(account.viewTracker.featuredStickerPacks()) + featured.set(context.account.viewTracker.featuredStickerPacks()) var previousPackCount: Int? var initialUnreadPacks: [ItemCollectionId: Bool] = [:] - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, stickerPacks.get() |> deliverOnMainQueue, featured.get() |> deliverOnMainQueue) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, stickerPacks.get() |> deliverOnMainQueue, featured.get() |> deliverOnMainQueue) |> deliverOnMainQueue |> map { presentationData, state, view, featured -> (ItemListControllerState, (ItemListNodeState, FeaturedStickerPacksEntry.ItemGenerationArguments)) in let packCount: Int? = featured.count @@ -221,7 +216,7 @@ public func featuredStickerPacksController(account: Account) -> ViewController { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) var alreadyReadIds = Set() diff --git a/TelegramUI/FeedGroupingController.swift b/TelegramUI/FeedGroupingController.swift index cde6f0b0be..d7a894ae12 100644 --- a/TelegramUI/FeedGroupingController.swift +++ b/TelegramUI/FeedGroupingController.swift @@ -9,15 +9,15 @@ final class FeedGroupingController: ViewController { return self.displayNode as! FeedGroupingControllerNode } - private let account: Account + private let context: AccountContext private let groupId: PeerGroupId private var presentationData: PresentationData - init(account: Account, groupId: PeerGroupId) { - self.account = account + init(context: AccountContext, groupId: PeerGroupId) { + self.context = context self.groupId = groupId - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -35,7 +35,7 @@ final class FeedGroupingController: ViewController { } override func loadDisplayNode() { - self.displayNode = FeedGroupingControllerNode(account: self.account, groupId: self.groupId, presentationData: self.presentationData, ungroupedAll: { [weak self] in + self.displayNode = FeedGroupingControllerNode(context: self.context, groupId: self.groupId, presentationData: self.presentationData, ungroupedAll: { [weak self] in (self?.navigationController as? NavigationController)?.popToRoot(animated: true) }) diff --git a/TelegramUI/FeedGroupingControllerNode.swift b/TelegramUI/FeedGroupingControllerNode.swift index 36eeb38ece..b33e793ca3 100644 --- a/TelegramUI/FeedGroupingControllerNode.swift +++ b/TelegramUI/FeedGroupingControllerNode.swift @@ -244,7 +244,7 @@ private func preparedItemListNodeEntryTransition(from fromEntries: [FeedGrouping } final class FeedGroupingControllerNode: ViewControllerTracingNode { - private let account: Account + private let context: AccountContext private let groupId: PeerGroupId private var presentationData: PresentationData private let ungroupedAll: () -> Void @@ -277,8 +277,8 @@ final class FeedGroupingControllerNode: ViewControllerTracingNode { private var transitionDisposable: Disposable? - init(account: Account, groupId: PeerGroupId, presentationData: PresentationData, ungroupedAll: @escaping () -> Void) { - self.account = account + init(context: AccountContext, groupId: PeerGroupId, presentationData: PresentationData, ungroupedAll: @escaping () -> Void) { + self.context = context self.groupId = groupId self.presentationData = presentationData self.ungroupedAll = ungroupedAll @@ -314,7 +314,7 @@ final class FeedGroupingControllerNode: ViewControllerTracingNode { let previousState = Atomic(value: nil) - let arguments = FeedGroupingControllerArguments(account: account, togglePeer: { [weak self] peer, value in + let arguments = FeedGroupingControllerArguments(account: context.account, togglePeer: { [weak self] peer, value in if let strongSelf = self { strongSelf.updateState({ current in var peers = current.peers @@ -328,12 +328,12 @@ final class FeedGroupingControllerNode: ViewControllerTracingNode { } return current.withUpdatedPeers(peers) }) - let _ = updatePeerGroupIdInteractively(postbox: strongSelf.account.postbox, peerId: peer.id, groupId: value ? strongSelf.groupId : nil).start() + let _ = updatePeerGroupIdInteractively(postbox: strongSelf.context.account.postbox, peerId: peer.id, groupId: value ? strongSelf.groupId : nil).start() } }, ungroupAll: { [weak self] in if let strongSelf = self { - let _ = (clearPeerGroupInteractively(postbox: strongSelf.account.postbox, groupId: strongSelf.groupId) + let _ = (clearPeerGroupInteractively(postbox: strongSelf.context.account.postbox, groupId: strongSelf.groupId) |> deliverOnMainQueue).start(completed: { self?.ungroupedAll() }) @@ -363,7 +363,7 @@ final class FeedGroupingControllerNode: ViewControllerTracingNode { return state }) - self.peersDisposable.set((availableGroupFeedPeers(postbox: self.account.postbox, network: self.account.network, groupId: groupId) + self.peersDisposable.set((availableGroupFeedPeers(postbox: self.context.account.postbox, network: self.context.account.network, groupId: groupId) |> deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { strongSelf.updateState({ state in diff --git a/TelegramUI/FetchCachedRepresentations.swift b/TelegramUI/FetchCachedRepresentations.swift index abfb78e452..8adc0cf90a 100644 --- a/TelegramUI/FetchCachedRepresentations.swift +++ b/TelegramUI/FetchCachedRepresentations.swift @@ -142,7 +142,7 @@ private func fetchCachedStickerAJpegRepresentation(account: Account, resource: M } } return EmptyDisposable - }) |> runOn(account.graphicsThreadPool) + }) |> runOn(Queue.concurrentDefaultQueue()) } private func fetchCachedScaledImageRepresentation(account: Account, resource: MediaResource, resourceData: MediaResourceData, representation: CachedScaledImageRepresentation) -> Signal { @@ -184,7 +184,7 @@ private func fetchCachedScaledImageRepresentation(account: Account, resource: Me } } return EmptyDisposable - }) |> runOn(account.graphicsThreadPool) + }) |> runOn(Queue.concurrentDefaultQueue()) } func generateVideoFirstFrame(_ path: String, maxDimensions: CGSize) -> UIImage? { @@ -248,7 +248,7 @@ private func fetchCachedVideoFirstFrameRepresentation(account: Account, resource } } return EmptyDisposable - } |> runOn(account.graphicsThreadPool) + } |> runOn(Queue.concurrentDefaultQueue()) } private func fetchCachedScaledVideoFirstFrameRepresentation(account: Account, resource: MediaResource, resourceData: MediaResourceData, representation: CachedScaledVideoFirstFrameRepresentation) -> Signal { @@ -286,7 +286,7 @@ private func fetchCachedScaledVideoFirstFrameRepresentation(account: Account, re } } return EmptyDisposable - }) |> runOn(account.graphicsThreadPool) + }) |> runOn(Queue.concurrentDefaultQueue()) } } @@ -316,5 +316,5 @@ private func fetchCachedBlurredWallpaperRepresentation(account: Account, resourc } } return EmptyDisposable - }) |> runOn(account.graphicsThreadPool) + }) |> runOn(Queue.concurrentDefaultQueue()) } diff --git a/TelegramUI/ForwardAccessoryPanelNode.swift b/TelegramUI/ForwardAccessoryPanelNode.swift index 58cc6105e9..e8e25d3717 100644 --- a/TelegramUI/ForwardAccessoryPanelNode.swift +++ b/TelegramUI/ForwardAccessoryPanelNode.swift @@ -71,7 +71,7 @@ final class ForwardAccessoryPanelNode: AccessoryPanelNode { var theme: PresentationTheme - init(account: Account, messageIds: [MessageId], theme: PresentationTheme, strings: PresentationStrings) { + init(context: AccountContext, messageIds: [MessageId], theme: PresentationTheme, strings: PresentationStrings) { self.messageIds = messageIds self.theme = theme @@ -102,34 +102,34 @@ final class ForwardAccessoryPanelNode: AccessoryPanelNode { self.addSubnode(self.titleNode) self.addSubnode(self.textNode) - self.messageDisposable.set((account.postbox.messagesAtIds(messageIds) - |> deliverOnMainQueue).start(next: { [weak self] messages in - if let strongSelf = self { - var authors = "" - var uniquePeerIds = Set() - var text = "" - for message in messages { - if let author = message.author, !uniquePeerIds.contains(author.id) { - uniquePeerIds.insert(author.id) - if !authors.isEmpty { - authors.append(", ") - } - authors.append(author.compactDisplayTitle) + self.messageDisposable.set((context.account.postbox.messagesAtIds(messageIds) + |> deliverOnMainQueue).start(next: { [weak self] messages in + if let strongSelf = self { + var authors = "" + var uniquePeerIds = Set() + var text = "" + for message in messages { + if let author = message.author, !uniquePeerIds.contains(author.id) { + uniquePeerIds.insert(author.id) + if !authors.isEmpty { + authors.append(", ") } + authors.append(author.compactDisplayTitle) } - if messages.count == 1 { - let (string, _) = textStringForForwardedMessage(messages[0], strings: strings) - text = string - } else { - text = strings.ForwardedMessages(Int32(messages.count)) - } - - strongSelf.titleNode.attributedText = NSAttributedString(string: authors, font: Font.medium(15.0), textColor: strongSelf.theme.chat.inputPanel.panelControlAccentColor) - strongSelf.textNode.attributedText = NSAttributedString(string: text, font: Font.regular(15.0), textColor: strongSelf.theme.chat.inputPanel.secondaryTextColor) - - strongSelf.setNeedsLayout() } - })) + if messages.count == 1 { + let (string, _) = textStringForForwardedMessage(messages[0], strings: strings) + text = string + } else { + text = strings.ForwardedMessages(Int32(messages.count)) + } + + strongSelf.titleNode.attributedText = NSAttributedString(string: authors, font: Font.medium(15.0), textColor: strongSelf.theme.chat.inputPanel.panelControlAccentColor) + strongSelf.textNode.attributedText = NSAttributedString(string: text, font: Font.regular(15.0), textColor: strongSelf.theme.chat.inputPanel.secondaryTextColor) + + strongSelf.setNeedsLayout() + } + })) } deinit { diff --git a/TelegramUI/GalleryController.swift b/TelegramUI/GalleryController.swift index 9e8a9faea6..2e15d6de36 100644 --- a/TelegramUI/GalleryController.swift +++ b/TelegramUI/GalleryController.swift @@ -131,12 +131,12 @@ private func galleryMessageCaptionText(_ message: Message) -> String { return message.text } -func galleryItemForEntry(account: Account, presentationData: PresentationData, entry: MessageHistoryEntry, streamVideos: Bool, loopVideos: Bool = false, hideControls: Bool = false, tempFilePath: String? = nil, playbackCompleted: @escaping () -> Void = {}, performAction: @escaping (GalleryControllerInteractionTapAction) -> Void = { _ in }, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void = { _ in }) -> GalleryItem? { +func galleryItemForEntry(context: AccountContext, presentationData: PresentationData, entry: MessageHistoryEntry, streamVideos: Bool, loopVideos: Bool = false, hideControls: Bool = false, tempFilePath: String? = nil, playbackCompleted: @escaping () -> Void = {}, performAction: @escaping (GalleryControllerInteractionTapAction) -> Void = { _ in }, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void = { _ in }) -> GalleryItem? { switch entry { case let .MessageEntry(message, _, location, _): if let (media, mediaImage) = mediaForMessage(message: message) { if let _ = media as? TelegramMediaImage { - return ChatImageGalleryItem(account: account, presentationData: presentationData, message: message, location: location, performAction: performAction, openActionOptions: openActionOptions) + return ChatImageGalleryItem(context: context, presentationData: presentationData, message: message, location: location, performAction: performAction, openActionOptions: openActionOptions) } else if let file = media as? TelegramMediaFile { if file.isVideo { let content: UniversalVideoContent @@ -158,7 +158,7 @@ func galleryItemForEntry(account: Account, presentationData: PresentationData, e } } let caption = galleryCaptionStringWithAppliedEntities(galleryMessageCaptionText(message), entities: entities) - return UniversalVideoGalleryItem(account: account, presentationData: presentationData, content: content, originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: caption, hideControls: hideControls, playbackCompleted: playbackCompleted, performAction: performAction, openActionOptions: openActionOptions) + return UniversalVideoGalleryItem(context: context, presentationData: presentationData, content: content, originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: caption, hideControls: hideControls, playbackCompleted: playbackCompleted, performAction: performAction, openActionOptions: openActionOptions) } else { if file.mimeType.hasPrefix("image/") && file.mimeType != "image/gif" { var pixelsCount: Int = 0 @@ -166,28 +166,25 @@ func galleryItemForEntry(account: Account, presentationData: PresentationData, e pixelsCount = Int(dimensions.width) * Int(dimensions.height) } if (file.size == nil || file.size! < 4 * 1024 * 1024) && pixelsCount < 4096 * 4096 { - return ChatImageGalleryItem(account: account, presentationData: presentationData, message: message, location: location, performAction: performAction, openActionOptions: openActionOptions) + return ChatImageGalleryItem(context: context, presentationData: presentationData, message: message, location: location, performAction: performAction, openActionOptions: openActionOptions) } else { - return ChatDocumentGalleryItem(account: account, presentationData: presentationData, message: message, location: location) + return ChatDocumentGalleryItem(context: context, presentationData: presentationData, message: message, location: location) } } else if internalDocumentItemSupportsMimeType(file.mimeType, fileName: file.fileName) { - return ChatDocumentGalleryItem(account: account, presentationData: presentationData, message: message, location: location) + return ChatDocumentGalleryItem(context: context, presentationData: presentationData, message: message, location: location) } else { - return ChatExternalFileGalleryItem(account: account, presentationData: presentationData, message: message, location: location) + return ChatExternalFileGalleryItem(context: context, presentationData: presentationData, message: message, location: location) } } } else if let webpage = media as? TelegramMediaWebpage, case let .Loaded(webpageContent) = webpage.content { switch websiteType(of: webpageContent) { case .instagram where webpageContent.file != nil && webpageContent.image != nil && webpageContent.file!.isVideo: - return UniversalVideoGalleryItem(account: account, presentationData: presentationData, content: NativeVideoContent(id: NativeVideoContentId.message(message.id, message.stableId, webpage.webpageId), fileReference: .message(message: MessageReference(message), media: webpageContent.file!), imageReference: webpageContent.image.flatMap({ ImageMediaReference.message(message: MessageReference(message), media: $0) }), streamVideo: true, enableSound: true), originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: NSAttributedString(string: ""), performAction: performAction, openActionOptions: openActionOptions) - //return UniversalVideoGalleryItem(account: account, theme: theme, strings: strings, content: SystemVideoContent(url: webpageContent.embedUrl!, image: webpageContent.image!, dimensions: webpageContent.embedSize ?? CGSize(width: 640.0, height: 640.0), duration: Int32(webpageContent.duration ?? 0)), originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: "") - /*case .twitter where webpageContent.embedUrl != nil && webpageContent.image != nil: - return UniversalVideoGalleryItem(account: account, theme: theme, strings: strings, content: SystemVideoContent(url: webpageContent.embedUrl!, image: webpageContent.image!, dimensions: webpageContent.embedSize ?? CGSize(width: 640.0, height: 640.0), duration: Int32(webpageContent.duration ?? 0)), originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: "")*/ + return UniversalVideoGalleryItem(context: context, presentationData: presentationData, content: NativeVideoContent(id: NativeVideoContentId.message(message.id, message.stableId, webpage.webpageId), fileReference: .message(message: MessageReference(message), media: webpageContent.file!), imageReference: webpageContent.image.flatMap({ ImageMediaReference.message(message: MessageReference(message), media: $0) }), streamVideo: true, enableSound: true), originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: NSAttributedString(string: ""), performAction: performAction, openActionOptions: openActionOptions) default: if let embedUrl = webpageContent.embedUrl, let image = webpageContent.image, URL(string: embedUrl)?.pathExtension == "mp4" { - return UniversalVideoGalleryItem(account: account, presentationData: presentationData, content: SystemVideoContent(url: embedUrl, imageReference: .webPage(webPage: WebpageReference(webpage), media: image), dimensions: webpageContent.embedSize ?? CGSize(width: 640.0, height: 640.0), duration: Int32(webpageContent.duration ?? 0)), originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: NSAttributedString(string: ""), performAction: performAction, openActionOptions: openActionOptions) + return UniversalVideoGalleryItem(context: context, presentationData: presentationData, content: SystemVideoContent(url: embedUrl, imageReference: .webPage(webPage: WebpageReference(webpage), media: image), dimensions: webpageContent.embedSize ?? CGSize(width: 640.0, height: 640.0), duration: Int32(webpageContent.duration ?? 0)), originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: NSAttributedString(string: ""), performAction: performAction, openActionOptions: openActionOptions) } else if let content = WebEmbedVideoContent(webPage: webpage, webpageContent: webpageContent) { - return UniversalVideoGalleryItem(account: account, presentationData: presentationData, content: content, originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: NSAttributedString(string: ""), performAction: performAction, openActionOptions: openActionOptions) + return UniversalVideoGalleryItem(context: context, presentationData: presentationData, content: content, originData: GalleryItemOriginData(title: message.author?.displayTitle, timestamp: message.timestamp), indexData: location.flatMap { GalleryItemIndexData(position: Int32($0.index), totalCount: Int32($0.count)) }, contentInfo: .message(message), caption: NSAttributedString(string: ""), performAction: performAction, openActionOptions: openActionOptions) } } } @@ -273,7 +270,7 @@ class GalleryController: ViewController { return self.displayNode as! GalleryControllerNode } - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let streamVideos: Bool @@ -311,14 +308,14 @@ class GalleryController: ViewController { private var performAction: (GalleryControllerInteractionTapAction) -> Void private var openActionOptions: (GalleryControllerInteractionTapAction) -> Void - init(account: Account, source: GalleryControllerItemSource, invertItemOrder: Bool = false, streamSingleVideo: Bool = false, synchronousLoad: Bool = false, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void, baseNavigationController: NavigationController?, actionInteraction: GalleryControllerActionInteraction? = nil) { - self.account = account + init(context: AccountContext, source: GalleryControllerItemSource, invertItemOrder: Bool = false, streamSingleVideo: Bool = false, synchronousLoad: Bool = false, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void, baseNavigationController: NavigationController?, actionInteraction: GalleryControllerActionInteraction? = nil) { + self.context = context self.replaceRootController = replaceRootController self.baseNavigationController = baseNavigationController self.actionInteraction = actionInteraction self.streamVideos = streamSingleVideo - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } var performActionImpl: ((GalleryControllerInteractionTapAction) -> Void)? self.performAction = { action in @@ -340,7 +337,7 @@ class GalleryController: ViewController { let message: Signal switch source { case let .peerMessagesAtId(messageId): - message = account.postbox.messageAtId(messageId) + message = context.account.postbox.messageAtId(messageId) case let .standaloneMessage(m): message = .single(m) } @@ -351,7 +348,7 @@ class GalleryController: ViewController { switch source { case .peerMessagesAtId: if let tags = tagsForMessage(message!) { - let view = account.postbox.aroundMessageHistoryViewForLocation(.peer(message!.id.peerId), index: .message(MessageIndex(message!)), anchorIndex: .message(MessageIndex(message!)), count: 50, clipHoles: false, fixedCombinedReadStates: nil, topTaggedMessageIdNamespaces: [], tagMask: tags, orderStatistics: [.combinedLocation]) + let view = context.account.postbox.aroundMessageHistoryViewForLocation(.peer(message!.id.peerId), index: .message(MessageIndex(message!)), anchorIndex: .message(MessageIndex(message!)), count: 50, clipHoles: false, fixedCombinedReadStates: nil, topTaggedMessageIdNamespaces: [], tagMask: tags, orderStatistics: [.combinedLocation]) return view |> mapToSignal { (view, _, _) -> Signal in @@ -419,7 +416,7 @@ class GalleryController: ViewController { var items: [GalleryItem] = [] var centralItemIndex: Int? for entry in strongSelf.entries { - if let item = galleryItemForEntry(account: account, presentationData: strongSelf.presentationData, entry: entry, streamVideos: streamSingleVideo, performAction: strongSelf.performAction, openActionOptions: strongSelf.openActionOptions) { + if let item = galleryItemForEntry(context: context, presentationData: strongSelf.presentationData, entry: entry, streamVideos: streamSingleVideo, performAction: strongSelf.performAction, openActionOptions: strongSelf.openActionOptions) { if case let .MessageEntry(message, _, _, _) = entry, message.stableId == strongSelf.centralEntryStableId { centralItemIndex = items.count } @@ -505,15 +502,14 @@ class GalleryController: ViewController { } })) - if let mediaManager = account.telegramApplicationContext.mediaManager { - self.hiddenMediaManagerIndex = mediaManager.galleryHiddenMediaManager.addSource(self._hiddenMedia.get() |> map { messageIdAndMedia in - if let (messageId, media) = messageIdAndMedia { - return .chat(messageId, media) - } else { - return nil - } - }) - } + let mediaManager = context.mediaManager + self.hiddenMediaManagerIndex = mediaManager.galleryHiddenMediaManager.addSource(self._hiddenMedia.get() |> map { messageIdAndMedia in + if let (messageId, media) = messageIdAndMedia { + return .chat(messageId, media) + } else { + return nil + } + }) performActionImpl = { [weak self] action in if let strongSelf = self { @@ -539,7 +535,7 @@ class GalleryController: ViewController { case let .url(url, _): var cleanUrl = url var canAddToReadingList = true - let canOpenIn = availableOpenInOptions(applicationContext: strongSelf.account.telegramApplicationContext, item: .url(url: url)).count > 1 + let canOpenIn = availableOpenInOptions(context: strongSelf.context, item: .url(url: url)).count > 1 let mailtoString = "mailto:" let telString = "tel:" var openText = strongSelf.presentationData.strings.Conversation_LinkDialogOpen @@ -691,7 +687,8 @@ class GalleryController: ViewController { deinit { self.disposable.dispose() self.centralItemAttributesDisposable.dispose() - if let hiddenMediaManagerIndex = self.hiddenMediaManagerIndex, let mediaManager = self.account.telegramApplicationContext.mediaManager { + if let hiddenMediaManagerIndex = self.hiddenMediaManagerIndex { + let mediaManager = self.context.mediaManager mediaManager.galleryHiddenMediaManager.removeSource(hiddenMediaManagerIndex) } } @@ -797,7 +794,7 @@ class GalleryController: ViewController { var items: [GalleryItem] = [] var centralItemIndex: Int? for entry in self.entries { - if let item = galleryItemForEntry(account: account, presentationData: self.presentationData, entry: entry, streamVideos: self.streamVideos, performAction: self.performAction, openActionOptions: self.openActionOptions) { + if let item = galleryItemForEntry(context: context, presentationData: self.presentationData, entry: entry, streamVideos: self.streamVideos, performAction: self.performAction, openActionOptions: self.openActionOptions) { if case let .MessageEntry(message, _, _, _) = entry, message.stableId == self.centralEntryStableId { centralItemIndex = items.count } diff --git a/TelegramUI/GameController.swift b/TelegramUI/GameController.swift index 0aa85f18f0..89a58dc5ad 100644 --- a/TelegramUI/GameController.swift +++ b/TelegramUI/GameController.swift @@ -10,18 +10,18 @@ final class GameController: ViewController { return self.displayNode as! GameControllerNode } - private let account: Account + private let context: AccountContext private let url: String private let message: Message private var presentationData: PresentationData - init(account: Account, url: String, message: Message) { - self.account = account + init(context: AccountContext, url: String, message: Message) { + self.context = context self.url = url self.message = message - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -67,7 +67,7 @@ final class GameController: ViewController { } override func loadDisplayNode() { - self.displayNode = GameControllerNode(account: self.account, presentationData: self.presentationData, url: self.url, present: { [weak self] c, a in + self.displayNode = GameControllerNode(context: self.context, presentationData: self.presentationData, url: self.url, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a) }, message: self.message) } diff --git a/TelegramUI/GameControllerNode.swift b/TelegramUI/GameControllerNode.swift index 925bb319a8..2f8abf0443 100644 --- a/TelegramUI/GameControllerNode.swift +++ b/TelegramUI/GameControllerNode.swift @@ -23,13 +23,13 @@ private class WeakGameScriptMessageHandler: NSObject, WKScriptMessageHandler { final class GameControllerNode: ViewControllerTracingNode { private var webView: WKWebView? - private let account: Account + private let context: AccountContext var presentationData: PresentationData private let present: (ViewController, Any?) -> Void private let message: Message - init(account: Account, presentationData: PresentationData, url: String, present: @escaping (ViewController, Any?) -> Void, message: Message) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, url: String, present: @escaping (ViewController, Any?) -> Void, message: Message) { + self.context = context self.presentationData = presentationData self.present = present self.message = message @@ -129,9 +129,9 @@ final class GameControllerNode: ViewControllerTracingNode { if eventName == "share_game" || eventName == "share_score" { if let (botPeer, gameName) = self.shareData(), let addressName = botPeer.addressName, !addressName.isEmpty, !gameName.isEmpty { if eventName == "share_score" { - self.present(ShareController(account: self.account, subject: .fromExternal({ [weak self] peerIds, text in + self.present(ShareController(context: self.context, subject: .fromExternal({ [weak self] peerIds, text in if let strongSelf = self { - let signals = peerIds.map { forwardGameWithScore(account: strongSelf.account, messageId: strongSelf.message.id, to: $0) } + let signals = peerIds.map { forwardGameWithScore(account: strongSelf.context.account, messageId: strongSelf.message.id, to: $0) } return .single(.preparing) |> then(combineLatest(signals) |> mapToSignal { _ -> Signal in return .complete() }) |> then(.single(.done)) } else { @@ -148,7 +148,7 @@ final class GameControllerNode: ViewControllerTracingNode { func shareWithoutScore() { if let (botPeer, gameName) = self.shareData(), let addressName = botPeer.addressName, !addressName.isEmpty, !gameName.isEmpty { let url = "https://t.me/\(addressName)?game=\(gameName)" - self.present(ShareController(account: self.account, subject: .url(url), showInChat: nil, externalShare: true), nil) + self.present(ShareController(context: self.context, subject: .url(url), showInChat: nil, externalShare: true), nil) } } } diff --git a/TelegramUI/GridMessageItem.swift b/TelegramUI/GridMessageItem.swift index 72d0714b5a..7d09f43e77 100644 --- a/TelegramUI/GridMessageItem.swift +++ b/TelegramUI/GridMessageItem.swift @@ -153,15 +153,15 @@ final class GridMessageItemSectionNode: ASDisplayNode { final class GridMessageItem: GridItem { fileprivate let theme: PresentationTheme private let strings: PresentationStrings - private let account: Account + private let context: AccountContext fileprivate let message: Message private let controllerInteraction: ChatControllerInteraction let section: GridSection? - init(theme: PresentationTheme, strings: PresentationStrings, account: Account, message: Message, controllerInteraction: ChatControllerInteraction) { + init(theme: PresentationTheme, strings: PresentationStrings, context: AccountContext, message: Message, controllerInteraction: ChatControllerInteraction) { self.theme = theme self.strings = strings - self.account = account + self.context = context self.message = message self.controllerInteraction = controllerInteraction self.section = GridMessageItemSection(timestamp: message.timestamp, theme: theme, strings: strings) @@ -170,7 +170,7 @@ final class GridMessageItem: GridItem { func node(layout: GridNodeLayout, synchronousLoad: Bool) -> GridItemNode { let node = GridMessageItemNode() if let media = mediaForMessage(self.message) { - node.setup(account: self.account, item: self, media: media, messageId: self.message.id, controllerInteraction: self.controllerInteraction) + node.setup(context: self.context, item: self, media: media, messageId: self.message.id, controllerInteraction: self.controllerInteraction) } return node } @@ -181,13 +181,13 @@ final class GridMessageItem: GridItem { return } if let media = mediaForMessage(self.message) { - node.setup(account: self.account, item: self, media: media, messageId: self.message.id, controllerInteraction: self.controllerInteraction) + node.setup(context: self.context, item: self, media: media, messageId: self.message.id, controllerInteraction: self.controllerInteraction) } } } final class GridMessageItemNode: GridItemNode { - private var currentState: (Account, Media, CGSize)? + private var currentState: (AccountContext, Media, CGSize)? private let imageNode: TransformImageNode private(set) var messageId: MessageId? private var item: GridMessageItem? @@ -229,13 +229,13 @@ final class GridMessageItemNode: GridItemNode { self.imageNode.view.addGestureRecognizer(recognizer) } - func setup(account: Account, item: GridMessageItem, media: Media, messageId: MessageId, controllerInteraction: ChatControllerInteraction) { - if self.currentState == nil || self.currentState!.0 !== account || !self.currentState!.1.isEqual(to: media) { + func setup(context: AccountContext, item: GridMessageItem, media: Media, messageId: MessageId, controllerInteraction: ChatControllerInteraction) { + if self.currentState == nil || self.currentState!.0 !== context || !self.currentState!.1.isEqual(to: media) { var mediaDimensions: CGSize? if let image = media as? TelegramMediaImage, let largestSize = largestImageRepresentation(image.representations)?.dimensions { mediaDimensions = largestSize - self.imageNode.setSignal(mediaGridMessagePhoto(account: account, photoReference: .message(message: MessageReference(item.message), media: image)), dispatchOnDisplayLink: true) + self.imageNode.setSignal(mediaGridMessagePhoto(account: context.account, photoReference: .message(message: MessageReference(item.message), media: image)), dispatchOnDisplayLink: true) self.fetchStatusDisposable.set(nil) self.statusNode.transitionToState(.none, completion: { [weak self] in @@ -245,7 +245,7 @@ final class GridMessageItemNode: GridItemNode { self.resourceStatus = nil } else if let file = media as? TelegramMediaFile, file.isVideo { mediaDimensions = file.dimensions - self.imageNode.setSignal(mediaGridMessageVideo(postbox: account.postbox, videoReference: .message(message: MessageReference(item.message), media: file))) + self.imageNode.setSignal(mediaGridMessageVideo(postbox: context.account.postbox, videoReference: .message(message: MessageReference(item.message), media: file))) if let duration = file.duration { self.videoAccessoryNode.setup(stringForDuration(duration)) @@ -255,7 +255,7 @@ final class GridMessageItemNode: GridItemNode { } self.resourceStatus = nil - self.fetchStatusDisposable.set((messageMediaFileStatus(account: account, messageId: messageId, file: file) |> deliverOnMainQueue).start(next: { [weak self] status in + self.fetchStatusDisposable.set((messageMediaFileStatus(account: context.account, messageId: messageId, file: file) |> deliverOnMainQueue).start(next: { [weak self] status in if let strongSelf = self { strongSelf.resourceStatus = status let statusState: RadialStatusNodeState @@ -291,7 +291,7 @@ final class GridMessageItemNode: GridItemNode { } if let mediaDimensions = mediaDimensions { - self.currentState = (account, media, mediaDimensions) + self.currentState = (context, media, mediaDimensions) self.setNeedsLayout() } } @@ -416,16 +416,16 @@ final class GridMessageItemNode: GridItemNode { if let (gesture, _) = recognizer.lastRecognizedGestureAndLocation { switch gesture { case .tap: - if let (account, media, _) = self.currentState { + if let (context, media, _) = self.currentState { if let file = media as? TelegramMediaFile { if let resourceStatus = self.resourceStatus { switch resourceStatus { case .Fetching: - messageMediaFileCancelInteractiveFetch(account: account, messageId: message.id, file: file) + messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: file) case .Local: let _ = controllerInteraction.openMessage(message, .default) case .Remote: - self.fetchDisposable.set(messageMediaFileInteractiveFetched(account: account, message: message, file: file, userInitiated: true).start()) + self.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: file, userInitiated: true).start()) } } } else { diff --git a/TelegramUI/GroupInfoController.swift b/TelegramUI/GroupInfoController.swift index ffa3280813..0308a8ebb1 100644 --- a/TelegramUI/GroupInfoController.swift +++ b/TelegramUI/GroupInfoController.swift @@ -1150,7 +1150,7 @@ private func valuesRequiringUpdate(state: GroupInfoState, view: PeerView) -> (ti } } -public func groupInfoController(account: Account, peerId originalPeerId: PeerId, membersLoaded: @escaping () -> Void = {}) -> ViewController { +public func groupInfoController(context: AccountContext, peerId originalPeerId: PeerId, membersLoaded: @escaping () -> Void = {}) -> ViewController { let statePromise = ValuePromise(GroupInfoState(updatingAvatar: nil, editingState: nil, updatingName: nil, peerIdWithRevealedOptions: nil, temporaryParticipants: [], successfullyAddedParticipantIds: Set(), removingParticipantIds: Set(), savingData: false, searchingMembers: false), ignoreRepeated: true) let stateValue = Atomic(value: GroupInfoState(updatingAvatar: nil, editingState: nil, updatingName: nil, peerIdWithRevealedOptions: nil, temporaryParticipants: [], successfullyAddedParticipantIds: Set(), removingParticipantIds: Set(), savingData: false, searchingMembers: false)) let updateState: ((GroupInfoState) -> GroupInfoState) -> Void = { f in @@ -1204,7 +1204,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, var upgradedToSupergroupImpl: ((PeerId, @escaping () -> Void) -> Void)? let actualPeerId = Promise() - actualPeerId.set(account.viewTracker.peerView(originalPeerId) + actualPeerId.set(context.account.viewTracker.peerView(originalPeerId) |> map { peerView -> PeerId in if let peer = peerView.peers[peerView.peerId] as? TelegramGroup, let migrationReference = peer.migrationReference { return migrationReference.peerId @@ -1218,11 +1218,11 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let peerViewSignal = actualPeerId.get() |> distinctUntilChanged |> mapToSignal { peerId -> Signal in - return account.viewTracker.peerView(peerId) + return context.account.viewTracker.peerView(peerId) } peerView.set(peerViewSignal) - let arguments = GroupInfoArguments(account: account, avatarAndNameInfoContext: avatarAndNameInfoContext, tapAvatarAction: { + let arguments = GroupInfoArguments(account: context.account, avatarAndNameInfoContext: avatarAndNameInfoContext, tapAvatarAction: { let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in @@ -1233,7 +1233,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, return } - let galleryController = AvatarGalleryController(account: 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 @@ -1249,10 +1249,10 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - let _ = (account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in + let _ = (context.account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in return (transaction.getPeer(peerView.peerId), currentSearchBotsConfiguration(transaction: transaction)) } |> deliverOnMainQueue).start(next: { peer, searchBotsConfiguration in - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: .custom, theme: presentationData.theme) legacyController.statusBar.statusBarStyle = .Ignore @@ -1274,13 +1274,13 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, 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) updateState { $0.withUpdatedUpdatingAvatar(.image(representation, true)) } - updateAvatarDisposable.set((updatePeerPhoto(postbox: account.postbox, network: account.network, stateManager: account.stateManager, accountPeerId: account.peerId, peerId: peerView.peerId, photo: uploadedPeerPhoto(postbox: account.postbox, network: account.network, resource: resource), mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) + updateAvatarDisposable.set((updatePeerPhoto(postbox: context.account.postbox, network: context.account.network, stateManager: context.account.stateManager, accountPeerId: context.account.peerId, peerId: peerView.peerId, photo: uploadedPeerPhoto(postbox: context.account.postbox, network: context.account.network, resource: resource), mapResourceToAvatarSizes: { resource, representations in + return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations) }) |> deliverOnMainQueue).start(next: { result in switch result { case .complete: @@ -1297,7 +1297,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let mixin = TGMediaAvatarMenuMixin(context: legacyController.context, parentController: emptyController, hasSearchButton: true, hasDeleteButton: hasPhotos, 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: peer?.displayTitle, completion: { result in + let controller = WebSearchController(context: context, peer: peer, configuration: searchBotsConfiguration, mode: .avatar(initialQuery: peer?.displayTitle, completion: { result in assetsController?.dismiss() completedImpl(result) })) @@ -1317,8 +1317,8 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, return $0.withUpdatedUpdatingAvatar(.none) } } - updateAvatarDisposable.set((updatePeerPhoto(postbox: account.postbox, network: account.network, stateManager: account.stateManager, accountPeerId: account.peerId, peerId: peerView.peerId, photo: nil, mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) + updateAvatarDisposable.set((updatePeerPhoto(postbox: context.account.postbox, network: context.account.network, stateManager: context.account.stateManager, accountPeerId: context.account.peerId, peerId: peerView.peerId, photo: nil, mapResourceToAvatarSizes: { resource, representations in + return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations) }) |> deliverOnMainQueue).start(next: { result in switch result { case .complete: @@ -1350,8 +1350,8 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - let _ = (account.postbox.transaction { transaction -> (TelegramPeerNotificationSettings, GlobalNotificationSettings) in + let presentationData = context.currentPresentationData.with { $0 } + let _ = (context.account.postbox.transaction { transaction -> (TelegramPeerNotificationSettings, GlobalNotificationSettings) in let peerSettings: TelegramPeerNotificationSettings = (transaction.getPeerNotificationSettings(peerView.peerId) as? TelegramPeerNotificationSettings) ?? TelegramPeerNotificationSettings.defaultSettings let globalSettings: GlobalNotificationSettings = (transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications) as? GlobalNotificationSettings) ?? GlobalNotificationSettings.defaultSettings return (peerSettings, globalSettings) @@ -1364,12 +1364,12 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, soundSettings = NotificationSoundSettings(value: peerSettings.messageSound) } let controller = notificationMuteSettingsController(presentationData: presentationData, notificationSettings: globalSettings.effective.groupChats, soundSettings: soundSettings, openSoundSettings: { - let controller = notificationSoundSelectionController(account: account, isModal: true, currentSound: peerSettings.messageSound, defaultSound: globalSettings.effective.groupChats.sound, completion: { sound in - let _ = updatePeerNotificationSoundInteractive(account: account, peerId: peerView.peerId, sound: sound).start() + 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() }) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, updateSettings: { value in - changeMuteSettingsDisposable.set(updatePeerMuteSetting(account: account, peerId: peerView.peerId, muteInterval: value).start()) + changeMuteSettingsDisposable.set(updatePeerMuteSetting(account: context.account, peerId: peerView.peerId, muteInterval: value).start()) }) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) @@ -1378,7 +1378,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - presentControllerImpl?(groupPreHistorySetupController(account: account, peerId: peerView.peerId, upgradedToSupergroup: { peerId, f in + presentControllerImpl?(groupPreHistorySetupController(context: context, peerId: peerView.peerId, upgradedToSupergroup: { peerId, f in upgradedToSupergroupImpl?(peerId, f) }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) @@ -1386,7 +1386,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - if let controller = peerSharedMediaController(account: account, peerId: peerView.peerId) { + if let controller = peerSharedMediaController(context: context, peerId: peerView.peerId) { pushControllerImpl?(controller) } }) @@ -1394,13 +1394,13 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - pushControllerImpl?(channelAdminsController(account: account, peerId: peerView.peerId)) + pushControllerImpl?(channelAdminsController(context: context, peerId: peerView.peerId)) }) }, openPermissions: { let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - pushControllerImpl?(channelPermissionsController(account: account, peerId: peerView.peerId)) + pushControllerImpl?(channelPermissionsController(context: context, peerId: peerView.peerId)) }) }, updateEditingName: { editingName in updateState { state in @@ -1432,7 +1432,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let members: Promise<[PeerId]> = Promise() if peerView.peerId.namespace == Namespaces.Peer.CloudChannel { var membersDisposable: Disposable? - let (disposable, _) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recent(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerView.peerId, updated: { listState in + let (disposable, _) = context.peerChannelMemberCategoriesContextsManager.recent(postbox: context.account.postbox, network: context.account.network, accountPeerId: context.account.peerId, peerId: peerView.peerId, updated: { listState in members.set(.single(listState.list.map {$0.peer.id})) membersDisposable?.dispose() }) @@ -1441,11 +1441,11 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, members.set(.single([])) } - let _ = (combineLatest(queue: .mainQueue(), account.postbox.loadedPeerWithId(peerView.peerId) + let _ = (combineLatest(queue: .mainQueue(), context.account.postbox.loadedPeerWithId(peerView.peerId) |> deliverOnMainQueue, members.get() |> take(1) |> deliverOnMainQueue)).start(next: { groupPeer, recentIds in var confirmationImpl: ((PeerId) -> Signal)? var options: [ContactListAdditionalOption] = [] - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } var inviteByLinkImpl: (() -> Void)? var canCreateInviteLink = false @@ -1470,7 +1470,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let contactsController: ViewController if peerView.peerId.namespace == Namespaces.Peer.CloudGroup { - contactsController = ContactSelectionController(account: account, autoDismiss: false, title: { $0.GroupInfo_AddParticipantTitle }, options: options, confirmation: { peer in + contactsController = ContactSelectionController(context: context, autoDismiss: false, title: { $0.GroupInfo_AddParticipantTitle }, options: options, confirmation: { peer in if let confirmationImpl = confirmationImpl, case let .peer(peer, _) = peer { return confirmationImpl(peer.id) } else { @@ -1478,7 +1478,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, } }) } else { - contactsController = ContactMultiselectionController(account: account, mode: .peerSelection(searchChatList: false), options: options, filters: [.excludeSelf, .disable(recentIds)]) + contactsController = ContactMultiselectionController(context: context, mode: .peerSelection(searchChatList: false), options: options, filters: [.excludeSelf, .disable(recentIds)]) } confirmationImpl = { [weak contactsController] peerId in @@ -1486,7 +1486,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, |> deliverOnMainQueue |> mapToSignal { peer in let result = ValuePromise() - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } if let contactsController = contactsController { let alertController = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.GroupInfo_AddParticipantConfirmation(peer.displayTitle).0, actions: [ TextAlertAction(type: .genericAction, title: presentationData.strings.Common_No, action: { @@ -1507,7 +1507,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, if case let .peer(selectedPeer, _) = memberPeer { let memberId = selectedPeer.id if peerView.peerId.namespace == Namespaces.Peer.CloudChannel { - return account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.addMember(account: account, peerId: peerView.peerId, memberId: memberId) + return context.peerChannelMemberCategoriesContextsManager.addMember(account: context.account, peerId: peerView.peerId, memberId: memberId) } if let peer = peerView.peers[memberId] { @@ -1530,7 +1530,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, } } - return addGroupMember(account: account, peerId: peerView.peerId, memberId: memberId) + return addGroupMember(account: context.account, peerId: peerView.peerId, memberId: memberId) |> deliverOnMainQueue |> afterCompleted { updateState { state in @@ -1558,7 +1558,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, } return .complete() case .groupFull: - let signal = convertGroupToSupergroup(account: account, peerId: peerView.peerId) + let signal = convertGroupToSupergroup(account: context.account, peerId: peerView.peerId) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -1567,7 +1567,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, guard let upgradedPeerId = upgradedPeerId else { return .single(nil) } - return account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.addMember(account: account, peerId: upgradedPeerId, memberId: memberId) + return context.peerChannelMemberCategoriesContextsManager.addMember(account: context.account, peerId: upgradedPeerId, memberId: memberId) |> mapToSignal { _ -> Signal in return .complete() } @@ -1597,12 +1597,12 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, return nil } } - return account.postbox.multiplePeersView(memberIds) + return context.account.postbox.multiplePeersView(memberIds) |> take(1) |> deliverOnMainQueue |> mapError { _ in return .generic} |> mapToSignal { view -> Signal in - return account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.addMembers(account: account, peerId: peerView.peerId, memberIds: memberIds) |> map { _ in + return context.peerChannelMemberCategoriesContextsManager.addMembers(account: context.account, peerId: peerView.peerId, memberIds: memberIds) |> map { _ in updateState { state in var state = state for (memberId, peer) in view.peers { @@ -1631,7 +1631,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, inviteByLinkImpl = { [weak contactsController] in contactsController?.dismiss() - presentControllerImpl?(channelVisibilityController(account: account, peerId: peerView.peerId, mode: .privateLink, upgradedToSupergroup: { updatedPeerId, f in + presentControllerImpl?(channelVisibilityController(context: context, peerId: peerView.peerId, mode: .privateLink, upgradedToSupergroup: { updatedPeerId, f in upgradedToSupergroupImpl?(updatedPeerId, f) }), ViewControllerPresentationArguments(presentationAnimation: ViewControllerPresentationAnimation.modalSheet)) } @@ -1665,7 +1665,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, if peers.count == 1, error == .restricted { switch peers[0] { case let .peer(peerId): - _ = (account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { peer in + _ = (context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { peer in let alert = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.Privacy_GroupsAndChannels_InviteToGroupError(peer.compactDisplayTitle, peer.compactDisplayTitle).0, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: {})]) presentControllerImpl?(alert, nil) }) @@ -1690,7 +1690,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - presentControllerImpl?(channelAdminController(account: account, peerId: peerView.peerId, adminId: participant.peer.id, initialParticipant: participant.participant, updated: { _ in + presentControllerImpl?(channelAdminController(context: context, peerId: peerView.peerId, adminId: participant.peer.id, initialParticipant: participant.participant, updated: { _ in }, upgradedToSupergroup: { upgradedPeerId, f in upgradedToSupergroupImpl?(upgradedPeerId, f) }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) @@ -1699,7 +1699,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - presentControllerImpl?(channelBannedMemberController(account: account, peerId: peerView.peerId, memberId: participant.peer.id, initialParticipant: participant.participant, updated: { _ in + presentControllerImpl?(channelBannedMemberController(context: context, peerId: peerView.peerId, memberId: participant.peer.id, initialParticipant: participant.participant, updated: { _ in }, upgradedToSupergroup: { upgradedPeerId, f in upgradedToSupergroupImpl?(upgradedPeerId, f) }), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) @@ -1708,7 +1708,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - let signal = account.postbox.loadedPeerWithId(memberId) + let signal = context.account.postbox.loadedPeerWithId(memberId) |> deliverOnMainQueue |> mapToSignal { peer -> Signal in let result = ValuePromise() @@ -1735,7 +1735,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, } if peerView.peerId.namespace == Namespaces.Peer.CloudChannel { - return account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: account, peerId: peerView.peerId, memberId: memberId, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: Int32.max)) + return context.peerChannelMemberCategoriesContextsManager.updateMemberBannedRights(account: context.account, peerId: peerView.peerId, memberId: memberId, bannedRights: TelegramChatBannedRights(flags: [.banReadMessages], untilDate: Int32.max)) |> afterDisposed { Queue.mainQueue().async { updateState { state in @@ -1748,7 +1748,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, } } - return removePeerMember(account: account, peerId: peerView.peerId, memberId: memberId) + return removePeerMember(account: context.account, peerId: peerView.peerId, memberId: memberId) |> deliverOnMainQueue |> afterDisposed { updateState { state in @@ -1768,7 +1768,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } if let channel = peerView.peers[peerView.peerId] as? TelegramChannel, channel.flags.contains(.isCreator), stateValue.with({ $0 }).editingState != nil { let controller = ActionSheetController(presentationTheme: presentationData.theme) @@ -1809,7 +1809,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, } }) }, displayUsernameShareMenu: { text in - let shareController = ShareController(account: account, subject: .url(text)) + let shareController = ShareController(context: context, subject: .url(text)) presentControllerImpl?(shareController, nil) }, displayUsernameContextMenu: { text in displayCopyContextMenuImpl?(text, .link) @@ -1821,18 +1821,18 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - let _ = (account.postbox.transaction { transaction -> StickerPackCollectionInfo? in + let _ = (context.account.postbox.transaction { transaction -> StickerPackCollectionInfo? in return (transaction.getPeerCachedData(peerId: peerView.peerId) as? CachedChannelData)?.stickerPack } |> deliverOnMainQueue).start(next: { stickerPack in - presentControllerImpl?(groupStickerPackSetupController(account: account, peerId: peerView.peerId, currentPackInfo: stickerPack), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + presentControllerImpl?(groupStickerPackSetupController(context: context, peerId: peerView.peerId, currentPackInfo: stickerPack), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) }) }, openGroupTypeSetup: { let _ = (peerView.get() |> take(1) |> deliverOnMainQueue).start(next: { peerView in - presentControllerImpl?(channelVisibilityController(account: account, peerId: peerView.peerId, mode: .generic, upgradedToSupergroup: { updatedPeerId, f in + presentControllerImpl?(channelVisibilityController(context: context, peerId: peerView.peerId, mode: .generic, upgradedToSupergroup: { updatedPeerId, f in upgradedToSupergroupImpl?(updatedPeerId, f) }), ViewControllerPresentationArguments(presentationAnimation: ViewControllerPresentationAnimation.modalSheet)) }) @@ -1850,7 +1850,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, |> distinctUntilChanged |> deliverOnMainQueue).start(next: { peerId in if peerId.namespace == Namespaces.Peer.CloudChannel { - let (disposable, control) = account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.recent(postbox: account.postbox, network: account.network, accountPeerId: account.peerId, peerId: peerId, updated: { state in + let (disposable, control) = context.peerChannelMemberCategoriesContextsManager.recent(postbox: contextaccount.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 { @@ -1879,7 +1879,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let previousChannelMembers = Atomic<[PeerId]?>(value: nil) let globalNotificationsKey: PostboxViewKey = .preferences(keys: Set([PreferencesKeys.globalNotifications])) - let signal = combineLatest(queue: .mainQueue(), (account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), peerView.get(), account.postbox.combinedView(keys: [globalNotificationsKey]), channelMembersPromise.get()) + let signal = combineLatest(queue: .mainQueue(), context.presentationData, statePromise.get(), peerView.get(), context.account.postbox.combinedView(keys: [globalNotificationsKey]), channelMembersPromise.get()) |> map { presentationData, state, view, combinedView, channelMembers -> (ItemListControllerState, (ItemListNodeState, GroupInfoEntry.ItemGenerationArguments)) in let peer = peerViewMainPeer(view) @@ -1939,7 +1939,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let updateTitle: Signal if let titleValue = updateValues.title { - updateTitle = updatePeerTitle(account: account, peerId: view.peerId, title: titleValue) + updateTitle = updatePeerTitle(account: context.account, peerId: view.peerId, title: titleValue) |> mapError { _ in return Void() } } else { updateTitle = .complete() @@ -1947,7 +1947,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let updateDescription: Signal if let descriptionValue = updateValues.description { - updateDescription = updatePeerDescription(account: account, peerId: view.peerId, description: descriptionValue.isEmpty ? nil : descriptionValue) + updateDescription = updatePeerDescription(account: context.account, peerId: view.peerId, description: descriptionValue.isEmpty ? nil : descriptionValue) |> mapError { _ in return Void() } } else { updateDescription = .complete() @@ -2005,12 +2005,12 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, var searchItem: ItemListControllerSearch? if state.searchingMembers { - searchItem = ChannelMembersSearchItem(account: account, peerId: view.peerId, cancel: { + searchItem = ChannelMembersSearchItem(context: context, peerId: view.peerId, cancel: { updateState { state in return state.withUpdatedSearchingMembers(false) } }, openPeer: { peer, _ in - if let infoController = peerInfoController(account: account, peer: peer) { + if let infoController = peerInfoController(context: context, peer: peer) { arguments.pushController(infoController) } }, present: { c, a in @@ -2020,7 +2020,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.GroupInfo_Title), leftNavigationButton: nil, rightNavigationButton: rightNavigationButton, secondaryRightNavigationButton: secondaryRightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) - let entries = groupInfoEntries(account: account, presentationData: presentationData, view: view, channelMembers: channelMembers, globalNotificationSettings: globalNotificationSettings, state: state) + let entries = groupInfoEntries(account: context.account, presentationData: presentationData, view: view, channelMembers: channelMembers, globalNotificationSettings: globalNotificationSettings, state: state) var memberIds: [PeerId] = [] for entry in entries { switch entry { @@ -2048,7 +2048,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] value in (controller?.navigationController as? NavigationController)?.pushViewController(value) @@ -2058,17 +2058,17 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, controller?.present(value, in: .window(.root), with: presentationArguments) } upgradedToSupergroupImpl = { [weak controller] upgradedPeerId, f in - let _ = (account.postbox.transaction { transaction -> Peer? in + let _ = (context.account.postbox.transaction { transaction -> Peer? in return transaction.getPeer(upgradedPeerId) } |> deliverOnMainQueue).start(next: { peer in guard let controller = controller, let navigationController = controller.navigationController as? NavigationController, let _ = peer else { return } - let infoController = groupInfoController(account: account, peerId: upgradedPeerId, membersLoaded: { + let infoController = groupInfoController(context: context, peerId: upgradedPeerId, membersLoaded: { f() }) - let chatController = ChatController(account: account, chatLocation: .peer(upgradedPeerId), messageId: nil, botStart: nil, mode: .standard(previewing: false)) + let chatController = ChatController(context: context, chatLocation: .peer(upgradedPeerId), messageId: nil, botStart: nil, mode: .standard(previewing: false)) var viewControllers: [UIViewController] = [] if let first = navigationController.viewControllers.first { viewControllers.append(first) @@ -2095,7 +2095,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, } displayCopyContextMenuImpl = { [weak controller] text, tag 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 var itemTag: GroupInfoEntryTag? = nil @@ -2136,7 +2136,7 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, |> take(1) |> deliverOnMainQueue).start(next: { peerView in if let controller = controller { - handlePeerInfoAboutTextAction(account: account, peerId: peerView.peerId, navigateDisposable: navigateDisposable, controller: controller, action: action, itemLink: itemLink) + handlePeerInfoAboutTextAction(context: context, peerId: peerView.peerId, navigateDisposable: navigateDisposable, controller: controller, action: action, itemLink: itemLink) } }) } @@ -2171,30 +2171,30 @@ public func groupInfoController(account: Account, peerId originalPeerId: PeerId, } controller.visibleBottomContentOffsetChanged = { offset in if let (peerId, loadMoreControl) = loadMoreControl.with({ $0 }), case let .known(value) = offset, value < 40.0 { - account.telegramApplicationContext.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: loadMoreControl) + context.peerChannelMemberCategoriesContextsManager.loadMore(peerId: peerId, control: loadMoreControl) } } return controller } -func handlePeerInfoAboutTextAction(account: Account, peerId: PeerId, navigateDisposable: MetaDisposable, controller: ViewController, action: TextLinkItemActionType, itemLink: TextLinkItem) { +func handlePeerInfoAboutTextAction(context: AccountContext, peerId: PeerId, navigateDisposable: MetaDisposable, controller: ViewController, action: TextLinkItemActionType, itemLink: TextLinkItem) { let presentImpl: (ViewController, Any?) -> Void = { controllerToPresent, _ in controller.present(controllerToPresent, in: .window(.root)) } let openResolvedPeerImpl: (PeerId?, ChatControllerInteractionNavigateToPeer) -> Void = { [weak controller] peerId, navigation in - openResolvedUrl(.peer(peerId, navigation), account: account, navigationController: (controller?.navigationController as? NavigationController), openPeer: { (peerId, navigation) in + openResolvedUrl(.peer(peerId, navigation), context: context, navigationController: (controller?.navigationController as? NavigationController), openPeer: { (peerId, navigation) in switch navigation { case let .chat(_, messageId): if let navigationController = controller?.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId), messageId: messageId, keepStack: .always) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId), messageId: messageId, keepStack: .always) } case .info: let peerSignal: Signal peerSignal = 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(account: account, peer: peer) { + if let infoController = peerInfoController(context: context, peer: peer) { (controller.navigationController as? NavigationController)?.pushViewController(infoController) } } @@ -2206,23 +2206,23 @@ func handlePeerInfoAboutTextAction(account: Account, peerId: PeerId, navigateDis } let openLinkImpl: (String) -> Void = { [weak controller] url in - navigateDisposable.set((resolveUrl(account: account, url: url) |> deliverOnMainQueue).start(next: { result in + navigateDisposable.set((resolveUrl(context: context, url: url) |> deliverOnMainQueue).start(next: { result in if let controller = controller { switch result { case let .externalUrl(url): - account.telegramApplicationContext.applicationBindings.openUrl(url) + context.applicationBindings.openUrl(url) case let .peer(peerId, _): openResolvedPeerImpl(peerId, .default) case let .channelMessage(peerId, messageId): if let navigationController = controller.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId), messageId: messageId) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId), messageId: messageId) } case let .stickerPack(name): - controller.present(StickerPackPreviewController(account: account, stickerPack: .name(name), parentNavigationController: controller.navigationController as? NavigationController), in: .window(.root)) + 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(account: account, webPage: webpage, anchor: anchor)) + (controller.navigationController as? NavigationController)?.pushViewController(InstantPageController(context: account, webPage: webpage, anchor: anchor)) case let .join(link): - controller.present(JoinLinkPreviewController(account: account, link: link, navigateToPeer: { peerId in + controller.present(JoinLinkPreviewController(context: context, link: link, navigateToPeer: { peerId in openResolvedPeerImpl(peerId, .chat(textInputState: nil, messageId: nil)) }), in: .window(.root)) default: @@ -2233,12 +2233,12 @@ func handlePeerInfoAboutTextAction(account: Account, peerId: PeerId, navigateDis } let openPeerMentionImpl: (String) -> Void = { mention in - navigateDisposable.set((resolvePeerByName(account: account, name: mention, ageLimit: 10) |> take(1) |> deliverOnMainQueue).start(next: { peerId in + navigateDisposable.set((resolvePeerByName(account: context.account, name: mention, ageLimit: 10) |> take(1) |> deliverOnMainQueue).start(next: { peerId in openResolvedPeerImpl(peerId, .default) })) } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } switch action { case .tap: switch itemLink { @@ -2247,17 +2247,17 @@ func handlePeerInfoAboutTextAction(account: Account, peerId: PeerId, navigateDis case let .mention(mention): openPeerMentionImpl(mention) case let .hashtag(_, hashtag): - let peerSignal = account.postbox.loadedPeerWithId(peerId) + let peerSignal = context.account.postbox.loadedPeerWithId(peerId) let _ = (peerSignal |> deliverOnMainQueue).start(next: { peer in - let searchController = HashtagSearchController(account: account, peer: peer, query: hashtag) + let searchController = HashtagSearchController(context: context, peer: peer, query: hashtag) (controller.navigationController as? NavigationController)?.pushViewController(searchController) }) } case .longTap: switch itemLink { case let .url(url): - let canOpenIn = availableOpenInOptions(applicationContext: account.telegramApplicationContext, item: .url(url: url)).count > 1 + let canOpenIn = availableOpenInOptions(context: context, item: .url(url: url)).count > 1 let openText = canOpenIn ? presentationData.strings.Conversation_FileOpenIn : presentationData.strings.Conversation_LinkDialogOpen let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) actionSheet.setItemGroups([ActionSheetItemGroup(items: [ @@ -2306,7 +2306,7 @@ func handlePeerInfoAboutTextAction(account: Account, peerId: PeerId, navigateDis ActionSheetTextItem(title: hashtag), ActionSheetButtonItem(title: presentationData.strings.Conversation_LinkDialogOpen, color: .accent, action: { [weak actionSheet] in actionSheet?.dismissAnimated() - let searchController = HashtagSearchController(account: account, peer: nil, query: hashtag) + let searchController = HashtagSearchController(context: context, peer: nil, query: hashtag) (controller.navigationController as? NavigationController)?.pushViewController(searchController) }), ActionSheetButtonItem(title: presentationData.strings.Conversation_LinkDialogCopy, color: .accent, action: { [weak actionSheet] in diff --git a/TelegramUI/GroupInfoSearchItem.swift b/TelegramUI/GroupInfoSearchItem.swift index dc9e9a9b72..bc36a28609 100644 --- a/TelegramUI/GroupInfoSearchItem.swift +++ b/TelegramUI/GroupInfoSearchItem.swift @@ -6,7 +6,7 @@ import TelegramCore import SwiftSignalKit final class ChannelMembersSearchItem: ItemListControllerSearch { - let account: Account + let context: AccountContext let peerId: PeerId let cancel: () -> Void let openPeer: (Peer, RenderedChannelParticipant?) -> Void @@ -17,8 +17,8 @@ final class ChannelMembersSearchItem: ItemListControllerSearch { private var activity: ValuePromise = ValuePromise(ignoreRepeated: false) private let activityDisposable = MetaDisposable() - init(account: Account, peerId: PeerId, searchMode: ChannelMembersSearchMode = .searchMembers, cancel: @escaping () -> Void, openPeer: @escaping (Peer, RenderedChannelParticipant?) -> Void, present: @escaping (ViewController, Any?) -> Void) { - self.account = account + init(context: AccountContext, peerId: PeerId, searchMode: ChannelMembersSearchMode = .searchMembers, cancel: @escaping () -> Void, openPeer: @escaping (Peer, RenderedChannelParticipant?) -> Void, present: @escaping (ViewController, Any?) -> Void) { + self.context = context self.peerId = peerId self.cancel = cancel self.openPeer = openPeer @@ -41,7 +41,7 @@ final class ChannelMembersSearchItem: ItemListControllerSearch { func isEqual(to: ItemListControllerSearch) -> Bool { if let to = to as? ChannelMembersSearchItem { - if self.account !== to.account { + if self.context !== to.context { return false } if self.peerId != to.peerId { @@ -57,7 +57,7 @@ final class ChannelMembersSearchItem: ItemListControllerSearch { if let current = current as? GroupInfoSearchNavigationContentNode { return current } else { - let presentationData = self.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = self.context.currentPresentationData.with { $0 } return GroupInfoSearchNavigationContentNode(theme: presentationData.theme, strings: presentationData.strings, mode: self.searchMode, cancel: self.cancel, updateActivity: { [weak self] value in self?.updateActivity = value }) @@ -65,7 +65,7 @@ final class ChannelMembersSearchItem: ItemListControllerSearch { } func node(current: ItemListControllerSearchNode?) -> ItemListControllerSearchNode { - return ChannelMembersSearchItemNode(account: self.account, peerId: self.peerId, searchMode: self.searchMode, openPeer: self.openPeer, cancel: self.cancel, updateActivity: { [weak self] value in + return ChannelMembersSearchItemNode(context: self.context, peerId: self.peerId, searchMode: self.searchMode, openPeer: self.openPeer, cancel: self.cancel, updateActivity: { [weak self] value in self?.activity.set(value) }, present: { [weak self] c, a in self?.present(c, a) @@ -76,8 +76,8 @@ final class ChannelMembersSearchItem: ItemListControllerSearch { private final class ChannelMembersSearchItemNode: ItemListControllerSearchNode { private let containerNode: ChannelMembersSearchContainerNode - init(account: Account, peerId: PeerId, searchMode: ChannelMembersSearchMode, openPeer: @escaping (Peer, RenderedChannelParticipant?) -> Void, cancel: @escaping () -> Void, updateActivity: @escaping(Bool) -> Void, present: @escaping (ViewController, Any?) -> Void) { - self.containerNode = ChannelMembersSearchContainerNode(account: account, peerId: peerId, mode: searchMode, filters: [], openPeer: { peer, participant in + init(context: AccountContext, peerId: PeerId, searchMode: ChannelMembersSearchMode, openPeer: @escaping (Peer, RenderedChannelParticipant?) -> Void, cancel: @escaping () -> Void, updateActivity: @escaping(Bool) -> Void, present: @escaping (ViewController, Any?) -> Void) { + self.containerNode = ChannelMembersSearchContainerNode(context: context, peerId: peerId, mode: searchMode, filters: [], openPeer: { peer, participant in openPeer(peer, participant) }, updateActivity: updateActivity, present: present) self.containerNode.cancel = { diff --git a/TelegramUI/GroupPreHistorySetupController.swift b/TelegramUI/GroupPreHistorySetupController.swift index df8246ef85..06865511fd 100644 --- a/TelegramUI/GroupPreHistorySetupController.swift +++ b/TelegramUI/GroupPreHistorySetupController.swift @@ -110,7 +110,7 @@ private func groupPreHistorySetupEntries(isSupergroup: Bool, presentationData: P return entries } -public func groupPreHistorySetupController(account: Account, peerId: PeerId, upgradedToSupergroup: @escaping (PeerId, @escaping () -> Void) -> Void) -> ViewController { +public func groupPreHistorySetupController(context: AccountContext, peerId: PeerId, upgradedToSupergroup: @escaping (PeerId, @escaping () -> Void) -> Void) -> ViewController { let statePromise = ValuePromise(GroupPreHistorySetupState(), ignoreRepeated: true) let stateValue = Atomic(value: GroupPreHistorySetupState()) let updateState: ((GroupPreHistorySetupState) -> GroupPreHistorySetupState) -> Void = { f in @@ -132,7 +132,7 @@ public func groupPreHistorySetupController(account: Account, peerId: PeerId, upg } }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), account.viewTracker.peerView(peerId)) + let signal = combineLatest(context.presentationData, statePromise.get(), context.account.viewTracker.peerView(peerId)) |> deliverOnMainQueue |> map { presentationData, state, view -> (ItemListControllerState, (ItemListNodeState, GroupPreHistorySetupEntry.ItemGenerationArguments)) in let defaultValue: Bool = (view.cachedData as? CachedChannelData)?.flags.contains(.preHistoryEnabled) ?? false @@ -153,7 +153,7 @@ public func groupPreHistorySetupController(account: Account, peerId: PeerId, upg } if let value = value, value != defaultValue { if peerId.namespace == Namespaces.Peer.CloudGroup { - let signal = convertGroupToSupergroup(account: account, peerId: peerId) + let signal = convertGroupToSupergroup(account: context.account, peerId: peerId) |> map(Optional.init) |> `catch` { _ -> Signal in return .single(nil) @@ -162,7 +162,7 @@ public func groupPreHistorySetupController(account: Account, peerId: PeerId, upg guard let upgradedPeerId = upgradedPeerId else { return .single(nil) } - return updateChannelHistoryAvailabilitySettingsInteractively(postbox: account.postbox, network: account.network, accountStateManager: account.stateManager, peerId: upgradedPeerId, historyAvailableForNewMembers: value) + return updateChannelHistoryAvailabilitySettingsInteractively(postbox: context.account.postbox, network: context.account.network, accountStateManager: context.account.stateManager, peerId: upgradedPeerId, historyAvailableForNewMembers: value) |> mapToSignal { _ -> Signal in return .complete() } @@ -178,7 +178,7 @@ public func groupPreHistorySetupController(account: Account, peerId: PeerId, upg } })) } else { - applyDisposable.set((updateChannelHistoryAvailabilitySettingsInteractively(postbox: account.postbox, network: account.network, accountStateManager: account.stateManager, peerId: peerId, historyAvailableForNewMembers: value) + applyDisposable.set((updateChannelHistoryAvailabilitySettingsInteractively(postbox: context.account.postbox, network: context.account.network, accountStateManager: context.account.stateManager, peerId: peerId, historyAvailableForNewMembers: value) |> deliverOnMainQueue).start(completed: { dismissImpl?() })) @@ -198,7 +198,7 @@ public func groupPreHistorySetupController(account: Account, peerId: PeerId, upg actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) dismissImpl = { [weak controller] in controller?.view.endEditing(true) controller?.dismiss() diff --git a/TelegramUI/GroupStickerPackSetupController.swift b/TelegramUI/GroupStickerPackSetupController.swift index 28b4ed59ac..1063acf06d 100644 --- a/TelegramUI/GroupStickerPackSetupController.swift +++ b/TelegramUI/GroupStickerPackSetupController.swift @@ -296,7 +296,7 @@ private func groupStickerPackSetupControllerEntries(presentationData: Presentati return entries } -public func groupStickerPackSetupController(account: Account, peerId: PeerId, currentPackInfo: StickerPackCollectionInfo?) -> ViewController { +public func groupStickerPackSetupController(context: AccountContext, peerId: PeerId, currentPackInfo: StickerPackCollectionInfo?) -> ViewController { let initialState = GroupStickerPackSetupControllerState(isSaving: false) let statePromise = ValuePromise(initialState, ignoreRepeated: true) @@ -309,7 +309,7 @@ public func groupStickerPackSetupController(account: Account, peerId: PeerId, cu let initialData = Promise() if let currentPackInfo = currentPackInfo { - initialData.set(cachedStickerPack(postbox: account.postbox, network: account.network, reference: .id(id: currentPackInfo.id.id, accessHash: currentPackInfo.accessHash), forceRemote: false) + initialData.set(cachedStickerPack(postbox: context.account.postbox, network: context.account.network, reference: .id(id: currentPackInfo.id.id, accessHash: currentPackInfo.accessHash), forceRemote: false) |> map { result -> InitialStickerPackData? in switch result { case .none: @@ -325,7 +325,7 @@ public func groupStickerPackSetupController(account: Account, peerId: PeerId, cu } let stickerPacks = Promise() - stickerPacks.set(account.postbox.combinedView(keys: [.itemCollectionInfos(namespaces: [Namespaces.ItemCollection.CloudStickerPacks])])) + stickerPacks.set(context.account.postbox.combinedView(keys: [.itemCollectionInfos(namespaces: [Namespaces.ItemCollection.CloudStickerPacks])])) let searchState = Promise<(String, GroupStickerPackSearchState)>() searchState.set(combineLatest(searchText.get(), initialData.get(), stickerPacks.get()) @@ -349,7 +349,7 @@ public func groupStickerPackSetupController(account: Account, peerId: PeerId, cu } } return .single((searchText, .searching)) - |> then((loadedStickerPack(postbox: account.postbox, network: account.network, reference: .name(searchText.lowercased()), forceActualized: false) |> delay(0.3, queue: Queue.concurrentDefaultQueue())) + |> then((loadedStickerPack(postbox: context.account.postbox, network: context.account.network, reference: .name(searchText.lowercased()), forceActualized: false) |> delay(0.3, queue: Queue.concurrentDefaultQueue())) |> mapToSignal { value -> Signal<(String, GroupStickerPackSearchState), NoError> in switch value { case .fetching: @@ -381,14 +381,14 @@ public func groupStickerPackSetupController(account: Account, peerId: PeerId, cu var presentStickerPackController: ((StickerPackCollectionInfo) -> Void)? - let arguments = GroupStickerPackSetupControllerArguments(account: account, selectStickerPack: { info in + let arguments = GroupStickerPackSetupControllerArguments(account: context.account, selectStickerPack: { info in searchText.set(info.shortName) }, openStickerPack: { info in presentStickerPackController?(info) }, updateSearchText: { text in searchText.set(text) }, openStickersBot: { - resolveDisposable.set((resolvePeerByName(account: account, name: "stickers") |> deliverOnMainQueue).start(next: { peerId in + resolveDisposable.set((resolvePeerByName(account: context.account, name: "stickers") |> deliverOnMainQueue).start(next: { peerId in if let peerId = peerId { dismissImpl?() navigateToChatControllerImpl?(peerId) @@ -398,7 +398,7 @@ public func groupStickerPackSetupController(account: Account, peerId: PeerId, cu let previousHadData = Atomic(value: false) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, initialData.get() |> deliverOnMainQueue, stickerPacks.get() |> deliverOnMainQueue, searchState.get() |> deliverOnMainQueue) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, initialData.get() |> deliverOnMainQueue, stickerPacks.get() |> deliverOnMainQueue, searchState.get() |> deliverOnMainQueue) |> map { presentationData, state, initialData, view, searchState -> (ItemListControllerState, (ItemListNodeState, GroupStickerPackEntry.ItemGenerationArguments)) in let leftNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Cancel), style: .regular, enabled: true, action: { dismissImpl?() @@ -429,7 +429,7 @@ public func groupStickerPackSetupController(account: Account, peerId: PeerId, cu state.isSaving = true return state } - saveDisposable.set((updateGroupSpecificStickerset(postbox: account.postbox, network: account.network, peerId: peerId, info: info) + saveDisposable.set((updateGroupSpecificStickerset(postbox: context.account.postbox, network: context.account.network, peerId: peerId, info: info) |> deliverOnMainQueue).start(error: { _ in updateState { state in var state = state @@ -460,7 +460,7 @@ public func groupStickerPackSetupController(account: Account, peerId: PeerId, cu actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, p in if let controller = controller { @@ -472,11 +472,11 @@ public func groupStickerPackSetupController(account: Account, peerId: PeerId, cu } presentStickerPackController = { [weak controller] info in dismissInputImpl?() - presentControllerImpl?(StickerPackPreviewController(account: account, stickerPack: .id(id: info.id.id, accessHash: info.accessHash), parentNavigationController: controller?.navigationController as? NavigationController), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + presentControllerImpl?(StickerPackPreviewController(context: context, stickerPack: .id(id: info.id.id, accessHash: info.accessHash), parentNavigationController: controller?.navigationController as? NavigationController), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } navigateToChatControllerImpl = { [weak controller] peerId in if let controller = controller, let navigationController = controller.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId)) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId)) } } dismissImpl = { [weak controller] in diff --git a/TelegramUI/GroupsInCommonController.swift b/TelegramUI/GroupsInCommonController.swift index b1861eab8d..46a9c529b9 100644 --- a/TelegramUI/GroupsInCommonController.swift +++ b/TelegramUI/GroupsInCommonController.swift @@ -129,7 +129,7 @@ private func groupsInCommonControllerEntries(presentationData: PresentationData, return entries } -public func groupsInCommonController(account: Account, peerId: PeerId) -> ViewController { +public func groupsInCommonController(context: AccountContext, peerId: PeerId) -> ViewController { let statePromise = ValuePromise(GroupsInCommonControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: GroupsInCommonControllerState()) let updateState: ((GroupsInCommonControllerState) -> GroupsInCommonControllerState) -> Void = { f in @@ -142,12 +142,12 @@ public func groupsInCommonController(account: Account, peerId: PeerId) -> ViewCo var pushControllerImpl: ((ViewController) -> Void)? - let arguments = GroupsInCommonControllerArguments(account: account, openPeer: { memberId in - pushControllerImpl?(ChatController(account: account, chatLocation: .peer(memberId))) + let arguments = GroupsInCommonControllerArguments(account: context.account, openPeer: { memberId in + pushControllerImpl?(ChatController(context: context, chatLocation: .peer(memberId))) }) - let peersSignal: Signal<[Peer]?, NoError> = .single(nil) |> then(groupsInCommon(account: account, peerId: peerId) |> mapToSignal { peerIds -> Signal<[Peer], NoError> in - return account.postbox.transaction { transaction -> [Peer] in + let peersSignal: Signal<[Peer]?, NoError> = .single(nil) |> then(groupsInCommon(account: context.account, peerId: peerId) |> mapToSignal { peerIds -> Signal<[Peer], NoError> in + return context.account.postbox.transaction { transaction -> [Peer] in var result: [Peer] = [] for id in peerIds { if let peer = transaction.getPeer(id) { @@ -163,7 +163,7 @@ public func groupsInCommonController(account: Account, peerId: PeerId) -> ViewCo var previousPeers: [Peer]? - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), peersPromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get(), peersPromise.get()) |> deliverOnMainQueue |> map { presentationData, state, peers -> (ItemListControllerState, (ItemListNodeState, GroupsInCommonEntry.ItemGenerationArguments)) in var emptyStateItem: ItemListControllerEmptyStateItem? @@ -182,7 +182,7 @@ public func groupsInCommonController(account: Account, peerId: PeerId) -> ViewCo actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] c in if let controller = controller { (controller.navigationController as? NavigationController)?.pushViewController(c) diff --git a/TelegramUI/HashtagChatInputContextPanelNode.swift b/TelegramUI/HashtagChatInputContextPanelNode.swift index 2b1f93cf8b..3b4df57ab2 100644 --- a/TelegramUI/HashtagChatInputContextPanelNode.swift +++ b/TelegramUI/HashtagChatInputContextPanelNode.swift @@ -59,14 +59,13 @@ private func preparedTransition(from fromEntries: [HashtagChatInputContextPanelE } final class HashtagChatInputContextPanelNode: ChatInputContextPanelNode { - private let listView: ListView private var currentEntries: [HashtagChatInputContextPanelEntry]? private var enqueuedTransitions: [(HashtagChatInputContextPanelTransition, 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 HashtagChatInputContextPanelNode: 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 HashtagChatInputContextPanelNode: ChatInputContextPanelNode { private func prepareTransition(from: [HashtagChatInputContextPanelEntry]? , to: [HashtagChatInputContextPanelEntry]) { 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 if let strongSelf = self, let interfaceInteraction = strongSelf.interfaceInteraction { interfaceInteraction.updateTextInputStateAndMode { textInputState, inputMode in var hashtagQueryRange: NSRange? diff --git a/TelegramUI/HashtagSearchController.swift b/TelegramUI/HashtagSearchController.swift index 0e6ac12941..1d72db6d11 100644 --- a/TelegramUI/HashtagSearchController.swift +++ b/TelegramUI/HashtagSearchController.swift @@ -7,7 +7,7 @@ import SwiftSignalKit final class HashtagSearchController: TelegramController { private let queue = Queue() - private let account: Account + private let context: AccountContext private let peer: Peer? private let query: String private var transitionDisposable: Disposable? @@ -19,14 +19,14 @@ final class HashtagSearchController: TelegramController { return self.displayNode as! HashtagSearchControllerNode } - init(account: Account, peer: Peer?, query: String) { - self.account = account + init(context: AccountContext, peer: Peer?, query: String) { + self.context = context self.peer = peer self.query = query - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } - super.init(account: account, navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData), mediaAccessoryPanelVisibility: .specific(size: .compact), locationBroadcastPanelSource: .none) + super.init(context: context, navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData), mediaAccessoryPanelVisibility: .specific(size: .compact), locationBroadcastPanelSource: .none) self.statusBar.statusBarStyle = self.presentationData.theme.rootController.statusBar.style.style @@ -36,7 +36,7 @@ final class HashtagSearchController: TelegramController { let chatListPresentationData = ChatListPresentationData(theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameSortOrder: self.presentationData.nameSortOrder, nameDisplayOrder: self.presentationData.nameDisplayOrder, disableAnimations: self.presentationData.disableAnimations) let location: SearchMessagesLocation = .general - let search = searchMessages(account: account, location: location, query: query, state: nil) + let search = searchMessages(account: context.account, location: location, query: query, state: nil) let foundMessages: Signal<[ChatListSearchEntry], NoError> = search |> map { result, _ in return result.messages.map({ .message($0, result.readStates[$0.id.peerId], chatListPresentationData) }) @@ -46,9 +46,9 @@ final class HashtagSearchController: TelegramController { }, togglePeerSelected: { _ in }, messageSelected: { [weak self] peer, message, _ in if let strongSelf = self { - strongSelf.openMessageFromSearchDisposable.set((storedMessageFromSearchPeer(account: strongSelf.account, peer: peer) |> deliverOnMainQueue).start(next: { actualPeerId in - if let strongSelf = self { - (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(account: strongSelf.account, chatLocation: .peer(actualPeerId), messageId: message.id.peerId == actualPeerId ? message.id : nil)) + strongSelf.openMessageFromSearchDisposable.set((storedMessageFromSearchPeer(account: strongSelf.context.account, peer: peer) |> deliverOnMainQueue).start(next: { actualPeerId in + if let strongSelf = self, let navigationController = strongSelf.navigationController as? NavigationController { + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(actualPeerId), messageId: message.id.peerId == actualPeerId ? message.id : nil) } })) strongSelf.controllerNode.listNode.clearHighlightAnimated(true) @@ -69,7 +69,7 @@ final class HashtagSearchController: TelegramController { let previousEntries = previousSearchItems.swap(entries) let firstTime = previousEntries == nil - let transition = chatListSearchContainerPreparedTransition(from: previousEntries ?? [], to: entries, displayingResults: true, account: account, enableHeaders: false, filter: [], interaction: interaction) + let transition = chatListSearchContainerPreparedTransition(from: previousEntries ?? [], to: entries, displayingResults: true, context: strongSelf.context, enableHeaders: false, filter: [], interaction: interaction) strongSelf.controllerNode.enqueueTransition(transition, firstTime: firstTime) } }) @@ -85,7 +85,7 @@ final class HashtagSearchController: TelegramController { } override func loadDisplayNode() { - self.displayNode = HashtagSearchControllerNode(account: self.account, peer: self.peer, query: self.query, theme: self.presentationData.theme, strings: self.presentationData.strings) + self.displayNode = HashtagSearchControllerNode(context: self.context, peer: self.peer, query: self.query, theme: self.presentationData.theme, strings: self.presentationData.strings) if let chatController = self.controllerNode.chatController { chatController.parentController = self } diff --git a/TelegramUI/HashtagSearchControllerNode.swift b/TelegramUI/HashtagSearchControllerNode.swift index 2ea1bdc9b8..60a55f9e1d 100644 --- a/TelegramUI/HashtagSearchControllerNode.swift +++ b/TelegramUI/HashtagSearchControllerNode.swift @@ -12,7 +12,7 @@ final class HashtagSearchControllerNode: ASDisplayNode { var chatController: ChatController? - private let account: Account + private let context: AccountContext private let query: String private var containerLayout: (ContainerViewLayout, CGFloat)? @@ -21,8 +21,8 @@ final class HashtagSearchControllerNode: ASDisplayNode { var navigationBar: NavigationBar? - init(account: Account, peer: Peer?, query: String, theme: PresentationTheme, strings: PresentationStrings) { - self.account = account + init(context: AccountContext, peer: Peer?, query: String, theme: PresentationTheme, strings: PresentationStrings) { + self.context = context self.query = query self.listNode = ListView() @@ -37,7 +37,7 @@ final class HashtagSearchControllerNode: ASDisplayNode { self.segmentedControl.selectedSegmentIndex = 0 if let peer = peer { - self.chatController = ChatController(account: account, chatLocation: .peer(peer.id), messageId: nil, botStart: nil, mode: .inline) + self.chatController = ChatController(context: context, chatLocation: .peer(peer.id), messageId: nil, botStart: nil, mode: .inline) } else { self.chatController = nil } diff --git a/TelegramUI/HorizontalListContextResultsChatInputContextPanelNode.swift b/TelegramUI/HorizontalListContextResultsChatInputContextPanelNode.swift index 795d6dac62..55ba69a730 100644 --- a/TelegramUI/HorizontalListContextResultsChatInputContextPanelNode.swift +++ b/TelegramUI/HorizontalListContextResultsChatInputContextPanelNode.swift @@ -80,7 +80,7 @@ final class HorizontalListContextResultsChatInputContextPanelNode: ChatInputCont private var enqueuedTransitions: [(HorizontalListContextResultsChatInputContextPanelTransition, Bool)] = [] private var hasValidLayout = false - override init(account: Account, theme: PresentationTheme, strings: PresentationStrings) { + override init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings) { self.strings = strings self.separatorNode = ASDisplayNode() @@ -94,7 +94,7 @@ final class HorizontalListContextResultsChatInputContextPanelNode: ChatInputCont self.listView.transform = CATransform3DMakeRotation(-CGFloat(CGFloat.pi / 2.0), 0.0, 0.0, 1.0) self.listView.isHidden = true - super.init(account: account, theme: theme, strings: strings) + super.init(context: context, theme: theme, strings: strings) self.isOpaque = false self.clipsToBounds = true @@ -143,7 +143,7 @@ final class HorizontalListContextResultsChatInputContextPanelNode: ChatInputCont } menuItems.append(PeekControllerMenuItem(title: strongSelf.strings.StickerPack_ViewPack, color: .accent, action: { if let strongSelf = self { - let controller = StickerPackPreviewController(account: strongSelf.account, stickerPack: packReference, parentNavigationController: strongSelf.interfaceInteraction?.getNavigationController()) + let controller = StickerPackPreviewController(context: strongSelf.context, stickerPack: packReference, parentNavigationController: strongSelf.interfaceInteraction?.getNavigationController()) controller.sendSticker = { file in if let strongSelf = self { strongSelf.interfaceInteraction?.sendSticker(file) @@ -155,18 +155,18 @@ final class HorizontalListContextResultsChatInputContextPanelNode: ChatInputCont } })) } - selectedItemNodeAndContent = (itemNode, StickerPreviewPeekContent(account: item.account, item: .found(FoundStickerItem(file: file, stringRepresentations: [])), menu: menuItems)) + selectedItemNodeAndContent = (itemNode, StickerPreviewPeekContent(account: item.context.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 { menuItems.append(PeekControllerMenuItem(title: strongSelf.strings.Preview_SaveGif, color: .accent, action: { - let _ = addSavedGif(postbox: strongSelf.account.postbox, fileReference: .standalone(media: file)).start() + let _ = addSavedGif(postbox: strongSelf.context.account.postbox, fileReference: .standalone(media: file)).start() })) } menuItems.append(PeekControllerMenuItem(title: strongSelf.strings.ShareMenu_Send, color: .accent, font: .bold, action: { item.resultSelected(item.result) })) - selectedItemNodeAndContent = (itemNode, ChatContextResultPeekContent(account: item.account, contextResult: item.result, menu: menuItems)) + selectedItemNodeAndContent = (itemNode, ChatContextResultPeekContent(account: item.context.account, contextResult: item.result, menu: menuItems)) } } } @@ -202,7 +202,7 @@ final class HorizontalListContextResultsChatInputContextPanelNode: ChatInputCont return } self.isLoadingMore = true - self.loadMoreDisposable.set((requestChatContextResults(account: self.account, botId: currentProcessedResults.botId, peerId: currentProcessedResults.peerId, query: currentProcessedResults.query, location: .single(currentProcessedResults.geoPoint), offset: nextOffset) + self.loadMoreDisposable.set((requestChatContextResults(account: self.context.account, botId: currentProcessedResults.botId, peerId: currentProcessedResults.peerId, query: currentProcessedResults.query, location: .single(currentProcessedResults.geoPoint), offset: nextOffset) |> deliverOnMainQueue).start(next: { [weak self] nextResults in guard let strongSelf = self, let nextResults = nextResults else { return @@ -242,7 +242,7 @@ final class HorizontalListContextResultsChatInputContextPanelNode: ChatInputCont } let firstTime = self.currentEntries == nil - let transition = preparedTransition(from: self.currentEntries ?? [], to: entries, hasMore: results.nextOffset != nil, account: self.account, resultSelected: { [weak self] result in + let transition = preparedTransition(from: self.currentEntries ?? [], to: entries, hasMore: results.nextOffset != nil, account: self.context.account, resultSelected: { [weak self] result in if let strongSelf = self, let interfaceInteraction = strongSelf.interfaceInteraction { interfaceInteraction.sendContextResult(results, result) } diff --git a/TelegramUI/HorizontalStickersChatContextPanelNode.swift b/TelegramUI/HorizontalStickersChatContextPanelNode.swift index 79a709373f..29366c1e08 100644 --- a/TelegramUI/HorizontalStickersChatContextPanelNode.swift +++ b/TelegramUI/HorizontalStickersChatContextPanelNode.swift @@ -102,7 +102,7 @@ final class HorizontalStickersChatContextPanelNode: ChatInputContextPanelNode { private var stickerPreviewController: StickerPreviewController? - override init(account: Account, theme: PresentationTheme, strings: PresentationStrings) { + override init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings) { self.strings = strings self.backgroundNode = ASImageNode() @@ -129,7 +129,7 @@ final class HorizontalStickersChatContextPanelNode: ChatInputContextPanelNode { self.stickersInteraction = HorizontalStickersChatContextPanelInteraction() - super.init(account: account, theme: theme, strings: strings) + super.init(context: context, theme: theme, strings: strings) self.placement = .overTextInput self.isOpaque = false @@ -153,55 +153,55 @@ final class HorizontalStickersChatContextPanelNode: ChatInputContextPanelNode { } if let itemNode = strongSelf.gridNode.itemNodeAtPoint(strongSelf.view.convert(point, to: strongSelf.gridNode.view)) as? HorizontalStickerGridItemNode, let item = itemNode.stickerItem { - return strongSelf.account.postbox.transaction { transaction -> Bool in + return strongSelf.context.account.postbox.transaction { transaction -> Bool in return getIsStickerSaved(transaction: transaction, fileId: item.file.fileId) - } - |> deliverOnMainQueue - |> map { isStarred -> (ASDisplayNode, PeekControllerContent)? in - if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { - var menuItems: [PeekControllerMenuItem] = [] - menuItems = [ - PeekControllerMenuItem(title: strongSelf.strings.StickerPack_Send, color: .accent, font: .bold, action: { - controllerInteraction.sendSticker(.standalone(media: item.file), true) - }), - PeekControllerMenuItem(title: isStarred ? strongSelf.strings.Stickers_RemoveFromFavorites : strongSelf.strings.Stickers_AddToFavorites, color: isStarred ? .destructive : .accent, action: { - if let strongSelf = self { - if isStarred { - let _ = removeSavedSticker(postbox: strongSelf.account.postbox, mediaId: item.file.fileId).start() - } else { - let _ = addSavedSticker(postbox: strongSelf.account.postbox, network: strongSelf.account.network, file: item.file).start() - } + } + |> deliverOnMainQueue + |> map { isStarred -> (ASDisplayNode, PeekControllerContent)? in + if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { + var menuItems: [PeekControllerMenuItem] = [] + menuItems = [ + PeekControllerMenuItem(title: strongSelf.strings.StickerPack_Send, color: .accent, font: .bold, action: { + controllerInteraction.sendSticker(.standalone(media: item.file), true) + }), + PeekControllerMenuItem(title: isStarred ? strongSelf.strings.Stickers_RemoveFromFavorites : strongSelf.strings.Stickers_AddToFavorites, color: isStarred ? .destructive : .accent, action: { + if let strongSelf = self { + if isStarred { + let _ = removeSavedSticker(postbox: strongSelf.context.account.postbox, mediaId: item.file.fileId).start() + } else { + let _ = addSavedSticker(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, file: item.file).start() } - }), - PeekControllerMenuItem(title: strongSelf.strings.StickerPack_ViewPack, color: .accent, action: { - if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { - loop: for attribute in item.file.attributes { - switch attribute { - case let .Sticker(_, packReference, _): - if let packReference = packReference { - let controller = StickerPackPreviewController(account: strongSelf.account, stickerPack: packReference, parentNavigationController: controllerInteraction.navigationController()) - controller.sendSticker = { file in - if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { - controllerInteraction.sendSticker(file, true) - } + } + }), + PeekControllerMenuItem(title: strongSelf.strings.StickerPack_ViewPack, color: .accent, action: { + if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { + loop: for attribute in item.file.attributes { + switch attribute { + case let .Sticker(_, packReference, _): + if let packReference = packReference { + let controller = StickerPackPreviewController(context: strongSelf.context, stickerPack: packReference, parentNavigationController: controllerInteraction.navigationController()) + controller.sendSticker = { file in + if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { + controllerInteraction.sendSticker(file, true) } - - controllerInteraction.navigationController()?.view.window?.endEditing(true) - controllerInteraction.presentController(controller, nil) } - break loop - default: - break + + controllerInteraction.navigationController()?.view.window?.endEditing(true) + controllerInteraction.presentController(controller, nil) } + break loop + default: + break } } - }), - PeekControllerMenuItem(title: strongSelf.strings.Common_Cancel, color: .accent, action: {}) - ] - return (itemNode, StickerPreviewPeekContent(account: strongSelf.account, item: .pack(item), menu: menuItems)) - } else { - return nil - } + } + }), + PeekControllerMenuItem(title: strongSelf.strings.Common_Cancel, color: .accent, action: {}) + ] + return (itemNode, StickerPreviewPeekContent(account: strongSelf.context.account, item: .pack(item), menu: menuItems)) + } else { + return nil + } } } } @@ -238,7 +238,7 @@ final class HorizontalStickersChatContextPanelNode: ChatInputContextPanelNode { self.updateLayout(size: validLayout.0, leftInset: validLayout.1, rightInset: validLayout.2, transition: .immediate, interfaceState: validLayout.3) } - let transition = preparedGridEntryTransition(account: self.account, from: previousEntries, to: entries, stickersInteraction: self.stickersInteraction, interfaceInteraction: self.interfaceInteraction!) + let transition = preparedGridEntryTransition(account: self.context.account, from: previousEntries, to: entries, stickersInteraction: self.stickersInteraction, interfaceInteraction: self.interfaceInteraction!) self.enqueueTransition(transition) } diff --git a/TelegramUI/InstalledStickerPacksController.swift b/TelegramUI/InstalledStickerPacksController.swift index f9b3afb9f3..8a70d811de 100644 --- a/TelegramUI/InstalledStickerPacksController.swift +++ b/TelegramUI/InstalledStickerPacksController.swift @@ -380,7 +380,7 @@ public enum InstalledStickerPacksControllerMode { case masks } -public func installedStickerPacksController(account: Account, mode: InstalledStickerPacksControllerMode, archivedPacks: [ArchivedStickerPackItem]? = nil, updatedPacks: @escaping ([ArchivedStickerPackItem]?) -> Void = { _ in }) -> ViewController { +public func installedStickerPacksController(context: AccountContext, mode: InstalledStickerPacksControllerMode, archivedPacks: [ArchivedStickerPackItem]? = nil, updatedPacks: @escaping ([ArchivedStickerPackItem]?) -> Void = { _ in }) -> ViewController { let initialState = InstalledStickerPacksControllerState().withUpdatedEditing(mode == .modal) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) @@ -402,7 +402,7 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti var presentStickerPackController: ((StickerPackCollectionInfo) -> Void)? - let arguments = InstalledStickerPacksControllerArguments(account: account, openStickerPack: { info in + let arguments = InstalledStickerPacksControllerArguments(account: context.account, openStickerPack: { info in presentStickerPackController?(info) }, setPackIdWithRevealedOptions: { packId, fromPackId in updateState { state in @@ -413,7 +413,7 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti } } }, removePack: { archivedItem in - 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() @@ -432,26 +432,26 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti updatedPacks(packs) }) - let _ = removeStickerPackInteractively(postbox: account.postbox, id: archivedItem.info.id, option: .archive).start() + let _ = removeStickerPackInteractively(postbox: context.account.postbox, id: archivedItem.info.id, option: .archive).start() }), ActionSheetButtonItem(title: presentationData.strings.Common_Delete, color: .destructive, action: { dismissAction() - let _ = removeStickerPackInteractively(postbox: account.postbox, id: archivedItem.info.id, option: .delete).start() + let _ = removeStickerPackInteractively(postbox: context.account.postbox, id: archivedItem.info.id, option: .delete).start() }) ]), ActionSheetItemGroup(items: [ActionSheetButtonItem(title: presentationData.strings.Common_Cancel, action: { dismissAction() })]) ]) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, openStickersBot: { - resolveDisposable.set((resolvePeerByName(account: account, name: "stickers") |> deliverOnMainQueue).start(next: { peerId in + resolveDisposable.set((resolvePeerByName(account: context.account, name: "stickers") |> deliverOnMainQueue).start(next: { peerId in if let peerId = peerId { navigateToChatControllerImpl?(peerId) } })) }, openMasks: { - pushControllerImpl?(installedStickerPacksController(account: account, mode: .masks, archivedPacks: archivedPacks, updatedPacks: { _ in})) + pushControllerImpl?(installedStickerPacksController(context: context, mode: .masks, archivedPacks: archivedPacks, updatedPacks: { _ in})) }, openFeatured: { - pushControllerImpl?(featuredStickerPacksController(account: account)) + pushControllerImpl?(featuredStickerPacksController(context: context)) }, openArchived: { archived in let archivedMode: ArchivedStickerPacksControllerMode switch mode { @@ -460,12 +460,12 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti default: archivedMode = .stickers } - pushControllerImpl?(archivedStickerPacksController(account: account, mode: archivedMode, archived: archived, updatedPacks: { packs in + pushControllerImpl?(archivedStickerPacksController(context: context, mode: archivedMode, archived: archived, updatedPacks: { packs in archivedPromise.set(.single(packs)) updatedPacks(packs) })) }, openSuggestOptions: { - 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() @@ -480,7 +480,7 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti for (option, title) in options { items.append(ActionSheetButtonItem(title: title, color: .accent, action: { dismissAction() - let _ = updateStickerSettingsInteractively(postbox: account.postbox, { current in + let _ = updateStickerSettingsInteractively(postbox: context.account.postbox, { current in return current.withUpdatedEmojiStickerSuggestionMode(option) }).start() })) @@ -504,17 +504,17 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti }) let stickerPacks = Promise() - stickerPacks.set(account.postbox.combinedView(keys: [.itemCollectionInfos(namespaces: [namespaceForMode(mode)])])) + stickerPacks.set(context.account.postbox.combinedView(keys: [.itemCollectionInfos(namespaces: [namespaceForMode(mode)])])) let featured = Promise<[FeaturedStickerPackItem]>() switch mode { case .general, .modal: - featured.set(account.viewTracker.featuredStickerPacks()) - archivedPromise.set(.single(archivedPacks) |> then(archivedStickerPacks(account: account) |> map(Optional.init))) + featured.set(context.account.viewTracker.featuredStickerPacks()) + archivedPromise.set(.single(archivedPacks) |> then(archivedStickerPacks(account: context.account) |> map(Optional.init))) case .masks: featured.set(.single([])) - archivedPromise.set(.single(nil) |> then(archivedStickerPacks(account: account, namespace: .masks) |> map(Optional.init))) + archivedPromise.set(.single(nil) |> then(archivedStickerPacks(account: context.account, namespace: .masks) |> map(Optional.init))) } @@ -522,9 +522,9 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti let stickerSettingsKey = ApplicationSpecificPreferencesKeys.stickerSettings let preferencesKey: PostboxViewKey = .preferences(keys: Set([stickerSettingsKey])) - let preferencesView = account.postbox.combinedView(keys: [preferencesKey]) + let preferencesView = context.account.postbox.combinedView(keys: [preferencesKey]) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, stickerPacks.get() |> deliverOnMainQueue, combineLatest(featured.get() |> deliverOnMainQueue, archivedPromise.get() |> deliverOnMainQueue), preferencesView |> deliverOnMainQueue) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, stickerPacks.get() |> deliverOnMainQueue, combineLatest(featured.get() |> deliverOnMainQueue, archivedPromise.get() |> deliverOnMainQueue), preferencesView |> deliverOnMainQueue) |> deliverOnMainQueue |> map { presentationData, state, view, featuredAndArchived, preferencesView -> (ItemListControllerState, (ItemListNodeState, InstalledStickerPacksEntry.ItemGenerationArguments)) in @@ -590,7 +590,7 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) controller.reorderEntry = { fromIndex, toIndex, entries in let fromEntry = entries[fromIndex] @@ -615,7 +615,7 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti afterAll = true } - let _ = (account.postbox.transaction { transaction -> Void in + let _ = (context.account.postbox.transaction { transaction -> Void in var infos = transaction.getItemCollectionsInfos(namespace: namespaceForMode(mode)) var reorderInfo: ItemCollectionInfo? for i in 0 ..< infos.count { @@ -659,14 +659,14 @@ public func installedStickerPacksController(account: Account, mode: InstalledSti } } 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)) } pushControllerImpl = { [weak controller] c in (controller?.navigationController as? NavigationController)?.pushViewController(c) } navigateToChatControllerImpl = { [weak controller] peerId in if let controller = controller, let navigationController = controller.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId)) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId)) } } dismissImpl = { [weak controller] in diff --git a/TelegramUI/InstantImageGalleryItem.swift b/TelegramUI/InstantImageGalleryItem.swift index 7cf7204fc7..d76b64894d 100644 --- a/TelegramUI/InstantImageGalleryItem.swift +++ b/TelegramUI/InstantImageGalleryItem.swift @@ -29,7 +29,7 @@ private struct InstantImageGalleryThumbnailItem: GalleryThumbnailItem { } class InstantImageGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let presentationData: PresentationData let imageReference: ImageMediaReference let caption: NSAttributedString @@ -38,8 +38,8 @@ class InstantImageGalleryItem: GalleryItem { let openUrl: (InstantPageUrlItem) -> Void let openUrlOptions: (InstantPageUrlItem) -> Void - init(account: Account, presentationData: PresentationData, imageReference: ImageMediaReference, caption: NSAttributedString, credit: NSAttributedString, location: InstantPageGalleryEntryLocation?, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlOptions: @escaping (InstantPageUrlItem) -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, imageReference: ImageMediaReference, caption: NSAttributedString, credit: NSAttributedString, location: InstantPageGalleryEntryLocation?, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlOptions: @escaping (InstantPageUrlItem) -> Void) { + self.context = context self.presentationData = presentationData self.imageReference = imageReference self.caption = caption @@ -50,7 +50,7 @@ class InstantImageGalleryItem: GalleryItem { } func node() -> GalleryItemNode { - let node = InstantImageGalleryItemNode(account: self.account, presentationData: self.presentationData, openUrl: self.openUrl, openUrlOptions: self.openUrlOptions) + let node = InstantImageGalleryItemNode(context: self.context, presentationData: self.presentationData, openUrl: self.openUrl, openUrlOptions: self.openUrlOptions) node.setImage(imageReference: self.imageReference) @@ -74,27 +74,27 @@ class InstantImageGalleryItem: GalleryItem { } func thumbnailItem() -> (Int64, GalleryThumbnailItem)? { - return (0, InstantImageGalleryThumbnailItem(account: self.account, mediaReference: imageReference.abstract)) + return (0, InstantImageGalleryThumbnailItem(account: self.context.account, mediaReference: imageReference.abstract)) } } final class InstantImageGalleryItemNode: ZoomableContentGalleryItemNode { - private let account: Account + private let context: AccountContext private let imageNode: TransformImageNode fileprivate let _ready = Promise() fileprivate let _title = Promise() private let footerContentNode: InstantPageGalleryFooterContentNode - private var accountAndMedia: (Account, AnyMediaReference)? + private var contextAndMedia: (AccountContext, AnyMediaReference)? private var fetchDisposable = MetaDisposable() - init(account: Account, presentationData: PresentationData, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlOptions: @escaping (InstantPageUrlItem) -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlOptions: @escaping (InstantPageUrlItem) -> Void) { + self.context = context self.imageNode = TransformImageNode() - self.footerContentNode = InstantPageGalleryFooterContentNode(account: account, presentationData: presentationData) + self.footerContentNode = InstantPageGalleryFooterContentNode(context: context, presentationData: presentationData) self.footerContentNode.openUrl = openUrl self.footerContentNode.openUrlOptions = openUrlOptions @@ -125,33 +125,33 @@ final class InstantImageGalleryItemNode: ZoomableContentGalleryItemNode { } fileprivate func setImage(imageReference: ImageMediaReference) { - if self.accountAndMedia == nil || !self.accountAndMedia!.1.media.isEqual(to: imageReference.media) { + if self.contextAndMedia == nil || !self.contextAndMedia!.1.media.isEqual(to: imageReference.media) { if let largestSize = largestRepresentationForPhoto(imageReference.media) { let displaySize = largestSize.dimensions.fitted(CGSize(width: 1280.0, height: 1280.0)).dividedByScreenScale().integralFloor self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: displaySize, boundingSize: displaySize, intrinsicInsets: UIEdgeInsets(), emptyColor: .black))() - self.imageNode.setSignal(chatMessagePhoto(postbox: account.postbox, photoReference: imageReference), dispatchOnDisplayLink: false) + self.imageNode.setSignal(chatMessagePhoto(postbox: self.context.account.postbox, photoReference: imageReference), dispatchOnDisplayLink: false) self.zoomableContent = (largestSize.dimensions, self.imageNode) - self.fetchDisposable.set(fetchedMediaResource(postbox: self.account.postbox, reference: imageReference.resourceReference(largestSize.resource)).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: self.context.account.postbox, reference: imageReference.resourceReference(largestSize.resource)).start()) } else { self._ready.set(.single(Void())) } } - self.accountAndMedia = (account, imageReference.abstract) + self.contextAndMedia = (self.context, imageReference.abstract) self.footerContentNode.setShareMedia(imageReference.abstract) } - func setFile(account: Account, fileReference: FileMediaReference) { - if self.accountAndMedia == nil || !self.accountAndMedia!.1.media.isEqual(to: fileReference.media) { + func setFile(context: AccountContext, fileReference: FileMediaReference) { + if self.contextAndMedia == nil || !self.contextAndMedia!.1.media.isEqual(to: fileReference.media) { if let largestSize = fileReference.media.dimensions { let displaySize = largestSize.dividedByScreenScale() self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: displaySize, boundingSize: displaySize, intrinsicInsets: UIEdgeInsets()))() - self.imageNode.setSignal(chatMessageImageFile(account: account, fileReference: fileReference, thumbnail: false), dispatchOnDisplayLink: false) + self.imageNode.setSignal(chatMessageImageFile(account: context.account, fileReference: fileReference, thumbnail: false), dispatchOnDisplayLink: false) self.zoomableContent = (largestSize, self.imageNode) } else { self._ready.set(.single(Void())) } } - self.accountAndMedia = (account, fileReference.abstract) + self.contextAndMedia = (context, fileReference.abstract) self.footerContentNode.setShareMedia(fileReference.abstract) } @@ -282,9 +282,9 @@ final class InstantImageGalleryItemNode: ZoomableContentGalleryItemNode { override func visibilityUpdated(isVisible: Bool) { super.visibilityUpdated(isVisible: isVisible) - if let (account, media) = self.accountAndMedia, let fileReference = media.concrete(TelegramMediaFile.self) { + if let (context, media) = self.contextAndMedia, let fileReference = media.concrete(TelegramMediaFile.self) { if isVisible { - self.fetchDisposable.set(fetchedMediaResource(postbox: account.postbox, reference: fileReference.resourceReference(fileReference.media.resource)).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: context.account.postbox, reference: fileReference.resourceReference(fileReference.media.resource)).start()) } else { self.fetchDisposable.set(nil) } diff --git a/TelegramUI/InstantPageController.swift b/TelegramUI/InstantPageController.swift index 1056101a1c..0b91195d64 100644 --- a/TelegramUI/InstantPageController.swift +++ b/TelegramUI/InstantPageController.swift @@ -5,7 +5,7 @@ import SwiftSignalKit import Display final class InstantPageController: ViewController { - private let account: Account + private let context: AccountContext private var webPage: TelegramMediaWebpage private let anchor: String? @@ -25,9 +25,9 @@ final class InstantPageController: ViewController { private var settings: InstantPagePresentationSettings? private var settingsDisposable: Disposable? - init(account: Account, webPage: TelegramMediaWebpage, anchor: String? = nil) { - self.account = account - self.presentationData = (account.telegramApplicationContext.currentPresentationData.with { $0 }) + init(context: AccountContext, webPage: TelegramMediaWebpage, anchor: String? = nil) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.webPage = webPage self.anchor = anchor @@ -36,7 +36,7 @@ final class InstantPageController: ViewController { self.statusBar.statusBarStyle = .White - self.webpageDisposable = (actualizedWebpage(postbox: self.account.postbox, network: self.account.network, webpage: webPage) |> deliverOnMainQueue).start(next: { [weak self] result in + self.webpageDisposable = (actualizedWebpage(postbox: self.context.account.postbox, network: self.context.account.network, webpage: webPage) |> deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { strongSelf.webPage = result if strongSelf.isNodeLoaded { @@ -45,7 +45,7 @@ final class InstantPageController: ViewController { } }) - self.settingsDisposable = (self.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.instantPagePresentationSettings]) |> deliverOnMainQueue).start(next: { [weak self] view in + self.settingsDisposable = (self.context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.instantPagePresentationSettings]) |> deliverOnMainQueue).start(next: { [weak self] view in if let strongSelf = self { let settings: InstantPagePresentationSettings if let current = view.values[ApplicationSpecificPreferencesKeys.instantPagePresentationSettings] as? InstantPagePresentationSettings { @@ -71,11 +71,11 @@ final class InstantPageController: ViewController { } override func viewWillDisappear(_ animated: Bool) { - let _ = updateInstantPageStoredStateInteractively(postbox: self.account.postbox, webPage: self.webPage, state: self.controllerNode.currentState).start() + let _ = updateInstantPageStoredStateInteractively(postbox: self.contextaccount.postbox, webPage: self.webPage, state: self.controllerNode.currentState).start() } override public func loadDisplayNode() { - self.displayNode = InstantPageControllerNode(account: self.account, settings: self.settings, presentationTheme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, statusBar: self.statusBar, getNavigationController: { [weak self] in + self.displayNode = InstantPageControllerNode(context: self.context, settings: self.settings, presentationTheme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, statusBar: self.statusBar, getNavigationController: { [weak self] in return self?.navigationController as? NavigationController }, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a) @@ -97,7 +97,7 @@ final class InstantPageController: ViewController { } }) - let _ = (instantPageStoredState(postbox: self.account.postbox, webPage: self.webPage) + let _ = (instantPageStoredState(postbox: self.context.account.postbox, webPage: self.webPage) |> deliverOnMainQueue).start(next: { [weak self] state in if let strongSelf = self { strongSelf.controllerNode.updateWebPage(strongSelf.webPage, anchor: strongSelf.anchor, state: state) diff --git a/TelegramUI/InstantPageControllerNode.swift b/TelegramUI/InstantPageControllerNode.swift index 25c9a92f15..4e67a70ae1 100644 --- a/TelegramUI/InstantPageControllerNode.swift +++ b/TelegramUI/InstantPageControllerNode.swift @@ -7,7 +7,7 @@ import Display import SafariServices final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { - private let account: Account + private let context: AccountContext private var settings: InstantPagePresentationSettings? private var presentationTheme: PresentationTheme private var strings: PresentationStrings @@ -73,8 +73,8 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { return InstantPageStoredState(contentOffset: Double(self.scrollNode.view.contentOffset.y), details: details) } - init(account: Account, settings: InstantPagePresentationSettings?, presentationTheme: PresentationTheme, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, statusBar: StatusBar, getNavigationController: @escaping () -> NavigationController?, present: @escaping (ViewController, Any?) -> Void, pushController: @escaping (ViewController) -> Void, openPeer: @escaping (PeerId) -> Void, navigateBack: @escaping () -> Void) { - self.account = account + init(context: AccountContext, settings: InstantPagePresentationSettings?, presentationTheme: PresentationTheme, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, statusBar: StatusBar, getNavigationController: @escaping () -> NavigationController?, present: @escaping (ViewController, Any?) -> Void, pushController: @escaping (ViewController) -> Void, openPeer: @escaping (PeerId) -> Void, navigateBack: @escaping () -> Void) { + self.context = context self.presentationTheme = presentationTheme self.dateTimeFormat = dateTimeFormat self.strings = strings @@ -119,7 +119,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { self.navigationBar.back = navigateBack self.navigationBar.share = { [weak self] in if let strongSelf = self, let webPage = strongSelf.webPage, case let .Loaded(content) = webPage.content { - let shareController = ShareController(account: account, subject: .url(content.url)) + let shareController = ShareController(context: context, subject: .url(content.url)) strongSelf.present(shareController, nil) } } @@ -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.account, strings: self.strings, theme: theme, openMedia: { [weak self] media in + if let newNode = item.node(account: self.context.account, strings: self.strings, theme: theme, openMedia: { [weak self] media in self?.openMedia(media) }, longPressMedia: { [weak self] media in self?.longPressMedia(media) @@ -866,16 +866,16 @@ 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(applicationContext: strongSelf.account.telegramApplicationContext, postbox: strongSelf.account.postbox, mediaReference: .standalone(media: media)).start() + let _ = copyToPasteboard(context: strongSelf.context, postbox: strongSelf.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(applicationContext: strongSelf.account.telegramApplicationContext, postbox: strongSelf.account.postbox, mediaReference: .standalone(media: media)).start() + let _ = saveToCameraRoll(context: strongSelf.context, postbox: strongSelf.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 { - strongSelf.present(ShareController(account: strongSelf.account, subject: .image(image.representations.map({ ImageRepresentationWithReference(representation: $0, reference: MediaResourceReference.media(media: .webPage(webPage: WebpageReference(webPage), media: image), resource: $0.resource)) }))), nil) + strongSelf.present(ShareController(context: strongSelf.context, subject: .image(image.representations.map({ ImageRepresentationWithReference(representation: $0, reference: MediaResourceReference.media(media: .webPage(webPage: WebpageReference(webPage), media: image), resource: $0.resource)) }))), nil) } })], catchTapsOutside: true) self.present(controller, ContextMenuControllerPresentationArguments(sourceNodeAndRect: { [weak self] in @@ -901,7 +901,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { } case .longTap: if let theme = self.theme, let url = self.urlForTapLocation(location) { - let canOpenIn = availableOpenInOptions(applicationContext: self.account.telegramApplicationContext, item: .url(url: url.url)).count > 1 + let canOpenIn = availableOpenInOptions(context: self.context, item: .url(url: url.url)).count > 1 let openText = canOpenIn ? self.strings.Conversation_FileOpenIn : self.strings.Conversation_LinkDialogOpen let actionSheet = ActionSheetController(instantPageTheme: theme) actionSheet.setItemGroups([ActionSheetItemGroup(items: [ @@ -972,7 +972,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { UIPasteboard.general.string = text }), ContextMenuAction(content: .text(self.strings.Conversation_ContextMenuShare), action: { [weak self] in if let strongSelf = self, let webPage = strongSelf.webPage, case let .Loaded(content) = webPage.content { - strongSelf.present(ShareController(account: strongSelf.account, subject: .quote(text: text, url: content.url)), nil) + strongSelf.present(ShareController(context: strongSelf.context, subject: .quote(text: text, url: content.url)), nil) } })]) controller.dismissed = { [weak self] in @@ -1023,7 +1023,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { guard let theme = self.theme, let webPage = self.webPage else { return } - let controller = InstantPageReferenceController(account: self.account, theme: theme, webPage: webPage, item: item, openUrl: { [weak self] url in + let controller = InstantPageReferenceController(context: self.context, theme: theme, webPage: webPage, item: item, openUrl: { [weak self] url in self?.openUrl(url) }, openUrlIn: { [weak self] url in self?.openUrlIn(url) @@ -1104,7 +1104,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { self.loadProgress.set(0.02) self.loadWebpageDisposable.set(nil) - self.resolveUrlDisposable.set((resolveUrl(account: self.account, url: url.url) |> deliverOnMainQueue).start(next: { [weak self] result in + self.resolveUrlDisposable.set((resolveUrl(account: self.context.account, url: url.url) |> deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { strongSelf.loadProgress.set(0.07) switch result { @@ -1114,14 +1114,14 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { if let anchorRange = externalUrl.range(of: "#") { anchor = String(externalUrl[anchorRange.upperBound...]) } - strongSelf.loadWebpageDisposable.set((webpagePreviewWithProgress(account: strongSelf.account, url: externalUrl, webpageId: webpageId) + strongSelf.loadWebpageDisposable.set((webpagePreviewWithProgress(account: strongSelf.context.account, url: externalUrl, webpageId: webpageId) |> deliverOnMainQueue).start(next: { result in if let strongSelf = self { switch result { case let .result(webpage): if let webpage = webpage, case .Loaded = webpage.content { strongSelf.loadProgress.set(1.0) - strongSelf.pushController(InstantPageController(account: strongSelf.account, webPage: webpage, anchor: anchor)) + strongSelf.pushController(InstantPageController(context: strongSelf.context, webPage: webpage, anchor: anchor)) } break case let .progress(progress): @@ -1131,27 +1131,27 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { })) } else { strongSelf.loadProgress.set(1.0) - openExternalUrl(account: strongSelf.account, url: externalUrl, presentationData: strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 }, applicationContext: strongSelf.account.telegramApplicationContext, navigationController: strongSelf.getNavigationController(), dismissInput: { + openExternalUrl(context: strongSelf.context, url: externalUrl, presentationData: context.currentPresentationData.with { $0 }, navigationController: strongSelf.getNavigationController(), dismissInput: { self?.view.endEditing(true) }) } default: strongSelf.loadProgress.set(1.0) - openResolvedUrl(result, account: strongSelf.account, navigationController: strongSelf.getNavigationController(), openPeer: { peerId, navigation in + openResolvedUrl(result, context: strongSelf.context, navigationController: strongSelf.getNavigationController(), openPeer: { peerId, navigation in switch navigation { case let .chat(_, messageId): if let navigationController = strongSelf.getNavigationController() { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(peerId), messageId: messageId) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peerId), messageId: messageId) } case let .withBotStartPayload(botStart): if let navigationController = strongSelf.getNavigationController() { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(peerId), botStart: botStart, keepStack: .always) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peerId), botStart: botStart, keepStack: .always) } case .info: - let _ = (strongSelf.account.postbox.loadedPeerWithId(peerId) + let _ = (strongSelf.context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { peer in if let strongSelf = self { - if let controller = peerInfoController(account: strongSelf.account, peer: peer) { + if let controller = peerInfoController(context: strongSelf.context, peer: peer) { strongSelf.getNavigationController()?.pushViewController(controller) } } @@ -1170,15 +1170,13 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { } private func openUrlIn(_ url: InstantPageUrlItem) { - if let applicationContext = self.account.applicationContext as? TelegramApplicationContext { - let presentationData = applicationContext.currentPresentationData.with { $0 } - let actionSheet = OpenInActionSheetController(account: self.account, item: .url(url: url.url), openUrl: { [weak self] url in - if let strongSelf = self, let navigationController = strongSelf.getNavigationController() { - openExternalUrl(account: strongSelf.account, url: url, forceExternal: true, presentationData: presentationData, applicationContext: applicationContext, navigationController: navigationController, dismissInput: {}) - } - }) - self.present(actionSheet, nil) - } + let presentationData = self.context.currentPresentationData.with { $0 } + let actionSheet = OpenInActionSheetController(context: self.context, item: .url(url: url.url), openUrl: { [weak self] url in + if let strongSelf = self, let navigationController = strongSelf.getNavigationController() { + openExternalUrl(context: strongSelf.context, url: url, forceExternal: true, presentationData: presentationData, navigationController: navigationController, dismissInput: {}) + } + }) + self.present(actionSheet, nil) } private func mediasFromItems(_ items: [InstantPageItem]) -> [InstantPageMedia] { @@ -1199,7 +1197,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { } if let map = media.media as? TelegramMediaMap { - let controller = legacyLocationController(message: nil, mapMedia: map, account: self.account, isModal: false, openPeer: { _ in }, sendLiveLocation: { _, _ in }, stopLiveLocation: { }, openUrl: { _ in }) + let controller = legacyLocationController(message: nil, mapMedia: map, context: self.context, isModal: false, openPeer: { _ in }, sendLiveLocation: { _, _ in }, stopLiveLocation: { }, openUrl: { _ in }) self.pushController(controller) return } @@ -1217,7 +1215,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { } } } - self.account.telegramApplicationContext.mediaManager?.setPlaylist(InstantPageMediaPlaylist(webPage: webPage, items: medias, initialItemIndex: initialIndex), type: file.isVoice ? .voice : .music) + self.context.mediaManager.setPlaylist(InstantPageMediaPlaylist(webPage: webPage, items: medias, initialItemIndex: initialIndex), type: file.isVoice ? .voice : .music) return } @@ -1246,7 +1244,7 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { } if let centralIndex = centralIndex { - let controller = InstantPageGalleryController(account: self.account, webPage: webPage, entries: entries, centralIndex: centralIndex, replaceRootController: { _, _ in + let controller = InstantPageGalleryController(context: self.context, webPage: webPage, entries: entries, centralIndex: centralIndex, replaceRootController: { _, _ in }, baseNavigationController: self.getNavigationController()) self.hiddenMediaDisposable.set((controller.hiddenMedia |> deliverOnMainQueue).start(next: { [weak self] entry in if let strongSelf = self { @@ -1309,13 +1307,13 @@ final class InstantPageControllerNode: ASDisplayNode, UIScrollViewDelegate { let settingsNode = InstantPageSettingsNode(strings: self.strings, settings: settings, currentThemeType: instantPageThemeTypeForSettingsAndTime(presentationTheme: self.presentationTheme, settings: settings, time: self.themeReferenceDate), applySettings: { [weak self] settings in if let strongSelf = self { strongSelf.update(settings: settings, strings: strongSelf.strings) - let _ = updateInstantPagePresentationSettingsInteractively(postbox: strongSelf.account.postbox, { _ in + let _ = updateInstantPagePresentationSettingsInteractively(postbox: strongSelf.context.account.postbox, { _ in return settings }).start() } }, openInSafari: { [weak self] in if let strongSelf = self, let webPage = strongSelf.webPage, case let .Loaded(content) = webPage.content { - strongSelf.account.telegramApplicationContext.applicationBindings.openUrl(content.url) + strongSelf.context.applicationBindings.openUrl(content.url) } }) self.addSubnode(settingsNode) diff --git a/TelegramUI/InstantPageGalleryController.swift b/TelegramUI/InstantPageGalleryController.swift index 57c646e03c..ea201316bd 100644 --- a/TelegramUI/InstantPageGalleryController.swift +++ b/TelegramUI/InstantPageGalleryController.swift @@ -28,7 +28,7 @@ struct InstantPageGalleryEntry: Equatable { return lhs.index == rhs.index && lhs.pageId == rhs.pageId && lhs.media == rhs.media && lhs.caption == rhs.caption && lhs.credit == rhs.credit && lhs.location == rhs.location } - func item(account: Account, webPage: TelegramMediaWebpage, presentationData: PresentationData, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlOptions: @escaping (InstantPageUrlItem) -> Void) -> GalleryItem { + func item(context: AccountContext, webPage: TelegramMediaWebpage, presentationData: PresentationData, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlOptions: @escaping (InstantPageUrlItem) -> Void) -> GalleryItem { let caption: NSAttributedString let credit: NSAttributedString @@ -71,16 +71,16 @@ struct InstantPageGalleryEntry: Equatable { } if let image = self.media.media as? TelegramMediaImage { - return InstantImageGalleryItem(account: account, presentationData: presentationData, imageReference: .webPage(webPage: WebpageReference(webPage), media: image), caption: caption, credit: credit, location: self.location, openUrl: openUrl, openUrlOptions: openUrlOptions) + return InstantImageGalleryItem(context: context, presentationData: presentationData, imageReference: .webPage(webPage: WebpageReference(webPage), media: image), caption: caption, credit: credit, location: self.location, openUrl: openUrl, openUrlOptions: openUrlOptions) } else if let file = self.media.media as? TelegramMediaFile, file.isVideo { var indexData: GalleryItemIndexData? if let location = self.location { indexData = GalleryItemIndexData(position: location.position, totalCount: location.totalCount) } - return UniversalVideoGalleryItem(account: account, presentationData: presentationData, content: NativeVideoContent(id: .instantPage(self.pageId, file.fileId), fileReference: .webPage(webPage: WebpageReference(webPage), media: file)), originData: nil, indexData: indexData, contentInfo: .webPage(webPage, file), caption: caption, credit: credit, performAction: { _ in }, openActionOptions: { _ in }) + return UniversalVideoGalleryItem(context: context, presentationData: presentationData, content: NativeVideoContent(id: .instantPage(self.pageId, file.fileId), fileReference: .webPage(webPage: WebpageReference(webPage), media: file)), originData: nil, indexData: indexData, contentInfo: .webPage(webPage, file), caption: caption, credit: credit, performAction: { _ in }, openActionOptions: { _ in }) } else if let embedWebpage = self.media.media as? TelegramMediaWebpage, case let .Loaded(webpageContent) = embedWebpage.content { if let content = WebEmbedVideoContent(webPage: embedWebpage, webpageContent: webpageContent) { - return UniversalVideoGalleryItem(account: account, presentationData: presentationData, content: content, originData: nil, indexData: nil, contentInfo: .webPage(webPage, embedWebpage), caption: NSAttributedString(string: ""), performAction: { _ in }, openActionOptions: { _ in }) + return UniversalVideoGalleryItem(context: context, presentationData: presentationData, content: content, originData: nil, indexData: nil, contentInfo: .webPage(webPage, embedWebpage), caption: NSAttributedString(string: ""), performAction: { _ in }, openActionOptions: { _ in }) } else { preconditionFailure() } @@ -103,7 +103,7 @@ class InstantPageGalleryController: ViewController { return self.displayNode as! GalleryControllerNode } - private let account: Account + private let context: AccountContext private let webPage: TelegramMediaWebpage private var presentationData: PresentationData @@ -136,13 +136,13 @@ class InstantPageGalleryController: ViewController { private var innerOpenUrl: (InstantPageUrlItem) -> Void private var openUrlOptions: (InstantPageUrlItem) -> Void - init(account: Account, webPage: TelegramMediaWebpage, entries: [InstantPageGalleryEntry], centralIndex: Int, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void, baseNavigationController: NavigationController?) { - self.account = account + init(context: AccountContext, webPage: TelegramMediaWebpage, entries: [InstantPageGalleryEntry], centralIndex: Int, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void, baseNavigationController: NavigationController?) { + self.context = context self.webPage = webPage self.replaceRootController = replaceRootController self.baseNavigationController = baseNavigationController - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } var openLinkImpl: ((InstantPageUrlItem) -> Void)? self.innerOpenUrl = { url in @@ -168,7 +168,7 @@ class InstantPageGalleryController: ViewController { strongSelf.centralEntryIndex = centralIndex if strongSelf.isViewLoaded { strongSelf.galleryNode.pager.replaceItems(strongSelf.entries.map({ - $0.item(account: account, webPage: webPage, presentationData: strongSelf.presentationData, openUrl: strongSelf.innerOpenUrl, openUrlOptions: strongSelf.openUrlOptions) + $0.item(context: context, webPage: webPage, presentationData: strongSelf.presentationData, openUrl: strongSelf.innerOpenUrl, openUrlOptions: strongSelf.openUrlOptions) }), centralItemIndex: centralIndex, keepFirst: false) let ready = strongSelf.galleryNode.pager.ready() |> timeout(2.0, queue: Queue.mainQueue(), alternate: .single(Void())) |> afterNext { [weak strongSelf] _ in @@ -202,7 +202,7 @@ class InstantPageGalleryController: ViewController { openLinkOptionsImpl = { [weak self] url in if let strongSelf = self { - let canOpenIn = availableOpenInOptions(applicationContext: account.telegramApplicationContext, item: .url(url: url.url)).count > 1 + let canOpenIn = availableOpenInOptions(context: context, item: .url(url: url.url)).count > 1 let openText = canOpenIn ? strongSelf.presentationData.strings.Conversation_FileOpenIn : strongSelf.presentationData.strings.Conversation_LinkDialogOpen let actionSheet = ActionSheetController(presentationTheme: strongSelf.presentationData.theme) actionSheet.setItemGroups([ActionSheetItemGroup(items: [ @@ -307,7 +307,7 @@ class InstantPageGalleryController: ViewController { } self.galleryNode.pager.replaceItems(self.entries.map({ - $0.item(account: account, webPage: self.webPage, presentationData: self.presentationData, openUrl: self.innerOpenUrl, openUrlOptions: self.openUrlOptions) + $0.item(context: self.context, webPage: self.webPage, presentationData: self.presentationData, openUrl: self.innerOpenUrl, openUrlOptions: self.openUrlOptions) }), centralItemIndex: self.centralEntryIndex) self.galleryNode.pager.centralItemIndexUpdated = { [weak self] index in diff --git a/TelegramUI/InstantPageGalleryFooterContentNode.swift b/TelegramUI/InstantPageGalleryFooterContentNode.swift index b904ac9cf0..2638ddf25b 100644 --- a/TelegramUI/InstantPageGalleryFooterContentNode.swift +++ b/TelegramUI/InstantPageGalleryFooterContentNode.swift @@ -11,7 +11,7 @@ private let actionImage = generateTintedImage(image: UIImage(bundleImageName: "C private let textFont = Font.regular(16.0) final class InstantPageGalleryFooterContentNode: GalleryFooterContentNode { - private let account: Account + private let context: AccountContext private var theme: PresentationTheme private var strings: PresentationStrings private var shareMedia: AnyMediaReference? @@ -24,8 +24,8 @@ final class InstantPageGalleryFooterContentNode: GalleryFooterContentNode { var openUrl: ((InstantPageUrlItem) -> Void)? var openUrlOptions: ((InstantPageUrlItem) -> Void)? - init(account: Account, presentationData: PresentationData) { - self.account = account + init(context: AccountContext, presentationData: PresentationData) { + self.context = context self.theme = presentationData.theme self.strings = presentationData.strings @@ -139,7 +139,7 @@ final class InstantPageGalleryFooterContentNode: GalleryFooterContentNode { @objc func actionButtonPressed() { if let shareMedia = self.shareMedia { - self.controllerInteraction?.presentController(ShareController(account: self.account, subject: .media(shareMedia), preferredAction: .saveToCameraRoll, showInChat: nil, externalShare: true, immediateExternalShare: false), nil) + self.controllerInteraction?.presentController(ShareController(context: self.context, subject: .media(shareMedia), preferredAction: .saveToCameraRoll, showInChat: nil, externalShare: true, immediateExternalShare: false), nil) } } } diff --git a/TelegramUI/InstantPagePlayableVideoNode.swift b/TelegramUI/InstantPagePlayableVideoNode.swift index 9e757578d2..58248b5d1f 100644 --- a/TelegramUI/InstantPagePlayableVideoNode.swift +++ b/TelegramUI/InstantPagePlayableVideoNode.swift @@ -31,7 +31,7 @@ final class InstantPagePlayableVideoNode: ASDisplayNode, InstantPageNode { imageReference = ImageMediaReference.webPage(webPage: WebpageReference(webPage), media: image) } - self.videoNode = UniversalVideoNode(postbox: account.postbox, audioSession: account.telegramApplicationContext.mediaManager!.audioSession, manager: account.telegramApplicationContext.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 = 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.isUserInteractionEnabled = false super.init() diff --git a/TelegramUI/InstantPageReferenceController.swift b/TelegramUI/InstantPageReferenceController.swift index 010fe0776e..a12b0421ac 100644 --- a/TelegramUI/InstantPageReferenceController.swift +++ b/TelegramUI/InstantPageReferenceController.swift @@ -12,7 +12,7 @@ final class InstantPageReferenceController: ViewController { private var animatedIn = false - private let account: Account + private let context: AccountContext private let theme: InstantPageTheme private let webPage: TelegramMediaWebpage private let item: InstantPageTextItem @@ -20,8 +20,8 @@ final class InstantPageReferenceController: ViewController { private let openUrlIn: (InstantPageUrlItem) -> Void private let present: (ViewController, Any?) -> Void - init(account: Account, theme: InstantPageTheme, webPage: TelegramMediaWebpage, item: InstantPageTextItem, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlIn: @escaping (InstantPageUrlItem) -> Void, present: @escaping (ViewController, Any?) -> Void) { - self.account = account + init(context: AccountContext, theme: InstantPageTheme, webPage: TelegramMediaWebpage, item: InstantPageTextItem, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlIn: @escaping (InstantPageUrlItem) -> Void, present: @escaping (ViewController, Any?) -> Void) { + self.context = context self.theme = theme self.webPage = webPage self.item = item @@ -39,7 +39,7 @@ final class InstantPageReferenceController: ViewController { } override public func loadDisplayNode() { - self.displayNode = InstantPageReferenceControllerNode(account: self.account, theme: self.theme, webPage: self.webPage, item: self.item, openUrl: self.openUrl, openUrlIn: self.openUrlIn, present: self.present) + self.displayNode = InstantPageReferenceControllerNode(context: self.context, theme: self.theme, webPage: self.webPage, item: self.item, openUrl: self.openUrl, openUrlIn: self.openUrlIn, present: self.present) self.controllerNode.dismiss = { [weak self] in self?.presentingViewController?.dismiss(animated: false, completion: nil) } diff --git a/TelegramUI/InstantPageReferenceControllerNode.swift b/TelegramUI/InstantPageReferenceControllerNode.swift index cf1a828565..d2c9e13a94 100644 --- a/TelegramUI/InstantPageReferenceControllerNode.swift +++ b/TelegramUI/InstantPageReferenceControllerNode.swift @@ -6,7 +6,7 @@ import TelegramCore import SafariServices class InstantPageReferenceControllerNode: ViewControllerTracingNode, UIScrollViewDelegate { - private let account: Account + private let context: AccountContext private let theme: InstantPageTheme private var presentationData: PresentationData private let webPage: TelegramMediaWebpage @@ -32,9 +32,9 @@ class InstantPageReferenceControllerNode: ViewControllerTracingNode, UIScrollVie var dismiss: (() -> Void)? var close: (() -> Void)? - init(account: Account, theme: InstantPageTheme, webPage: TelegramMediaWebpage, item: InstantPageTextItem, openUrl: @escaping (InstantPageUrlItem) -> Void, openUrlIn: @escaping (InstantPageUrlItem) -> Void, present: @escaping (ViewController, Any?) -> 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.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.theme = theme self.webPage = webPage self.item = item @@ -196,7 +196,7 @@ class InstantPageReferenceControllerNode: ViewControllerTracingNode, UIScrollVie let sideInset: CGFloat = 16.0 let (_, items, contentSize) = layoutTextItemWithString(self.item.attributedString, boundingWidth: width - sideInset * 2.0, offset: CGPoint(x: sideInset, y: sideInset), media: media, webpage: self.webPage) - let contentNode = InstantPageContentNode(account: self.account, strings: self.presentationData.strings, theme: self.theme, items: items, contentSize: CGSize(width: width, height: contentSize.height), inOverlayPanel: true, openMedia: { _ in }, longPressMedia: { _ in }, openPeer: { _ in }, openUrl: { _ in }) + let contentNode = InstantPageContentNode(context: self.context, strings: self.presentationData.strings, theme: self.theme, items: items, contentSize: CGSize(width: width, height: contentSize.height), inOverlayPanel: true, openMedia: { _ in }, longPressMedia: { _ in }, openPeer: { _ in }, openUrl: { _ in }) transition.updateFrame(node: contentNode, frame: CGRect(origin: CGPoint(x: 0.0, y: titleAreaHeight), size: CGSize(width: width, height: contentSize.height))) self.contentContainerNode.insertSubnode(contentNode, at: 0) self.contentNode = contentNode @@ -335,7 +335,7 @@ class InstantPageReferenceControllerNode: ViewControllerTracingNode, UIScrollVie } case .longTap: if let url = self.urlForTapLocation(location) { - let canOpenIn = availableOpenInOptions(applicationContext: self.account.telegramApplicationContext, item: .url(url: url.url)).count > 1 + let canOpenIn = availableOpenInOptions(context: self.context, item: .url(url: url.url)).count > 1 let openText = canOpenIn ? self.presentationData.strings.Conversation_FileOpenIn : self.presentationData.strings.Conversation_LinkDialogOpen let actionSheet = ActionSheetController(instantPageTheme: self.theme) actionSheet.setItemGroups([ActionSheetItemGroup(items: [ @@ -407,7 +407,7 @@ class InstantPageReferenceControllerNode: ViewControllerTracingNode, UIScrollVie UIPasteboard.general.string = text }), ContextMenuAction(content: .text(self.presentationData.strings.Conversation_ContextMenuShare), action: { [weak self] in if let strongSelf = self, case let .Loaded(content) = strongSelf.webPage.content { - strongSelf.present(ShareController(account: strongSelf.account, subject: .quote(text: text, url: content.url)), nil) + strongSelf.present(ShareController(context: strongSelf.context, subject: .quote(text: text, url: content.url)), nil) } })]) controller.dismissed = { [weak self] in diff --git a/TelegramUI/InviteContactsController.swift b/TelegramUI/InviteContactsController.swift index fb7c7cdb4e..1bc46cd38f 100644 --- a/TelegramUI/InviteContactsController.swift +++ b/TelegramUI/InviteContactsController.swift @@ -7,7 +7,7 @@ import TelegramCore import MessageUI public class InviteContactsController: ViewController, MFMessageComposeViewControllerDelegate, UINavigationControllerDelegate { - private let account: Account + private let context: AccountContext private var contactsNode: InviteContactsControllerNode { return self.displayNode as! InviteContactsControllerNode @@ -25,10 +25,10 @@ public class InviteContactsController: ViewController, MFMessageComposeViewContr private var searchContentNode: NavigationBarSearchContentNode? - public init(account: Account) { - self.account = account + public init(context: AccountContext) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -48,7 +48,7 @@ public class InviteContactsController: ViewController, MFMessageComposeViewContr } } - 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 @@ -103,7 +103,7 @@ public class InviteContactsController: ViewController, MFMessageComposeViewContr let url = strongSelf.presentationData.strings.InviteText_URL let body = strongSelf.presentationData.strings.InviteText_SingleContact(url).0 - let shareController = ShareController(account: strongSelf.account, subject: .text(body), externalShare: true, immediateExternalShare: true) + let shareController = ShareController(context: strongSelf.context, subject: .text(body), externalShare: true, immediateExternalShare: true) strongSelf.present(shareController, in: .window(.root)) } } diff --git a/TelegramUI/InviteContactsControllerNode.swift b/TelegramUI/InviteContactsControllerNode.swift index 0ee3e93929..f06ae300c2 100644 --- a/TelegramUI/InviteContactsControllerNode.swift +++ b/TelegramUI/InviteContactsControllerNode.swift @@ -229,7 +229,7 @@ private struct InviteContactsTransition { final class InviteContactsControllerNode: ASDisplayNode { let listNode: ListView - private let account: Account + private let context: AccountContext private var searchDisplayController: SearchDisplayController? private var validLayout: (ContainerViewLayout, CGFloat, CGFloat)? @@ -283,10 +283,10 @@ final class InviteContactsControllerNode: ASDisplayNode { private let currentContactIds = Atomic<[String]>(value: []) - init(account: Account) { - self.account = account + init(context: AccountContext) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.themeAndStringsPromise = Promise((self.presentationData.theme, self.presentationData.strings, self.presentationData.nameSortOrder, self.presentationData.nameDisplayOrder)) @@ -308,7 +308,7 @@ final class InviteContactsControllerNode: ASDisplayNode { self.addSubnode(self.listNode) self.addSubnode(self.countPanelNode) - 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 @@ -350,7 +350,7 @@ final class InviteContactsControllerNode: ASDisplayNode { } let currentSortedContacts = self.currentSortedContacts - let sortedContacts: Signal<[(DeviceContactStableId, DeviceContactBasicData, Int32)], NoError> = combineLatest(existingNumbers, account.telegramApplicationContext.contactDataManager.basicData() |> take(1)) + let sortedContacts: Signal<[(DeviceContactStableId, DeviceContactBasicData, Int32)], NoError> = combineLatest(existingNumbers, context.contactDataManager.basicData() |> take(1)) |> mapToSignal { existingNumbers, contacts -> Signal<[(DeviceContactStableId, DeviceContactBasicData, Int32)], NoError> in var mappedContacts: [(String, [DeviceContactNormalizedPhoneNumber])] = [] for (id, basicData) in contacts { @@ -358,7 +358,7 @@ final class InviteContactsControllerNode: ASDisplayNode { return DeviceContactNormalizedPhoneNumber(rawValue: formatPhoneNumber(phoneNumber.value)) }))) } - return deviceContactsImportedByCount(postbox: account.postbox, contacts: mappedContacts) + return deviceContactsImportedByCount(postbox: context.account.postbox, contacts: mappedContacts) |> map { counts -> [(DeviceContactStableId, DeviceContactBasicData, Int32)] in var result: [(DeviceContactStableId, DeviceContactBasicData, Int32)] = [] var contactValues: [DeviceContactStableId: DeviceContactBasicData] = [:] @@ -409,7 +409,7 @@ final class InviteContactsControllerNode: ASDisplayNode { } else { animated = false } - return .single(preparedInviteContactsTransition(account: account, from: previous ?? [], to: entries, sortedContats: sortedContacts, interaction: interaction, firstTime: previous == nil, animated: animated)) + return .single(preparedInviteContactsTransition(account: context.account, from: previous ?? [], to: entries, sortedContats: sortedContacts, interaction: interaction, firstTime: previous == nil, animated: animated)) } if OSAtomicCompareAndSwap32(1, 0, &firstTime) { @@ -519,7 +519,7 @@ final class InviteContactsControllerNode: ASDisplayNode { return } - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(account: self.account, onlyWriteable: false, categories: [.deviceContacts], openPeer: { _ in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(context: self.context, onlyWriteable: false, categories: [.deviceContacts], openPeer: { _ in }), cancel: { [weak self] in if let requestDeactivateSearch = self?.requestDeactivateSearch { requestDeactivateSearch() diff --git a/TelegramUI/ItemListAvatarAndNameItem.swift b/TelegramUI/ItemListAvatarAndNameItem.swift index 58aa5ae325..e983b14d4e 100644 --- a/TelegramUI/ItemListAvatarAndNameItem.swift +++ b/TelegramUI/ItemListAvatarAndNameItem.swift @@ -637,7 +637,7 @@ class ItemListAvatarAndNameInfoItemNode: ListViewItemNode, ItemListItemNode, Ite overrideImage = AvatarNodeImageOverride.editAvatarIcon } - strongSelf.avatarNode.setPeer(account: item.account, peer: peer, overrideImage: overrideImage, emptyColor: ignoreEmpty ? nil : item.theme.list.mediaPlaceholderColor, synchronousLoad: synchronousLoads) + strongSelf.avatarNode.setPeer(account: item.account, theme: item.theme, peer: peer, overrideImage: overrideImage, emptyColor: ignoreEmpty ? nil : item.theme.list.mediaPlaceholderColor, synchronousLoad: synchronousLoads) } let avatarFrame = CGRect(origin: CGPoint(x: params.leftInset + 15.0, y: avatarOriginY), size: CGSize(width: 66.0, height: 66.0)) diff --git a/TelegramUI/ItemListController.swift b/TelegramUI/ItemListController.swift index 3e39fa5a99..edd5dfd980 100644 --- a/TelegramUI/ItemListController.swift +++ b/TelegramUI/ItemListController.swift @@ -197,9 +197,9 @@ class ItemListController: ViewController { var willDisappear: ((Bool) -> Void)? - convenience init(account: Account, state: Signal<(ItemListControllerState, (ItemListNodeState, Entry.ItemGenerationArguments)), NoError>, tabBarItem: Signal? = nil) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - self.init(theme: presentationData.theme, strings: presentationData.strings, updatedPresentationData: account.telegramApplicationContext.presentationData |> map { ($0.theme, $0.strings) }, state: state, tabBarItem: tabBarItem) + convenience init(context: AccountContext, state: Signal<(ItemListControllerState, (ItemListNodeState, Entry.ItemGenerationArguments)), NoError>, tabBarItem: Signal? = nil) { + let presentationData = context.currentPresentationData.with { $0 } + self.init(theme: presentationData.theme, strings: presentationData.strings, updatedPresentationData: context.presentationData |> map { ($0.theme, $0.strings) }, state: state, tabBarItem: tabBarItem) } init(theme: PresentationTheme, strings: PresentationStrings, updatedPresentationData: Signal<(theme: PresentationTheme, strings: PresentationStrings), NoError>, state: Signal<(ItemListControllerState, (ItemListNodeState, Entry.ItemGenerationArguments)), NoError>, tabBarItem: Signal?) { diff --git a/TelegramUI/ItemListPeerItem.swift b/TelegramUI/ItemListPeerItem.swift index 262c842444..a9f38e393e 100644 --- a/TelegramUI/ItemListPeerItem.swift +++ b/TelegramUI/ItemListPeerItem.swift @@ -664,7 +664,7 @@ class ItemListPeerItemNode: ItemListRevealOptionsItemNode { transition.updateFrame(node: strongSelf.avatarNode, frame: CGRect(origin: CGPoint(x: params.leftInset + revealOffset + editingOffset + 15.0, y: 5.0), size: CGSize(width: 40.0, height: 40.0))) if item.peer.id == item.account.peerId, case .threatSelfAsSaved = item.aliasHandling { - strongSelf.avatarNode.setPeer(account: item.account, peer: item.peer, overrideImage: .savedMessagesIcon, emptyColor: item.theme.list.mediaPlaceholderColor) + strongSelf.avatarNode.setPeer(account: item.account, theme: item.theme, peer: item.peer, overrideImage: .savedMessagesIcon, emptyColor: item.theme.list.mediaPlaceholderColor) } else { strongSelf.avatarNode.setPeer(account: item.account, theme: item.theme, peer: item.peer, emptyColor: item.theme.list.mediaPlaceholderColor) } diff --git a/TelegramUI/JoinLinkPreviewController.swift b/TelegramUI/JoinLinkPreviewController.swift index 0945d56b16..c66c81a068 100644 --- a/TelegramUI/JoinLinkPreviewController.swift +++ b/TelegramUI/JoinLinkPreviewController.swift @@ -12,19 +12,19 @@ public final class JoinLinkPreviewController: ViewController { private var animatedIn = false - private let account: Account + private let context: AccountContext private let link: String private let navigateToPeer: (PeerId) -> Void private var presentationData: PresentationData private let disposable = MetaDisposable() - public init(account: Account, link: String, navigateToPeer: @escaping (PeerId) -> Void) { - self.account = account + public init(context: AccountContext, link: String, navigateToPeer: @escaping (PeerId) -> Void) { + self.context = context self.link = link self.navigateToPeer = navigateToPeer - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: nil) } @@ -38,7 +38,7 @@ public final class JoinLinkPreviewController: ViewController { } override public func loadDisplayNode() { - self.displayNode = JoinLinkPreviewControllerNode(account: self.account, requestLayout: { [weak self] transition in + self.displayNode = JoinLinkPreviewControllerNode(context: self.context, requestLayout: { [weak self] transition in self?.requestLayout(transition: transition) }) self.controllerNode.dismiss = { [weak self] in @@ -51,7 +51,7 @@ public final class JoinLinkPreviewController: ViewController { self?.join() } self.displayNodeDidLoad() - self.disposable.set((joinLinkInformation(self.link, account: self.account) + self.disposable.set((joinLinkInformation(self.link, account: self.context.account) |> deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { switch result { @@ -96,7 +96,7 @@ public final class JoinLinkPreviewController: ViewController { } private func join() { - self.disposable.set((joinChatInteractively(with: self.link, account: self.account) |> deliverOnMainQueue).start(next: { [weak self] peerId in + self.disposable.set((joinChatInteractively(with: self.link, account: self.context.account) |> deliverOnMainQueue).start(next: { [weak self] peerId in if let strongSelf = self { if let peerId = peerId { strongSelf.navigateToPeer(peerId) diff --git a/TelegramUI/JoinLinkPreviewControllerNode.swift b/TelegramUI/JoinLinkPreviewControllerNode.swift index ce13ffbd96..6b69dc9bdd 100644 --- a/TelegramUI/JoinLinkPreviewControllerNode.swift +++ b/TelegramUI/JoinLinkPreviewControllerNode.swift @@ -11,7 +11,7 @@ struct JoinLinkPreviewData { } final class JoinLinkPreviewControllerNode: ViewControllerTracingNode, UIScrollViewDelegate { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let requestLayout: (ContainedViewLayoutTransition) -> Void @@ -46,9 +46,9 @@ final class JoinLinkPreviewControllerNode: ViewControllerTracingNode, UIScrollVi private let disposable = MetaDisposable() - init(account: Account, requestLayout: @escaping (ContainedViewLayoutTransition) -> Void) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, requestLayout: @escaping (ContainedViewLayoutTransition) -> Void) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.requestLayout = requestLayout @@ -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.account, image: image, title: title, memberCount: memberCount, members: members, theme: self.presentationData.theme, strings: self.presentationData.strings)) + self.transitionToContentNode(JoinLinkPreviewPeerContentNode(account: self.context.account, image: image, title: title, memberCount: memberCount, members: members, theme: self.presentationData.theme, strings: self.presentationData.strings)) } } diff --git a/TelegramUI/JoinLinkPreviewPeerContentNode.swift b/TelegramUI/JoinLinkPreviewPeerContentNode.swift index 6682ccdf80..aa1aabe441 100644 --- a/TelegramUI/JoinLinkPreviewPeerContentNode.swift +++ b/TelegramUI/JoinLinkPreviewPeerContentNode.swift @@ -32,7 +32,7 @@ final class JoinLinkPreviewPeerContentNode: ASDisplayNode, ShareContentContainer private let peerNodes: [SelectablePeerNode] private let moreNode: MoreNode? - init(account: Account, image: TelegramMediaImageRepresentation?, title: String, memberCount: Int32, members: [Peer], theme: PresentationTheme, strings: PresentationStrings) { + init(context: AccountContext, image: TelegramMediaImageRepresentation?, title: String, memberCount: Int32, members: [Peer], theme: PresentationTheme, strings: PresentationStrings) { self.avatarNode = AvatarNode(font: avatarFont) self.titleNode = ASTextNode() self.countNode = ASTextNode() @@ -43,7 +43,7 @@ final class JoinLinkPreviewPeerContentNode: ASDisplayNode, ShareContentContainer self.peerNodes = members.map { peer in let node = SelectablePeerNode() - node.setup(account: account, strings: strings, peer: RenderedPeer(peer: peer), synchronousLoad: false) + node.setup(account: context.account, theme: theme, strings: strings, peer: RenderedPeer(peer: peer), synchronousLoad: false) node.theme = itemTheme return node } @@ -59,7 +59,7 @@ final class JoinLinkPreviewPeerContentNode: ASDisplayNode, ShareContentContainer let peer = TelegramGroup(id: PeerId(namespace: 0, id: 0), title: title, photo: image.flatMap { [$0] } ?? [], participantCount: Int(memberCount), role: .member, membership: .Left, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) self.addSubnode(self.avatarNode) - self.avatarNode.setPeer(account: account, peer: peer, emptyColor: theme.list.mediaPlaceholderColor) + self.avatarNode.setPeer(account: context.account, theme: theme, peer: peer, emptyColor: theme.list.mediaPlaceholderColor) self.addSubnode(self.titleNode) self.titleNode.attributedText = NSAttributedString(string: title, font: Font.semibold(16.0), textColor: theme.actionSheet.primaryTextColor) diff --git a/TelegramUI/LanguageLinkPreviewContentNode.swift b/TelegramUI/LanguageLinkPreviewContentNode.swift index 42b746b465..f7f736119b 100644 --- a/TelegramUI/LanguageLinkPreviewContentNode.swift +++ b/TelegramUI/LanguageLinkPreviewContentNode.swift @@ -10,7 +10,7 @@ final class LanguageLinkPreviewContentNode: ASDisplayNode, ShareContentContainer private let titleNode: ImmediateTextNode private let textNode: ImmediateTextNode - init(account: Account, localizationInfo: LocalizationInfo, theme: PresentationTheme, strings: PresentationStrings, openTranslationUrl: @escaping (String) -> Void) { + init(context: AccountContext, localizationInfo: LocalizationInfo, theme: PresentationTheme, strings: PresentationStrings, openTranslationUrl: @escaping (String) -> Void) { self.titleNode = ImmediateTextNode() self.titleNode.textAlignment = .center diff --git a/TelegramUI/LanguageLinkPreviewController.swift b/TelegramUI/LanguageLinkPreviewController.swift index aa093214fa..439354652d 100644 --- a/TelegramUI/LanguageLinkPreviewController.swift +++ b/TelegramUI/LanguageLinkPreviewController.swift @@ -12,18 +12,18 @@ public final class LanguageLinkPreviewController: ViewController { private var animatedIn = false - private let account: Account + private let context: AccountContext private let identifier: String private var localizationInfo: LocalizationInfo? private var presentationData: PresentationData private let disposable = MetaDisposable() - public init(account: Account, identifier: String) { - self.account = account + public init(context: AccountContext, identifier: String) { + self.context = context self.identifier = identifier - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: nil) } @@ -37,13 +37,13 @@ public final class LanguageLinkPreviewController: ViewController { } override public func loadDisplayNode() { - self.displayNode = LanguageLinkPreviewControllerNode(account: self.account, requestLayout: { [weak self] transition in + self.displayNode = LanguageLinkPreviewControllerNode(context: self.context, requestLayout: { [weak self] transition in self?.requestLayout(transition: transition) }, openUrl: { [weak self] url in guard let strongSelf = self else { return } - openExternalUrl(account: strongSelf.account, url: url, presentationData: strongSelf.presentationData, applicationContext: strongSelf.account.telegramApplicationContext, navigationController: nil, dismissInput: { + openExternalUrl(context: strongSelf.context, url: url, presentationData: strongSelf.presentationData, navigationController: nil, dismissInput: { }) }) self.controllerNode.dismiss = { [weak self] in @@ -57,7 +57,7 @@ public final class LanguageLinkPreviewController: ViewController { } self.displayNodeDidLoad() - self.disposable.set((requestLocalizationPreview(network: self.account.network, identifier: self.identifier) + self.disposable.set((requestLocalizationPreview(network: self.context.account.network, identifier: self.identifier) |> deliverOnMainQueue).start(next: { [weak self] result in guard let strongSelf = self else { return @@ -109,7 +109,7 @@ public final class LanguageLinkPreviewController: ViewController { return } self.controllerNode.setInProgress(true) - self.disposable.set((downloadAndApplyLocalization(postbox: self.account.postbox, network: self.account.network, languageCode: localizationInfo.languageCode) + self.disposable.set((downloadAndApplyLocalization(postbox: self.context.account.postbox, network: self.context.account.network, languageCode: localizationInfo.languageCode) |> deliverOnMainQueue).start(error: { [weak self] _ in guard let strongSelf = self else { return diff --git a/TelegramUI/LanguageLinkPreviewControllerNode.swift b/TelegramUI/LanguageLinkPreviewControllerNode.swift index c2bda95ebb..33d5a4916b 100644 --- a/TelegramUI/LanguageLinkPreviewControllerNode.swift +++ b/TelegramUI/LanguageLinkPreviewControllerNode.swift @@ -6,7 +6,7 @@ import Postbox import TelegramCore final class LanguageLinkPreviewControllerNode: ViewControllerTracingNode, UIScrollViewDelegate { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let requestLayout: (ContainedViewLayoutTransition) -> Void @@ -43,9 +43,9 @@ final class LanguageLinkPreviewControllerNode: ViewControllerTracingNode, UIScro private let disposable = MetaDisposable() - init(account: Account, requestLayout: @escaping (ContainedViewLayoutTransition) -> Void, openUrl: @escaping (String) -> Void) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, requestLayout: @escaping (ContainedViewLayoutTransition) -> Void, openUrl: @escaping (String) -> Void) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.requestLayout = requestLayout self.openUrl = openUrl @@ -463,7 +463,7 @@ final class LanguageLinkPreviewControllerNode: ViewControllerTracingNode, UIScro self.actionButtonNode.setTitle(self.presentationData.strings.ApplyLanguage_ChangeLanguageAction, with: Font.medium(20.0), with: self.presentationData.theme.actionSheet.disabledActionTextColor, for: .disabled) } - self.transitionToContentNode(LanguageLinkPreviewContentNode(account: self.account, localizationInfo: localizationInfo, theme: self.presentationData.theme, strings: self.presentationData.strings, openTranslationUrl: { [weak self] url in + self.transitionToContentNode(LanguageLinkPreviewContentNode(context: self.context, localizationInfo: localizationInfo, theme: self.presentationData.theme, strings: self.presentationData.strings, openTranslationUrl: { [weak self] url in self?.openUrl(url) })) } diff --git a/TelegramUI/LanguageSuggestionController.swift b/TelegramUI/LanguageSuggestionController.swift index 5aad335071..0ff2edfa6d 100644 --- a/TelegramUI/LanguageSuggestionController.swift +++ b/TelegramUI/LanguageSuggestionController.swift @@ -321,12 +321,12 @@ private final class LanguageSuggestionAlertContentNode: AlertContentNode { } } -func languageSuggestionController(account: Account, suggestedLocalization: SuggestedLocalizationInfo, currentLanguageCode: String, openSelection: @escaping () -> Void) -> AlertController? { +func languageSuggestionController(context: AccountContext, suggestedLocalization: SuggestedLocalizationInfo, currentLanguageCode: String, openSelection: @escaping () -> Void) -> AlertController? { guard let localization = suggestedLocalization.availableLocalizations.filter({ $0.languageCode == suggestedLocalization.languageCode }).first else { return nil } - let theme = account.telegramApplicationContext.currentPresentationData.with { $0 }.theme + let theme = context.currentPresentationData.with { $0 }.theme let strings = LanguageSuggestionControllerStrings(localization: suggestedLocalization) guard let mainPath = Bundle.main.path(forResource: "en", ofType: "lproj") else { return nil @@ -344,7 +344,7 @@ func languageSuggestionController(account: Account, suggestedLocalization: Sugge dismissImpl?(true) } else { startActivity() - disposable.set((downloadAndApplyLocalization(postbox: account.postbox, network: account.network, languageCode: languageCode) + disposable.set((downloadAndApplyLocalization(postbox: context.account.postbox, network: context.account.network, languageCode: languageCode) |> deliverOnMainQueue).start(completed: { dismissImpl?(true) })) diff --git a/TelegramUI/LegacyCamera.swift b/TelegramUI/LegacyCamera.swift index a87796f575..96667125a4 100644 --- a/TelegramUI/LegacyCamera.swift +++ b/TelegramUI/LegacyCamera.swift @@ -6,7 +6,7 @@ import TelegramCore import Postbox import SwiftSignalKit -func presentedLegacyCamera(account: Account, peer: Peer, cameraView: TGAttachmentCameraView?, menuController: TGMenuSheetController?, parentController: ViewController, editingMedia: Bool, saveCapturedPhotos: Bool, mediaGrouping: Bool, sendMessagesWithSignals: @escaping ([Any]?) -> Void, recognizedQRCode: @escaping (String) -> Void = { _ in }) { +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 legacyController = LegacyController(presentation: .custom, theme: presentationData.theme) legacyController.supportedOrientations = ViewControllerSupportedOrientations(regularSize: .portrait, compactSize: .portrait) @@ -150,8 +150,8 @@ func presentedLegacyCamera(account: Account, peer: Peer, cameraView: TGAttachmen parentController.present(legacyController, in: .window(.root)) } -func presentedLegacyShortcutCamera(account: Account, saveCapturedMedia: Bool, saveEditedPhotos: Bool, mediaGrouping: Bool, parentController: ViewController) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } +func presentedLegacyShortcutCamera(context: AccountContext, saveCapturedMedia: Bool, saveEditedPhotos: Bool, mediaGrouping: Bool, parentController: ViewController) { + 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 diff --git a/TelegramUI/LegacyInstantVideoController.swift b/TelegramUI/LegacyInstantVideoController.swift index 70b65c3251..92b387c8a8 100644 --- a/TelegramUI/LegacyInstantVideoController.swift +++ b/TelegramUI/LegacyInstantVideoController.swift @@ -89,7 +89,7 @@ func legacyInputMicPalette(from theme: PresentationTheme) -> TGModernConversatio return TGModernConversationInputMicPallete(dark: theme.overallDarkAppearance, buttonColor: inputPanelTheme.actionControlFillColor, iconColor: inputPanelTheme.actionControlForegroundColor, backgroundColor: inputPanelTheme.panelBackgroundColor, borderColor: inputPanelTheme.panelStrokeColor, lock: inputPanelTheme.panelControlAccentColor, textColor: inputPanelTheme.primaryTextColor, secondaryTextColor: inputPanelTheme.secondaryTextColor, recording: inputPanelTheme.mediaRecordingDotColor) } -func legacyInstantVideoController(theme: PresentationTheme, panelFrame: CGRect, account: Account, peerId: PeerId, send: @escaping (EnqueueMessage) -> Void) -> InstantVideoController { +func legacyInstantVideoController(theme: PresentationTheme, panelFrame: CGRect, context: AccountContext, peerId: PeerId, send: @escaping (EnqueueMessage) -> Void) -> InstantVideoController { let legacyController = InstantVideoController(presentation: .custom, theme: theme) legacyController.supportedOrientations = ViewControllerSupportedOrientations(regularSize: .all, compactSize: .all) legacyController.lockOrientation = true diff --git a/TelegramUI/LegacyLocationController.swift b/TelegramUI/LegacyLocationController.swift index 6a60648dec..2be200210f 100644 --- a/TelegramUI/LegacyLocationController.swift +++ b/TelegramUI/LegacyLocationController.swift @@ -120,7 +120,7 @@ func legacyLocationPalette(from theme: PresentationTheme) -> TGLocationPallete { return TGLocationPallete(backgroundColor: listTheme.plainBackgroundColor, selectionColor: listTheme.itemHighlightedBackgroundColor, separatorColor: listTheme.itemPlainSeparatorColor, textColor: listTheme.itemPrimaryTextColor, secondaryTextColor: listTheme.itemSecondaryTextColor, accentColor: listTheme.itemAccentColor, destructiveColor: listTheme.itemDestructiveColor, locationColor: UIColor(rgb: 0x008df2), liveLocationColor: UIColor(rgb: 0xff6464), iconColor: searchTheme.backgroundColor, sectionHeaderBackgroundColor: theme.chatList.sectionHeaderFillColor, sectionHeaderTextColor: theme.chatList.sectionHeaderTextColor, searchBarPallete: TGSearchBarPallete(dark: theme.overallDarkAppearance, backgroundColor: searchTheme.backgroundColor, highContrastBackgroundColor: searchTheme.backgroundColor, textColor: searchTheme.inputTextColor, placeholderColor: searchTheme.inputPlaceholderTextColor, clearIcon: generateClearIcon(color: theme.rootController.activeNavigationSearchBar.inputClearButtonColor), barBackgroundColor: searchTheme.backgroundColor, barSeparatorColor: searchTheme.separatorColor, plainBackgroundColor: searchTheme.backgroundColor, accentColor: searchTheme.accentColor, accentContrastColor: searchTheme.backgroundColor, menuBackgroundColor: searchTheme.backgroundColor, segmentedControlBackgroundImage: nil, segmentedControlSelectedImage: nil, segmentedControlHighlightedImage: nil, segmentedControlDividerImage: nil), avatarPlaceholder: nil) } -func legacyLocationController(message: Message?, mapMedia: TelegramMediaMap, account: Account, isModal: Bool, openPeer: @escaping (Peer) -> Void, sendLiveLocation: @escaping (CLLocationCoordinate2D, Int32) -> Void, stopLiveLocation: @escaping () -> Void, openUrl: @escaping (String) -> Void) -> ViewController { +func legacyLocationController(message: Message?, mapMedia: TelegramMediaMap, context: AccountContext, isModal: Bool, openPeer: @escaping (Peer) -> Void, sendLiveLocation: @escaping (CLLocationCoordinate2D, Int32) -> Void, stopLiveLocation: @escaping () -> Void, openUrl: @escaping (String) -> Void) -> ViewController { let legacyLocation = TGLocationMediaAttachment() legacyLocation.latitude = mapMedia.latitude legacyLocation.longitude = mapMedia.longitude diff --git a/TelegramUI/LegacyLocationPicker.swift b/TelegramUI/LegacyLocationPicker.swift index 8550effd94..3e969a213f 100644 --- a/TelegramUI/LegacyLocationPicker.swift +++ b/TelegramUI/LegacyLocationPicker.swift @@ -9,7 +9,7 @@ private func generateClearIcon(color: UIColor) -> UIImage? { return generateTintedImage(image: UIImage(bundleImageName: "Components/Search Bar/Clear"), color: color) } -func legacyLocationPickerController(account: Account, selfPeer: Peer, peer: Peer, sendLocation: @escaping (CLLocationCoordinate2D, MapVenue?) -> Void, sendLiveLocation: @escaping (CLLocationCoordinate2D, Int32) -> Void, theme: PresentationTheme) -> ViewController { +func legacyLocationPickerController(context: AccountContext, selfPeer: Peer, peer: Peer, sendLocation: @escaping (CLLocationCoordinate2D, MapVenue?) -> Void, sendLiveLocation: @escaping (CLLocationCoordinate2D, Int32) -> Void, theme: PresentationTheme) -> ViewController { let legacyController = LegacyController(presentation: .modal(animateIn: true), theme: theme) let controller = TGLocationPickerController(context: legacyController.context, intent: TGLocationPickerControllerDefaultIntent)! controller.peer = makeLegacyPeer(selfPeer) diff --git a/TelegramUI/LegacyMediaPickers.swift b/TelegramUI/LegacyMediaPickers.swift index d3f3a62fa6..16bdbecc44 100644 --- a/TelegramUI/LegacyMediaPickers.swift +++ b/TelegramUI/LegacyMediaPickers.swift @@ -13,7 +13,7 @@ func guessMimeTypeByFileExtension(_ ext: String) -> String { return TGMimeTypeMap.mimeType(forExtension: ext) ?? "application/binary" } -func configureLegacyAssetPicker(_ controller: TGMediaAssetsController, account: Account, peer: Peer, captionsEnabled: Bool = true, storeCreatedAssets: Bool = true, showFileTooltip: Bool = false, presentWebSearch: (() -> Void)?) { +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) @@ -28,7 +28,7 @@ func configureLegacyAssetPicker(_ controller: TGMediaAssetsController, account: controller.requestSearchController = presentWebSearch } -func legacyAssetPicker(applicationContext: TelegramApplicationContext, presentationData: PresentationData, editingMedia: Bool, fileMode: Bool, peer: Peer?, saveEditedPhotos: Bool, allowGrouping: Bool) -> Signal<(LegacyComponentsContext) -> TGMediaAssetsController, Void> { +func legacyAssetPicker(context: AccountContext, presentationData: PresentationData, editingMedia: Bool, fileMode: Bool, peer: Peer?, saveEditedPhotos: Bool, allowGrouping: Bool) -> Signal<(LegacyComponentsContext) -> TGMediaAssetsController, Void> { let isSecretChat = (peer?.id.namespace ?? 0) == Namespaces.Peer.SecretChat return Signal { subscriber in diff --git a/TelegramUI/LegacyPeerAvatarPlaceholderDataSource.swift b/TelegramUI/LegacyPeerAvatarPlaceholderDataSource.swift index a88a8da523..9dde6438a4 100644 --- a/TelegramUI/LegacyPeerAvatarPlaceholderDataSource.swift +++ b/TelegramUI/LegacyPeerAvatarPlaceholderDataSource.swift @@ -47,16 +47,16 @@ final class LegacyPeerAvatarPlaceholderDataSource: TGImageDataSource { override func loadDataAsync(withUri uri: String!, progress: ((Float) -> Void)!, partialCompletion: ((TGDataResource?) -> Void)!, completion: ((TGDataResource?) -> Void)!) -> Any! { if let account = self.account() { - let task = ThreadPoolTask { state in + let signal: Signal = Signal { subscriber in let args: [AnyHashable : Any] let argumentsString = String(uri[uri.index(uri.startIndex, offsetBy: "placeholder://?".characters.count)...]) args = TGStringUtils.argumentDictionary(inUrlString: argumentsString)! guard let width = Int((args["w"] as! String)), width > 1 else { - return + return EmptyDisposable } guard let height = Int((args["h"] as! String)), height > 1 else { - return + return EmptyDisposable } var peerId = PeerId(namespace: 0, id: 0) @@ -100,13 +100,13 @@ final class LegacyPeerAvatarPlaceholderDataSource: TGImageDataSource { sharedImageCache.setImage(image, forKey: uri, attributes: nil) completion?(TGDataResource(image: image, decoded: true)) + + subscriber.putCompletion() + + return EmptyDisposable } - account.graphicsThreadPool.addTask(task) - - return ActionDisposable { - task.cancel() - } + return (signal |> runOn(Queue.concurrentDefaultQueue())).start() } else { return nil } diff --git a/TelegramUI/LegacyWebSearchEditor.swift b/TelegramUI/LegacyWebSearchEditor.swift index a313c46b00..e93cb6dbb0 100644 --- a/TelegramUI/LegacyWebSearchEditor.swift +++ b/TelegramUI/LegacyWebSearchEditor.swift @@ -7,7 +7,7 @@ import SSignalKit import UIKit import Display -func presentLegacyWebSearchEditor(account: Account, 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) { +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 { return } diff --git a/TelegramUI/LegacyWebSearchGallery.swift b/TelegramUI/LegacyWebSearchGallery.swift index 3cad293a21..f59fe46c87 100644 --- a/TelegramUI/LegacyWebSearchGallery.swift +++ b/TelegramUI/LegacyWebSearchGallery.swift @@ -301,7 +301,7 @@ private func galleryItems(account: Account, results: [ChatContextResult], curren return (galleryItems, focusItem) } -func presentLegacyWebSearchGallery(account: Account, peer: Peer?, theme: PresentationTheme, results: [ChatContextResult], current: ChatContextResult, selectionContext: TGMediaSelectionContext?, editingContext: TGMediaEditingContext, updateHiddenMedia: @escaping (String?) -> Void, initialLayout: ContainerViewLayout?, transitionHostView: @escaping () -> UIView?, transitionView: @escaping (ChatContextResult) -> UIView?, completed: @escaping (ChatContextResult) -> Void, present: (ViewController, Any?) -> Void) { +func presentLegacyWebSearchGallery(context: AccountContext, peer: Peer?, theme: PresentationTheme, results: [ChatContextResult], current: ChatContextResult, selectionContext: TGMediaSelectionContext?, editingContext: TGMediaEditingContext, updateHiddenMedia: @escaping (String?) -> Void, initialLayout: ContainerViewLayout?, transitionHostView: @escaping () -> UIView?, transitionView: @escaping (ChatContextResult) -> UIView?, completed: @escaping (ChatContextResult) -> Void, present: (ViewController, Any?) -> Void) { let legacyController = LegacyController(presentation: .custom, theme: theme, initialLayout: nil) legacyController.statusBar.statusBarStyle = theme.rootController.statusBar.style.style diff --git a/TelegramUI/ListMessageFileItemNode.swift b/TelegramUI/ListMessageFileItemNode.swift index a278235edd..a0c823fa32 100644 --- a/TelegramUI/ListMessageFileItemNode.swift +++ b/TelegramUI/ListMessageFileItemNode.swift @@ -167,7 +167,7 @@ final class ListMessageFileItemNode: ListMessageNode { private let progressNode: RadialProgressNode private var playbackOverlayNode: ListMessagePlaybackOverlayNode? - private var account: Account? + private var context: AccountContext? private (set) var message: Message? private var appliedItem: ListMessageItem? @@ -413,18 +413,18 @@ final class ListMessageFileItemNode: ListMessageNode { if let selectedMedia = selectedMedia { if mediaUpdated { - let account = item.account + let context = item.context updatedFetchControls = FetchControls(fetch: { [weak self] in if let strongSelf = self { - strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: account, message: message, file: selectedMedia, userInitiated: true).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: context.account, message: message, file: selectedMedia, userInitiated: true).start()) } }, cancel: { - messageMediaFileCancelInteractiveFetch(account: account, messageId: message.id, file: selectedMedia) + messageMediaFileCancelInteractiveFetch(account: context.account, messageId: message.id, file: selectedMedia) }) } if statusUpdated { - updatedStatusSignal = messageFileMediaResourceStatus(account: item.account, file: selectedMedia, message: message, isRecentActions: false) + updatedStatusSignal = messageFileMediaResourceStatus(account: item.context.account, file: selectedMedia, message: message, isRecentActions: false) if isAudio { if let currentUpdatedStatusSignal = updatedStatusSignal { @@ -468,9 +468,9 @@ final class ListMessageFileItemNode: ListMessageNode { if let iconImage = iconImage { switch iconImage { case let .imageRepresentation(file, representation): - updateIconImageSignal = chatWebpageSnippetFile(account: item.account, fileReference: .message(message: MessageReference(message), media: file), representation: representation) + updateIconImageSignal = chatWebpageSnippetFile(account: item.context.account, fileReference: .message(message: MessageReference(message), media: file), representation: representation) case let .albumArt(file, albumArt): - updateIconImageSignal = playerAlbumArt(postbox: item.account.postbox, fileReference: .message(message: MessageReference(message), media: file), albumArt: albumArt, thumbnail: true) + updateIconImageSignal = playerAlbumArt(postbox: item.context.account.postbox, fileReference: .message(message: MessageReference(message), media: file), albumArt: albumArt, thumbnail: true) } } else { @@ -496,7 +496,7 @@ final class ListMessageFileItemNode: ListMessageNode { strongSelf.currentMedia = selectedMedia strongSelf.message = message - strongSelf.account = item.account + strongSelf.context = item.context strongSelf.appliedItem = item strongSelf.layoutParams = params strongSelf.contentSizeValue = nodeLayout.contentSize diff --git a/TelegramUI/ListMessageItem.swift b/TelegramUI/ListMessageItem.swift index 4b3b1f3efe..1cf81e869a 100644 --- a/TelegramUI/ListMessageItem.swift +++ b/TelegramUI/ListMessageItem.swift @@ -9,7 +9,7 @@ final class ListMessageItem: ListViewItem { let theme: PresentationTheme let strings: PresentationStrings let dateTimeFormat: PresentationDateTimeFormat - let account: Account + let context: AccountContext let chatLocation: ChatLocation let controllerInteraction: ChatControllerInteraction let message: Message @@ -19,11 +19,11 @@ final class ListMessageItem: ListViewItem { let selectable: Bool = true - public init(theme: PresentationTheme, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, account: Account, chatLocation: ChatLocation, controllerInteraction: ChatControllerInteraction, message: Message, selection: ChatHistoryMessageSelection, displayHeader: Bool) { + public init(theme: PresentationTheme, strings: PresentationStrings, dateTimeFormat: PresentationDateTimeFormat, context: AccountContext, chatLocation: ChatLocation, controllerInteraction: ChatControllerInteraction, message: Message, selection: ChatHistoryMessageSelection, displayHeader: Bool) { self.theme = theme self.strings = strings self.dateTimeFormat = dateTimeFormat - self.account = account + self.context = context self.chatLocation = chatLocation self.controllerInteraction = controllerInteraction self.message = message diff --git a/TelegramUI/ListMessageSnippetItemNode.swift b/TelegramUI/ListMessageSnippetItemNode.swift index 522688f85d..bf856a80a7 100644 --- a/TelegramUI/ListMessageSnippetItemNode.swift +++ b/TelegramUI/ListMessageSnippetItemNode.swift @@ -309,9 +309,9 @@ final class ListMessageSnippetItemNode: ListMessageNode { if currentIconImageRepresentation != iconImageReferenceAndRepresentation?.1 { if let iconImageReferenceAndRepresentation = iconImageReferenceAndRepresentation { if let imageReference = iconImageReferenceAndRepresentation.0.concrete(TelegramMediaImage.self) { - updateIconImageSignal = chatWebpageSnippetPhoto(account: item.account, photoReference: imageReference) + updateIconImageSignal = chatWebpageSnippetPhoto(account: item.context.account, photoReference: imageReference) } else if let fileReference = iconImageReferenceAndRepresentation.0.concrete(TelegramMediaFile.self) { - updateIconImageSignal = chatWebpageSnippetFile(account: item.account, fileReference: fileReference, representation: iconImageReferenceAndRepresentation.1) + updateIconImageSignal = chatWebpageSnippetFile(account: item.context.account, fileReference: fileReference, representation: iconImageReferenceAndRepresentation.1) } } else { updateIconImageSignal = .complete() @@ -586,7 +586,7 @@ final class ListMessageSnippetItemNode: ListMessageNode { if let current = self.linkHighlightingNode { linkHighlightingNode = current } else { - linkHighlightingNode = LinkHighlightingNode(color: item.message.effectivelyIncoming(item.account.peerId) ? item.theme.chat.bubble.incomingLinkHighlightColor : item.theme.chat.bubble.outgoingLinkHighlightColor) + linkHighlightingNode = LinkHighlightingNode(color: item.message.effectivelyIncoming(item.context.account.peerId) ? item.theme.chat.bubble.incomingLinkHighlightColor : item.theme.chat.bubble.outgoingLinkHighlightColor) self.linkHighlightingNode = linkHighlightingNode self.insertSubnode(linkHighlightingNode, belowSubnode: self.linkNode) } diff --git a/TelegramUI/LocalizationListController.swift b/TelegramUI/LocalizationListController.swift index dd93cc6970..10c243c45b 100644 --- a/TelegramUI/LocalizationListController.swift +++ b/TelegramUI/LocalizationListController.swift @@ -6,7 +6,7 @@ import SwiftSignalKit import TelegramCore public class LocalizationListController: ViewController { - private let account: Account + private let context: AccountContext private var controllerNode: LocalizationListControllerNode { return self.displayNode as! LocalizationListControllerNode @@ -25,10 +25,10 @@ public class LocalizationListController: ViewController { private var searchContentNode: NavigationBarSearchContentNode? - public init(account: Account) { - self.account = account + public init(context: AccountContext) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -50,7 +50,7 @@ public class LocalizationListController: 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 @@ -99,7 +99,7 @@ public class LocalizationListController: ViewController { } override public func loadDisplayNode() { - self.displayNode = LocalizationListControllerNode(account: self.account, presentationData: self.presentationData, navigationBar: self.navigationBar!, requestActivateSearch: { [weak self] in + self.displayNode = LocalizationListControllerNode(context: self.context, presentationData: self.presentationData, navigationBar: self.navigationBar!, requestActivateSearch: { [weak self] in self?.activateSearch() }, requestDeactivateSearch: { [weak self] in self?.deactivateSearch() diff --git a/TelegramUI/LocalizationListControllerNode.swift b/TelegramUI/LocalizationListControllerNode.swift index 3cff315520..58909122e5 100644 --- a/TelegramUI/LocalizationListControllerNode.swift +++ b/TelegramUI/LocalizationListControllerNode.swift @@ -83,8 +83,8 @@ private final class LocalizationListSearchContainerNode: SearchDisplayController private let themeAndStringsPromise: Promise<(PresentationTheme, PresentationStrings)> - init(account: Account, listState: LocalizationListState, selectLocalization: @escaping (LocalizationInfo) -> Void, applyingCode: Signal) { - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, listState: LocalizationListState, selectLocalization: @escaping (LocalizationInfo) -> Void, applyingCode: Signal) { + self.presentationData = context.currentPresentationData.with { $0 } self.themeAndStringsPromise = Promise((self.presentationData.theme, self.presentationData.strings)) @@ -138,7 +138,7 @@ private final class LocalizationListSearchContainerNode: SearchDisplayController strongSelf.enqueueTransition(transition) })) - 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 @@ -271,7 +271,7 @@ private func preparedLanguageListNodeTransition(theme: PresentationTheme, string } final class LocalizationListControllerNode: ViewControllerTracingNode { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let navigationBar: NavigationBar private let requestActivateSearch: () -> Void @@ -301,8 +301,8 @@ final class LocalizationListControllerNode: ViewControllerTracingNode { } } - init(account: Account, presentationData: PresentationData, navigationBar: NavigationBar, requestActivateSearch: @escaping () -> Void, requestDeactivateSearch: @escaping () -> Void, updateCanStartEditing: @escaping (Bool?) -> Void, present: @escaping (ViewController, Any?) -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, navigationBar: NavigationBar, requestActivateSearch: @escaping () -> Void, requestDeactivateSearch: @escaping () -> Void, updateCanStartEditing: @escaping (Bool?) -> Void, present: @escaping (ViewController, Any?) -> Void) { + self.context = context self.presentationData = presentationData self.presentationDataValue.set(.single((presentationData.theme, presentationData.strings))) self.navigationBar = navigationBar @@ -332,7 +332,7 @@ final class LocalizationListControllerNode: ViewControllerTracingNode { } let removeItem: (String) -> Void = { id in - let _ = (account.postbox.transaction { transaction -> LocalizationInfo? in + let _ = (context.account.postbox.transaction { transaction -> LocalizationInfo? in removeSavedLocalization(transaction: transaction, languageCode: id) if let settings = transaction.getPreferencesEntry(key: PreferencesKeys.localizationSettings) as? LocalizationSettings, let state = transaction.getPreferencesEntry(key: PreferencesKeys.localizationListState) as? LocalizationListState { if settings.primaryComponent.languageCode == id { @@ -358,7 +358,7 @@ final class LocalizationListControllerNode: ViewControllerTracingNode { let preferencesKey: PostboxViewKey = .preferences(keys: Set([PreferencesKeys.localizationListState, PreferencesKeys.localizationSettings])) let previousEntriesHolder = Atomic<([LanguageListEntry], PresentationTheme, PresentationStrings)?>(value: nil) - self.listDisposable = combineLatest(queue: .mainQueue(), account.postbox.combinedView(keys: [preferencesKey]), self.presentationDataValue.get(), self.applyingCode.get(), revealedCode.get(), self.isEditing.get()).start(next: { [weak self] view, presentationData, applyingCode, revealedCode, isEditing in + self.listDisposable = combineLatest(queue: .mainQueue(), context.account.postbox.combinedView(keys: [preferencesKey]), self.presentationDataValue.get(), self.applyingCode.get(), revealedCode.get(), self.isEditing.get()).start(next: { [weak self] view, presentationData, applyingCode, revealedCode, isEditing in guard let strongSelf = self else { return } @@ -399,7 +399,7 @@ final class LocalizationListControllerNode: ViewControllerTracingNode { let transition = preparedLanguageListNodeTransition(theme: presentationData.0, strings: presentationData.1, from: previousEntriesAndPresentationData?.0 ?? [], to: entries, openSearch: openSearch, selectLocalization: { [weak self] info in self?.selectLocalization(info) }, setItemWithRevealedOptions: setItemWithRevealedOptions, removeItem: removeItem, firstTime: previousEntriesAndPresentationData == nil, forceUpdate: previousEntriesAndPresentationData?.1 !== presentationData.0 || previousEntriesAndPresentationData?.2 !== presentationData.1, animated: (previousEntriesAndPresentationData?.0.count ?? 0) >= entries.count) strongSelf.enqueueTransition(transition) }) - self.updatedDisposable = synchronizedLocalizationListState(postbox: account.postbox, network: account.network).start() + self.updatedDisposable = synchronizedLocalizationListState(postbox: context.account.postbox, network: context.account.network).start() } deinit { @@ -500,7 +500,7 @@ final class LocalizationListControllerNode: ViewControllerTracingNode { return } strongSelf.applyingCode.set(.single(info.languageCode)) - strongSelf.applyDisposable.set((downloadAndApplyLocalization(postbox: strongSelf.account.postbox, network: strongSelf.account.network, languageCode: info.languageCode) + strongSelf.applyDisposable.set((downloadAndApplyLocalization(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, languageCode: info.languageCode) |> deliverOnMainQueue).start(completed: { self?.applyingCode.set(.single(nil)) })) @@ -526,7 +526,7 @@ final class LocalizationListControllerNode: ViewControllerTracingNode { guard let strongSelf = self else { return } - let shareController = ShareController(account: strongSelf.account, subject: .url("https://t.me/setlanguage/\(info.languageCode)")) + let shareController = ShareController(context: strongSelf.context, subject: .url("https://t.me/setlanguage/\(info.languageCode)")) strongSelf.present(shareController, nil) })) controller.setItemGroups([ @@ -546,7 +546,7 @@ final class LocalizationListControllerNode: ViewControllerTracingNode { return } - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: LocalizationListSearchContainerNode(account: self.account, listState: self.currentListState ?? LocalizationListState.defaultSettings, selectLocalization: { [weak self] info in self?.selectLocalization(info) }, applyingCode: self.applyingCode.get()), cancel: { [weak self] in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: LocalizationListSearchContainerNode(context: self.context, listState: self.currentListState ?? LocalizationListState.defaultSettings, selectLocalization: { [weak self] info in self?.selectLocalization(info) }, applyingCode: self.applyingCode.get()), cancel: { [weak self] in self?.requestDeactivateSearch() }) diff --git a/TelegramUI/LocationBroadcastActionSheetItem.swift b/TelegramUI/LocationBroadcastActionSheetItem.swift index d685d3545a..883ea974f8 100644 --- a/TelegramUI/LocationBroadcastActionSheetItem.swift +++ b/TelegramUI/LocationBroadcastActionSheetItem.swift @@ -5,7 +5,7 @@ import TelegramCore import Postbox public class LocationBroadcastActionSheetItem: ActionSheetItem { - public let account: Account + public let context: AccountContext public let peer: Peer public let title: String public let beginTimestamp: Double @@ -13,8 +13,8 @@ public class LocationBroadcastActionSheetItem: ActionSheetItem { public let strings: PresentationStrings public let action: () -> Void - public init(account: Account, peer: Peer, title: String, beginTimestamp: Double, timeout: Double, strings: PresentationStrings, action: @escaping () -> Void) { - self.account = account + public init(context: AccountContext, peer: Peer, title: String, beginTimestamp: Double, timeout: Double, strings: PresentationStrings, action: @escaping () -> Void) { + self.context = context self.peer = peer self.title = title self.beginTimestamp = beginTimestamp @@ -96,7 +96,7 @@ public class LocationBroadcastActionSheetItemNode: ActionSheetItemNode { let textColor: UIColor = self.theme.primaryTextColor self.label.attributedText = NSAttributedString(string: item.title, font: ActionSheetButtonNode.defaultFont, textColor: textColor) - self.avatarNode.setPeer(account: item.account, peer: item.peer) + self.avatarNode.setPeer(account: item.context.account, theme: (item.context.currentPresentationData.with { $0 }).theme, peer: item.peer) self.timerNode.update(backgroundColor: self.theme.controlAccentColor.withAlphaComponent(0.4), foregroundColor: self.theme.controlAccentColor, textColor: self.theme.controlAccentColor, beginTimestamp: item.beginTimestamp, timeout: item.timeout, strings: item.strings) diff --git a/TelegramUI/MapInputController.swift b/TelegramUI/MapInputController.swift deleted file mode 100644 index 8f7b04a57c..0000000000 --- a/TelegramUI/MapInputController.swift +++ /dev/null @@ -1,62 +0,0 @@ -import Foundation -import Display -import AsyncDisplayKit -import UIKit -import SwiftSignalKit - -final class MapInputController: ViewController { - private let _ready = Promise() - override var ready: Promise { - return self._ready - } - private var didSetReady = false - - var mapInputNode: MapInputControllerNode { - get { - return super.displayNode as! MapInputControllerNode - } - } - - init() { - super.init(navigationBarPresentationData: nil) - - self._ready.set(.single(true)) - - /*self.statusBar.style = .White - self.navigationBar.backgroundColor = UIColor(white: 0.0, alpha: 0.9) - self.navigationBar.foregroundColor = UIColor.white() - self.navigationBar.accentColor = UIColor.white() - self.navigationBar.stripeColor = UIColor.black()*/ - - self.navigationItem.title = "Location" - self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.cancelPressed)) - } - - required init(coder aDecoder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - @objc func cancelPressed() { - self.mapInputNode.animateOut() - } - - override func loadDisplayNode() { - self.displayNode = MapInputControllerNode() - - self.mapInputNode.dismiss = { [weak self] in - self?.presentingViewController?.dismiss(animated: true, completion: nil) - } - } - - override func viewDidAppear(_ animated: Bool) { - super.viewDidAppear(animated) - - self.mapInputNode.animateIn() - } - - override func containerLayoutUpdated(_ layout: ContainerViewLayout, transition: ContainedViewLayoutTransition) { - super.containerLayoutUpdated(layout, transition: transition) - - self.mapInputNode.containerLayoutUpdated(layout, navigationBarHeight: self.navigationHeight, transition: transition) - } -} diff --git a/TelegramUI/MapInputControllerNode.swift b/TelegramUI/MapInputControllerNode.swift deleted file mode 100644 index ed0e4934e6..0000000000 --- a/TelegramUI/MapInputControllerNode.swift +++ /dev/null @@ -1,69 +0,0 @@ -import Foundation -import Display -import AsyncDisplayKit -import MapKit - -private var previousUserLocation: CLLocation? - -final class MapInputControllerNode: ASDisplayNode, MKMapViewDelegate { - var dismiss: () -> Void = { } - - let locationManager: CLLocationManager - let mapView: MKMapView - - override init() { - self.locationManager = CLLocationManager() - self.mapView = MKMapView() - - super.init() - - self.setViewBlock({ - return UITracingLayerView() - }) - - self.backgroundColor = UIColor.white - - self.mapView.delegate = self - self.view.addSubview(self.mapView) - - if let location = previousUserLocation { - let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000.0 * 2.0, 1000.0 * 2.0) - mapView.setRegion(coordinateRegion, animated: true) - } - } - - func containerLayoutUpdated(_ layout: ContainerViewLayout, navigationBarHeight: CGFloat, transition: ContainedViewLayoutTransition) { - self.mapView.frame = CGRect(origin: CGPoint(), size: layout.size) - } - - func animateIn() { - self.checkLocationAuthorizationStatus() - - self.layer.animatePosition(from: CGPoint(x: self.layer.position.x, y: self.layer.position.y + self.layer.bounds.size.height), to: self.layer.position, duration: 0.5, timingFunction: kCAMediaTimingFunctionSpring) - } - - func animateOut() { - self.layer.animatePosition(from: self.layer.position, to: CGPoint(x: self.layer.position.x, y: self.layer.position.y + self.layer.bounds.size.height), duration: 0.2, timingFunction: kCAMediaTimingFunctionEaseInEaseOut, removeOnCompletion: false, completion: { [weak self] _ in - if let strongSelf = self { - strongSelf.dismiss() - } - }) - } - - private func checkLocationAuthorizationStatus() { - if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { - mapView.showsUserLocation = true - } else { - locationManager.requestWhenInUseAuthorization() - } - } - - func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { - if let location = userLocation.location { - previousUserLocation = location - - let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000.0 * 2.0, 1000.0 * 2.0) - mapView.setRegion(coordinateRegion, animated: true) - } - } -} diff --git a/TelegramUI/MediaNavigationAccessoryContainerNode.swift b/TelegramUI/MediaNavigationAccessoryContainerNode.swift index b56fe9b998..b9eb80f320 100644 --- a/TelegramUI/MediaNavigationAccessoryContainerNode.swift +++ b/TelegramUI/MediaNavigationAccessoryContainerNode.swift @@ -11,8 +11,8 @@ final class MediaNavigationAccessoryContainerNode: ASDisplayNode, UIGestureRecog private var presentationData: PresentationData - init(account: Account) { - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext) { + self.presentationData = context.currentPresentationData.with { $0 } self.backgroundNode = ASDisplayNode() self.headerNode = MediaNavigationAccessoryHeaderNode(presentationData: self.presentationData) diff --git a/TelegramUI/MediaNavigationAccessoryPanel.swift b/TelegramUI/MediaNavigationAccessoryPanel.swift index 4ddb854b8e..16beb08089 100644 --- a/TelegramUI/MediaNavigationAccessoryPanel.swift +++ b/TelegramUI/MediaNavigationAccessoryPanel.swift @@ -11,8 +11,8 @@ final class MediaNavigationAccessoryPanel: ASDisplayNode { var togglePlayPause: (() -> Void)? var tapAction: (() -> Void)? - init(account: Account) { - self.containerNode = MediaNavigationAccessoryContainerNode(account: account) + init(context: AccountContext) { + self.containerNode = MediaNavigationAccessoryContainerNode(context: context) super.init() diff --git a/TelegramUI/MentionChatInputContextPanelNode.swift b/TelegramUI/MentionChatInputContextPanelNode.swift index 159ebefda4..8448d23bd7 100644 --- a/TelegramUI/MentionChatInputContextPanelNode.swift +++ b/TelegramUI/MentionChatInputContextPanelNode.swift @@ -55,7 +55,7 @@ final class MentionChatInputContextPanelNode: ChatInputContextPanelNode { private var enqueuedTransitions: [(CommandChatInputContextPanelTransition, Bool)] = [] private var validLayout: (CGSize, CGFloat, CGFloat)? - init(account: Account, theme: PresentationTheme, strings: PresentationStrings, mode: MentionChatInputContextPanelMode) { + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings, mode: MentionChatInputContextPanelMode) { self.mode = mode self.listView = ListView() @@ -65,7 +65,7 @@ final class MentionChatInputContextPanelNode: 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 @@ -95,7 +95,7 @@ final class MentionChatInputContextPanelNode: ChatInputContextPanelNode { private func updateToEntries(entries: [MentionChatInputContextPanelEntry], forceUpdate: Bool) { let firstTime = self.currentEntries == nil - let transition = preparedTransition(from: self.currentEntries ?? [], to: entries, account: self.account, theme: self.theme, inverted: self.mode == .search, forceUpdate: forceUpdate, peerSelected: { [weak self] peer in + let transition = preparedTransition(from: self.currentEntries ?? [], to: entries, account: self.context.account, theme: self.theme, inverted: self.mode == .search, forceUpdate: forceUpdate, peerSelected: { [weak self] peer in if let strongSelf = self, let interfaceInteraction = strongSelf.interfaceInteraction { switch strongSelf.mode { case .input: diff --git a/TelegramUI/MergedItemListItem.swift b/TelegramUI/MergedItemListItem.swift deleted file mode 100644 index 8b13789179..0000000000 --- a/TelegramUI/MergedItemListItem.swift +++ /dev/null @@ -1 +0,0 @@ - diff --git a/TelegramUI/NavigateToChatController.swift b/TelegramUI/NavigateToChatController.swift index db118e3dd5..66e6cee5e0 100644 --- a/TelegramUI/NavigateToChatController.swift +++ b/TelegramUI/NavigateToChatController.swift @@ -9,7 +9,7 @@ public enum NavigateToChatKeepStack { case never } -public func navigateToChatController(navigationController: NavigationController, chatController: ChatController? = nil, account: Account, chatLocation: ChatLocation, messageId: MessageId? = nil, botStart: ChatControllerInitialBotStart? = nil, keepStack: NavigateToChatKeepStack = .default, purposefulAction: (() -> Void)? = nil, scrollToEndIfExists: Bool = false, animated: Bool = true, completion: @escaping () -> Void = {}) { +public func navigateToChatController(navigationController: NavigationController, chatController: ChatController? = nil, context: AccountContext, chatLocation: ChatLocation, messageId: MessageId? = nil, botStart: ChatControllerInitialBotStart? = nil, keepStack: NavigateToChatKeepStack = .default, purposefulAction: (() -> Void)? = nil, scrollToEndIfExists: Bool = false, animated: Bool = true, completion: @escaping () -> Void = {}) { var found = false var isFirst = true for controller in navigationController.viewControllers.reversed() { @@ -37,13 +37,13 @@ public func navigateToChatController(navigationController: NavigationController, if let chatController = chatController { controller = chatController } else { - controller = ChatController(account: account, chatLocation: chatLocation, messageId: messageId, botStart: botStart) + controller = ChatController(context: context, chatLocation: chatLocation, messageId: messageId, botStart: botStart) } controller.purposefulAction = purposefulAction let resolvedKeepStack: Bool switch keepStack { case .default: - resolvedKeepStack = account.telegramApplicationContext.immediateExperimentalUISettings.keepChatNavigationStack + resolvedKeepStack = context.immediateExperimentalUISettings.keepChatNavigationStack case .always: resolvedKeepStack = true case .never: diff --git a/TelegramUI/NetworkUsageStatsController.swift b/TelegramUI/NetworkUsageStatsController.swift index 9b81c926cc..5850c746ad 100644 --- a/TelegramUI/NetworkUsageStatsController.swift +++ b/TelegramUI/NetworkUsageStatsController.swift @@ -373,7 +373,7 @@ private func networkUsageStatsControllerEntries(presentationData: PresentationDa return entries } -func networkUsageStatsController(account: Account) -> ViewController { +func networkUsageStatsController(context: AccountContext) -> ViewController { let section = ValuePromise(.cellular) let stats = Promise() stats.set(accountNetworkUsageStats(account: account, reset: [])) @@ -381,7 +381,7 @@ func networkUsageStatsController(account: Account) -> ViewController { var presentControllerImpl: ((ViewController) -> Void)? let arguments = NetworkUsageStatsControllerArguments(resetStatistics: { [weak stats] section in - 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() @@ -398,7 +398,7 @@ func networkUsageStatsController(account: Account) -> ViewController { case .cellular: reset = .cellular } - stats?.set(accountNetworkUsageStats(account: account, reset: reset)) + stats?.set(accountNetworkUsageStats(account: context.account, reset: reset)) }), ]), ActionSheetItemGroup(items: [ActionSheetButtonItem(title: presentationData.strings.Common_Cancel, action: { dismissAction() })]) @@ -406,7 +406,7 @@ func networkUsageStatsController(account: Account) -> ViewController { presentControllerImpl?(controller) }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, section.get(), stats.get()) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, section.get(), stats.get()) |> deliverOnMainQueue |> map { presentationData, section, stats -> (ItemListControllerState, (ItemListNodeState, NetworkUsageStatsEntry.ItemGenerationArguments)) in let controllerState = ItemListControllerState(theme: presentationData.theme, title: .sectionControl([presentationData.strings.NetworkUsageSettings_Cellular, presentationData.strings.NetworkUsageSettings_Wifi], 0), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: false) @@ -415,7 +415,7 @@ func networkUsageStatsController(account: Account) -> ViewController { return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) controller.titleControlValueChanged = { [weak section] index in section?.set(index == 0 ? .cellular : .wifi) } diff --git a/TelegramUI/NotificationExceptionControllerNode.swift b/TelegramUI/NotificationExceptionControllerNode.swift index 8237b54bcf..60015d17b7 100644 --- a/TelegramUI/NotificationExceptionControllerNode.swift +++ b/TelegramUI/NotificationExceptionControllerNode.swift @@ -485,7 +485,7 @@ private extension PeerMuteState { } final class NotificationExceptionsControllerNode: ViewControllerTracingNode { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let navigationBar: NavigationBar private let requestActivateSearch: () -> Void @@ -514,8 +514,8 @@ final class NotificationExceptionsControllerNode: ViewControllerTracingNode { self.arguments?.selectPeer() } - init(account: Account, presentationData: PresentationData, navigationBar: NavigationBar, mode: NotificationExceptionMode, updatedMode:@escaping(NotificationExceptionMode)->Void, requestActivateSearch: @escaping () -> Void, requestDeactivateSearch: @escaping () -> Void, updateCanStartEditing: @escaping (Bool?) -> Void, present: @escaping (ViewController, Any?) -> Void, pushController: @escaping (ViewController) -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, navigationBar: NavigationBar, mode: NotificationExceptionMode, updatedMode:@escaping(NotificationExceptionMode)->Void, requestActivateSearch: @escaping () -> Void, requestDeactivateSearch: @escaping () -> Void, updateCanStartEditing: @escaping (Bool?) -> Void, present: @escaping (ViewController, Any?) -> Void, pushController: @escaping (ViewController) -> Void) { + self.context = context self.presentationData = presentationData self.presentationDataValue.set(.single((presentationData.theme, presentationData.strings))) self.navigationBar = navigationBar @@ -546,9 +546,9 @@ final class NotificationExceptionsControllerNode: ViewControllerTracingNode { updateState { current in peerIds = peerIds.union(current.mode.peerIds) let key: PostboxViewKey = .peerNotificationSettings(peerIds: peerIds) - updateNotificationsDisposable.set((account.postbox.combinedView(keys: [key]) |> deliverOnMainQueue).start(next: { view in + updateNotificationsDisposable.set((context.account.postbox.combinedView(keys: [key]) |> deliverOnMainQueue).start(next: { view in if let view = view.views[key] as? PeerNotificationSettingsView { - _ = account.postbox.transaction { transaction in + _ = context.account.postbox.transaction { transaction in updateState { current in var current = current for (key, value) in view.notificationSettings { @@ -576,14 +576,14 @@ final class NotificationExceptionsControllerNode: ViewControllerTracingNode { var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.modify {$0} + let presentationData = context.currentPresentationData.modify {$0} let updatePeerSound: (PeerId, PeerMessageSound) -> Signal = { peerId, sound in - return updatePeerNotificationSoundInteractive(account: account, peerId: peerId, sound: sound) |> deliverOnMainQueue + return updatePeerNotificationSoundInteractive(account: context.account, peerId: peerId, sound: sound) |> deliverOnMainQueue } let updatePeerNotificationInterval:(PeerId, Int32?) -> Signal = { peerId, muteInterval in - return updatePeerMuteSetting(account: account, peerId: peerId, muteInterval: muteInterval) |> deliverOnMainQueue + return updatePeerMuteSetting(account: context.account, peerId: peerId, muteInterval: muteInterval) |> deliverOnMainQueue } self.backgroundColor = presentationData.theme.list.blocksBackgroundColor @@ -593,18 +593,18 @@ final class NotificationExceptionsControllerNode: ViewControllerTracingNode { requestActivateSearch() } - let arguments = NotificationExceptionArguments(account: account, activateSearch: { + let arguments = NotificationExceptionArguments(account: context.account, activateSearch: { openSearch() }, openPeer: { [weak self] peer in if let strongSelf = self { - _ = (strongSelf.account.postbox.transaction { transaction in + _ = (strongSelf.context.account.postbox.transaction { transaction in if transaction.getPeer(peer.id) == nil { updatePeers(transaction: transaction, peers: [peer], update: { previousPeer, updatedPeer in return updatedPeer }) } } |> deliverOnMainQueue).start(completed: { [weak strongSelf] in - if let strongSelf = strongSelf, let infoController = peerInfoController(account: strongSelf.account, peer: peer) { + if let strongSelf = strongSelf, let infoController = peerInfoController(context: strongSelf.context, peer: peer) { strongSelf.pushController(infoController) strongSelf.requestDeactivateSearch() } @@ -623,14 +623,14 @@ final class NotificationExceptionsControllerNode: ViewControllerTracingNode { case .channels: filter.insert(.onlyChannels) } - let controller = PeerSelectionController(account: account, filter: filter, hasContactSelector: false, title: presentationData.strings.Notifications_AddExceptionTitle) + let controller = PeerSelectionController(context: context, filter: filter, hasContactSelector: false, title: presentationData.strings.Notifications_AddExceptionTitle) controller.peerSelected = { [weak controller] peerId in controller?.dismiss() - presentControllerImpl?(notificationPeerExceptionController(account: account, peerId: peerId, mode: mode, updatePeerSound: { peerId, sound in + presentControllerImpl?(notificationPeerExceptionController(context: context, peerId: peerId, mode: mode, updatePeerSound: { peerId, sound in _ = updatePeerSound(peerId, sound).start(next: { _ in updateNotificationsDisposable.set(nil) - _ = combineLatest(updatePeerSound(peerId, sound), account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { _, peer in + _ = combineLatest(updatePeerSound(peerId, sound), context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { _, peer in updateState { value in return value.withUpdatedPeerSound(peer, sound) } @@ -640,7 +640,7 @@ final class NotificationExceptionsControllerNode: ViewControllerTracingNode { }) }, updatePeerNotificationInterval: { peerId, muteInterval in updateNotificationsDisposable.set(nil) - _ = combineLatest(updatePeerNotificationInterval(peerId, muteInterval), account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { _, peer in + _ = combineLatest(updatePeerNotificationInterval(peerId, muteInterval), context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { _, peer in updateState { value in return value.withUpdatedPeerMuteInterval(peer, muteInterval) } @@ -654,7 +654,7 @@ final class NotificationExceptionsControllerNode: ViewControllerTracingNode { return current.withUpdatedRevealedPeerId(peerId) } }, deletePeer: { peer in - _ = (account.postbox.transaction { transaction in + _ = (context.account.postbox.transaction { transaction in if transaction.getPeer(peer.id) == nil { updatePeers(transaction: transaction, peers: [peer], update: { _, updated in return updated}) } @@ -678,11 +678,11 @@ final class NotificationExceptionsControllerNode: ViewControllerTracingNode { self?.present(c, a) } - let preferences = account.postbox.preferencesView(keys: [PreferencesKeys.globalNotifications]) + let preferences = context.account.postbox.preferencesView(keys: [PreferencesKeys.globalNotifications]) let previousEntriesHolder = Atomic<([NotificationExceptionEntry], PresentationTheme, PresentationStrings)?>(value: nil) - self.listDisposable = (combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), preferences) |> deliverOnMainQueue).start(next: { [weak self] (presentationData, state, prefs) in + self.listDisposable = (combineLatest(context.presentationData, statePromise.get(), preferences) |> deliverOnMainQueue).start(next: { [weak self] (presentationData, state, prefs) in let entries = notificationsExceptionEntries(presentationData: presentationData, state: state) let previousEntriesAndPresentationData = previousEntriesHolder.swap((entries, presentationData.theme, presentationData.strings)) @@ -805,7 +805,7 @@ final class NotificationExceptionsControllerNode: ViewControllerTracingNode { return } - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: NotificationExceptionsSearchContainerNode(account: self.account, mode: self.stateValue.modify {$0}.mode, arguments: self.arguments!), cancel: { [weak self] in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: NotificationExceptionsSearchContainerNode(context: self.context, mode: self.stateValue.modify {$0}.mode, arguments: self.arguments!), cancel: { [weak self] in self?.requestDeactivateSearch() }) @@ -867,8 +867,8 @@ private final class NotificationExceptionsSearchContainerNode: SearchDisplayCont private let updateNotificationsDisposable = MetaDisposable() private let themeAndStringsPromise: Promise<(PresentationTheme, PresentationStrings)> - init(account: Account, mode: NotificationExceptionMode, arguments: NotificationExceptionArguments) { - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, mode: NotificationExceptionMode, arguments: NotificationExceptionArguments) { + self.presentationData = context.currentPresentationData.with { $0 } self.themeAndStringsPromise = Promise((self.presentationData.theme, self.presentationData.strings)) @@ -898,9 +898,9 @@ private final class NotificationExceptionsSearchContainerNode: SearchDisplayCont let updateNotificationsView:()->Void = { let key: PostboxViewKey = .peerNotificationSettings(peerIds: Set(mode.peerIds)) - updateNotificationsDisposable.set(account.postbox.combinedView(keys: [key]).start(next: { view in + updateNotificationsDisposable.set(context.account.postbox.combinedView(keys: [key]).start(next: { view in if let view = view.views[key] as? PeerNotificationSettingsView { - _ = account.postbox.transaction { transaction in + _ = context.account.postbox.transaction { transaction in updateState { current in var current = current for (key, value) in view.notificationSettings { @@ -929,12 +929,12 @@ private final class NotificationExceptionsSearchContainerNode: SearchDisplayCont } - let preferences = account.postbox.preferencesView(keys: [PreferencesKeys.globalNotifications]) + let preferences = context.account.postbox.preferencesView(keys: [PreferencesKeys.globalNotifications]) let previousEntriesHolder = Atomic<([NotificationExceptionEntry], PresentationTheme, PresentationStrings)?>(value: nil) - self.searchDisposable.set((combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, stateAndPeers, preferences) |> deliverOnMainQueue).start(next: { [weak self] (presentationData, state, prefs) in + self.searchDisposable.set((combineLatest(context.presentationData, stateAndPeers, preferences) |> deliverOnMainQueue).start(next: { [weak self] (presentationData, state, prefs) in let entries = notificationsExceptionEntries(presentationData: presentationData, state: state.0, query: state.1) let previousEntriesAndPresentationData = previousEntriesHolder.swap((entries, presentationData.theme, presentationData.strings)) @@ -944,7 +944,7 @@ private final class NotificationExceptionsSearchContainerNode: SearchDisplayCont })) - 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 a20e082ac7..f0d4af1963 100644 --- a/TelegramUI/NotificationExceptions.swift +++ b/TelegramUI/NotificationExceptions.swift @@ -5,7 +5,7 @@ import Postbox import TelegramCore public class NotificationExceptionsController: ViewController { - private let account: Account + private let context: AccountContext private var controllerNode: NotificationExceptionsControllerNode { return self.displayNode as! NotificationExceptionsControllerNode @@ -27,11 +27,11 @@ public class NotificationExceptionsController: ViewController { private var searchContentNode: NavigationBarSearchContentNode? - public init(account: Account, mode: NotificationExceptionMode, updatedMode: @escaping(NotificationExceptionMode) -> Void) { + public init(context: AccountContext, mode: NotificationExceptionMode, updatedMode: @escaping(NotificationExceptionMode) -> Void) { self.account = account self.mode = mode self.updatedMode = updatedMode - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -53,7 +53,7 @@ public class NotificationExceptionsController: 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 @@ -101,7 +101,7 @@ public class NotificationExceptionsController: ViewController { } override public func loadDisplayNode() { - self.displayNode = NotificationExceptionsControllerNode(account: self.account, presentationData: self.presentationData, navigationBar: self.navigationBar!, mode: self.mode, updatedMode: self.updatedMode, requestActivateSearch: { [weak self] in + self.displayNode = NotificationExceptionsControllerNode(context: self.context, presentationData: self.presentationData, navigationBar: self.navigationBar!, mode: self.mode, updatedMode: self.updatedMode, requestActivateSearch: { [weak self] in self?.activateSearch() }, requestDeactivateSearch: { [weak self] in self?.deactivateSearch() diff --git a/TelegramUI/NotificationExcetionSettingsController.swift b/TelegramUI/NotificationExcetionSettingsController.swift index eb8cb3b9e0..1ad8a8581b 100644 --- a/TelegramUI/NotificationExcetionSettingsController.swift +++ b/TelegramUI/NotificationExcetionSettingsController.swift @@ -245,9 +245,7 @@ private struct NotificationExceptionPeerState : Equatable { } -func notificationPeerExceptionController(account: Account, peerId: PeerId, mode: NotificationExceptionMode, updatePeerSound: @escaping(PeerId, PeerMessageSound) -> Void, updatePeerNotificationInterval: @escaping(PeerId, Int32?) -> Void) -> ViewController { - - +func notificationPeerExceptionController(context: AccountContext, peerId: PeerId, mode: NotificationExceptionMode, updatePeerSound: @escaping(PeerId, PeerMessageSound) -> Void, updatePeerNotificationInterval: @escaping(PeerId, Int32?) -> Void) -> ViewController { let initialState = NotificationExceptionPeerState() let statePromise = Promise(initialState) let stateValue = Atomic(value: initialState) @@ -260,10 +258,10 @@ func notificationPeerExceptionController(account: Account, peerId: PeerId, mode: let playSoundDisposable = MetaDisposable() - let arguments = NotificationPeerExceptionArguments(account: account, selectSound: { sound in + let arguments = NotificationPeerExceptionArguments(account: context.account, selectSound: { sound in updateState { state in - playSoundDisposable.set(playSound(account: account, sound: sound, defaultSound: state.defaultSound).start()) + playSoundDisposable.set(playSound(account: context.account, sound: sound, defaultSound: state.defaultSound).start()) return state.withUpdatedSound(sound) } @@ -280,7 +278,7 @@ func notificationPeerExceptionController(account: Account, peerId: PeerId, mode: - statePromise.set(account.postbox.transaction { transaction -> NotificationExceptionPeerState in + statePromise.set(context.account.postbox.transaction { transaction -> NotificationExceptionPeerState in var state = NotificationExceptionPeerState(notifications: transaction.getPeerNotificationSettings(peerId) as? TelegramPeerNotificationSettings) let globalSettings: GlobalNotificationSettings = (transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications) as? GlobalNotificationSettings) ?? GlobalNotificationSettings.defaultSettings switch mode { @@ -296,7 +294,7 @@ func notificationPeerExceptionController(account: Account, peerId: PeerId, mode: }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> distinctUntilChanged) + let signal = combineLatest(context.presentationData, statePromise.get() |> distinctUntilChanged) |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, NotificationPeerExceptionEntry.ItemGenerationArguments)) in let leftNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Cancel), style: .regular, enabled: true, action: { @@ -313,7 +311,7 @@ func notificationPeerExceptionController(account: Account, peerId: PeerId, mode: return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal |> afterDisposed { + let controller = ItemListController(context: context, state: signal |> afterDisposed { playSoundDisposable.dispose() }) diff --git a/TelegramUI/NotificationSoundSelection.swift b/TelegramUI/NotificationSoundSelection.swift index 636617d28f..68a599bfc9 100644 --- a/TelegramUI/NotificationSoundSelection.swift +++ b/TelegramUI/NotificationSoundSelection.swift @@ -209,14 +209,14 @@ public func fileNameForNotificationSound(_ sound: PeerMessageSound, defaultSound } } -func playSound(account: Account, sound: PeerMessageSound, defaultSound: PeerMessageSound?) -> Signal { +func playSound(context: AccountContext, sound: PeerMessageSound, defaultSound: PeerMessageSound?) -> Signal { if case .none = sound { return .complete() } else { return Signal { subscriber in var currentPlayer: AudioPlayerWrapper? var deactivateImpl: (() -> Void)? - let session = account.telegramApplicationContext.mediaManager?.audioSession.push(audioSessionType: .play, activate: { _ in + let session = context.mediaManager.audioSession.push(audioSessionType: .play, activate: { _ in if let url = Bundle.main.url(forResource: fileNameForNotificationSound(sound, defaultSound: defaultSound), withExtension: "m4a") { currentPlayer = AudioPlayerWrapper(url: url, completed: { deactivateImpl?() @@ -241,7 +241,7 @@ func playSound(account: Account, sound: PeerMessageSound, defaultSound: PeerMess } } -public func notificationSoundSelectionController(account: Account, isModal: Bool, currentSound: PeerMessageSound, defaultSound: PeerMessageSound?, completion: @escaping (PeerMessageSound) -> Void) -> ViewController { +public func notificationSoundSelectionController(context: AccountContext, isModal: Bool, currentSound: PeerMessageSound, defaultSound: PeerMessageSound?, completion: @escaping (PeerMessageSound) -> Void) -> ViewController { let statePromise = ValuePromise(NotificationSoundSelectionState(selectedSound: currentSound), ignoreRepeated: true) let stateValue = Atomic(value: NotificationSoundSelectionState(selectedSound: currentSound)) let updateState: ((NotificationSoundSelectionState) -> NotificationSoundSelectionState) -> Void = { f in @@ -253,19 +253,19 @@ public func notificationSoundSelectionController(account: Account, isModal: Bool let playSoundDisposable = MetaDisposable() - let arguments = NotificationSoundSelectionArguments(account: account, selectSound: { sound in + let arguments = NotificationSoundSelectionArguments(account: context.account, selectSound: { sound in updateState { state in return NotificationSoundSelectionState(selectedSound: sound) } - playSoundDisposable.set(playSound(account: account, sound: sound, defaultSound: defaultSound).start()) + playSoundDisposable.set(playSound(context: context, sound: sound, defaultSound: defaultSound).start()) }, complete: { completeImpl?() }, cancel: { cancelImpl?() }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get()) |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, NotificationSoundSelectionEntry.ItemGenerationArguments)) in let leftNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Cancel), style: .regular, enabled: true, action: { @@ -282,7 +282,7 @@ public func notificationSoundSelectionController(account: Account, isModal: Bool return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal |> afterDisposed { + let controller = ItemListController(context: context, state: signal |> afterDisposed { playSoundDisposable.dispose() }) controller.enableInteractiveDismiss = true diff --git a/TelegramUI/NotificationsAndSounds.swift b/TelegramUI/NotificationsAndSounds.swift index ea264fa6ee..c2e4d01a50 100644 --- a/TelegramUI/NotificationsAndSounds.swift +++ b/TelegramUI/NotificationsAndSounds.swift @@ -679,7 +679,7 @@ private func notificationsAndSoundsEntries(authorizationStatus: AccessType, warn return entries } -public func notificationsAndSoundsController(account: Account, exceptionsList: NotificationExceptionsList?) -> ViewController { +public func notificationsAndSoundsController(context: AccountContext, exceptionsList: NotificationExceptionsList?) -> ViewController { var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? var pushControllerImpl: ((ViewController) -> Void)? @@ -689,119 +689,119 @@ public func notificationsAndSoundsController(account: Account, exceptionsList: N notificationExceptions.set(.single(value)) } - let arguments = NotificationsAndSoundsArguments(account: account, presentController: { controller, arguments in + let arguments = NotificationsAndSoundsArguments(account: context.account, presentController: { controller, arguments in presentControllerImpl?(controller, arguments) }, pushController: { controller in pushControllerImpl?(controller) }, soundSelectionDisposable: MetaDisposable(), authorizeNotifications: { - let _ = (DeviceAccess.authorizationStatus(account: account, subject: .notifications) + let _ = (DeviceAccess.authorizationStatus(account: context.account, subject: .notifications) |> take(1) |> deliverOnMainQueue).start(next: { status in switch status { case .notDetermined: - DeviceAccess.authorizeAccess(to: .notifications, account: account) + DeviceAccess.authorizeAccess(to: .notifications, account: context.account) case .denied, .restricted: - account.telegramApplicationContext.applicationBindings.openSettings() + context.applicationBindings.openSettings() case .unreachable: - ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: account.postbox, value: Int32(Date().timeIntervalSince1970)) - account.telegramApplicationContext.applicationBindings.openSettings() + ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: context.account.postbox, value: Int32(Date().timeIntervalSince1970)) + context.applicationBindings.openSettings() default: break } }) }, suppressWarning: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - presentControllerImpl?(textAlertController(account: account, title: presentationData.strings.Notifications_PermissionsSuppressWarningTitle, text: presentationData.strings.Notifications_PermissionsSuppressWarningText, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Notifications_PermissionsKeepDisabled, action: { - ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: account.postbox, value: Int32(Date().timeIntervalSince1970)) + let presentationData = context.currentPresentationData.with { $0 } + presentControllerImpl?(textAlertController(context: context, title: presentationData.strings.Notifications_PermissionsSuppressWarningTitle, text: presentationData.strings.Notifications_PermissionsSuppressWarningText, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Notifications_PermissionsKeepDisabled, action: { + ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: context.account.postbox, value: Int32(Date().timeIntervalSince1970)) }), TextAlertAction(type: .defaultAction, title: presentationData.strings.Notifications_PermissionsEnable, action: { - account.telegramApplicationContext.applicationBindings.openSettings() + context.applicationBindings.openSettings() })]), nil) }, updateMessageAlerts: { value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.privateChats.enabled = value return settings }).start() }, updateMessagePreviews: { value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.privateChats.displayPreviews = value return settings }).start() }, updateMessageSound: { value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.privateChats.sound = value return settings }).start() }, updateGroupAlerts: { value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.groupChats.enabled = value return settings }).start() }, updateGroupPreviews: { value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.groupChats.displayPreviews = value return settings }).start() }, updateGroupSound: {value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.groupChats.sound = value return settings }).start() }, updateChannelAlerts: { value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.channels.enabled = value return settings }).start() }, updateChannelPreviews: { value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.channels.displayPreviews = value return settings }).start() }, updateChannelSound: {value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.channels.sound = value return settings }).start() }, updateInAppSounds: { value in - let _ = updateInAppNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateInAppNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.playSounds = value return settings }).start() }, updateInAppVibration: { value in - let _ = updateInAppNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateInAppNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.vibrate = value return settings }).start() }, updateInAppPreviews: { value in - let _ = updateInAppNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateInAppNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.displayPreviews = value return settings }).start() }, updateDisplayNameOnLockscreen: { value in - let _ = updateInAppNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateInAppNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.displayNameOnLockscreen = value return settings }).start() }, updateTotalUnreadCountStyle: { value in - let _ = updateInAppNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateInAppNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.totalUnreadCountDisplayStyle = value ? .raw : .filtered return settings }).start() }, updateIncludeTag: { tag, value in - let _ = updateInAppNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateInAppNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings if !value { settings.totalUnreadCountIncludeTags.remove(tag) @@ -811,25 +811,25 @@ public func notificationsAndSoundsController(account: Account, exceptionsList: N return settings }).start() }, updateTotalUnreadCountCategory: { value in - let _ = updateInAppNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateInAppNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.totalUnreadCountDisplayCategory = value ? .messages : .chats return settings }).start() }, resetNotifications: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) actionSheet.setItemGroups([ActionSheetItemGroup(items: [ ActionSheetButtonItem(title: presentationData.strings.Notifications_Reset, color: .destructive, action: { [weak actionSheet] in actionSheet?.dismissAnimated() - let modifyPeers = account.postbox.transaction { transaction -> Void in + let modifyPeers = context.account.postbox.transaction { transaction -> Void in transaction.resetAllPeerNotificationSettings(TelegramPeerNotificationSettings.defaultSettings) } - let updateGlobal = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { _ in + let updateGlobal = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { _ in return GlobalNotificationSettingsSet.defaultSettings }) - let reset = resetPeerNotificationSettings(network: account.network) + let reset = resetPeerNotificationSettings(network: context.account.network) let signal = combineLatest(modifyPeers, updateGlobal, reset) let _ = signal.start() }) @@ -851,18 +851,18 @@ public func notificationsAndSoundsController(account: Account, exceptionsList: N } }) }, openAppSettings: { - account.telegramApplicationContext.applicationBindings.openSettings() + context.applicationBindings.openSettings() }, updateJoinedNotifications: { value in - let _ = updateGlobalNotificationSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.contactsJoined = value return settings }).start() }) - let preferences = account.postbox.preferencesView(keys: [PreferencesKeys.globalNotifications, ApplicationSpecificPreferencesKeys.inAppNotificationSettings]) + let preferences = context.account.postbox.preferencesView(keys: [PreferencesKeys.globalNotifications, ApplicationSpecificPreferencesKeys.inAppNotificationSettings]) - let exceptionsSignal = Signal.single(exceptionsList) |> then(notificationExceptionsList(network: account.network) |> map(Optional.init)) + let exceptionsSignal = Signal.single(exceptionsList) |> then(notificationExceptionsList(network: context.account.network) |> map(Optional.init)) notificationExceptions.set(exceptionsSignal |> map { list -> (NotificationExceptionMode, NotificationExceptionMode, NotificationExceptionMode) in var users:[PeerId : NotificationExceptionWrapper] = [:] @@ -870,7 +870,7 @@ public func notificationsAndSoundsController(account: Account, exceptionsList: N var channels:[PeerId : NotificationExceptionWrapper] = [:] if let list = list { for (key, value) in list.settings { - if let peer = list.peers[key], !peer.debugDisplayTitle.isEmpty, peer.id != account.peerId { + if let peer = list.peers[key], !peer.debugDisplayTitle.isEmpty, peer.id != context.account.peerId { switch value.muteState { case .default: switch value.messageSound { @@ -911,7 +911,7 @@ public func notificationsAndSoundsController(account: Account, exceptionsList: N if #available(iOSApplicationExtension 10.0, *) { let warningKey = PostboxViewKey.noticeEntry(ApplicationSpecificNotice.notificationsPermissionWarningKey()) notificationsWarningSuppressed.set(.single(true) - |> then(account.postbox.combinedView(keys: [warningKey]) + |> then(context.account.postbox.combinedView(keys: [warningKey]) |> map { combined -> Bool in let timestamp = (combined.views[warningKey] as? NoticeEntryView)?.value.flatMap({ ApplicationSpecificNotice.getTimestampValue($0) }) if let timestamp = timestamp, timestamp > 0 { @@ -922,7 +922,7 @@ public func notificationsAndSoundsController(account: Account, exceptionsList: N })) } - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, preferences, notificationExceptions.get(), DeviceAccess.authorizationStatus(account: account, subject: .notifications), notificationsWarningSuppressed.get()) + let signal = combineLatest(context.presentationData, preferences, notificationExceptions.get(), DeviceAccess.authorizationStatus(account: context.account, subject: .notifications), notificationsWarningSuppressed.get()) |> map { presentationData, view, exceptions, authorizationStatus, warningSuppressed -> (ItemListControllerState, (ItemListNodeState, NotificationsAndSoundsEntry.ItemGenerationArguments)) in let viewSettings: GlobalNotificationSettingsSet @@ -945,7 +945,7 @@ public func notificationsAndSoundsController(account: Account, exceptionsList: N return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, a in controller?.present(c, in: .window(.root), with: a) } diff --git a/TelegramUI/OpenAddContact.swift b/TelegramUI/OpenAddContact.swift index 0771785b8a..aa58f67536 100644 --- a/TelegramUI/OpenAddContact.swift +++ b/TelegramUI/OpenAddContact.swift @@ -3,7 +3,7 @@ import SwiftSignalKit import TelegramCore import Display -func openAddContact(account: Account, firstName: String = "", lastName: String = "", phoneNumber: String, label: String = "_$!!$_", present: @escaping (ViewController, Any?) -> Void, completed: @escaping () -> Void = {}) { +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) |> take(1) |> deliverOnMainQueue).start(next: { value in diff --git a/TelegramUI/OpenChatMessage.swift b/TelegramUI/OpenChatMessage.swift index 65cb66854a..7bbf5a9fed 100644 --- a/TelegramUI/OpenChatMessage.swift +++ b/TelegramUI/OpenChatMessage.swift @@ -151,8 +151,8 @@ func chatMessagePreviewControllerData(account: Account, message: Message, standa return nil } -func openChatMessage(account: Account, 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: account, message: message, navigationController: navigationController, standalone: standalone, reverseMessageGalleryOrder: reverseMessageGalleryOrder, stream: stream, synchronousLoad: false, excludeWebPageMedia: excludeWebPageMedia, actionInteraction: actionInteraction) { +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) { switch mediaData { case let .url(url): openUrl(url) @@ -351,7 +351,7 @@ func openChatMessage(account: Account, message: Message, standalone: Bool, rever return false } -func openChatInstantPage(account: Account, message: Message, navigationController: NavigationController) { +func openChatInstantPage(context: AccountContext, message: Message, navigationController: NavigationController) { for media in message.media { if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { if let _ = content.instantPage { @@ -401,7 +401,7 @@ func openChatInstantPage(account: Account, message: Message, navigationControlle } } -func openChatWallpaper(account: Account, message: Message, present: @escaping (ViewController, Any?) -> Void) { +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) diff --git a/TelegramUI/OpenInActionSheetController.swift b/TelegramUI/OpenInActionSheetController.swift index 98c8cccc53..d4c9bacc2b 100644 --- a/TelegramUI/OpenInActionSheetController.swift +++ b/TelegramUI/OpenInActionSheetController.swift @@ -19,15 +19,14 @@ final class OpenInActionSheetController: ActionSheetController { return self._ready } - init(account: Account, item: OpenInItem, additionalAction: OpenInControllerAction? = nil, openUrl: @escaping (String) -> Void) { - let applicationContext = account.telegramApplicationContext - let presentationData = applicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, item: OpenInItem, additionalAction: OpenInControllerAction? = nil, openUrl: @escaping (String) -> 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.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) } @@ -55,7 +54,7 @@ final class OpenInActionSheetController: ActionSheetController { } var items: [ActionSheetItem] = [] - items.append(OpenInActionSheetItem(postbox: account.postbox, applicationContext: applicationContext, strings: strings, options: availableOpenInOptions(applicationContext: applicationContext, item: item), invokeAction: invokeActionImpl)) + items.append(OpenInActionSheetItem(postbox: context.account.postbox, context: context, strings: strings, options: availableOpenInOptions(context: context, item: item), invokeAction: invokeActionImpl)) if let action = additionalAction { items.append(ActionSheetButtonItem(title: action.title, action: { [weak self] in @@ -85,21 +84,21 @@ final class OpenInActionSheetController: ActionSheetController { private final class OpenInActionSheetItem: ActionSheetItem { let postbox: Postbox - let applicationContext: TelegramApplicationContext + let context: AccountContext let strings: PresentationStrings let options: [OpenInOption] let invokeAction: (OpenInAction) -> Void - init(postbox: Postbox, applicationContext: TelegramApplicationContext, strings: PresentationStrings, options: [OpenInOption], invokeAction: @escaping (OpenInAction) -> Void) { + init(postbox: Postbox, context: AccountContext, strings: PresentationStrings, options: [OpenInOption], invokeAction: @escaping (OpenInAction) -> Void) { self.postbox = postbox - self.applicationContext = applicationContext + self.context = context self.strings = strings self.options = options self.invokeAction = invokeAction } func node(theme: ActionSheetControllerTheme) -> ActionSheetItemNode { - return OpenInActionSheetItemNode(postbox: self.postbox, applicationContext: self.applicationContext, theme: theme, strings: self.strings, options: self.options, invokeAction: self.invokeAction) + return OpenInActionSheetItemNode(postbox: self.postbox, context: self.context, theme: theme, strings: self.strings, options: self.options, invokeAction: self.invokeAction) } func updateNode(_ node: ActionSheetItemNode) { @@ -118,7 +117,7 @@ private final class OpenInActionSheetItemNode: ActionSheetItemNode { let openInNodes: [OpenInAppNode] - init(postbox: Postbox, applicationContext: TelegramApplicationContext, theme: ActionSheetControllerTheme, strings: PresentationStrings, options: [OpenInOption], invokeAction: @escaping (OpenInAction) -> Void) { + init(postbox: Postbox, context: AccountContext, theme: ActionSheetControllerTheme, strings: PresentationStrings, options: [OpenInOption], invokeAction: @escaping (OpenInAction) -> Void) { self.theme = theme self.strings = strings @@ -137,7 +136,7 @@ private final class OpenInActionSheetItemNode: ActionSheetItemNode { self.openInNodes = options.map { option in let node = OpenInAppNode() - node.setup(postbox: postbox, applicationContext: applicationContext, theme: theme, option: option, invokeAction: invokeAction) + node.setup(postbox: postbox, context: context, theme: theme, option: option, invokeAction: invokeAction) return node } @@ -205,7 +204,7 @@ private final class OpenInAppNode : ASDisplayNode { self.addSubnode(self.textNode) } - func setup(postbox: Postbox, applicationContext: TelegramApplicationContext, theme: ActionSheetControllerTheme, option: OpenInOption, invokeAction: @escaping (OpenInAction) -> Void) { + func setup(postbox: Postbox, context: AccountContext, theme: ActionSheetControllerTheme, option: OpenInOption, invokeAction: @escaping (OpenInAction) -> Void) { self.textNode.attributedText = NSAttributedString(string: option.title, font: textFont, textColor: theme.primaryTextColor, paragraphAlignment: .center) let iconSize = CGSize(width: 60.0, height: 60.0) diff --git a/TelegramUI/OpenInOptions.swift b/TelegramUI/OpenInOptions.swift index c1cd52484b..0bdaa2a504 100644 --- a/TelegramUI/OpenInOptions.swift +++ b/TelegramUI/OpenInOptions.swift @@ -43,17 +43,17 @@ final class OpenInOption { } } -func availableOpenInOptions(applicationContext: TelegramApplicationContext, item: OpenInItem) -> [OpenInOption] { - return allOpenInOptions(applicationContext: applicationContext, item: item).filter { option in +func availableOpenInOptions(context: AccountContext, item: OpenInItem) -> [OpenInOption] { + return allOpenInOptions(context: context, item: item).filter { option in if case let .other(_, _, scheme) = option.application { - return applicationContext.applicationBindings.canOpenUrl("\(scheme)://") + return context.applicationBindings.canOpenUrl("\(scheme)://") } else { return true } } } -private func allOpenInOptions(applicationContext: TelegramApplicationContext, item: OpenInItem) -> [OpenInOption] { +private func allOpenInOptions(context: AccountContext, item: OpenInItem) -> [OpenInOption] { var options: [OpenInOption] = [] switch item { case let .url(url): diff --git a/TelegramUI/OpenResolvedUrl.swift b/TelegramUI/OpenResolvedUrl.swift index 0cd5d20bdb..e1b6abbf88 100644 --- a/TelegramUI/OpenResolvedUrl.swift +++ b/TelegramUI/OpenResolvedUrl.swift @@ -20,11 +20,11 @@ private func defaultNavigationForPeerId(_ peerId: PeerId?, navigation: ChatContr } } -func openResolvedUrl(_ resolvedUrl: ResolvedUrl, account: Account, context: OpenURLContext = .generic, navigationController: NavigationController?, openPeer: @escaping (PeerId, ChatControllerInteractionNavigateToPeer) -> Void, sendFile: ((FileMediaReference) -> Void)? = nil, present: @escaping (ViewController, Any?) -> Void, dismissInput: @escaping () -> Void) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } +func openResolvedUrl(_ resolvedUrl: ResolvedUrl, context: AccountContext, urlContext: OpenURLContext = .generic, navigationController: NavigationController?, openPeer: @escaping (PeerId, ChatControllerInteractionNavigateToPeer) -> Void, sendFile: ((FileMediaReference) -> Void)? = nil, present: @escaping (ViewController, Any?) -> Void, dismissInput: @escaping () -> Void) { + let presentationData = context.currentPresentationData.with { $0 } switch resolvedUrl { case let .externalUrl(url): - openExternalUrl(account: account, context: context, url: url, presentationData: account.telegramApplicationContext.currentPresentationData.with { $0 }, applicationContext: account.telegramApplicationContext, navigationController: navigationController, dismissInput: dismissInput) + openExternalUrl(context: context, urlContext: urlContext, url: url, presentationData: context.currentPresentationData.with { $0 }, navigationController: navigationController, dismissInput: dismissInput) case let .peer(peerId, navigation): if let peerId = peerId { openPeer(peerId, defaultNavigationForPeerId(peerId, navigation: navigation)) @@ -35,7 +35,7 @@ func openResolvedUrl(_ resolvedUrl: ResolvedUrl, account: Account, context: Open case let .botStart(peerId, payload): openPeer(peerId, .withBotStartPayload(ChatControllerInitialBotStart(payload: payload, behavior: .interactive))) case let .groupBotStart(botPeerId, payload): - let controller = PeerSelectionController(account: account, filter: [.onlyWriteable, .onlyGroups, .onlyManageable], title: presentationData.strings.UserInfo_InviteBotToGroup) + let controller = PeerSelectionController(context: context, filter: [.onlyWriteable, .onlyGroups, .onlyManageable], title: presentationData.strings.UserInfo_InviteBotToGroup) controller.peerSelected = { [weak controller] peerId in if payload.isEmpty { if peerId.namespace == Namespaces.Peer.CloudGroup { diff --git a/TelegramUI/OpenUrl.swift b/TelegramUI/OpenUrl.swift index b0bb2198ca..381fe0cd80 100644 --- a/TelegramUI/OpenUrl.swift +++ b/TelegramUI/OpenUrl.swift @@ -171,9 +171,9 @@ public enum OpenURLContext { case chat } -public func openExternalUrl(account: Account, context: OpenURLContext = .generic, url: String, forceExternal: Bool = false, presentationData: PresentationData, applicationContext: TelegramApplicationContext, navigationController: NavigationController?, dismissInput: @escaping () -> Void) { +public func openExternalUrl(context: AccountContext, urlContext: OpenURLContext = .generic, url: String, forceExternal: Bool = false, presentationData: PresentationData, navigationController: NavigationController?, dismissInput: @escaping () -> Void) { if forceExternal || url.lowercased().hasPrefix("tel:") || url.lowercased().hasPrefix("calshow:") { - applicationContext.applicationBindings.openUrl(url) + context.applicationBindings.openUrl(url) return } diff --git a/TelegramUI/OverlayPlayerController.swift b/TelegramUI/OverlayPlayerController.swift index 8e8f37fa24..987613581e 100644 --- a/TelegramUI/OverlayPlayerController.swift +++ b/TelegramUI/OverlayPlayerController.swift @@ -5,7 +5,7 @@ import Display import SwiftSignalKit final class OverlayPlayerController: ViewController { - private let account: Account + private let context: AccountContext let peerId: PeerId let type: MediaManagerPlayerType let initialMessageId: MessageId @@ -19,8 +19,8 @@ final class OverlayPlayerController: ViewController { return self.displayNode as! OverlayPlayerControllerNode } - init(account: Account, peerId: PeerId, type: MediaManagerPlayerType, initialMessageId: MessageId, initialOrder: MusicPlaybackSettingsOrder, parentNavigationController: NavigationController?) { - self.account = account + init(context: AccountContext, peerId: PeerId, type: MediaManagerPlayerType, initialMessageId: MessageId, initialOrder: MusicPlaybackSettingsOrder, parentNavigationController: NavigationController?) { + self.context = context self.peerId = peerId self.type = type self.initialMessageId = initialMessageId @@ -39,7 +39,7 @@ final class OverlayPlayerController: ViewController { } override public func loadDisplayNode() { - self.displayNode = OverlayPlayerControllerNode(account: self.account, peerId: self.peerId, type: self.type, initialMessageId: self.initialMessageId, initialOrder: self.initialOrder, requestDismiss: { [weak self] in + self.displayNode = OverlayPlayerControllerNode(context: self.context, peerId: self.peerId, type: self.type, initialMessageId: self.initialMessageId, initialOrder: self.initialOrder, requestDismiss: { [weak self] in self?.dismiss() }, requestShare: { [weak self] messageId in if let strongSelf = self { diff --git a/TelegramUI/OverlayPlayerControllerNode.swift b/TelegramUI/OverlayPlayerControllerNode.swift index 2103833f0d..37e640672b 100644 --- a/TelegramUI/OverlayPlayerControllerNode.swift +++ b/TelegramUI/OverlayPlayerControllerNode.swift @@ -8,7 +8,7 @@ import TelegramCore final class OverlayPlayerControllerNode: ViewControllerTracingNode, UIGestureRecognizerDelegate { let ready = Promise() - private let account: Account + private let context: AccountContext private let peerId: PeerId private let presentationData: PresentationData private let type: MediaManagerPlayerType @@ -33,10 +33,10 @@ final class OverlayPlayerControllerNode: ViewControllerTracingNode, UIGestureRec private let replacementHistoryNodeReadyDisposable = MetaDisposable() - init(account: Account, peerId: PeerId, type: MediaManagerPlayerType, initialMessageId: MessageId, initialOrder: MusicPlaybackSettingsOrder, requestDismiss: @escaping () -> Void, requestShare: @escaping (MessageId) -> Void) { - self.account = account + init(context: AccountContext, peerId: PeerId, type: MediaManagerPlayerType, initialMessageId: MessageId, initialOrder: MusicPlaybackSettingsOrder, requestDismiss: @escaping () -> Void, requestShare: @escaping (MessageId) -> Void) { + self.context = context self.peerId = peerId - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.type = type self.requestDismiss = requestDismiss self.requestShare = requestShare @@ -81,7 +81,7 @@ final class OverlayPlayerControllerNode: ViewControllerTracingNode, UIGestureRec self.contentNode = ASDisplayNode() - self.controlsNode = OverlayPlayerControlsNode(postbox: account.postbox, theme: self.presentationData.theme, status: account.telegramApplicationContext.mediaManager!.musicMediaPlayerState) + self.controlsNode = OverlayPlayerControlsNode(postbox: context.account.postbox, theme: self.presentationData.theme, status: context.mediaManager.musicMediaPlayerState) self.historyBackgroundNode = ASDisplayNode() self.historyBackgroundNode.isLayerBacked = true @@ -100,7 +100,7 @@ final class OverlayPlayerControllerNode: ViewControllerTracingNode, UIGestureRec tagMask = .voiceOrInstantVideo } - self.historyNode = ChatHistoryListNode(account: account, chatLocation: .peer(peerId), tagMask: tagMask, messageId: initialMessageId, controllerInteraction: self.controllerInteraction, selectedMessages: .single(nil), mode: .list(search: false, reversed: currentIsReversed)) + self.historyNode = ChatHistoryListNode(context: context, chatLocation: .peer(peerId), tagMask: tagMask, messageId: initialMessageId, controllerInteraction: self.controllerInteraction, selectedMessages: .single(nil), mode: .list(search: false, reversed: currentIsReversed)) super.init() @@ -148,7 +148,7 @@ final class OverlayPlayerControllerNode: ViewControllerTracingNode, UIGestureRec self.controlsNode.control = { [weak self] action in if let strongSelf = self { - strongSelf.account.telegramApplicationContext.mediaManager?.playlistControl(action, type: strongSelf.type) + strongSelf.context.mediaManager.playlistControl(action, type: strongSelf.type) } } @@ -164,7 +164,7 @@ final class OverlayPlayerControllerNode: ViewControllerTracingNode, UIGestureRec openMessageImpl = { [weak self] id in if let strongSelf = self, strongSelf.isNodeLoaded, let message = strongSelf.historyNode.messageInCurrentHistoryView(id) { - return openChatMessage(account: strongSelf.account, message: message, standalone: false, reverseMessageGalleryOrder: false, navigationController: nil, dismissInput: { }, present: { _, _ in }, transitionNode: { _, _ in return nil }, addToTransitionSurface: { _ in }, openUrl: { _ in }, openPeer: { _, _ in }, callPeer: { _ in }, enqueueMessage: { _ in }, sendSticker: nil, setupTemporaryHiddenMedia: { _, _, _ in }, chatAvatarHiddenMedia: { _, _ in}) + return openChatMessage(context: strongSelf.context, message: message, standalone: false, reverseMessageGalleryOrder: false, navigationController: nil, dismissInput: { }, present: { _, _ in }, transitionNode: { _, _ in return nil }, addToTransitionSurface: { _ in }, openUrl: { _ in }, openPeer: { _, _ in }, callPeer: { _ in }, enqueueMessage: { _ in }, sendSticker: nil, setupTemporaryHiddenMedia: { _, _, _ in }, chatAvatarHiddenMedia: { _, _ in}) } return false } @@ -403,7 +403,7 @@ final class OverlayPlayerControllerNode: ViewControllerTracingNode, UIGestureRec tagMask = .voiceOrInstantVideo } - let historyNode = ChatHistoryListNode(account: self.account, chatLocation: .peer(self.peerId), tagMask: tagMask, messageId: messageId, controllerInteraction: self.controllerInteraction, selectedMessages: .single(nil), mode: .list(search: false, reversed: self.currentIsReversed)) + let historyNode = ChatHistoryListNode(context: self.context, chatLocation: .peer(self.peerId), tagMask: tagMask, messageId: messageId, controllerInteraction: self.controllerInteraction, selectedMessages: .single(nil), mode: .list(search: false, reversed: self.currentIsReversed)) historyNode.preloadPages = true historyNode.stackFromBottom = true historyNode.updateFloatingHeaderOffset = { [weak self] offset, _ in diff --git a/TelegramUI/OverlayUniversalVideoNode.swift b/TelegramUI/OverlayUniversalVideoNode.swift index 3dc20bd44e..bd6cecd461 100644 --- a/TelegramUI/OverlayUniversalVideoNode.swift +++ b/TelegramUI/OverlayUniversalVideoNode.swift @@ -3,6 +3,7 @@ import AsyncDisplayKit import SwiftSignalKit import Display import TelegramCore +import Postbox final class OverlayUniversalVideoNode: OverlayMediaItemNode { private let content: UniversalVideoContent @@ -25,7 +26,7 @@ final class OverlayUniversalVideoNode: OverlayMediaItemNode { } } - init(account: Account, audioSession: ManagedAudioSession, manager: UniversalVideoContentManager, content: UniversalVideoContent, expand: @escaping () -> Void, close: @escaping () -> Void) { + init(postbox: Postbox, audioSession: ManagedAudioSession, manager: UniversalVideoContentManager, content: UniversalVideoContent, expand: @escaping () -> Void, close: @escaping () -> Void) { self.content = content var unminimizeImpl: (() -> Void)? var togglePlayPauseImpl: (() -> Void)? @@ -39,7 +40,7 @@ final class OverlayUniversalVideoNode: OverlayMediaItemNode { }, close: { closeImpl?() }) - self.videoNode = UniversalVideoNode(postbox: account.postbox, audioSession: audioSession, manager: manager, decoration: decoration, content: content, priority: .overlay) + self.videoNode = UniversalVideoNode(postbox: postbox, audioSession: audioSession, manager: manager, decoration: decoration, content: content, priority: .overlay) self.decoration = decoration super.init() diff --git a/TelegramUI/PasscodeOptionsController.swift b/TelegramUI/PasscodeOptionsController.swift index 9ebcd4cfb2..353fcb5345 100644 --- a/TelegramUI/PasscodeOptionsController.swift +++ b/TelegramUI/PasscodeOptionsController.swift @@ -219,7 +219,7 @@ private func passcodeOptionsControllerEntries(presentationData: PresentationData return entries } -func passcodeOptionsController(account: Account) -> ViewController { +func passcodeOptionsController(context: AccountContext) -> ViewController { let initialState = PasscodeOptionsControllerState() let statePromise = ValuePromise(initialState, ignoreRepeated: true) @@ -233,22 +233,22 @@ func passcodeOptionsController(account: Account) -> ViewController { let actionsDisposable = DisposableSet() let passcodeOptionsDataPromise = Promise() - passcodeOptionsDataPromise.set(combineLatest(account.postbox.transaction { transaction -> PostboxAccessChallengeData in + passcodeOptionsDataPromise.set(combineLatest(context.account.postbox.transaction { transaction -> PostboxAccessChallengeData in return transaction.getAccessChallengeData() - }, account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.presentationPasscodeSettings]) |> take(1)) |> map { accessChallenge, preferences -> PasscodeOptionsData in + }, context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.presentationPasscodeSettings]) |> take(1)) |> map { accessChallenge, preferences -> PasscodeOptionsData in return PasscodeOptionsData(accessChallenge: accessChallenge, presentationSettings: (preferences.values[ApplicationSpecificPreferencesKeys.presentationPasscodeSettings] as? PresentationPasscodeSettings) ?? PresentationPasscodeSettings.defaultSettings) }) let arguments = PasscodeOptionsControllerArguments(turnPasscodeOn: { var dismissImpl: (() -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: LegacyControllerPresentation.modal(animateIn: true), theme: presentationData.theme) let controller = TGPasscodeEntryController(context: legacyController.context, style: TGPasscodeEntryControllerStyleDefault, mode: TGPasscodeEntryControllerModeSetupSimple, cancelEnabled: true, allowTouchId: false, attemptData: nil, completion: { result in if let result = result { let challenge = PostboxAccessChallengeData.numericalPassword(value: result, timeout: nil, attempts: nil) - let _ = account.postbox.transaction({ transaction -> Void in + let _ = context.account.postbox.transaction({ transaction -> Void in transaction.setAccessChallengeData(challenge) updatePresentationPasscodeSettingsInternal(transaction: transaction, { current in return current.withUpdatedAutolockTimeout(1 * 60 * 60) @@ -273,14 +273,14 @@ func passcodeOptionsController(account: Account) -> ViewController { legacyController?.dismiss() } }, turnPasscodeOff: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) actionSheet.setItemGroups([ActionSheetItemGroup(items: [ ActionSheetButtonItem(title: presentationData.strings.PasscodeSettings_TurnPasscodeOff, color: .destructive, action: { [weak actionSheet] in actionSheet?.dismissAnimated() let challenge = PostboxAccessChallengeData.none - let _ = account.postbox.transaction({ transaction -> Void in + let _ = context.account.postbox.transaction({ transaction -> Void in transaction.setAccessChallengeData(challenge) }).start() @@ -295,8 +295,8 @@ func passcodeOptionsController(account: Account) -> ViewController { ])]) presentControllerImpl?(actionSheet, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, changePasscode: { - let _ = (account.postbox.transaction({ transaction -> Bool in - switch transaction.getAccessChallengeData() { + let _ = (context.account.postbox.transaction({ transaction -> Bool in + switch transaction.getAccessChallengeData() { case .none, .numericalPassword: return true case .plaintextPassword: @@ -306,12 +306,12 @@ func passcodeOptionsController(account: Account) -> ViewController { |> deliverOnMainQueue).start(next: { isSimple in var dismissImpl: (() -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: LegacyControllerPresentation.modal(animateIn: true), theme: presentationData.theme) let controller = TGPasscodeEntryController(context: legacyController.context, style: TGPasscodeEntryControllerStyleDefault, mode: isSimple ? TGPasscodeEntryControllerModeSetupSimple : TGPasscodeEntryControllerModeSetupComplex, cancelEnabled: true, allowTouchId: false, attemptData: nil, completion: { result in if let result = result { - let _ = account.postbox.transaction({ transaction -> Void in + let _ = context.account.postbox.transaction({ transaction -> Void in var data = transaction.getAccessChallengeData() data = PostboxAccessChallengeData.numericalPassword(value: result, timeout: data.autolockDeadline, attempts: nil) transaction.setAccessChallengeData(data) @@ -335,14 +335,14 @@ func passcodeOptionsController(account: Account) -> ViewController { } }) }, changePasscodeTimeout: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) var items: [ActionSheetItem] = [] let setAction: (Int32?) -> Void = { value in let _ = (passcodeOptionsDataPromise.get() |> take(1)).start(next: { [weak passcodeOptionsDataPromise] data in passcodeOptionsDataPromise?.set(.single(data.withUpdatedPresentationSettings(data.presentationSettings.withUpdatedAutolockTimeout(value)))) - let _ = updatePresentationPasscodeSettingsInteractively(postbox: account.postbox, { current in + let _ = updatePresentationPasscodeSettingsInteractively(postbox: context.account.postbox, { current in return current.withUpdatedAutolockTimeout(value) }).start() }) @@ -376,20 +376,20 @@ func passcodeOptionsController(account: Account) -> ViewController { let _ = (passcodeOptionsDataPromise.get() |> take(1)).start(next: { [weak passcodeOptionsDataPromise] data in passcodeOptionsDataPromise?.set(.single(data.withUpdatedPresentationSettings(data.presentationSettings.withUpdatedEnableBiometrics(value)))) - let _ = updatePresentationPasscodeSettingsInteractively(postbox: account.postbox, { current in + let _ = updatePresentationPasscodeSettingsInteractively(postbox: context.account.postbox, { current in return current.withUpdatedEnableBiometrics(value) }).start() }) }, toggleSimplePasscode: { value in var dismissImpl: (() -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: LegacyControllerPresentation.modal(animateIn: true), theme: presentationData.theme) let controller = TGPasscodeEntryController(context: legacyController.context, style: TGPasscodeEntryControllerStyleDefault, mode: value ? TGPasscodeEntryControllerModeSetupSimple : TGPasscodeEntryControllerModeSetupComplex, cancelEnabled: true, allowTouchId: false, attemptData: nil, completion: { result in if let result = result { let challenge = value ? PostboxAccessChallengeData.numericalPassword(value: result, timeout: nil, attempts: nil) : PostboxAccessChallengeData.plaintextPassword(value: result, timeout: nil, attempts: nil) - let _ = account.postbox.transaction({ transaction -> Void in + let _ = context.account.postbox.transaction({ transaction -> Void in transaction.setAccessChallengeData(challenge) updatePresentationPasscodeSettingsInternal(transaction: transaction, { current in return current.withUpdatedAutolockTimeout(1 * 60 * 60) @@ -414,7 +414,7 @@ func passcodeOptionsController(account: Account) -> ViewController { } }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), passcodeOptionsDataPromise.get()) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, statePromise.get(), passcodeOptionsDataPromise.get()) |> deliverOnMainQueue |> map { presentationData, state, passcodeOptionsData -> (ItemListControllerState, (ItemListNodeState, PasscodeOptionsEntry.ItemGenerationArguments)) in let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.PasscodeSettings_Title), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: false) @@ -425,7 +425,7 @@ func passcodeOptionsController(account: Account) -> ViewController { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, p in if let controller = controller { controller.present(c, in: .window(.root), with: p) @@ -435,8 +435,8 @@ func passcodeOptionsController(account: Account) -> ViewController { return controller } -public func passcodeOptionsAccessController(account: Account, animateIn: Bool = true, completion: @escaping (Bool) -> Void) -> Signal { - return account.postbox.transaction { transaction -> PostboxAccessChallengeData in +public func passcodeOptionsAccessController(context: AccountContext, animateIn: Bool = true, completion: @escaping (Bool) -> Void) -> Signal { + return context.account.postbox.transaction { transaction -> PostboxAccessChallengeData in return transaction.getAccessChallengeData() } |> deliverOnMainQueue @@ -451,7 +451,7 @@ public func passcodeOptionsAccessController(account: Account, animateIn: Bool = } var dismissImpl: (() -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: LegacyControllerPresentation.modal(animateIn: true), theme: presentationData.theme) let mode: TGPasscodeEntryControllerMode @@ -482,7 +482,7 @@ public func passcodeOptionsAccessController(account: Account, animateIn: Bool = } } controller.updateAttemptData = { attemptData in - let _ = account.postbox.transaction({ transaction -> Void in + let _ = context.account.postbox.transaction({ transaction -> Void in var attempts: AccessChallengeAttempts? if let attemptData = attemptData { attempts = AccessChallengeAttempts(count: Int32(attemptData.numberOfInvalidAttempts), timestamp: Int32(attemptData.dateOfLastInvalidAttempt)) @@ -510,8 +510,8 @@ public func passcodeOptionsAccessController(account: Account, animateIn: Bool = } } -public func passcodeEntryController(account: Account, animateIn: Bool = true, completion: @escaping (Bool) -> Void) -> Signal { - return account.postbox.transaction { transaction -> (PostboxAccessChallengeData, PresentationPasscodeSettings?) in +public func passcodeEntryController(context: AccountContext, animateIn: Bool = true, completion: @escaping (Bool) -> Void) -> Signal { + return context.account.postbox.transaction { transaction -> (PostboxAccessChallengeData, PresentationPasscodeSettings?) in let passcodeSettings = transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.presentationPasscodeSettings) as? PresentationPasscodeSettings return (transaction.getAccessChallengeData(), passcodeSettings) } @@ -527,7 +527,7 @@ public func passcodeEntryController(account: Account, animateIn: Bool = true, co } var dismissImpl: (() -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: LegacyControllerPresentation.modal(animateIn: true), theme: presentationData.theme) let mode: TGPasscodeEntryControllerMode @@ -562,7 +562,7 @@ public func passcodeEntryController(account: Account, animateIn: Bool = true, co } } controller.updateAttemptData = { attemptData in - let _ = account.postbox.transaction({ transaction -> Void in + let _ = context.account.postbox.transaction({ transaction -> Void in var attempts: AccessChallengeAttempts? if let attemptData = attemptData { attempts = AccessChallengeAttempts(count: Int32(attemptData.numberOfInvalidAttempts), timestamp: Int32(attemptData.dateOfLastInvalidAttempt)) diff --git a/TelegramUI/PeerAvatar.swift b/TelegramUI/PeerAvatar.swift index 4dd947442a..05b194cdce 100644 --- a/TelegramUI/PeerAvatar.swift +++ b/TelegramUI/PeerAvatar.swift @@ -88,7 +88,7 @@ func peerAvatarImage(account: Account, peer: Peer, authorOfMessage: MessageRefer if synchronousLoad { return generate } else { - return generate |> runOn(account.graphicsThreadPool) + return generate |> runOn(Queue.concurrentDefaultQueue()) } } } else { diff --git a/TelegramUI/PeerAvatarImageGalleryItem.swift b/TelegramUI/PeerAvatarImageGalleryItem.swift index ec9d61cdb3..6a8f151284 100644 --- a/TelegramUI/PeerAvatarImageGalleryItem.swift +++ b/TelegramUI/PeerAvatarImageGalleryItem.swift @@ -34,14 +34,14 @@ private struct PeerAvatarImageGalleryThumbnailItem: GalleryThumbnailItem { } class PeerAvatarImageGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let peer: Peer let presentationData: PresentationData let entry: AvatarGalleryEntry let delete: (() -> Void)? - init(account: Account, peer: Peer, presentationData: PresentationData, entry: AvatarGalleryEntry, delete: (() -> Void)?) { - self.account = account + init(context: AccountContext, peer: Peer, presentationData: PresentationData, entry: AvatarGalleryEntry, delete: (() -> Void)?) { + self.context = context self.peer = peer self.presentationData = presentationData self.entry = entry @@ -49,7 +49,7 @@ class PeerAvatarImageGalleryItem: GalleryItem { } func node() -> GalleryItemNode { - let node = PeerAvatarImageGalleryItemNode(account: self.account, presentationData: self.presentationData, peer: self.peer) + let node = PeerAvatarImageGalleryItemNode(context: self.context, presentationData: self.presentationData, peer: self.peer) if let indexData = self.entry.indexData { node._title.set(.single("\(indexData.position + 1) \(self.presentationData.strings.Common_of) \(indexData.totalCount)")) @@ -81,12 +81,12 @@ class PeerAvatarImageGalleryItem: GalleryItem { content = representations } - return (0, PeerAvatarImageGalleryThumbnailItem(account: self.account, peer: self.peer, content: content)) + return (0, PeerAvatarImageGalleryThumbnailItem(account: self.context.account, peer: self.peer, content: content)) } } final class PeerAvatarImageGalleryItemNode: ZoomableContentGalleryItemNode { - private let account: Account + private let context: AccountContext private let peer: Peer private var entry: AvatarGalleryEntry? @@ -102,12 +102,12 @@ final class PeerAvatarImageGalleryItemNode: ZoomableContentGalleryItemNode { private let statusDisposable = MetaDisposable() private var status: MediaResourceStatus? - init(account: Account, presentationData: PresentationData, peer: Peer) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, peer: Peer) { + self.context = context self.peer = peer self.imageNode = TransformImageNode() - self.footerContentNode = AvatarGalleryItemFooterContentNode(account: account, presentationData: presentationData) + self.footerContentNode = AvatarGalleryItemFooterContentNode(context: context, presentationData: presentationData) self.statusNodeContainer = HighlightableButtonNode() self.statusNode = RadialStatusNode(backgroundNodeColor: UIColor(white: 0.0, alpha: 0.5)) @@ -130,7 +130,7 @@ final class PeerAvatarImageGalleryItemNode: ZoomableContentGalleryItemNode { self.footerContentNode.share = { [weak self] interaction in if let strongSelf = self, let entry = strongSelf.entry, !entry.representations.isEmpty { - let shareController = ShareController(account: strongSelf.account, subject: .image(entry.representations), preferredAction: .saveToCameraRoll) + let shareController = ShareController(context: strongSelf.context, subject: .image(entry.representations), preferredAction: .saveToCameraRoll) interaction.presentController(shareController, nil) } } @@ -169,13 +169,13 @@ final class PeerAvatarImageGalleryItemNode: ZoomableContentGalleryItemNode { case let .image(_, imageRepresentations, _, _, _): representations = imageRepresentations } - self.imageNode.setSignal(chatAvatarGalleryPhoto(account: account, representations: representations), dispatchOnDisplayLink: false) + self.imageNode.setSignal(chatAvatarGalleryPhoto(account: self.context.account, representations: representations), dispatchOnDisplayLink: false) self.zoomableContent = (largestSize.dimensions, self.imageNode) if let largestIndex = representations.index(where: { $0.representation == largestSize }) { - self.fetchDisposable.set(fetchedMediaResource(postbox: self.account.postbox, reference: representations[largestIndex].reference).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: self.context.account.postbox, reference: representations[largestIndex].reference).start()) } - self.statusDisposable.set((account.postbox.mediaBox.resourceStatus(largestSize.resource) + self.statusDisposable.set((self.context.account.postbox.mediaBox.resourceStatus(largestSize.resource) |> deliverOnMainQueue).start(next: { [weak self] status in if let strongSelf = self { let previousStatus = strongSelf.status @@ -328,7 +328,7 @@ final class PeerAvatarImageGalleryItemNode: ZoomableContentGalleryItemNode { if let entry = self.entry, let largestSize = largestImageRepresentation(entry.representations.map({ $0.representation })), let status = self.status { switch status { case .Fetching: - self.account.postbox.mediaBox.cancelInteractiveResourceFetch(largestSize.resource) + self.context.account.postbox.mediaBox.cancelInteractiveResourceFetch(largestSize.resource) case .Remote: let representations: [ImageRepresentationWithReference] switch entry { @@ -339,7 +339,7 @@ final class PeerAvatarImageGalleryItemNode: ZoomableContentGalleryItemNode { } if let largestIndex = representations.index(where: { $0.representation == largestSize }) { - self.fetchDisposable.set(fetchedMediaResource(postbox: self.account.postbox, reference: representations[largestIndex].reference).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: self.context.account.postbox, reference: representations[largestIndex].reference).start()) } default: break diff --git a/TelegramUI/PeerBanTimeoutController.swift b/TelegramUI/PeerBanTimeoutController.swift index f0fe99fa3b..bbe0c3cdad 100644 --- a/TelegramUI/PeerBanTimeoutController.swift +++ b/TelegramUI/PeerBanTimeoutController.swift @@ -13,8 +13,8 @@ final class PeerBanTimeoutController: 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 @@ -22,7 +22,7 @@ final class PeerBanTimeoutController: ActionSheetController { self._ready.set(.single(true)) - 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/PeerInfoController.swift b/TelegramUI/PeerInfoController.swift index fce3894669..288bebafe9 100644 --- a/TelegramUI/PeerInfoController.swift +++ b/TelegramUI/PeerInfoController.swift @@ -4,22 +4,17 @@ import Postbox import SwiftSignalKit import TelegramCore - -/* - - */ - -func peerInfoController(account: Account, peer: Peer) -> ViewController? { +func peerInfoController(context: AccountContext, peer: Peer) -> ViewController? { if let _ = peer as? TelegramGroup { - return groupInfoController(account: account, peerId: peer.id) + return groupInfoController(context: context, peerId: peer.id) } else if let channel = peer as? TelegramChannel { if case .group = channel.info { - return groupInfoController(account: account, peerId: peer.id) + return groupInfoController(context: context, peerId: peer.id) } else { - return channelInfoController(account: account, peerId: peer.id) + return channelInfoController(context: context, peerId: peer.id) } } else if peer is TelegramUser || peer is TelegramSecretChat { - return userInfoController(account: account, peerId: peer.id) + return userInfoController(context: context, peerId: peer.id) } return nil } diff --git a/TelegramUI/PeerMediaCollectionController.swift b/TelegramUI/PeerMediaCollectionController.swift index 110613bc56..d3fc974308 100644 --- a/TelegramUI/PeerMediaCollectionController.swift +++ b/TelegramUI/PeerMediaCollectionController.swift @@ -10,7 +10,7 @@ import SafariServices public class PeerMediaCollectionController: TelegramController { private var validLayout: ContainerViewLayout? - private let account: Account + private let context: AccountContext private let peerId: PeerId private let messageId: MessageId? @@ -39,15 +39,15 @@ public class PeerMediaCollectionController: TelegramController { private var resolveUrlDisposable: MetaDisposable? - public init(account: Account, peerId: PeerId, messageId: MessageId? = nil) { - self.account = account + public init(context: AccountContext, peerId: PeerId, messageId: MessageId? = nil) { + self.context = context self.peerId = peerId self.messageId = messageId - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.interfaceState = PeerMediaCollectionInterfaceState(theme: self.presentationData.theme, strings: self.presentationData.strings) - super.init(account: account, navigationBarPresentationData: NavigationBarPresentationData(theme: NavigationBarTheme(rootControllerTheme: self.presentationData.theme).withUpdatedSeparatorColor(self.presentationData.theme.rootController.navigationBar.backgroundColor), strings: NavigationBarStrings(presentationStrings: self.presentationData.strings)), mediaAccessoryPanelVisibility: .specific(size: .compact), locationBroadcastPanelSource: .none) + super.init(context: context, navigationBarPresentationData: NavigationBarPresentationData(theme: NavigationBarTheme(rootControllerTheme: self.presentationData.theme).withUpdatedSeparatorColor(self.presentationData.theme.rootController.navigationBar.backgroundColor), strings: NavigationBarStrings(presentationStrings: self.presentationData.strings)), mediaAccessoryPanelVisibility: .specific(size: .compact), locationBroadcastPanelSource: .none) self.title = self.presentationData.strings.SharedMedia_TitleAll @@ -63,7 +63,7 @@ public class PeerMediaCollectionController: TelegramController { } } - 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 @@ -84,7 +84,7 @@ public class PeerMediaCollectionController: TelegramController { return false } strongSelf.mediaCollectionDisplayNode.view.endEditing(true) - return openChatMessage(account: account, message: galleryMessage.message, standalone: false, reverseMessageGalleryOrder: true, excludeWebPageMedia: mode == .shared, navigationController: navigationController, dismissInput: { + return openChatMessage(context: context, message: galleryMessage.message, standalone: false, reverseMessageGalleryOrder: true, excludeWebPageMedia: mode == .shared, navigationController: navigationController, dismissInput: { self?.mediaCollectionDisplayNode.view.endEditing(true) }, present: { c, a in self?.present(c, in: .window(.root), with: a, blockInteraction: true) @@ -108,10 +108,8 @@ public class PeerMediaCollectionController: TelegramController { } return false }, openPeer: { [weak self] id, navigation, _ in - if let strongSelf = self { - if let id = id { - (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(account: strongSelf.account, chatLocation: .peer(id), messageId: nil)) - } + if let strongSelf = self, let id = id, let navigationController = strongSelf.navigationController as? NavigationController { + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(id)) } }, openPeerMention: { _ in }, openMessageContextMenu: { [weak self] message, _, _, _ in @@ -125,7 +123,7 @@ public class PeerMediaCollectionController: TelegramController { ActionSheetButtonItem(title: strongSelf.presentationData.strings.SharedMedia_ViewInChat, color: .accent, action: { [weak actionSheet] in actionSheet?.dismissAnimated() if let strongSelf = self, let navigationController = strongSelf.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(strongSelf.peerId), messageId: message.id) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(strongSelf.peerId), messageId: message.id) } }), ActionSheetButtonItem(title: strongSelf.presentationData.strings.Conversation_ContextMenuForward, color: .accent, action: { [weak actionSheet] in @@ -170,7 +168,7 @@ public class PeerMediaCollectionController: TelegramController { } }*/ } else { - (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(account: strongSelf.account, chatLocation: .peer(id.peerId), messageId: id)) + (strongSelf.navigationController as? NavigationController)?.pushViewController(ChatController(context: strongSelf.context, chatLocation: .peer(id.peerId), messageId: id)) } } }, clickThroughMessage: { [weak self] in @@ -191,11 +189,11 @@ public class PeerMediaCollectionController: TelegramController { }, sendBotCommand: { _, _ in }, openInstantPage: { [weak self] message in if let strongSelf = self, strongSelf.isNodeLoaded, let navigationController = strongSelf.navigationController as? NavigationController, let message = strongSelf.mediaCollectionDisplayNode.messageForGallery(message.id)?.message { - openChatInstantPage(account: strongSelf.account, message: message, navigationController: navigationController) + openChatInstantPage(context: strongSelf.context, message: message, navigationController: navigationController) } }, openWallpaper: { [weak self] message in if let strongSelf = self, strongSelf.isNodeLoaded, let message = strongSelf.mediaCollectionDisplayNode.messageForGallery(message.id)?.message { - openChatWallpaper(account: strongSelf.account, message: message, present: { [weak self] c, a in + openChatWallpaper(context: strongSelf.context, message: message, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a, blockInteraction: true) }) } @@ -212,7 +210,7 @@ public class PeerMediaCollectionController: TelegramController { strongSelf.view.endEditing(true) switch content { case let .url(url): - let canOpenIn = availableOpenInOptions(applicationContext: strongSelf.account.telegramApplicationContext, item: .url(url: url)).count > 1 + let canOpenIn = availableOpenInOptions(context: strongSelf.context, item: .url(url: url)).count > 1 let openText = canOpenIn ? strongSelf.presentationData.strings.Conversation_FileOpenIn : strongSelf.presentationData.strings.Conversation_LinkDialogOpen let actionSheet = ActionSheetController(presentationTheme: strongSelf.presentationData.theme) actionSheet.setItemGroups([ActionSheetItemGroup(items: [ @@ -220,9 +218,7 @@ public class PeerMediaCollectionController: TelegramController { ActionSheetButtonItem(title: openText, color: .accent, action: { [weak actionSheet] in actionSheet?.dismissAnimated() if let strongSelf = self { - if let applicationContext = strongSelf.account.applicationContext as? TelegramApplicationContext { - applicationContext.applicationBindings.openUrl(url) - } + strongSelf.context.applicationBindings.openUrl(url) } }), ActionSheetButtonItem(title: strongSelf.presentationData.strings.ShareMenu_CopyShareLink, color: .accent, action: { [weak actionSheet] in @@ -273,7 +269,7 @@ public class PeerMediaCollectionController: TelegramController { } }, reportSelectedMessages: { [weak self] in if let strongSelf = self, let messageIds = strongSelf.interfaceState.selectionState?.selectedIds, !messageIds.isEmpty { - strongSelf.present(peerReportOptionsController(account: strongSelf.account, subject: .messages(Array(messageIds).sorted()), present: { c, a in + strongSelf.present(peerReportOptionsController(context: strongSelf.context, subject: .messages(Array(messageIds).sorted()), present: { c, a in self?.present(c, in: .window(.root), with: a) }), in: .window(.root)) } @@ -288,7 +284,7 @@ public class PeerMediaCollectionController: TelegramController { }, forwardMessages: { _ in }, shareSelectedMessages: { [weak self] in if let strongSelf = self, let selectedIds = strongSelf.interfaceState.selectionState?.selectedIds, !selectedIds.isEmpty { - let _ = (strongSelf.account.postbox.transaction { transaction -> [Message] in + let _ = (strongSelf.context.account.postbox.transaction { transaction -> [Message] in var messages: [Message] = [] for id in selectedIds { if let message = transaction.getMessage(id) { @@ -302,7 +298,7 @@ public class PeerMediaCollectionController: TelegramController { $0.withoutSelectionState() }) - let shareController = ShareController(account: strongSelf.account, subject: .messages(messages.sorted(by: { lhs, rhs in + let shareController = ShareController(context: strongSelf.context, subject: .messages(messages.sorted(by: { lhs, rhs in return MessageIndex(lhs) < MessageIndex(rhs) })), externalShare: true, immediateExternalShare: true) strongSelf.present(shareController, in: .window(.root)) @@ -358,7 +354,7 @@ public class PeerMediaCollectionController: TelegramController { self.updateInterfaceState(animated: false, { return $0 }) - self.peer.set(account.postbox.peerView(id: peerId) |> map { $0.peers[$0.peerId] }) + self.peer.set(context.account.postbox.peerView(id: peerId) |> map { $0.peers[$0.peerId] }) peerDisposable.set((self.peer.get() |> deliverOnMainQueue).start(next: { [weak self] peer in @@ -405,35 +401,34 @@ public class PeerMediaCollectionController: TelegramController { } override public func loadDisplayNode() { - self.displayNode = PeerMediaCollectionControllerNode(account: self.account, peerId: self.peerId, messageId: self.messageId, controllerInteraction: self.controllerInteraction!, interfaceInteraction: self.interfaceInteraction!, navigationBar: self.navigationBar, requestDeactivateSearch: { [weak self] in + self.displayNode = PeerMediaCollectionControllerNode(context: self.context, peerId: self.peerId, messageId: self.messageId, controllerInteraction: self.controllerInteraction!, interfaceInteraction: self.interfaceInteraction!, navigationBar: self.navigationBar, requestDeactivateSearch: { [weak self] in self?.deactivateSearch() }) - if let mediaManager = self.account.telegramApplicationContext.mediaManager { - self.galleryHiddenMesageAndMediaDisposable.set(mediaManager.galleryHiddenMediaManager.hiddenIds().start(next: { [weak self] ids in - if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { - var messageIdAndMedia: [MessageId: [Media]] = [:] - - for id in ids { - if case let .chat(messageId, media) = id { - messageIdAndMedia[messageId] = [media] - } + let mediaManager = self.context.mediaManager + self.galleryHiddenMesageAndMediaDisposable.set(mediaManager.galleryHiddenMediaManager.hiddenIds().start(next: { [weak self] ids in + if let strongSelf = self, let controllerInteraction = strongSelf.controllerInteraction { + var messageIdAndMedia: [MessageId: [Media]] = [:] + + for id in ids { + if case let .chat(messageId, media) = id { + messageIdAndMedia[messageId] = [media] } - - //if controllerInteraction.hiddenMedia != messageIdAndMedia { - controllerInteraction.hiddenMedia = messageIdAndMedia - - strongSelf.mediaCollectionDisplayNode.historyNode.forEachItemNode { itemNode in - if let itemNode = itemNode as? GridMessageItemNode { - itemNode.updateHiddenMedia() - } else if let itemNode = itemNode as? ListMessageNode { - itemNode.updateHiddenMedia() - } - } - //} } - })) - } + + //if controllerInteraction.hiddenMedia != messageIdAndMedia { + controllerInteraction.hiddenMedia = messageIdAndMedia + + strongSelf.mediaCollectionDisplayNode.historyNode.forEachItemNode { itemNode in + if let itemNode = itemNode as? GridMessageItemNode { + itemNode.updateHiddenMedia() + } else if let itemNode = itemNode as? ListMessageNode { + itemNode.updateHiddenMedia() + } + } + //} + } + })) self.ready.set(combineLatest(self.mediaCollectionDisplayNode.historyNode.historyState.get(), self._peerReady.get()) |> map { $1 }) @@ -549,31 +544,31 @@ public class PeerMediaCollectionController: TelegramController { if external { resolvedUrl = .single(.externalUrl(url)) } else { - resolvedUrl = resolveUrl(account: self.account, url: url) + resolvedUrl = resolveUrl(account: self.context.account, url: url) } disposable.set((resolvedUrl |> deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { - openResolvedUrl(result, account: strongSelf.account, navigationController: strongSelf.navigationController as? NavigationController, openPeer: { peerId, navigation in + openResolvedUrl(result, context: strongSelf.context, navigationController: strongSelf.navigationController as? NavigationController, openPeer: { peerId, navigation in if let strongSelf = self { switch navigation { case let .chat(_, messageId): if let navigationController = strongSelf.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(peerId), messageId: messageId, keepStack: .always) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peerId), messageId: messageId, keepStack: .always) } case .info: - strongSelf.navigationActionDisposable.set((strongSelf.account.postbox.loadedPeerWithId(peerId) + strongSelf.navigationActionDisposable.set((strongSelf.context.account.postbox.loadedPeerWithId(peerId) |> take(1) |> deliverOnMainQueue).start(next: { [weak self] peer in if let strongSelf = self, peer.restrictionText == nil { - if let infoController = peerInfoController(account: strongSelf.account, peer: peer) { + if let infoController = peerInfoController(context: strongSelf.context, peer: peer) { (strongSelf.navigationController as? NavigationController)?.pushViewController(infoController) } } })) case let .withBotStartPayload(startPayload): if let navigationController = strongSelf.navigationController as? NavigationController { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(peerId), botStart: startPayload) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peerId), botStart: startPayload) } default: break @@ -590,7 +585,7 @@ public class PeerMediaCollectionController: TelegramController { func forwardMessages(_ messageIds: Set) { let currentMessages = (self.mediaCollectionDisplayNode.searchDisplayController?.contentNode as? ChatHistorySearchContainerNode)?.currentMessages - let _ = (self.account.postbox.transaction { transaction -> Void in + let _ = (self.context.account.postbox.transaction { transaction -> Void in for id in messageIds { if transaction.getMessage(id) == nil { if let message = currentMessages?[id] { @@ -605,10 +600,10 @@ public class PeerMediaCollectionController: TelegramController { } let forwardMessageIds = Array(messageIds).sorted() - let controller = PeerSelectionController(account: strongSelf.account) + let controller = PeerSelectionController(context: strongSelf.context) controller.peerSelected = { [weak controller] peerId in if let strongSelf = self, let _ = controller { - let _ = (strongSelf.account.postbox.transaction({ transaction -> Void in + let _ = (strongSelf.context.account.postbox.transaction({ transaction -> Void in transaction.updatePeerChatInterfaceState(peerId, update: { currentState in if let currentState = currentState as? ChatInterfaceState { return currentState.withUpdatedForwardMessageIds(forwardMessageIds) @@ -628,7 +623,7 @@ public class PeerMediaCollectionController: TelegramController { } })) - (strongSelf.navigationController as? NavigationController)?.replaceTopController(ChatController(account: strongSelf.account, chatLocation: .peer(peerId)), animated: false, ready: ready) + (strongSelf.navigationController as? NavigationController)?.replaceTopController(ChatController(context: strongSelf.context, chatLocation: .peer(peerId)), animated: false, ready: ready) } }) } @@ -639,7 +634,7 @@ public class PeerMediaCollectionController: TelegramController { func deleteMessages(_ messageIds: Set) { if !messageIds.isEmpty { - self.messageContextDisposable.set((combineLatest(chatAvailableMessageActions(postbox: self.account.postbox, accountPeerId: self.account.peerId, messageIds: messageIds), self.peer.get() |> take(1)) |> deliverOnMainQueue).start(next: { [weak self] actions, peer in + self.messageContextDisposable.set((combineLatest(chatAvailableMessageActions(postbox: self.context.account.postbox, accountPeerId: self.context.account.peerId, messageIds: messageIds), self.peer.get() |> take(1)) |> deliverOnMainQueue).start(next: { [weak self] actions, peer in if let strongSelf = self, let peer = peer, !actions.options.isEmpty { let actionSheet = ActionSheetController(presentationTheme: strongSelf.presentationData.theme) var items: [ActionSheetItem] = [] @@ -664,13 +659,13 @@ public class PeerMediaCollectionController: TelegramController { actionSheet?.dismissAnimated() if let strongSelf = self { strongSelf.updateInterfaceState(animated: true, { $0.withoutSelectionState() }) - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: Array(messageIds), type: .forEveryone).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: Array(messageIds), type: .forEveryone).start() } })) } if actions.options.contains(.deleteLocally) { var localOptionText = strongSelf.presentationData.strings.Conversation_DeleteMessagesForMe - if strongSelf.account.peerId == strongSelf.peerId { + if strongSelf.context.account.peerId == strongSelf.peerId { if messageIds.count == 1 { localOptionText = strongSelf.presentationData.strings.Conversation_Moderate_Delete } else { @@ -681,7 +676,7 @@ public class PeerMediaCollectionController: TelegramController { actionSheet?.dismissAnimated() if let strongSelf = self { strongSelf.updateInterfaceState(animated: true, { $0.withoutSelectionState() }) - let _ = deleteMessagesInteractively(postbox: strongSelf.account.postbox, messageIds: Array(messageIds), type: .forLocalPeer).start() + let _ = deleteMessagesInteractively(postbox: strongSelf.context.account.postbox, messageIds: Array(messageIds), type: .forLocalPeer).start() } })) } diff --git a/TelegramUI/PeerMediaCollectionControllerNode.swift b/TelegramUI/PeerMediaCollectionControllerNode.swift index 96c547c143..a9e29d9eb5 100644 --- a/TelegramUI/PeerMediaCollectionControllerNode.swift +++ b/TelegramUI/PeerMediaCollectionControllerNode.swift @@ -10,10 +10,10 @@ struct PeerMediaCollectionMessageForGallery { let fromSearchResults: Bool } -private func historyNodeImplForMode(_ mode: PeerMediaCollectionMode, account: Account, theme: PresentationTheme, peerId: PeerId, messageId: MessageId?, controllerInteraction: ChatControllerInteraction, selectedMessages: Signal?, NoError>) -> ChatHistoryNode & ASDisplayNode { +private func historyNodeImplForMode(_ mode: PeerMediaCollectionMode, context: AccountContext, theme: PresentationTheme, peerId: PeerId, messageId: MessageId?, controllerInteraction: ChatControllerInteraction, selectedMessages: Signal?, NoError>) -> ChatHistoryNode & ASDisplayNode { switch mode { case .photoOrVideo: - let node = ChatHistoryGridNode(account: account, peerId: peerId, messageId: messageId, tagMask: .photoOrVideo, controllerInteraction: controllerInteraction) + let node = ChatHistoryGridNode(context: context, peerId: peerId, messageId: messageId, tagMask: .photoOrVideo, controllerInteraction: controllerInteraction) node.showVerticalScrollIndicator = true if theme.list.plainBackgroundColor.argb == 0xffffffff { node.indicatorStyle = .default @@ -22,7 +22,7 @@ private func historyNodeImplForMode(_ mode: PeerMediaCollectionMode, account: Ac } return node case .file: - let node = ChatHistoryListNode(account: account, chatLocation: .peer(peerId), tagMask: .file, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: selectedMessages, mode: .list(search: true, reversed: false)) + let node = ChatHistoryListNode(context: context, chatLocation: .peer(peerId), tagMask: .file, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: selectedMessages, mode: .list(search: true, reversed: false)) node.verticalScrollIndicatorColor = theme.list.scrollIndicatorColor node.didEndScrolling = { [weak node] in guard let node = node else { @@ -33,7 +33,7 @@ private func historyNodeImplForMode(_ mode: PeerMediaCollectionMode, account: Ac node.preloadPages = true return node case .music: - let node = ChatHistoryListNode(account: account, chatLocation: .peer(peerId), tagMask: .music, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: selectedMessages, mode: .list(search: true, reversed: false)) + let node = ChatHistoryListNode(context: context, chatLocation: .peer(peerId), tagMask: .music, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: selectedMessages, mode: .list(search: true, reversed: false)) node.verticalScrollIndicatorColor = theme.list.scrollIndicatorColor node.didEndScrolling = { [weak node] in guard let node = node else { @@ -44,7 +44,7 @@ private func historyNodeImplForMode(_ mode: PeerMediaCollectionMode, account: Ac node.preloadPages = true return node case .webpage: - let node = ChatHistoryListNode(account: account, chatLocation: .peer(peerId), tagMask: .webPage, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: selectedMessages, mode: .list(search: true, reversed: false)) + let node = ChatHistoryListNode(context: context, chatLocation: .peer(peerId), tagMask: .webPage, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: selectedMessages, mode: .list(search: true, reversed: false)) node.verticalScrollIndicatorColor = theme.list.scrollIndicatorColor node.didEndScrolling = { [weak node] in guard let node = node else { @@ -90,7 +90,7 @@ private func tagMaskForMode(_ mode: PeerMediaCollectionMode) -> MessageTags { } class PeerMediaCollectionControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private let peerId: PeerId private let controllerInteraction: ChatControllerInteraction private let interfaceInteraction: ChatPanelInterfaceInteraction @@ -130,8 +130,8 @@ class PeerMediaCollectionControllerNode: ASDisplayNode { private var presentationData: PresentationData - init(account: Account, peerId: PeerId, messageId: MessageId?, controllerInteraction: ChatControllerInteraction, interfaceInteraction: ChatPanelInterfaceInteraction, navigationBar: NavigationBar?, requestDeactivateSearch: @escaping () -> Void) { - self.account = account + init(context: AccountContext, peerId: PeerId, messageId: MessageId?, controllerInteraction: ChatControllerInteraction, interfaceInteraction: ChatPanelInterfaceInteraction, navigationBar: NavigationBar?, requestDeactivateSearch: @escaping () -> Void) { + self.context = context self.peerId = peerId self.controllerInteraction = controllerInteraction self.interfaceInteraction = interfaceInteraction @@ -139,16 +139,16 @@ class PeerMediaCollectionControllerNode: ASDisplayNode { self.requestDeactivateSearch = requestDeactivateSearch - self.presentationData = (account.applicationContext as! TelegramApplicationContext).currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.mediaCollectionInterfaceState = PeerMediaCollectionInterfaceState(theme: self.presentationData.theme, strings: self.presentationData.strings) self.sectionsNode = PeerMediaCollectionSectionsNode(theme: self.presentationData.theme, strings: self.presentationData.strings) - self.historyNode = historyNodeImplForMode(self.mediaCollectionInterfaceState.mode, account: account, theme: self.presentationData.theme, peerId: peerId, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: self.selectedMessagesPromise.get()) + self.historyNode = historyNodeImplForMode(self.mediaCollectionInterfaceState.mode, context: context, theme: self.presentationData.theme, peerId: peerId, messageId: messageId, controllerInteraction: controllerInteraction, selectedMessages: self.selectedMessagesPromise.get()) self.historyEmptyNode = PeerMediaCollectionEmptyNode(mode: self.mediaCollectionInterfaceState.mode, theme: self.presentationData.theme, strings: self.presentationData.strings) self.historyEmptyNode.isHidden = true - self.chatPresentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, chatWallpaperMode: self.presentationData.chatWallpaperMode, theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, fontSize: self.presentationData.fontSize, accountPeerId: account.peerId, mode: .standard(previewing: false), chatLocation: .peer(self.peerId)) + self.chatPresentationInterfaceState = ChatPresentationInterfaceState(chatWallpaper: self.presentationData.chatWallpaper, chatWallpaperMode: self.presentationData.chatWallpaperMode, theme: self.presentationData.theme, strings: self.presentationData.strings, dateTimeFormat: self.presentationData.dateTimeFormat, nameDisplayOrder: self.presentationData.nameDisplayOrder, fontSize: self.presentationData.fontSize, accountPeerId: context.account.peerId, mode: .standard(previewing: false), chatLocation: .peer(self.peerId)) super.init() @@ -267,7 +267,7 @@ class PeerMediaCollectionControllerNode: ASDisplayNode { self.selectionPanelBackgroundNode = selectionPanelBackgroundNode let selectionPanel = ChatMessageSelectionInputPanelNode(theme: self.chatPresentationInterfaceState.theme) - selectionPanel.account = self.account + selectionPanel.account = self.context.account selectionPanel.backgroundColor = self.presentationData.theme.chat.inputPanel.panelBackgroundColor selectionPanel.interfaceInteraction = self.interfaceInteraction selectionPanel.selectedMessages = selectionState.selectedIds @@ -374,7 +374,7 @@ class PeerMediaCollectionControllerNode: ASDisplayNode { } if let placeholderNode = maybePlaceholderNode { - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, mode: .list, contentNode: ChatHistorySearchContainerNode(account: self.account, peerId: self.peerId, tagMask: tagMaskForMode(self.mediaCollectionInterfaceState.mode), interfaceInteraction: self.controllerInteraction), cancel: { [weak self] in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, mode: .list, contentNode: ChatHistorySearchContainerNode(context: self.context, peerId: self.peerId, tagMask: tagMaskForMode(self.mediaCollectionInterfaceState.mode), interfaceInteraction: self.controllerInteraction), cancel: { [weak self] in self?.requestDeactivateSearch() }) @@ -409,7 +409,7 @@ class PeerMediaCollectionControllerNode: ASDisplayNode { if self.mediaCollectionInterfaceState.mode != mediaCollectionInterfaceState.mode { let previousMode = self.mediaCollectionInterfaceState.mode if let containerLayout = self.containerLayout, self.candidateHistoryNode == nil || self.candidateHistoryNode!.1 != mediaCollectionInterfaceState.mode { - let node = historyNodeImplForMode(mediaCollectionInterfaceState.mode, account: self.account, theme: self.presentationData.theme, peerId: self.peerId, messageId: nil, controllerInteraction: self.controllerInteraction, selectedMessages: self.selectedMessagesPromise.get()) + let node = historyNodeImplForMode(mediaCollectionInterfaceState.mode, context: self.context, theme: self.presentationData.theme, peerId: self.peerId, messageId: nil, controllerInteraction: self.controllerInteraction, selectedMessages: self.selectedMessagesPromise.get()) node.backgroundColor = mediaCollectionInterfaceState.theme.list.plainBackgroundColor self.candidateHistoryNode = (node, mediaCollectionInterfaceState.mode) diff --git a/TelegramUI/PeerReportController.swift b/TelegramUI/PeerReportController.swift index 9aae60adb7..5c326448ff 100644 --- a/TelegramUI/PeerReportController.swift +++ b/TelegramUI/PeerReportController.swift @@ -18,8 +18,8 @@ private enum PeerReportOption { case other } -func peerReportOptionsController(account: Account, subject: PeerReportSubject, present: @escaping (ViewController, Any?) -> Void) -> ViewController { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } +func peerReportOptionsController(context: AccountContext, subject: PeerReportSubject, present: @escaping (ViewController, Any?) -> Void) -> ViewController { + let presentationData = context.currentPresentationData.with { $0 } let controller = ActionSheetController(theme: ActionSheetControllerTheme(presentationTheme: presentationData.theme)) let options: [PeerReportOption] = [ @@ -68,7 +68,7 @@ func peerReportOptionsController(account: Account, subject: PeerReportSubject, p if let reportReason = reportReason { switch subject { case let .peer(peerId): - let _ = (reportPeer(account: account, peerId: peerId, reason: reportReason) + let _ = (reportPeer(account: context.account, peerId: peerId, reason: reportReason) |> deliverOnMainQueue).start(completed: { let alert = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.ReportPeer_AlertSuccess, actions: [TextAlertAction.init(type: TextAlertActionType.defaultAction, title: presentationData.strings.Common_OK, action: { @@ -76,7 +76,7 @@ func peerReportOptionsController(account: Account, subject: PeerReportSubject, p present(alert, nil) }) case let .messages(messageIds): - let _ = (reportPeerMessages(account: account, messageIds: messageIds, reason: reportReason) + let _ = (reportPeerMessages(account: context.account, messageIds: messageIds, reason: reportReason) |> deliverOnMainQueue).start(completed: { let alert = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.ReportPeer_AlertSuccess, actions: [TextAlertAction.init(type: TextAlertActionType.defaultAction, title: presentationData.strings.Common_OK, action: { @@ -85,7 +85,7 @@ func peerReportOptionsController(account: Account, subject: PeerReportSubject, p }) } } else { - controller?.present(peerReportController(account: account, subject: subject), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + controller?.present(peerReportController(account: context.account, subject: subject), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } controller?.dismissAnimated() @@ -189,7 +189,7 @@ private func peerReportControllerEntries(presentationData: PresentationData, sta return entries } -private func peerReportController(account: Account, subject: PeerReportSubject) -> ViewController { +private func peerReportController(context: AccountContext, subject: PeerReportSubject) -> ViewController { var dismissImpl: (() -> Void)? var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? @@ -209,7 +209,7 @@ private func peerReportController(account: Account, subject: PeerReportSubject) let reportDisposable = MetaDisposable() - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get()) |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, PeerReportControllerEntry.ItemGenerationArguments)) in let rightButton: ItemListNavigationButton if state.isReporting { @@ -228,7 +228,7 @@ private func peerReportController(account: Account, subject: PeerReportSubject) if !text.isEmpty { let completed: () -> Void = { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let alert = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.ReportPeer_AlertSuccess, actions: [TextAlertAction.init(type: TextAlertActionType.defaultAction, title: presentationData.strings.Common_OK, action: { @@ -238,12 +238,12 @@ private func peerReportController(account: Account, subject: PeerReportSubject) } switch subject { case let .peer(peerId): - reportDisposable.set((reportPeer(account: account, peerId: peerId, reason: .custom(text)) + reportDisposable.set((reportPeer(account: context.account, peerId: peerId, reason: .custom(text)) |> deliverOnMainQueue).start(completed: { completed() })) case let .messages(messageIds): - reportDisposable.set((reportPeerMessages(account: account, messageIds: messageIds, reason: .custom(text)) + reportDisposable.set((reportPeerMessages(account: context.account, messageIds: messageIds, reason: .custom(text)) |> deliverOnMainQueue).start(completed: { completed() })) @@ -263,7 +263,7 @@ private func peerReportController(account: Account, subject: PeerReportSubject) reportDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, a in controller?.present(c, in: .window(.root), with: a) } diff --git a/TelegramUI/PeerSelectionController.swift b/TelegramUI/PeerSelectionController.swift index c209bb3a0d..e79d1673dd 100644 --- a/TelegramUI/PeerSelectionController.swift +++ b/TelegramUI/PeerSelectionController.swift @@ -5,7 +5,7 @@ import TelegramCore import Postbox public final class PeerSelectionController: ViewController { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private var presentationDataDisposable: Disposable? @@ -44,11 +44,11 @@ public final class PeerSelectionController: ViewController { private var searchContentNode: NavigationBarSearchContentNode? - public init(account: Account, filter: ChatListNodePeersFilter = [.onlyWriteable], hasContactSelector: Bool = true, title: String? = nil) { - self.account = account + public init(context: AccountContext, filter: ChatListNodePeersFilter = [.onlyWriteable], hasContactSelector: Bool = true, title: String? = nil) { + self.context = context self.filter = filter self.hasContactSelector = hasContactSelector - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) self.statusBar.statusBarStyle = self.presentationData.theme.rootController.statusBar.style.style @@ -66,7 +66,7 @@ public final class PeerSelectionController: 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 @@ -104,7 +104,7 @@ public final class PeerSelectionController: ViewController { } override public func loadDisplayNode() { - self.displayNode = PeerSelectionControllerNode(account: self.account, filter: self.filter, hasContactSelector: hasContactSelector, present: { [weak self] c, a in + self.displayNode = PeerSelectionControllerNode(context: self.context, filter: self.filter, hasContactSelector: hasContactSelector, present: { [weak self] c, a in self?.present(c, in: .window(.root), with: a) }, dismiss: { [weak self] in self?.presentingViewController?.dismiss(animated: false, completion: nil) @@ -128,7 +128,7 @@ public final class PeerSelectionController: ViewController { self.peerSelectionNode.requestOpenPeerFromSearch = { [weak self] peer in if let strongSelf = self { - let storedPeer = strongSelf.account.postbox.transaction { transaction -> Void in + let storedPeer = strongSelf.context.account.postbox.transaction { transaction -> Void in if transaction.getPeer(peer.id) == nil { updatePeers(transaction: transaction, peers: [peer], update: { previousPeer, updatedPeer in return updatedPeer diff --git a/TelegramUI/PeerSelectionControllerNode.swift b/TelegramUI/PeerSelectionControllerNode.swift index bbe42e6a0a..0d4d2f9277 100644 --- a/TelegramUI/PeerSelectionControllerNode.swift +++ b/TelegramUI/PeerSelectionControllerNode.swift @@ -6,7 +6,7 @@ import TelegramCore import SwiftSignalKit final class PeerSelectionControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private let present: (ViewController, Any?) -> Void private let dismiss: () -> Void private let filter: ChatListNodePeersFilter @@ -49,14 +49,13 @@ final class PeerSelectionControllerNode: ASDisplayNode { return self.readyValue.get() } - - init(account: Account, filter: ChatListNodePeersFilter, hasContactSelector: Bool, present: @escaping (ViewController, Any?) -> Void, dismiss: @escaping () -> Void) { - self.account = account + init(context: AccountContext, filter: ChatListNodePeersFilter, hasContactSelector: Bool, present: @escaping (ViewController, Any?) -> Void, dismiss: @escaping () -> Void) { + self.context = context self.present = present self.dismiss = dismiss self.filter = filter - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } if hasContactSelector { self.toolbarBackgroundNode = ASDisplayNode() @@ -75,7 +74,7 @@ final class PeerSelectionControllerNode: ASDisplayNode { } - self.chatListNode = ChatListNode(account: account, groupId: nil, controlsHistoryPreload: false, mode: .peers(filter: filter), theme: presentationData.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameSortOrder: presentationData.nameSortOrder, nameDisplayOrder: presentationData.nameDisplayOrder, disableAnimations: presentationData.disableAnimations) + self.chatListNode = ChatListNode(context: context, groupId: nil, controlsHistoryPreload: false, mode: .peers(filter: filter), theme: presentationData.theme, strings: presentationData.strings, dateTimeFormat: presentationData.dateTimeFormat, nameSortOrder: presentationData.nameSortOrder, nameDisplayOrder: presentationData.nameDisplayOrder, disableAnimations: presentationData.disableAnimations) super.init() @@ -102,7 +101,7 @@ final class PeerSelectionControllerNode: ASDisplayNode { } self.addSubnode(self.chatListNode) - 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 @@ -217,7 +216,7 @@ final class PeerSelectionControllerNode: ASDisplayNode { } if self.chatListNode.supernode != nil { - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ChatListSearchContainerNode(account: self.account, filter: self.filter, groupId: nil, openPeer: { [weak self] peer, _ in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ChatListSearchContainerNode(context: self.context, filter: self.filter, groupId: nil, openPeer: { [weak self] peer, _ in if let requestOpenPeerFromSearch = self?.requestOpenPeerFromSearch { requestOpenPeerFromSearch(peer) } @@ -244,11 +243,11 @@ final class PeerSelectionControllerNode: ASDisplayNode { }, placeholder: placeholderNode) } else if let contactListNode = self.contactListNode, contactListNode.supernode != nil { - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(account: self.account, onlyWriteable: true, categories: [.cloudContacts, .global], openPeer: { [weak self] peer in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ContactsSearchContainerNode(context: self.context, onlyWriteable: true, categories: [.cloudContacts, .global], openPeer: { [weak self] peer in if let strongSelf = self { switch peer { case let .peer(peer, _): - let _ = (strongSelf.account.postbox.transaction { transaction -> Peer? in + let _ = (strongSelf.context.account.postbox.transaction { transaction -> Peer? in return transaction.getPeer(peer.id) } |> deliverOnMainQueue).start(next: { peer in if let strongSelf = self, let peer = peer { @@ -327,7 +326,7 @@ final class PeerSelectionControllerNode: ASDisplayNode { self.recursivelyEnsureDisplaySynchronously(true) contactListNode.enableUpdates = true } else { - let contactListNode = ContactListNode(account: account, presentation: .single(.natural(options: []))) + let contactListNode = ContactListNode(context: context, presentation: .single(.natural(options: []))) self.contactListNode = contactListNode contactListNode.enableUpdates = true contactListNode.activateSearch = { [weak self] in @@ -340,7 +339,7 @@ final class PeerSelectionControllerNode: ASDisplayNode { } contactListNode.suppressPermissionWarning = { [weak self] in if let strongSelf = self { - presentContactsWarningSuppression(account: strongSelf.account, present: { c, a in + presentContactsWarningSuppression(context: strongSelf.context, present: { c, a in strongSelf.present(c, a) }) } diff --git a/TelegramUI/PermissionController.swift b/TelegramUI/PermissionController.swift index 0ae0eddab0..9af909f11b 100644 --- a/TelegramUI/PermissionController.swift +++ b/TelegramUI/PermissionController.swift @@ -5,7 +5,7 @@ import SwiftSignalKit import TelegramCore public final class PermissionController : ViewController { - private let account: Account + private let context: AccountContext private let splitTest: PermissionUISplitTest private var state: PermissionState? @@ -27,10 +27,10 @@ public final class PermissionController : ViewController { private var skip: (() -> Void)? public var proceed: ((Bool) -> Void)? - public init(account: Account, splitTest: PermissionUISplitTest) { - self.account = account + public init(context: AccountContext, splitTest: PermissionUISplitTest) { + self.context = context self.splitTest = splitTest - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(theme: NavigationBarTheme(buttonColor: self.presentationData.theme.rootController.navigationBar.accentTextColor, disabledButtonColor: self.presentationData.theme.rootController.navigationBar.disabledButtonColor, primaryTextColor: self.presentationData.theme.rootController.navigationBar.primaryTextColor, backgroundColor: .clear, separatorColor: .clear, badgeBackgroundColor: .clear, badgeStrokeColor: .clear, badgeTextColor: .clear), strings: NavigationBarStrings(presentationStrings: self.presentationData.strings))) @@ -38,19 +38,19 @@ public final class PermissionController : ViewController { self.updateThemeAndStrings() - self.presentationDataDisposable = (account.telegramApplicationContext.presentationData - |> deliverOnMainQueue).start(next: { [weak self] presentationData in - if let strongSelf = self { - let previousTheme = strongSelf.presentationData.theme - let previousStrings = strongSelf.presentationData.strings - - strongSelf.presentationData = presentationData - - if previousTheme !== presentationData.theme || previousStrings !== presentationData.strings { - strongSelf.updateThemeAndStrings() - } + self.presentationDataDisposable = (context.presentationData + |> deliverOnMainQueue).start(next: { [weak self] presentationData in + if let strongSelf = self { + let previousTheme = strongSelf.presentationData.theme + let previousStrings = strongSelf.presentationData.strings + + strongSelf.presentationData = presentationData + + if previousTheme !== presentationData.theme || previousStrings !== presentationData.strings { + strongSelf.updateThemeAndStrings() } - }) + } + }) } required init(coder aDecoder: NSCoder) { @@ -81,7 +81,7 @@ public final class PermissionController : ViewController { } private func openAppSettings() { - self.account.telegramApplicationContext.applicationBindings.openSettings() + self.context.applicationBindings.openSettings() } public func setState(_ state: PermissionState, animated: Bool) { @@ -99,7 +99,7 @@ public final class PermissionController : ViewController { switch status { case .requestable: strongSelf.splitTest.addEvent(.ContactsRequest) - DeviceAccess.authorizeAccess(to: .contacts, account: strongSelf.account, { [weak self] result in + DeviceAccess.authorizeAccess(to: .contacts, account: strongSelf.context.account, { [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.account, { [weak self] result in + DeviceAccess.authorizeAccess(to: .notifications, account: strongSelf.context.account, { [weak self] result in if let strongSelf = self { if result { strongSelf.splitTest.addEvent(.NotificationsAllowed) @@ -160,7 +160,7 @@ public final class PermissionController : ViewController { } public override func loadDisplayNode() { - self.displayNode = PermissionControllerNode(account: self.account, splitTest: self.splitTest) + self.displayNode = PermissionControllerNode(context: self.context, splitTest: self.splitTest) self.displayNodeDidLoad() self.controllerNode.allow = { [weak self] in @@ -168,7 +168,7 @@ public final class PermissionController : ViewController { } self.controllerNode.openPrivacyPolicy = { [weak self] in if let strongSelf = self { - openExternalUrl(account: strongSelf.account, context: .generic, url: "https://telegram.org/privacy", forceExternal: true, presentationData: strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 }, applicationContext: strongSelf.account.telegramApplicationContext, navigationController: nil, dismissInput: {}) + openExternalUrl(context: strongSelf.context, context: .generic, url: "https://telegram.org/privacy", forceExternal: true, presentationData: strongSelf.context.currentPresentationData.with { $0 }, navigationController: nil, dismissInput: {}) } } } diff --git a/TelegramUI/PermissionControllerNode.swift b/TelegramUI/PermissionControllerNode.swift index d14b11fd02..71adb753d2 100644 --- a/TelegramUI/PermissionControllerNode.swift +++ b/TelegramUI/PermissionControllerNode.swift @@ -43,7 +43,7 @@ private func localizedString(for key: String, strings: PresentationStrings, fall } final class PermissionControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let splitTest: PermissionUISplitTest @@ -55,9 +55,9 @@ final class PermissionControllerNode: ASDisplayNode { var openPrivacyPolicy: (() -> Void)? var dismiss: (() -> Void)? - init(account: Account, splitTest: PermissionUISplitTest) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, splitTest: PermissionUISplitTest) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.splitTest = splitTest self.innerState = PermissionControllerInnerState(layout: nil, data: PermissionControllerDataState(state: nil)) diff --git a/TelegramUI/PreparedChatHistoryViewTransition.swift b/TelegramUI/PreparedChatHistoryViewTransition.swift index e834c5be40..686d37ba03 100644 --- a/TelegramUI/PreparedChatHistoryViewTransition.swift +++ b/TelegramUI/PreparedChatHistoryViewTransition.swift @@ -4,7 +4,7 @@ import Postbox import TelegramCore import Display -func preparedChatHistoryViewTransition(from fromView: ChatHistoryView?, to toView: ChatHistoryView, reason: ChatHistoryViewTransitionReason, reverse: Bool, account: Account, chatLocation: ChatLocation, controllerInteraction: ChatControllerInteraction, scrollPosition: ChatHistoryViewScrollPosition?, initialData: InitialMessageHistoryData?, keyboardButtonsMessage: Message?, cachedData: CachedPeerData?, cachedDataMessages: [MessageId: Message]?, readStateData: [PeerId: ChatHistoryCombinedInitialReadStateData]?) -> Signal { +func preparedChatHistoryViewTransition(from fromView: ChatHistoryView?, to toView: ChatHistoryView, reason: ChatHistoryViewTransitionReason, reverse: Bool, chatLocation: ChatLocation, controllerInteraction: ChatControllerInteraction, scrollPosition: ChatHistoryViewScrollPosition?, initialData: InitialMessageHistoryData?, keyboardButtonsMessage: Message?, cachedData: CachedPeerData?, cachedDataMessages: [MessageId: Message]?, readStateData: [PeerId: ChatHistoryCombinedInitialReadStateData]?) -> Signal { return Signal { subscriber in let mergeResult: (deleteIndices: [Int], indicesAndItems: [(Int, ChatHistoryEntry, Int?)], updateIndices: [(Int, ChatHistoryEntry, Int)]) let allUpdated = fromView?.associatedData != toView.associatedData diff --git a/TelegramUI/PrivacyAndSecurityController.swift b/TelegramUI/PrivacyAndSecurityController.swift index 09e2c3064a..f58ee9176e 100644 --- a/TelegramUI/PrivacyAndSecurityController.swift +++ b/TelegramUI/PrivacyAndSecurityController.swift @@ -338,7 +338,7 @@ private func privacyAndSecurityControllerEntries(presentationData: PresentationD return entries } -public func privacyAndSecurityController(account: Account, initialSettings: Signal) -> ViewController { +public func privacyAndSecurityController(context: AccountContext, initialSettings: Signal) -> ViewController { let statePromise = ValuePromise(PrivacyAndSecurityControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: PrivacyAndSecurityControllerState()) let updateState: ((PrivacyAndSecurityControllerState) -> PrivacyAndSecurityControllerState) -> Void = { f in @@ -360,15 +360,15 @@ public func privacyAndSecurityController(account: Account, initialSettings: Sign let privacySettingsPromise = Promise() privacySettingsPromise.set(initialSettings) - let arguments = PrivacyAndSecurityControllerArguments(account: account, openBlockedUsers: { - pushControllerImpl?(blockedPeersController(account: account)) + let arguments = PrivacyAndSecurityControllerArguments(account: context.account, openBlockedUsers: { + pushControllerImpl?(blockedPeersController(context: context)) }, openLastSeenPrivacy: { let signal = privacySettingsPromise.get() |> take(1) |> deliverOnMainQueue currentInfoDisposable.set(signal.start(next: { [weak currentInfoDisposable] info in if let info = info { - pushControllerImpl?(selectivePrivacySettingsController(account: account, kind: .presence, current: info.presence, updated: { updated, _ in + pushControllerImpl?(selectivePrivacySettingsController(context: context, kind: .presence, current: info.presence, updated: { updated, _ in if let currentInfoDisposable = currentInfoDisposable { let applySetting: Signal = privacySettingsPromise.get() |> filter { $0 != nil } @@ -391,7 +391,7 @@ public func privacyAndSecurityController(account: Account, initialSettings: Sign |> deliverOnMainQueue currentInfoDisposable.set(signal.start(next: { [weak currentInfoDisposable] info in if let info = info { - pushControllerImpl?(selectivePrivacySettingsController(account: account, kind: .groupInvitations, current: info.groupInvitations, updated: { updated, _ in + pushControllerImpl?(selectivePrivacySettingsController(context: context, kind: .groupInvitations, current: info.groupInvitations, updated: { updated, _ in if let currentInfoDisposable = currentInfoDisposable { let applySetting: Signal = privacySettingsPromise.get() |> filter { $0 != nil } @@ -412,7 +412,7 @@ public func privacyAndSecurityController(account: Account, initialSettings: Sign let privacySignal = privacySettingsPromise.get() |> take(1) - let callsSignal = account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.voiceCallSettings, PreferencesKeys.voipConfiguration]) + let callsSignal = context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.voiceCallSettings, PreferencesKeys.voipConfiguration]) |> take(1) |> map { view -> (VoiceCallSettings, VoipConfiguration) in let voiceCallSettings: VoiceCallSettings = view.values[ApplicationSpecificPreferencesKeys.voiceCallSettings] as? VoiceCallSettings ?? .defaultSettings @@ -424,9 +424,9 @@ public func privacyAndSecurityController(account: Account, initialSettings: Sign currentInfoDisposable.set((combineLatest(privacySignal, callsSignal) |> deliverOnMainQueue).start(next: { [weak currentInfoDisposable] info, callSettings in if let info = info { - pushControllerImpl?(selectivePrivacySettingsController(account: account, kind: .voiceCalls, current: info.voiceCalls, callSettings: (info.voiceCallsP2P, callSettings.0), voipConfiguration: callSettings.1, callIntegrationAvailable: CallKitIntegration.isAvailable, updated: { updated, updatedCallSettings in + pushControllerImpl?(selectivePrivacySettingsController(context: context, kind: .voiceCalls, current: info.voiceCalls, callSettings: (info.voiceCallsP2P, callSettings.0), voipConfiguration: callSettings.1, callIntegrationAvailable: CallKitIntegration.isAvailable, updated: { updated, updatedCallSettings in if let currentInfoDisposable = currentInfoDisposable, let (updatedCallsPrivacy, updatedCallSettings) = updatedCallSettings { - let _ = updateVoiceCallSettingsSettingsInteractively(postbox: account.postbox, { _ in + let _ = updateVoiceCallSettingsSettingsInteractively(postbox: context.account.postbox, { _ in return updatedCallSettings }).start() @@ -446,11 +446,11 @@ public func privacyAndSecurityController(account: Account, initialSettings: Sign } })) }, openPasscode: { - let _ = passcodeOptionsAccessController(account: account, completion: { animated in + let _ = passcodeOptionsAccessController(context: context, completion: { animated in if animated { - pushControllerImpl?(passcodeOptionsController(account: account)) + pushControllerImpl?(passcodeOptionsController(context: context)) } else { - pushControllerInstantImpl?(passcodeOptionsController(account: account)) + pushControllerInstantImpl?(passcodeOptionsController(context: context)) } }).start(next: { controller in if let controller = controller { @@ -458,16 +458,16 @@ public func privacyAndSecurityController(account: Account, initialSettings: Sign } }) }, openTwoStepVerification: { - pushControllerImpl?(twoStepVerificationUnlockSettingsController(account: account, mode: .access)) + pushControllerImpl?(twoStepVerificationUnlockSettingsController(context: context, mode: .access)) }, openActiveSessions: { - pushControllerImpl?(recentSessionsController(account: account)) + pushControllerImpl?(recentSessionsController(context: context)) }, setupAccountAutoremove: { let signal = privacySettingsPromise.get() |> take(1) |> deliverOnMainQueue updateAccountTimeoutDisposable.set(signal.start(next: { [weak updateAccountTimeoutDisposable] privacySettingsValue in if let _ = privacySettingsValue { - 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() @@ -489,7 +489,7 @@ public func privacyAndSecurityController(account: Account, initialSettings: Sign } return .complete() } - updateAccountTimeoutDisposable.set((updateAccountRemovalTimeout(account: account, timeout: timeout) + updateAccountTimeoutDisposable.set((updateAccountRemovalTimeout(account: context.account, timeout: timeout) |> then(applyTimeout) |> deliverOnMainQueue).start(completed: { updateState { state in @@ -520,16 +520,16 @@ public func privacyAndSecurityController(account: Account, initialSettings: Sign } })) }, openDataSettings: { - pushControllerImpl?(dataPrivacyController(account: account)) + pushControllerImpl?(dataPrivacyController(context: context)) }) let previousState = Atomic(value: nil) let preferencesKey = PostboxViewKey.preferences(keys: Set([ApplicationSpecificPreferencesKeys.contactSynchronizationSettings])) - actionsDisposable.add(managedUpdatedRecentPeers(accountPeerId: account.peerId, postbox: account.postbox, network: account.network).start()) + actionsDisposable.add(managedUpdatedRecentPeers(accountPeerId: context.account.peerId, postbox: context.account.postbox, network: context.account.network).start()) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, privacySettingsPromise.get(), account.postbox.combinedView(keys: [.noticeEntry(ApplicationSpecificNotice.secretChatLinkPreviewsKey()), preferencesKey]), recentPeers(account: account)) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, privacySettingsPromise.get(), context.account.postbox.combinedView(keys: [.noticeEntry(ApplicationSpecificNotice.secretChatLinkPreviewsKey()), preferencesKey]), recentPeers(account: context.account)) |> map { presentationData, state, privacySettings, combined, recentPeers -> (ItemListControllerState, (ItemListNodeState, PrivacyAndSecurityEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? if privacySettings == nil || state.updatingAccountTimeoutValue != nil { @@ -548,7 +548,7 @@ public func privacyAndSecurityController(account: Account, initialSettings: Sign actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] c in (controller?.navigationController as? NavigationController)?.pushViewController(c) } diff --git a/TelegramUI/ProxyListSettingsController.swift b/TelegramUI/ProxyListSettingsController.swift index 69d306d466..57568007ed 100644 --- a/TelegramUI/ProxyListSettingsController.swift +++ b/TelegramUI/ProxyListSettingsController.swift @@ -296,9 +296,9 @@ public enum ProxySettingsControllerMode { case modal } -public func proxySettingsController(account: Account, mode: ProxySettingsControllerMode = .default) -> ViewController { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - return proxySettingsController(postbox: account.postbox, network: account.network, mode: mode, theme: presentationData.theme, strings: presentationData.strings, updatedPresentationData: account.telegramApplicationContext.presentationData |> map { ($0.theme, $0.strings) }) +public func proxySettingsController(context: AccountContext, mode: ProxySettingsControllerMode = .default) -> ViewController { + let presentationData = context.currentPresentationData.with { $0 } + return proxySettingsController(postbox: context.account.postbox, network: context.account.network, mode: mode, theme: presentationData.theme, strings: presentationData.strings, updatedPresentationData: context.presentationData |> map { ($0.theme, $0.strings) }) } public func proxySettingsController(postbox: Postbox, network: Network, mode: ProxySettingsControllerMode, theme: PresentationTheme, strings: PresentationStrings, updatedPresentationData: Signal<(theme: PresentationTheme, strings: PresentationStrings), NoError>) -> ViewController { diff --git a/TelegramUI/ProxyServerActionSheetController.swift b/TelegramUI/ProxyServerActionSheetController.swift index 68346bf921..be0aaf76cd 100644 --- a/TelegramUI/ProxyServerActionSheetController.swift +++ b/TelegramUI/ProxyServerActionSheetController.swift @@ -16,9 +16,9 @@ public final class ProxyServerActionSheetController: ActionSheetController { private var isDismissed: Bool = false - convenience init(account: Account, server: ProxyServerSettings) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - self.init(theme: presentationData.theme, strings: presentationData.strings, postbox: account.postbox, network: account.network, server: server, presentationData: account.telegramApplicationContext.presentationData) + 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) } public init(theme: PresentationTheme, strings: PresentationStrings, postbox: Postbox, network: Network, server: ProxyServerSettings, presentationData: Signal?) { diff --git a/TelegramUI/RecentSessionsController.swift b/TelegramUI/RecentSessionsController.swift index 989627d72d..b41c57151e 100644 --- a/TelegramUI/RecentSessionsController.swift +++ b/TelegramUI/RecentSessionsController.swift @@ -406,7 +406,7 @@ private func recentSessionsControllerEntries(presentationData: PresentationData, return entries } -public func recentSessionsController(account: Account) -> ViewController { +public func recentSessionsController(context: AccountContext) -> ViewController { let statePromise = ValuePromise(RecentSessionsControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: RecentSessionsControllerState()) let updateState: ((RecentSessionsControllerState) -> RecentSessionsControllerState) -> Void = { f in @@ -427,7 +427,7 @@ public func recentSessionsController(account: Account) -> ViewController { let sessionsPromise = Promise<[RecentAccountSession]?>(nil) let websitesPromise = Promise<([WebAuthorization], [PeerId : Peer])?>(nil) - let arguments = RecentSessionsControllerArguments(account: account, setSessionIdWithRevealedOptions: { sessionId, fromSessionId in + let arguments = RecentSessionsControllerArguments(account: context.account, setSessionIdWithRevealedOptions: { sessionId, fromSessionId in updateState { state in if (sessionId == nil && fromSessionId == state.sessionIdWithRevealedOptions) || (sessionId != nil && fromSessionId == nil) { return state.withUpdatedSessionIdWithRevealedOptions(sessionId) @@ -436,7 +436,7 @@ public func recentSessionsController(account: Account) -> ViewController { } } }, removeSession: { sessionId in - 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() @@ -469,7 +469,7 @@ public func recentSessionsController(account: Account) -> ViewController { return .complete() } - removeSessionDisposable.set((terminateAccountSession(account: account, hash: sessionId) |> then((applySessions |> mapError { _ in TerminateSessionError.generic })) |> deliverOnMainQueue).start(error: { _ in + removeSessionDisposable.set((terminateAccountSession(account: context.account, hash: sessionId) |> then((applySessions |> mapError { _ in TerminateSessionError.generic })) |> deliverOnMainQueue).start(error: { _ in updateState { return $0.withUpdatedRemovingSessionId(nil) } @@ -484,7 +484,7 @@ public func recentSessionsController(account: Account) -> ViewController { ]) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, terminateOtherSessions: { - 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() @@ -511,7 +511,7 @@ public func recentSessionsController(account: Account) -> ViewController { return .complete() } - terminateOtherSessionsDisposable.set((terminateOtherAccountSessions(account: account) |> then(applySessions) |> deliverOnMainQueue).start(error: { _ in + terminateOtherSessionsDisposable.set((terminateOtherAccountSessions(account: context.account) |> then(applySessions) |> deliverOnMainQueue).start(error: { _ in updateState { return $0.withUpdatedTerminatingOtherSessions(false) } @@ -553,7 +553,7 @@ public func recentSessionsController(account: Account) -> ViewController { return .complete() } - removeSessionDisposable.set(((terminateWebSession(network: account.network, hash: sessionId) + removeSessionDisposable.set(((terminateWebSession(network: context.account.network, hash: sessionId) |> mapToSignal { _ -> Signal in return .complete() }) |> then(applySessions) |> deliverOnMainQueue).start(error: { _ in @@ -566,7 +566,7 @@ public func recentSessionsController(account: Account) -> ViewController { } })) }, terminateAllWebSessions: { - 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() @@ -580,7 +580,7 @@ public func recentSessionsController(account: Account) -> ViewController { return $0.withUpdatedTerminatingOtherSessions(true) } - terminateOtherSessionsDisposable.set((terminateAllWebSessions(network: account.network) |> deliverOnMainQueue).start(error: { _ in + terminateOtherSessionsDisposable.set((terminateAllWebSessions(network: context.account.network) |> deliverOnMainQueue).start(error: { _ in updateState { return $0.withUpdatedTerminatingOtherSessions(false) } @@ -598,15 +598,15 @@ public func recentSessionsController(account: Account) -> ViewController { presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) - let sessionsSignal: Signal<[RecentAccountSession]?, NoError> = .single(nil) |> then(requestRecentAccountSessions(account: account) |> map(Optional.init)) + let sessionsSignal: Signal<[RecentAccountSession]?, NoError> = .single(nil) |> then(requestRecentAccountSessions(account: context.account) |> map(Optional.init)) sessionsPromise.set(sessionsSignal) - let websitesSignal: Signal<([WebAuthorization], [PeerId : Peer])?, NoError> = .single(nil) |> then(webSessions(network: account.network) |> map(Optional.init)) + let websitesSignal: Signal<([WebAuthorization], [PeerId : Peer])?, NoError> = .single(nil) |> then(webSessions(network: context.account.network) |> map(Optional.init)) websitesPromise.set(websitesSignal) let previousMode = Atomic(value: .sessions) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, mode.get(), statePromise.get(), sessionsPromise.get(), websitesPromise.get()) + let signal = combineLatest(context.presentationData, mode.get(), statePromise.get(), sessionsPromise.get(), websitesPromise.get()) |> deliverOnMainQueue |> map { presentationData, mode, state, sessions, websitesAndPeers -> (ItemListControllerState, (ItemListNodeState, RecentSessionsEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? @@ -670,7 +670,7 @@ public func recentSessionsController(account: Account) -> ViewController { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) controller.titleControlValueChanged = { [weak mode] index in mode?.set(index == 0 ? .sessions : .websites) } diff --git a/TelegramUI/ReplyAccessoryPanelNode.swift b/TelegramUI/ReplyAccessoryPanelNode.swift index 15d8785839..b71e61344a 100644 --- a/TelegramUI/ReplyAccessoryPanelNode.swift +++ b/TelegramUI/ReplyAccessoryPanelNode.swift @@ -19,7 +19,7 @@ final class ReplyAccessoryPanelNode: AccessoryPanelNode { var theme: PresentationTheme - init(account: Account, messageId: MessageId, theme: PresentationTheme, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder) { + init(context: AccountContext, messageId: MessageId, theme: PresentationTheme, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder) { self.messageId = messageId self.theme = theme @@ -56,7 +56,7 @@ final class ReplyAccessoryPanelNode: AccessoryPanelNode { self.addSubnode(self.textNode) self.addSubnode(self.imageNode) - self.messageDisposable.set((account.postbox.messageAtId(messageId) + self.messageDisposable.set((context.account.postbox.messageAtId(messageId) |> deliverOnMainQueue).start(next: { [weak self] message in if let strongSelf = self { var authorName = "" @@ -65,7 +65,7 @@ final class ReplyAccessoryPanelNode: AccessoryPanelNode { authorName = author.displayTitle(strings: strings, displayOrder: nameDisplayOrder) } if let message = message { - (text, _) = descriptionStringForMessage(message, strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: account.peerId) + (text, _) = descriptionStringForMessage(message, strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: context.account.peerId) } var updatedMediaReference: AnyMediaReference? @@ -116,12 +116,12 @@ final class ReplyAccessoryPanelNode: AccessoryPanelNode { if mediaUpdated { if let updatedMediaReference = updatedMediaReference, imageDimensions != nil { if let imageReference = updatedMediaReference.concrete(TelegramMediaImage.self) { - updateImageSignal = chatMessagePhotoThumbnail(account: account, photoReference: imageReference) + updateImageSignal = chatMessagePhotoThumbnail(account: context.account, photoReference: imageReference) } else if let fileReference = updatedMediaReference.concrete(TelegramMediaFile.self) { if fileReference.media.isVideo { - updateImageSignal = chatMessageVideoThumbnail(account: account, fileReference: fileReference) + updateImageSignal = chatMessageVideoThumbnail(account: context.account, fileReference: fileReference) } else if let iconImageRepresentation = smallestImageRepresentation(fileReference.media.previewRepresentations) { - updateImageSignal = chatWebpageSnippetFile(account: account, fileReference: fileReference, representation: iconImageRepresentation) + updateImageSignal = chatWebpageSnippetFile(account: context.account, fileReference: fileReference, representation: iconImageRepresentation) } } } else { @@ -131,7 +131,7 @@ final class ReplyAccessoryPanelNode: AccessoryPanelNode { let isMedia: Bool if let message = message { - switch messageContentKind(message, strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: account.peerId) { + switch messageContentKind(message, strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: context.account.peerId) { case .text: isMedia = false default: diff --git a/TelegramUI/ResetPasswordController.swift b/TelegramUI/ResetPasswordController.swift index ddea0e806e..da4f590b9f 100644 --- a/TelegramUI/ResetPasswordController.swift +++ b/TelegramUI/ResetPasswordController.swift @@ -106,7 +106,7 @@ enum ResetPasswordState: Equatable { case pendingVerification(emailPattern: String) } -func resetPasswordController(account: Account, emailPattern: String, completion: @escaping () -> Void) -> ViewController { +func resetPasswordController(context: AccountContext, emailPattern: String, completion: @escaping () -> Void) -> ViewController { let statePromise = ValuePromise(ResetPasswordControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: ResetPasswordControllerState()) let updateState: ((ResetPasswordControllerState) -> ResetPasswordControllerState) -> Void = { f in @@ -128,13 +128,13 @@ func resetPasswordController(account: Account, emailPattern: String, completion: return state } }, openHelp: { - 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.TwoStepAuth_RecoveryFailed, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) }) var initialFocusImpl: (() -> Void)? - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get()) |> deliverOnMainQueue |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, ResetPasswordEntry.ItemGenerationArguments)) in @@ -157,7 +157,7 @@ func resetPasswordController(account: Account, emailPattern: String, completion: state.checking = true return state } - saveDisposable.set((recoverTwoStepVerificationPassword(network: account.network, code: state.code) + saveDisposable.set((recoverTwoStepVerificationPassword(network: context.account.network, code: state.code) |> deliverOnMainQueue).start(error: { error in updateState { state in var state = state @@ -175,7 +175,7 @@ func resetPasswordController(account: Account, emailPattern: String, completion: case .generic: text = presentationData.strings.Login_UnknownError } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) }, completed: { completion() @@ -193,7 +193,7 @@ func resetPasswordController(account: Account, emailPattern: String, completion: actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) dismissImpl = { [weak controller] in controller?.view.endEditing(true) controller?.dismiss() diff --git a/TelegramUI/SaveIncomingMediaController.swift b/TelegramUI/SaveIncomingMediaController.swift index ef4f4e6e04..e3303b8d37 100644 --- a/TelegramUI/SaveIncomingMediaController.swift +++ b/TelegramUI/SaveIncomingMediaController.swift @@ -89,9 +89,9 @@ private func saveIncomingMediaControllerEntries(presentationData: PresentationDa return entries } -func saveIncomingMediaController(account: Account) -> ViewController { +func saveIncomingMediaController(context: AccountContext) -> ViewController { let arguments = SaveIncomingMediaControllerArguments(toggle: { type in - let _ = updateMediaDownloadSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings switch type { case .contact: @@ -107,7 +107,7 @@ func saveIncomingMediaController(account: Account) -> ViewController { }).start() }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings])) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings])) |> deliverOnMainQueue |> map { presentationData, prefs -> (ItemListControllerState, (ItemListNodeState, SaveIncomingMediaEntry.ItemGenerationArguments)) in let automaticMediaDownloadSettings: AutomaticMediaDownloadSettings if let value = prefs.values[ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings] as? AutomaticMediaDownloadSettings { @@ -122,7 +122,7 @@ func saveIncomingMediaController(account: Account) -> ViewController { return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) return controller } diff --git a/TelegramUI/SaveToCameraRoll.swift b/TelegramUI/SaveToCameraRoll.swift index 0bfb0fb17b..fe55dfee0c 100644 --- a/TelegramUI/SaveToCameraRoll.swift +++ b/TelegramUI/SaveToCameraRoll.swift @@ -12,7 +12,7 @@ private enum SaveToCameraRollState { case data(MediaResourceData) } -private func fetchMediaData(applicationContext: TelegramApplicationContext, postbox: Postbox, mediaReference: AnyMediaReference) -> Signal<(SaveToCameraRollState, Bool), NoError> { +private func fetchMediaData(context: AccountContext, postbox: Postbox, mediaReference: AnyMediaReference) -> Signal<(SaveToCameraRollState, Bool), NoError> { var resource: MediaResource? var isImage = true var fileExtension: String? @@ -75,8 +75,8 @@ private func fetchMediaData(applicationContext: TelegramApplicationContext, post } } -func saveToCameraRoll(applicationContext: TelegramApplicationContext, postbox: Postbox, mediaReference: AnyMediaReference) -> Signal { - return fetchMediaData(applicationContext: applicationContext, postbox: postbox, mediaReference: mediaReference) +func saveToCameraRoll(context: AccountContext, postbox: Postbox, mediaReference: AnyMediaReference) -> Signal { + return fetchMediaData(context: context, postbox: postbox, mediaReference: mediaReference) |> mapToSignal { state, isImage -> Signal in switch state { case let .progress(value): @@ -84,9 +84,9 @@ func saveToCameraRoll(applicationContext: TelegramApplicationContext, postbox: P case let .data(data): if data.complete { return Signal { subscriber in - DeviceAccess.authorizeAccess(to: .mediaLibrary(.save), presentationData: applicationContext.currentPresentationData.with { $0 }, present: { c, a in - applicationContext.presentGlobalController(c, a) - }, openSettings: applicationContext.applicationBindings.openSettings, { authorized in + DeviceAccess.authorizeAccess(to: .mediaLibrary(.save), presentationData: context.currentPresentationData.with { $0 }, present: { c, a in + context.presentGlobalController(c, a) + }, openSettings: context.applicationBindings.openSettings, { authorized in if !authorized { subscriber.putCompletion() return @@ -129,8 +129,8 @@ func saveToCameraRoll(applicationContext: TelegramApplicationContext, postbox: P } } -func copyToPasteboard(applicationContext: TelegramApplicationContext, postbox: Postbox, mediaReference: AnyMediaReference) -> Signal { - return fetchMediaData(applicationContext: applicationContext, postbox: postbox, mediaReference: mediaReference) +func copyToPasteboard(context: AccountContext, postbox: Postbox, mediaReference: AnyMediaReference) -> Signal { + return fetchMediaData(context: context, postbox: postbox, mediaReference: mediaReference) |> mapToSignal { state, isImage -> Signal in if case let .data(data) = state, data.complete { return Signal { subscriber in diff --git a/TelegramUI/SecretChatKeyController.swift b/TelegramUI/SecretChatKeyController.swift index 4c3f657daf..3d899a3ad9 100644 --- a/TelegramUI/SecretChatKeyController.swift +++ b/TelegramUI/SecretChatKeyController.swift @@ -9,18 +9,18 @@ final class SecretChatKeyController: ViewController { return self.displayNode as! SecretChatKeyControllerNode } - private let account: Account + private let context: AccountContext private let fingerprint: SecretChatKeyFingerprint private let peer: Peer private var presentationData: PresentationData - init(account: Account, fingerprint: SecretChatKeyFingerprint, peer: Peer) { + init(context: AccountContext, fingerprint: SecretChatKeyFingerprint, peer: Peer) { self.account = account self.fingerprint = fingerprint self.peer = peer - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -33,7 +33,7 @@ final class SecretChatKeyController: ViewController { } override func loadDisplayNode() { - self.displayNode = SecretChatKeyControllerNode(account: self.account, presentationData: self.presentationData, fingerprint: self.fingerprint, peer: self.peer, getNavigationController: { [weak self] in + self.displayNode = SecretChatKeyControllerNode(context: self.context, presentationData: self.presentationData, fingerprint: self.fingerprint, peer: self.peer, getNavigationController: { [weak self] in return self?.navigationController as? NavigationController }) self.displayNodeDidLoad() diff --git a/TelegramUI/SecretChatKeyControllerNode.swift b/TelegramUI/SecretChatKeyControllerNode.swift index 738897f6b2..e27098c544 100644 --- a/TelegramUI/SecretChatKeyControllerNode.swift +++ b/TelegramUI/SecretChatKeyControllerNode.swift @@ -21,7 +21,7 @@ private func processHexString(_ string: String) -> String { } final class SecretChatKeyControllerNode: ViewControllerTracingNode { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let fingerprint: SecretChatKeyFingerprint private let peer: Peer @@ -34,8 +34,8 @@ final class SecretChatKeyControllerNode: ViewControllerTracingNode { private var validImageSize: CGSize? - init(account: Account, presentationData: PresentationData, fingerprint: SecretChatKeyFingerprint, peer: Peer, getNavigationController: @escaping () -> NavigationController?) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, fingerprint: SecretChatKeyFingerprint, peer: Peer, getNavigationController: @escaping () -> NavigationController?) { + self.context = context self.presentationData = presentationData self.fingerprint = fingerprint self.peer = peer @@ -152,7 +152,7 @@ final class SecretChatKeyControllerNode: ViewControllerTracingNode { let point = recognizer.location(in: recognizer.view) if let attributes = self.infoNode.attributesAtPoint(point)?.1 { if let url = attributes[NSAttributedStringKey(rawValue: TelegramTextAttributes.URL)] as? String { - openExternalUrl(account: self.account, url: url, presentationData: self.presentationData, applicationContext: self.account.telegramApplicationContext, navigationController: self.getNavigationController(), dismissInput: { [weak self] in + openExternalUrl(context: self.context, url: url, presentationData: self.presentationData, navigationController: self.getNavigationController(), dismissInput: { [weak self] in self?.view.endEditing(true) }) } diff --git a/TelegramUI/SecretMediaPreviewController.swift b/TelegramUI/SecretMediaPreviewController.swift index b5d6a11f84..7016820152 100644 --- a/TelegramUI/SecretMediaPreviewController.swift +++ b/TelegramUI/SecretMediaPreviewController.swift @@ -113,7 +113,7 @@ private final class SecretMediaPreviewControllerNode: GalleryControllerNode { } public final class SecretMediaPreviewController: ViewController { - private let account: Account + private let context: AccountContext private let _ready = Promise() override public var ready: Promise { @@ -140,9 +140,9 @@ public final class SecretMediaPreviewController: ViewController { private var screenCaptureEventsDisposable: Disposable? - public init(account: Account, messageId: MessageId) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + public init(context: AccountContext, messageId: MessageId) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(theme: GalleryController.darkNavigationTheme, strings: NavigationBarStrings(presentationStrings: self.presentationData.strings))) @@ -153,7 +153,7 @@ public final class SecretMediaPreviewController: ViewController { - self.disposable.set((account.postbox.messageView(messageId) |> deliverOnMainQueue).start(next: { [weak self] view in + self.disposable.set((context.account.postbox.messageView(messageId) |> deliverOnMainQueue).start(next: { [weak self] view in if let strongSelf = self { strongSelf.messageView = view if strongSelf.isViewLoaded { @@ -162,24 +162,23 @@ public final class SecretMediaPreviewController: ViewController { } })) - if let mediaManager = account.telegramApplicationContext.mediaManager { - self.hiddenMediaManagerIndex = mediaManager.galleryHiddenMediaManager.addSource(self._hiddenMedia.get() - |> map { messageIdAndMedia in - if let (messageId, media) = messageIdAndMedia { - return .chat(messageId, media) - } else { - return nil - } - }) - } + let mediaManager = context.mediaManager + self.hiddenMediaManagerIndex = mediaManager.galleryHiddenMediaManager.addSource(self._hiddenMedia.get() + |> map { messageIdAndMedia in + if let (messageId, media) = messageIdAndMedia { + return .chat(messageId, media) + } else { + return nil + } + }) self.screenCaptureEventsDisposable = (screenCaptureEvents() |> deliverOnMainQueue).start(next: { [weak self] _ in if let strongSelf = self, strongSelf.traceVisibility() { if messageId.peerId.namespace == Namespaces.Peer.CloudUser { - let _ = enqueueMessages(account: account, peerId: messageId.peerId, messages: [.message(text: "", attributes: [], mediaReference: .standalone(media: TelegramMediaAction(action: TelegramMediaActionType.historyScreenshot)), replyToMessageId: nil, localGroupingKey: nil)]).start() + let _ = enqueueMessages(account: context.account, peerId: messageId.peerId, messages: [.message(text: "", attributes: [], mediaReference: .standalone(media: TelegramMediaAction(action: TelegramMediaActionType.historyScreenshot)), replyToMessageId: nil, localGroupingKey: nil)]).start() } else if messageId.peerId.namespace == Namespaces.Peer.SecretChat { - let _ = addSecretChatMessageScreenshot(account: account, peerId: messageId.peerId).start() + let _ = addSecretChatMessageScreenshot(account: context.account, peerId: messageId.peerId).start() } } }) @@ -192,7 +191,8 @@ public final class SecretMediaPreviewController: ViewController { deinit { self.disposable.dispose() self.markMessageAsConsumedDisposable.dispose() - if let hiddenMediaManagerIndex = self.hiddenMediaManagerIndex, let mediaManager = self.account.telegramApplicationContext.mediaManager { + if let hiddenMediaManagerIndex = self.hiddenMediaManagerIndex { + let mediaManager = self.context.mediaManager mediaManager.galleryHiddenMediaManager.removeSource(hiddenMediaManagerIndex) } self.screenCaptureEventsDisposable?.dispose() @@ -413,7 +413,7 @@ public final class SecretMediaPreviewController: ViewController { var tempFilePath: String? for media in message.media { if let file = media as? TelegramMediaFile { - if let path = self.account.postbox.mediaBox.completedResourcePath(file.resource) { + if let path = self.context.account.postbox.mediaBox.completedResourcePath(file.resource) { let tempFile = TempBox.shared.file(path: path, fileName: file.fileName ?? "file") self.tempFile = tempFile tempFilePath = tempFile.path @@ -423,7 +423,7 @@ public final class SecretMediaPreviewController: ViewController { } } - guard let item = galleryItemForEntry(account: self.account, presentationData: self.presentationData, entry: .MessageEntry(message, false, nil, nil), streamVideos: false, hideControls: true, tempFilePath: tempFilePath, playbackCompleted: { [weak self] in + guard let item = galleryItemForEntry(context: self.context, presentationData: self.presentationData, entry: .MessageEntry(message, false, nil, nil), streamVideos: false, hideControls: true, tempFilePath: tempFilePath, playbackCompleted: { [weak self] in self?.dismiss(forceAway: false) }) else { self._ready.set(.single(true)) @@ -435,7 +435,7 @@ public final class SecretMediaPreviewController: ViewController { self?.didSetReady = true } self._ready.set(ready |> map { true }) - self.markMessageAsConsumedDisposable.set(markMessageContentAsConsumedInteractively(postbox: self.account.postbox, messageId: message.id).start()) + self.markMessageAsConsumedDisposable.set(markMessageContentAsConsumedInteractively(postbox: self.context.account.postbox, messageId: message.id).start()) } else { var beginTimeAndTimeout: (Double, Double)? var videoDuration: Int32? diff --git a/TelegramUI/SecretMediaPreviewControllerNode.swift b/TelegramUI/SecretMediaPreviewControllerNode.swift deleted file mode 100644 index e47fa88bf5..0000000000 --- a/TelegramUI/SecretMediaPreviewControllerNode.swift +++ /dev/null @@ -1,5 +0,0 @@ -import Foundation -import AsyncDisplayKit -import Display - - diff --git a/TelegramUI/SecureIdAuthController.swift b/TelegramUI/SecureIdAuthController.swift index 2bf10dc833..a9f8a344c7 100644 --- a/TelegramUI/SecureIdAuthController.swift +++ b/TelegramUI/SecureIdAuthController.swift @@ -63,7 +63,7 @@ final class SecureIdAuthController: ViewController { return self.displayNode as! SecureIdAuthControllerNode } - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let mode: SecureIdAuthControllerMode @@ -79,9 +79,9 @@ final class SecureIdAuthController: ViewController { private let hapticFeedback = HapticFeedback() - init(account: Account, mode: SecureIdAuthControllerMode) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, mode: SecureIdAuthControllerMode) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.mode = mode @@ -107,12 +107,12 @@ final class SecureIdAuthController: ViewController { } self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: PresentationResourcesRootController.navigationInfoIcon(self.presentationData.theme), style: .plain, target: self, action: #selector(self.infoPressed)) - self.challengeDisposable.set((twoStepAuthData(account.network) + self.challengeDisposable.set((twoStepAuthData(context.account.network) |> deliverOnMainQueue).start(next: { [weak self] data in if let strongSelf = self { - let storedPassword = strongSelf.account.telegramApplicationContext.getStoredSecureIdPassword() + let storedPassword = context.getStoredSecureIdPassword() if data.currentPasswordDerivation != nil, let storedPassword = storedPassword { - strongSelf.authenthicateDisposable.set((accessSecureId(network: strongSelf.account.network, password: storedPassword) + strongSelf.authenthicateDisposable.set((accessSecureId(network: strongSelf.context.account.network, password: storedPassword) |> deliverOnMainQueue).start(next: { context in guard let strongSelf = self, strongSelf.state.verificationState == nil else { return @@ -184,7 +184,7 @@ final class SecureIdAuthController: ViewController { if appUpdateRequired { let errorText = strongSelf.presentationData.strings.Passport_UpdateRequiredError strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: strongSelf.presentationData.theme), title: nil, text: errorText, actions: [TextAlertAction(type: .defaultAction, title: strongSelf.presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: strongSelf.presentationData.strings.Application_Update, action: { - account.telegramApplicationContext.applicationBindings.openAppStorePage() + context.applicationBindings.openAppStorePage() })]), in: .window(.root)) } else if let callbackUrl = callbackUrl, let peerId = peerId { let errorText = strongSelf.presentationData.strings.Login_UnknownError @@ -200,10 +200,10 @@ final class SecureIdAuthController: ViewController { switch self.mode { case let .form(peerId, scope, publicKey, callbackUrl, _, _): - self.formDisposable = (combineLatest(requestSecureIdForm(postbox: account.postbox, network: account.network, peerId: peerId, scope: scope, publicKey: publicKey), secureIdConfiguration(postbox: account.postbox, network: account.network) |> introduceError(RequestSecureIdFormError.self)) + self.formDisposable = (combineLatest(requestSecureIdForm(postbox: context.account.postbox, network: context.account.network, peerId: peerId, scope: scope, publicKey: publicKey), secureIdConfiguration(postbox: context.account.postbox, network: context.account.network) |> introduceError(RequestSecureIdFormError.self)) |> mapToSignal { form, configuration -> Signal in - return account.postbox.transaction { transaction -> Signal in - guard let accountPeer = transaction.getPeer(account.peerId), let servicePeer = transaction.getPeer(form.peerId) else { + return context.account.postbox.transaction { transaction -> Signal in + guard let accountPeer = transaction.getPeer(context.account.peerId), let servicePeer = transaction.getPeer(form.peerId) else { return .fail(.generic) } @@ -231,8 +231,8 @@ final class SecureIdAuthController: ViewController { handleError(error, callbackUrl, peerId) }) case .list: - self.formDisposable = (combineLatest(getAllSecureIdValues(network: self.account.network), secureIdConfiguration(postbox: account.postbox, network: account.network) |> introduceError(GetAllSecureIdValuesError.self), account.postbox.transaction { transaction -> Signal in - guard let accountPeer = transaction.getPeer(account.peerId) else { + self.formDisposable = (combineLatest(getAllSecureIdValues(network: self.context.account.network), secureIdConfiguration(postbox: context.account.postbox, network: context.account.network) |> introduceError(GetAllSecureIdValuesError.self), context.account.postbox.transaction { transaction -> Signal in + guard let accountPeer = transaction.getPeer(context.account.peerId) else { return .fail(.generic) } @@ -307,7 +307,7 @@ final class SecureIdAuthController: ViewController { self?.grantAccess() }, openUrl: { [weak self] url in if let strongSelf = self { - openExternalUrl(account: strongSelf.account, url: url, presentationData: strongSelf.presentationData, applicationContext: strongSelf.account.telegramApplicationContext, navigationController: strongSelf.navigationController as? NavigationController, dismissInput: { + openExternalUrl(context: strongSelf.context, url: url, presentationData: strongSelf.presentationData, navigationController: strongSelf.navigationController as? NavigationController, dismissInput: { self?.view.endEditing(true) }) } @@ -315,12 +315,12 @@ final class SecureIdAuthController: ViewController { guard let strongSelf = self else { return } - let _ = (strongSelf.account.postbox.loadedPeerWithId(mention.peerId) + let _ = (strongSelf.context.account.postbox.loadedPeerWithId(mention.peerId) |> deliverOnMainQueue).start(next: { peer in guard let strongSelf = self else { return } - if let infoController = peerInfoController(account: strongSelf.account, peer: peer) { + if let infoController = peerInfoController(context: strongSelf.context, peer: peer) { (strongSelf.navigationController as? NavigationController)?.pushViewController(infoController) } }) @@ -331,7 +331,7 @@ final class SecureIdAuthController: ViewController { let item = UIBarButtonItem(customDisplayNode: ProgressNavigationButtonNode(theme: strongSelf.presentationData.theme)) strongSelf.navigationItem.rightBarButtonItem = item - strongSelf.deleteDisposable.set((deleteSecureIdValues(network: strongSelf.account.network, keys: Set(values.map({ $0.value.key }))) + strongSelf.deleteDisposable.set((deleteSecureIdValues(network: strongSelf.context.account.network, keys: Set(values.map({ $0.value.key }))) |> deliverOnMainQueue).start(completed: { guard let strongSelf = self else { return @@ -347,7 +347,7 @@ final class SecureIdAuthController: ViewController { })) }) - self.displayNode = SecureIdAuthControllerNode(account: self.account, presentationData: presentationData, requestLayout: { [weak self] transition in + self.displayNode = SecureIdAuthControllerNode(context: self.context, presentationData: presentationData, requestLayout: { [weak self] transition in self?.requestLayout(transition: transition) }, interaction: interaction) self.controllerNode.updateState(self.state, transition: .immediate) @@ -394,7 +394,7 @@ final class SecureIdAuthController: ViewController { } private func openUrl(_ url: String) { - openExternalUrl(account: self.account, url: url, forceExternal: true, presentationData: self.presentationData, applicationContext: self.account.telegramApplicationContext, navigationController: nil, dismissInput: { [weak self] in + openExternalUrl(context: self.context, url: url, forceExternal: true, presentationData: self.presentationData, navigationController: nil, dismissInput: { [weak self] in self?.view.endEditing(true) }) } @@ -420,12 +420,12 @@ final class SecureIdAuthController: ViewController { state.verificationState = .passwordChallenge(hint: hint, state: .checking, hasRecoveryEmail: hasRecoveryEmail) return state }) - self.challengeDisposable.set((accessSecureId(network: self.account.network, password: password) + self.challengeDisposable.set((accessSecureId(network: self.context.account.network, password: password) |> deliverOnMainQueue).start(next: { [weak self] context in guard let strongSelf = self, let verificationState = strongSelf.state.verificationState, case .passwordChallenge(_, .checking, _) = verificationState else { return } - strongSelf.account.telegramApplicationContext.storeSecureIdPassword(password: password) + strongSelf.context.storeSecureIdPassword(password: password) strongSelf.updateState(animated: !inBackground, { state in var state = state state.verificationState = .verified(context.context) @@ -491,13 +491,13 @@ final class SecureIdAuthController: ViewController { guard let strongSelf = self else { return } - strongSelf.recoveryDisposable.set((requestTwoStepVerificationPasswordRecoveryCode(network: strongSelf.account.network) + strongSelf.recoveryDisposable.set((requestTwoStepVerificationPasswordRecoveryCode(network: strongSelf.context.account.network) |> deliverOnMainQueue).start(next: { emailPattern in guard let strongSelf = self else { return } var completionImpl: (() -> Void)? - let controller = resetPasswordController(account: strongSelf.account, emailPattern: emailPattern, completion: { + let controller = resetPasswordController(context: strongSelf.context, emailPattern: emailPattern, completion: { completionImpl?() }) completionImpl = { [weak controller] in @@ -532,7 +532,7 @@ final class SecureIdAuthController: ViewController { case let .awaitingConfirmation(password, emailPattern, codeLength): initialState = .confirmEmail(password: password, hasSecureValues: false, pattern: emailPattern, codeLength: codeLength) } - let controller = SetupTwoStepVerificationController(account: self.account, initialState: initialState, stateUpdated: { [weak self] update, shouldDismiss, controller in + let controller = SetupTwoStepVerificationController(context: self.context, initialState: initialState, stateUpdated: { [weak self] update, shouldDismiss, controller in guard let strongSelf = self else { return } @@ -621,7 +621,7 @@ final class SecureIdAuthController: ViewController { if case let .form(reqForm) = self.mode, let encryptedFormData = form.encryptedFormData, let formData = form.formData { let values = parseRequestedFormFields(formData.requestedFields, values: formData.values, primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry).map({ $0.1 }).flatMap({ $0 }) - let _ = (grantSecureIdAccess(network: self.account.network, peerId: encryptedFormData.servicePeer.id, publicKey: reqForm.publicKey, scope: reqForm.scope, opaquePayload: reqForm.opaquePayload, opaqueNonce: reqForm.opaqueNonce, values: values, requestedFields: formData.requestedFields) + let _ = (grantSecureIdAccess(network: self.context.account.network, peerId: encryptedFormData.servicePeer.id, publicKey: reqForm.publicKey, scope: reqForm.scope, opaquePayload: reqForm.opaquePayload, opaqueNonce: reqForm.opaqueNonce, values: values, requestedFields: formData.requestedFields) |> deliverOnMainQueue).start(completed: { [weak self] in self?.dismiss() self?.openUrl(secureIdCallbackUrl(with: reqForm.callbackUrl, peerId: reqForm.peerId, result: .success, parameters: [:])) @@ -637,7 +637,7 @@ final class SecureIdAuthController: ViewController { guard let strongSelf = self else { return } - openExternalUrl(account: strongSelf.account, url: strongSelf.presentationData.strings.Passport_InfoFAQ_URL, presentationData: strongSelf.presentationData, applicationContext: strongSelf.account.telegramApplicationContext, navigationController: strongSelf.navigationController as? NavigationController, dismissInput: { + openExternalUrl(context: strongSelf.context, url: strongSelf.presentationData.strings.Passport_InfoFAQ_URL, presentationData: strongSelf.presentationData, navigationController: strongSelf.navigationController as? NavigationController, dismissInput: { self?.view.endEditing(true) }) })]), in: .window(.root)) diff --git a/TelegramUI/SecureIdAuthControllerNode.swift b/TelegramUI/SecureIdAuthControllerNode.swift index 7752bc2076..359057db5c 100644 --- a/TelegramUI/SecureIdAuthControllerNode.swift +++ b/TelegramUI/SecureIdAuthControllerNode.swift @@ -6,7 +6,7 @@ import Postbox import TelegramCore final class SecureIdAuthControllerNode: ViewControllerTracingNode { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let requestLayout: (ContainedViewLayoutTransition) -> Void private let interaction: SecureIdAuthControllerInteraction @@ -29,8 +29,8 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { private let deleteValueDisposable = MetaDisposable() - init(account: Account, presentationData: PresentationData, requestLayout: @escaping (ContainedViewLayoutTransition) -> Void, interaction: SecureIdAuthControllerInteraction) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, requestLayout: @escaping (ContainedViewLayoutTransition) -> Void, interaction: SecureIdAuthControllerInteraction) { + self.context = context self.presentationData = presentationData self.requestLayout = requestLayout self.interaction = interaction @@ -39,7 +39,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { self.activityIndicator.isHidden = true self.scrollNode = ASScrollNode() - self.headerNode = SecureIdAuthHeaderNode(account: account, theme: presentationData.theme, strings: presentationData.strings) + self.headerNode = SecureIdAuthHeaderNode(account: context.account, theme: presentationData.theme, strings: presentationData.strings) self.acceptNode = SecureIdAuthAcceptNode(title: presentationData.strings.Passport_Authorize, theme: presentationData.theme) super.init() @@ -508,7 +508,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { else if requireTranslation && !hasTranslation { scrollTo = .translation } - self.interaction.present(SecureIdDocumentFormController(account: self.account, 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, context: context, 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(account: self.account, 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, context: context, 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(account: self.account, 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, context: context, 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(account: self.account, 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, context: context, 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(account: strongSelf.account, context: context, requestedData: requestedData, primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in + let controller = SecureIdDocumentFormController(context: strongSelf.context, context: context, requestedData: requestedData, primaryLanguageByCountry: encryptedFormData.primaryLanguageByCountry, values: formData.values, updatedValues: { values in var keys: [SecureIdValueKey] = [] switch requestedData { case let .identity(details, document, _, _): @@ -648,7 +648,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { }) if let attachmentType = attachmentType, let type = attachmentTarget { - presentLegacySecureIdAttachmentMenu(account: strongSelf.account, present: { [weak self] c in + presentLegacySecureIdAttachmentMenu(context: strongSelf.context, present: { [weak self] c in self?.interaction.present(c, nil) }, validLayout: validLayout, type: attachmentType, recognizeDocumentData: true, completion: { [weak self] resources, recognizedData in guard let strongSelf = self else { @@ -667,7 +667,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { if itemsForField.count == 1 { completionImpl(itemsForField[0].1) } else { - let controller = SecureIdDocumentTypeSelectionController(account: self.account, field: field, currentValues: formData.values, completion: completionImpl) + let controller = SecureIdDocumentTypeSelectionController(context: self.context, field: field, currentValues: formData.values, completion: completionImpl) self.interaction.present(controller, nil) } } @@ -695,7 +695,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { guard let strongSelf = self else { return } - strongSelf.interaction.present(SecureIdPlaintextFormController(account: strongSelf.account, context: context, type: type, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { valueWithContext in + strongSelf.interaction.present(SecureIdPlaintextFormController(context: strongSelf.context, context: context, 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 { @@ -746,7 +746,7 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { } return state } - strongSelf.deleteValueDisposable.set((deleteSecureIdValues(network: strongSelf.account.network, keys: Set([currentValue.value.key])) + strongSelf.deleteValueDisposable.set((deleteSecureIdValues(network: strongSelf.context.account.network, keys: Set([currentValue.value.key])) |> deliverOnMainQueue).start(completed: { guard let strongSelf = self else { return @@ -809,27 +809,27 @@ final class SecureIdAuthControllerNode: ViewControllerTracingNode { let primaryLanguageByCountry = list.primaryLanguageByCountry ?? [:] switch field { case .personalDetails: - strongSelf.interaction.present(SecureIdDocumentFormController(account: strongSelf.account, 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, context: context, 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(account: strongSelf.account, 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, context: context, 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(account: strongSelf.account, 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, context: context, 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(account: strongSelf.account, 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, context: context, 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(account: strongSelf.account, 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, context: context, 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(account: strongSelf.account, 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, context: context, requestedData: .address(details: true, document: nil, translations: false), primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .utilityBill: - strongSelf.interaction.present(SecureIdDocumentFormController(account: strongSelf.account, 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, context: context, requestedData: .address(details: false, document: .utilityBill, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .bankStatement: - strongSelf.interaction.present(SecureIdDocumentFormController(account: strongSelf.account, 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, context: context, requestedData: .address(details: false, document: .bankStatement, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .rentalAgreement: - strongSelf.interaction.present(SecureIdDocumentFormController(account: strongSelf.account, 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, context: context, requestedData: .address(details: false, document: .rentalAgreement, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .passportRegistration: - strongSelf.interaction.present(SecureIdDocumentFormController(account: strongSelf.account, 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, context: context, requestedData: .address(details: false, document: .passportRegistration, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .temporaryRegistration: - strongSelf.interaction.present(SecureIdDocumentFormController(account: strongSelf.account, 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, context: context, requestedData: .address(details: false, document: .temporaryRegistration, translations: false), requestOptionalData: true, primaryLanguageByCountry: primaryLanguageByCountry, values: values, updatedValues: updatedValues(field)), nil) case .phone: break case .email: @@ -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(account: self.account, context: context, type: .phone, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { value in + self.interaction.present(SecureIdPlaintextFormController(context: self.context, context: context, 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(account: self.account, context: context, type: .email, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { value in + self.interaction.present(SecureIdPlaintextFormController(context: self.context, context: context, type: .email, immediatelyAvailableValue: immediatelyAvailableValue, updatedValue: { value in updatedValues(.email)(value.flatMap({ [$0] }) ?? []) }), nil) } diff --git a/TelegramUI/SecureIdAuthHeaderNode.swift b/TelegramUI/SecureIdAuthHeaderNode.swift index eaab53760e..0af657cff5 100644 --- a/TelegramUI/SecureIdAuthHeaderNode.swift +++ b/TelegramUI/SecureIdAuthHeaderNode.swift @@ -45,7 +45,7 @@ final class SecureIdAuthHeaderNode: ASDisplayNode { func updateState(formData: SecureIdEncryptedFormData?, verificationState: SecureIdAuthControllerVerificationState) { if let formData = formData { - self.serviceAvatarNode.setPeer(account: self.account, peer: formData.servicePeer) + self.serviceAvatarNode.setPeer(account: self.account, theme: self.theme, peer: formData.servicePeer) let titleData = self.strings.Passport_RequestHeader(formData.servicePeer.displayTitle) let titleString = NSMutableAttributedString() diff --git a/TelegramUI/SecureIdDocumentFormController.swift b/TelegramUI/SecureIdDocumentFormController.swift index afb78d87bf..0c4e79dd0c 100644 --- a/TelegramUI/SecureIdDocumentFormController.swift +++ b/TelegramUI/SecureIdDocumentFormController.swift @@ -16,11 +16,11 @@ enum SecureIdDocumentFormRequestedData { } final class SecureIdDocumentFormController: FormController { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let updatedValues: ([SecureIdValueWithContext]) -> Void - private let context: SecureIdAccessContext + private let secureIdContext: SecureIdAccessContext private let requestedData: SecureIdDocumentFormRequestedData private let requestOptionalData: Bool private let primaryLanguageByCountry: [String: String] @@ -29,10 +29,10 @@ final class SecureIdDocumentFormController: FormController Void) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, secureIdContext: SecureIdAccessContext, requestedData: SecureIdDocumentFormRequestedData, requestOptionalData: Bool = false, scrollTo: SecureIdDocumentFormScrollToSubject? = nil, primaryLanguageByCountry: [String: String], values: [SecureIdValueWithContext], updatedValues: @escaping ([SecureIdValueWithContext]) -> Void) { self.context = context + self.presentationData = context.currentPresentationData.with { $0 } + self.secureIdContext = secureIdContext self.requestedData = requestedData self.requestOptionalData = requestOptionalData self.primaryLanguageByCountry = primaryLanguageByCountry @@ -40,7 +40,7 @@ final class SecureIdDocumentFormController: FormController { @@ -2137,8 +2137,8 @@ final class SecureIdDocumentFormControllerNode: FormControllerNode Void)? - self.uploadContext = SecureIdVerificationDocumentsContext(postbox: self.account.postbox, network: self.account.network, context: self.context, update: { id, state in + self.uploadContext = SecureIdVerificationDocumentsContext(postbox: self.context.account.postbox, network: self.context.account.network, context: self.secureIdContext, update: { id, state in updateImpl?(id, state) }) super.init(initParams: initParams, presentationData: presentationData) - self._itemParams = SecureIdDocumentFormParams(account: self.account, context: self.context, addFile: { [weak self] type in + self._itemParams = SecureIdDocumentFormParams(account: self.context.account, context: self.secureIdContext, addFile: { [weak self] type in if let strongSelf = self { strongSelf.view.endEditing(true) strongSelf.presentAssetPicker(type) @@ -2360,7 +2360,7 @@ final class SecureIdDocumentFormControllerNode: FormControllerNode] = [] for (_, value) in values { - saveValues.append(saveSecureIdValue(postbox: self.account.postbox, network: self.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.context, value: value, uploadedFiles: self.uploadContext.uploadedFiles)) } self.actionDisposable.set((combineLatest(saveValues) @@ -2781,7 +2781,7 @@ final class SecureIdDocumentFormControllerNode: FormControllerNode deliverOnMainQueue).start(error: { error in guard let strongSelf = self else { return @@ -2965,7 +2965,7 @@ final class SecureIdDocumentFormControllerNode: FormControllerNode() @@ -75,12 +75,12 @@ class SecureIdDocumentGalleryController: ViewController { var deleteResource: ((TelegramMediaResource) -> Void)? - init(account: Account, context: SecureIdAccessContext, entries: [SecureIdDocumentGalleryEntry], centralIndex: Int, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void) { - self.account = account + init(context: AccountContext, secureIdContext: SecureIdAccessContext, entries: [SecureIdDocumentGalleryEntry], centralIndex: Int, replaceRootController: @escaping (ViewController, ValuePromise?) -> Void) { self.context = context + self.secureIdContext = secureIdContext self.replaceRootController = replaceRootController - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(theme: GalleryController.darkNavigationTheme, strings: NavigationBarStrings(presentationStrings: self.presentationData.strings))) @@ -97,7 +97,7 @@ class SecureIdDocumentGalleryController: ViewController { strongSelf.centralEntryIndex = centralIndex if strongSelf.isViewLoaded { strongSelf.galleryNode.pager.replaceItems(strongSelf.entries.map({ - $0.item(account: account, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, context: strongSelf.context, delete: { resource in + $0.item(account: context.account, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, context: 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: account, theme: self.presentationData.theme, strings: self.presentationData.strings, context: self.context, delete: { [weak self] resource in + $0.item(account: context.account, theme: self.presentationData.theme, strings: self.presentationData.strings, context: self.secureIdContext, delete: { [weak self] resource in self?.deleteItem(resource) }) }), centralItemIndex: self.centralEntryIndex) diff --git a/TelegramUI/SecureIdDocumentGalleryFooterContentNode.swift b/TelegramUI/SecureIdDocumentGalleryFooterContentNode.swift index 341efdcfc4..234fd54b10 100644 --- a/TelegramUI/SecureIdDocumentGalleryFooterContentNode.swift +++ b/TelegramUI/SecureIdDocumentGalleryFooterContentNode.swift @@ -13,7 +13,7 @@ private let titleFont = Font.medium(15.0) private let dateFont = Font.regular(14.0) final class SecureIdDocumentGalleryFooterContentNode: GalleryFooterContentNode { - private let account: Account + private let context: AccountContext private var theme: PresentationTheme private var strings: PresentationStrings @@ -28,8 +28,8 @@ final class SecureIdDocumentGalleryFooterContentNode: GalleryFooterContentNode { var delete: (() -> Void)? - init(account: Account, theme: PresentationTheme, strings: PresentationStrings) { - self.account = account + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings) { + self.context = context self.theme = theme self.strings = strings @@ -135,7 +135,7 @@ final class SecureIdDocumentGalleryFooterContentNode: GalleryFooterContentNode { } @objc func deleteButtonPressed() { - let presentationData = self.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = self.context.currentPresentationData.with { $0 } let actionSheet = ActionSheetController(presentationTheme: presentationData.theme) let items: [ActionSheetItem] = [ ActionSheetButtonItem(title: presentationData.strings.Common_Delete, color: .destructive, action: { [weak self, weak actionSheet] in diff --git a/TelegramUI/SecureIdDocumentImageGalleryItem.swift b/TelegramUI/SecureIdDocumentImageGalleryItem.swift index a9e5c0838e..29d8919d40 100644 --- a/TelegramUI/SecureIdDocumentImageGalleryItem.swift +++ b/TelegramUI/SecureIdDocumentImageGalleryItem.swift @@ -6,20 +6,20 @@ import Postbox import TelegramCore class SecureIdDocumentGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let theme: PresentationTheme let strings: PresentationStrings - let context: SecureIdAccessContext + let secureIdContext: SecureIdAccessContext let resource: TelegramMediaResource let caption: String let location: SecureIdDocumentGalleryEntryLocation let delete: () -> Void - init(account: Account, theme: PresentationTheme, strings: PresentationStrings, context: SecureIdAccessContext, resource: TelegramMediaResource, caption: String, location: SecureIdDocumentGalleryEntryLocation, delete: @escaping () -> Void) { - self.account = account + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings, secureIdContext: SecureIdAccessContext, resource: TelegramMediaResource, caption: String, location: SecureIdDocumentGalleryEntryLocation, delete: @escaping () -> Void) { + self.context = context self.theme = theme self.strings = strings - self.context = context + self.secureIdContext = secureIdContext self.resource = resource self.caption = caption self.location = location @@ -27,9 +27,9 @@ class SecureIdDocumentGalleryItem: GalleryItem { } func node() -> GalleryItemNode { - let node = SecureIdDocumentGalleryItemNode(account: self.account, theme: self.theme, strings: self.strings) + let node = SecureIdDocumentGalleryItemNode(context: self.context, theme: self.theme, strings: self.strings) - node.setResource(context: self.context, resource: self.resource) + node.setResource(secureIdContext: self.secureIdContext, resource: self.resource) node._title.set(.single("\(self.location.position + 1) \(self.strings.Common_of) \(self.location.totalCount)")) @@ -54,14 +54,14 @@ class SecureIdDocumentGalleryItem: GalleryItem { } final class SecureIdDocumentGalleryItemNode: ZoomableContentGalleryItemNode { - private let account: Account + private let context: AccountContext private let imageNode: TransformImageNode fileprivate let _ready = Promise() fileprivate let _title = Promise() private let footerContentNode: SecureIdDocumentGalleryFooterContentNode - private var accountAndMedia: (Account, SecureIdAccessContext, TelegramMediaResource)? + private var contextAndMedia: (AccountContext, SecureIdAccessContext, TelegramMediaResource)? private var fetchDisposable = MetaDisposable() @@ -71,8 +71,8 @@ final class SecureIdDocumentGalleryItemNode: ZoomableContentGalleryItemNode { } } - init(account: Account, theme: PresentationTheme, strings: PresentationStrings) { - self.account = account + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings) { + self.context = context self.imageNode = TransformImageNode() self.footerContentNode = SecureIdDocumentGalleryFooterContentNode(account: account, theme: theme, strings: strings) @@ -103,11 +103,11 @@ final class SecureIdDocumentGalleryItemNode: ZoomableContentGalleryItemNode { self.footerContentNode.setup(caption: caption) } - fileprivate func setResource(context: SecureIdAccessContext, resource: TelegramMediaResource) { - if self.accountAndMedia == nil || !self.accountAndMedia!.2.isEqual(to: resource) { + fileprivate func setResource(secureIdContext: SecureIdAccessContext, resource: TelegramMediaResource) { + if self.contextAndMedia == nil || !self.contextAndMedia!.2.isEqual(to: resource) { let displaySize = CGSize(width: 1280.0, height: 1280.0) //self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: displaySize, boundingSize: displaySize, intrinsicInsets: UIEdgeInsets()))() - self.imageNode.setSignal(securePhotoInternal(account: account, resource: resource, accessContext: context) |> beforeNext { [weak self] value in + self.imageNode.setSignal(securePhotoInternal(account: context.account, resource: resource, accessContext: secureIdContext) |> beforeNext { [weak self] value in Queue.mainQueue().async { if let strongSelf = self { if let size = value.0(), strongSelf.zoomableContent?.0 != size { @@ -120,9 +120,9 @@ final class SecureIdDocumentGalleryItemNode: ZoomableContentGalleryItemNode { return value.1 }) self.zoomableContent = (displaySize, self.imageNode) - self.fetchDisposable.set(account.postbox.mediaBox.fetchedResource(resource, parameters: nil).start()) + self.fetchDisposable.set(context.account.postbox.mediaBox.fetchedResource(resource, parameters: nil).start()) } - self.accountAndMedia = (account, context, resource) + self.contextAndMedia = (context, secureIdContext, resource) } override func animateIn(from node: (ASDisplayNode, () -> UIView?), addToTransitionSurface: (UIView) -> Void) { diff --git a/TelegramUI/SecureIdPlaintextFormController.swift b/TelegramUI/SecureIdPlaintextFormController.swift index f2ce9152e7..5a17a45606 100644 --- a/TelegramUI/SecureIdPlaintextFormController.swift +++ b/TelegramUI/SecureIdPlaintextFormController.swift @@ -11,26 +11,26 @@ enum SecureIdPlaintextFormType { } final class SecureIdPlaintextFormController: FormController { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let updatedValue: (SecureIdValueWithContext?) -> Void - private let context: SecureIdAccessContext + private let secureIdContext: SecureIdAccessContext private let type: SecureIdPlaintextFormType private var immediatelyAvailableValue: SecureIdValue? private var nextItem: UIBarButtonItem? private var doneItem: UIBarButtonItem? - init(account: Account, context: SecureIdAccessContext, type: SecureIdPlaintextFormType, immediatelyAvailableValue: SecureIdValue?, updatedValue: @escaping (SecureIdValueWithContext?) -> Void) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, secureIdContext: SecureIdAccessContext, type: SecureIdPlaintextFormType, immediatelyAvailableValue: SecureIdValue?, updatedValue: @escaping (SecureIdValueWithContext?) -> Void) { self.context = context + self.presentationData = context.currentPresentationData.with { $0 } + self.secureIdContext = secureIdContext self.type = type self.immediatelyAvailableValue = immediatelyAvailableValue self.updatedValue = updatedValue - super.init(initParams: SecureIdPlaintextFormControllerNodeInitParams(account: account, context: context), presentationData: self.presentationData) + super.init(initParams: SecureIdPlaintextFormControllerNodeInitParams(context: context, secureIdContext: secureIdContext), presentationData: self.presentationData) switch type { case .phone: diff --git a/TelegramUI/SecureIdPlaintextFormControllerNode.swift b/TelegramUI/SecureIdPlaintextFormControllerNode.swift index 20301ab795..f4d095730b 100644 --- a/TelegramUI/SecureIdPlaintextFormControllerNode.swift +++ b/TelegramUI/SecureIdPlaintextFormControllerNode.swift @@ -623,8 +623,8 @@ enum SecureIdPlaintextFormEntry: FormControllerEntry { } struct SecureIdPlaintextFormControllerNodeInitParams { - let account: Account - let context: SecureIdAccessContext + let context: AccountContext + let secureIdContext: SecureIdAccessContext } final class SecureIdPlaintextFormControllerNode: FormControllerNode { @@ -636,8 +636,8 @@ final class SecureIdPlaintextFormControllerNode: FormControllerNode Void)? var completedWithValue: ((SecureIdValueWithContext?) -> Void)? @@ -648,8 +648,8 @@ final class SecureIdPlaintextFormControllerNode: FormControllerNode deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { guard let innerState = strongSelf.innerState else { @@ -803,7 +803,7 @@ final class SecureIdPlaintextFormControllerNode: FormControllerNode deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { guard var innerState = strongSelf.innerState else { @@ -849,7 +849,7 @@ final class SecureIdPlaintextFormControllerNode: FormControllerNode deliverOnMainQueue).start(next: { [weak self] result in guard let strongSelf = self else { return @@ -859,7 +859,7 @@ final class SecureIdPlaintextFormControllerNode: FormControllerNode deliverOnMainQueue).start(next: { result in guard let strongSelf = self else { return @@ -913,7 +913,7 @@ final class SecureIdPlaintextFormControllerNode: FormControllerNode deliverOnMainQueue).start(next: { [weak self] result in if let strongSelf = self { guard let innerState = strongSelf.innerState else { diff --git a/TelegramUI/SelectablePeerNode.swift b/TelegramUI/SelectablePeerNode.swift index ae829d7260..cea07e2f6e 100644 --- a/TelegramUI/SelectablePeerNode.swift +++ b/TelegramUI/SelectablePeerNode.swift @@ -109,7 +109,7 @@ final class SelectablePeerNode: ASDisplayNode { } - func setup(account: Account, strings: PresentationStrings, peer: RenderedPeer, numberOfLines: Int = 2, synchronousLoad: Bool) { + func setup(account: Account, theme: PresentationTheme, strings: PresentationStrings, peer: RenderedPeer, numberOfLines: Int = 2, synchronousLoad: Bool) { self.peer = peer guard let mainPeer = peer.chatMainPeer else { return @@ -127,7 +127,7 @@ final class SelectablePeerNode: ASDisplayNode { } self.textNode.maximumNumberOfLines = UInt(numberOfLines) self.textNode.attributedText = NSAttributedString(string: text, font: textFont, textColor: self.currentSelected ? self.theme.selectedTextColor : defaultColor, paragraphAlignment: .center) - self.avatarNode.setPeer(account: account, peer: mainPeer, overrideImage: overrideImage, emptyColor: self.theme.avatarPlaceholderColor, synchronousLoad: synchronousLoad) + self.avatarNode.setPeer(account: account, theme: theme, peer: mainPeer, overrideImage: overrideImage, emptyColor: self.theme.avatarPlaceholderColor, synchronousLoad: synchronousLoad) self.setNeedsLayout() } diff --git a/TelegramUI/SelectivePrivacySettingsController.swift b/TelegramUI/SelectivePrivacySettingsController.swift index 6ba9b68649..0be9a59e50 100644 --- a/TelegramUI/SelectivePrivacySettingsController.swift +++ b/TelegramUI/SelectivePrivacySettingsController.swift @@ -499,8 +499,8 @@ private func selectivePrivacySettingsControllerEntries(presentationData: Present return entries } -func selectivePrivacySettingsController(account: Account, kind: SelectivePrivacySettingsKind, current: SelectivePrivacySettings, callSettings: (SelectivePrivacySettings, VoiceCallSettings)? = nil, voipConfiguration: VoipConfiguration? = nil, callIntegrationAvailable: Bool? = nil, updated: @escaping (SelectivePrivacySettings, (SelectivePrivacySettings, VoiceCallSettings)?) -> Void) -> ViewController { - let strings = account.telegramApplicationContext.currentPresentationData.with { $0 }.strings +func selectivePrivacySettingsController(context: AccountContext, kind: SelectivePrivacySettingsKind, current: SelectivePrivacySettings, callSettings: (SelectivePrivacySettings, VoiceCallSettings)? = nil, voipConfiguration: VoipConfiguration? = nil, callIntegrationAvailable: Bool? = nil, updated: @escaping (SelectivePrivacySettings, (SelectivePrivacySettings, VoiceCallSettings)?) -> Void) -> ViewController { + let strings = context.currentPresentationData.with { $0 }.strings var initialEnableFor = Set() var initialDisableFor = Set() @@ -545,7 +545,7 @@ func selectivePrivacySettingsController(account: Account, kind: SelectivePrivacy let updateSettingsDisposable = MetaDisposable() actionsDisposable.add(updateSettingsDisposable) - let arguments = SelectivePrivacySettingsControllerArguments(account: account, updateType: { type in + let arguments = SelectivePrivacySettingsControllerArguments(account: context.account, updateType: { type in updateState { $0.withUpdatedSetting(type) } @@ -564,7 +564,7 @@ func selectivePrivacySettingsController(account: Account, kind: SelectivePrivacy peerIds = state.enableFor return state } - pushControllerImpl?(selectivePrivacyPeersController(account: account, title: title, initialPeerIds: Array(peerIds), updated: { updatedPeerIds in + pushControllerImpl?(selectivePrivacyPeersController(context: context, title: title, initialPeerIds: Array(peerIds), updated: { updatedPeerIds in updateState { state in switch target { case .main: @@ -589,7 +589,7 @@ func selectivePrivacySettingsController(account: Account, kind: SelectivePrivacy peerIds = state.disableFor return state } - pushControllerImpl?(selectivePrivacyPeersController(account: account, title: title, initialPeerIds: Array(peerIds), updated: { updatedPeerIds in + pushControllerImpl?(selectivePrivacyPeersController(context: context, title: title, initialPeerIds: Array(peerIds), updated: { updatedPeerIds in updateState { state in switch target { case .main: @@ -607,14 +607,14 @@ func selectivePrivacySettingsController(account: Account, kind: SelectivePrivacy updateState { state in return state.withUpdatedCallsIntegrationEnabled(enabled) } - let _ = updateVoiceCallSettingsSettingsInteractively(postbox: account.postbox, { settings in + let _ = updateVoiceCallSettingsSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.enableSystemIntegration = enabled return settings }).start() }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get()) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, statePromise.get()) |> deliverOnMainQueue |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, SelectivePrivacySettingsEntry.ItemGenerationArguments)) in let leftNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Cancel), style: .regular, enabled: true, action: { @@ -665,10 +665,10 @@ func selectivePrivacySettingsController(account: Account, kind: SelectivePrivacy type = .voiceCalls } - let updateSettingsSignal = updateSelectiveAccountPrivacySettings(account: account, type: type, settings: settings) + let updateSettingsSignal = updateSelectiveAccountPrivacySettings(account: context.account, type: type, settings: settings) var updateCallP2PSettingsSignal: Signal = Signal.complete() if let callP2PSettings = callP2PSettings { - updateCallP2PSettingsSignal = updateSelectiveAccountPrivacySettings(account: account, type: .voiceCallsP2P, settings: callP2PSettings) + updateCallP2PSettingsSignal = updateSelectiveAccountPrivacySettings(account: context.account, type: .voiceCallsP2P, settings: callP2PSettings) } updateSettingsDisposable.set((combineLatest(updateSettingsSignal, updateCallP2PSettingsSignal) |> deliverOnMainQueue).start(completed: { @@ -703,7 +703,7 @@ func selectivePrivacySettingsController(account: Account, kind: SelectivePrivacy actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] c in (controller?.navigationController as? NavigationController)?.pushViewController(c) } diff --git a/TelegramUI/SelectivePrivacySettingsPeersController.swift b/TelegramUI/SelectivePrivacySettingsPeersController.swift index a48963a038..a7bc1002f8 100644 --- a/TelegramUI/SelectivePrivacySettingsPeersController.swift +++ b/TelegramUI/SelectivePrivacySettingsPeersController.swift @@ -195,7 +195,7 @@ private func selectivePrivacyPeersControllerEntries(presentationData: Presentati return entries } -public func selectivePrivacyPeersController(account: Account, title: String, initialPeerIds: [PeerId], updated: @escaping ([PeerId]) -> Void) -> ViewController { +public func selectivePrivacyPeersController(context: AccountContext, title: String, initialPeerIds: [PeerId], updated: @escaping ([PeerId]) -> Void) -> ViewController { let statePromise = ValuePromise(SelectivePrivacyPeersControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: SelectivePrivacyPeersControllerState()) let updateState: ((SelectivePrivacyPeersControllerState) -> SelectivePrivacyPeersControllerState) -> Void = { f in @@ -213,7 +213,7 @@ public func selectivePrivacyPeersController(account: Account, title: String, ini actionsDisposable.add(removePeerDisposable) let peersPromise = Promise<[Peer]>() - peersPromise.set(account.postbox.transaction { transaction -> [Peer] in + peersPromise.set(context.account.postbox.transaction { transaction -> [Peer] in var result: [Peer] = [] for peerId in initialPeerIds { if let peer = transaction.getPeer(peerId) { @@ -223,7 +223,7 @@ public func selectivePrivacyPeersController(account: Account, title: String, ini return result }) - let arguments = SelectivePrivacyPeersControllerArguments(account: account, setPeerIdWithRevealedOptions: { peerId, fromPeerId in + let arguments = SelectivePrivacyPeersControllerArguments(account: context.account, setPeerIdWithRevealedOptions: { peerId, fromPeerId in updateState { state in if (peerId == nil && fromPeerId == state.peerIdWithRevealedOptions) || (peerId != nil && fromPeerId == nil) { return state.withUpdatedPeerIdWithRevealedOptions(peerId) @@ -251,12 +251,12 @@ public func selectivePrivacyPeersController(account: Account, title: String, ini removePeerDisposable.set(applyPeers.start()) }, addPeer: { - let controller = ContactMultiselectionController(account: account, mode: .peerSelection(searchChatList: true), options: []) + let controller = ContactMultiselectionController(context: context, mode: .peerSelection(searchChatList: true), options: []) addPeerDisposable.set((controller.result |> take(1) |> deliverOnMainQueue).start(next: { [weak controller] peerIds in let applyPeers: Signal = peersPromise.get() |> take(1) |> mapToSignal { peers -> Signal<[Peer], NoError> in - return account.postbox.transaction { transaction -> [Peer] in + return context.account.postbox.transaction { transaction -> [Peer] in var updatedPeers = peers var existingIds = Set(updatedPeers.map { $0.id }) for peerId in peerIds { @@ -286,7 +286,7 @@ public func selectivePrivacyPeersController(account: Account, title: String, ini var previousPeers: [Peer]? - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), peersPromise.get()) + let signal = combineLatest(context.presentationData, statePromise.get(), peersPromise.get()) |> deliverOnMainQueue |> map { presentationData, state, peers -> (ItemListControllerState, (ItemListNodeState, SelectivePrivacyPeersEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? @@ -317,7 +317,7 @@ public func selectivePrivacyPeersController(account: Account, title: String, ini actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, p in if let controller = controller { controller.present(c, in: .window(.root), with: p) diff --git a/TelegramUI/SettingsController.swift b/TelegramUI/SettingsController.swift index a9a6a69295..98a97d2bc8 100644 --- a/TelegramUI/SettingsController.swift +++ b/TelegramUI/SettingsController.swift @@ -465,21 +465,21 @@ private func settingsEntries(account: Account, presentationData: PresentationDat } public protocol SettingsController: class { - func updateAccount(account: Account) + func updateContext(context: AccountContext) } private final class SettingsControllerImpl: ItemListController, SettingsController { - let accountValue: Promise + let contextValue: Promise - init(currentAccount: Account, accountValue: Promise, state: Signal<(ItemListControllerState, (ItemListNodeState, SettingsEntry.ItemGenerationArguments)), NoError>, tabBarItem: Signal?) { - self.accountValue = accountValue - let presentationData = currentAccount.telegramApplicationContext.currentPresentationData.with { $0 } + init(currentContext: AccountContext, contextValue: Promise, state: Signal<(ItemListControllerState, (ItemListNodeState, SettingsEntry.ItemGenerationArguments)), NoError>, tabBarItem: Signal?) { + self.contextValue = contextValue + let presentationData = currentContext.currentPresentationData.with { $0 } - self.accountValue.set(.single(currentAccount)) + self.contextValue.set(.single(currentContext)) - let updatedPresentationData = self.accountValue.get() - |> mapToSignal { account -> Signal<(theme: PresentationTheme, strings: PresentationStrings), NoError> in - return account.telegramApplicationContext.presentationData + let updatedPresentationData = self.contextValue.get() + |> mapToSignal { context -> Signal<(theme: PresentationTheme, strings: PresentationStrings), NoError> in + return context.presentationData |> map { ($0.theme, $0.strings) } } @@ -490,12 +490,12 @@ private final class SettingsControllerImpl: ItemListController, S fatalError("init(coder:) has not been implemented") } - func updateAccount(account: Account) { - self.accountValue.set(.single(account)) + func updateContext(context: AccountContext) { + self.contextValue.set(.single(context)) } } -public func settingsController(account currentAccount: Account, accountManager: AccountManager) -> SettingsController & ViewController { +public func settingsController(context: AccountContext, accountManager: AccountManager) -> SettingsController & ViewController { let statePromise = ValuePromise(SettingsState(), ignoreRepeated: true) let stateValue = Atomic(value: SettingsState()) let updateState: ((SettingsState) -> SettingsState) -> Void = { f in @@ -534,11 +534,11 @@ public func settingsController(account currentAccount: Account, accountManager: let archivedPacks = Promise<[ArchivedStickerPackItem]?>() - let accountValue = Promise() + let contextValue = Promise() - let networkArguments = currentAccount.networkArguments - let auxiliaryMethods = currentAccount.auxiliaryMethods - let rootPath = rootPathForBasePath(currentAccount.telegramApplicationContext.applicationBindings.containerPath) + let networkArguments = context.account.networkArguments + let auxiliaryMethods = context.account.auxiliaryMethods + let rootPath = rootPathForBasePath(context.applicationBindings.containerPath) let accountsAndPeers: Signal<[(Account, Peer, Int32)], NoError> = accountManager.accountRecords() |> map { view -> [AccountRecordId] in @@ -551,7 +551,7 @@ public func settingsController(account currentAccount: Account, accountManager: } |> distinctUntilChanged |> mapToSignal { recordIds -> Signal<[(Account, Peer, Int32)], NoError> in - return accountValue.get() + return contextValue.get() |> mapToSignal { currentAccount -> Signal<[(Account, Peer, Int32)], NoError> in var accounts: [Signal<(Account, Peer, Int32)?, NoError>] = [] func accountWithPeer(_ account: Signal) -> Signal<(Account, Peer, Int32)?, NoError> { @@ -598,10 +598,10 @@ public func settingsController(account currentAccount: Account, accountManager: } let openFaq: (Promise) -> Void = { resolvedUrl in - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + |> take(1)).start(next: { context in + let presentationData = context.currentPresentationData.with { $0 } let controller = OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .loading(cancelled: nil)) presentControllerImpl?(controller, nil) let _ = (resolvedUrl.get() @@ -609,7 +609,7 @@ public func settingsController(account currentAccount: Account, accountManager: |> deliverOnMainQueue).start(next: { [weak controller] resolvedUrl in controller?.dismiss() - openResolvedUrl(resolvedUrl, account: account, navigationController: getNavigationControllerImpl?(), openPeer: { peer, navigation in + openResolvedUrl(resolvedUrl, context: context, navigationController: getNavigationControllerImpl?(), openPeer: { peer, navigation in }, present: { controller, arguments in pushControllerImpl?(controller) }, dismissInput: {}) @@ -617,14 +617,14 @@ public func settingsController(account currentAccount: Account, accountManager: }) } - let resolvedUrl = accountValue.get() + let resolvedUrl = contextValue.get() |> deliverOnMainQueue - |> mapToSignal { account -> Signal in - var faqUrl = account.telegramApplicationContext.currentPresentationData.with { $0 }.strings.Settings_FAQ_URL + |> mapToSignal { context -> Signal in + var faqUrl = context.currentPresentationData.with { $0 }.strings.Settings_FAQ_URL if faqUrl == "Settings.FAQ_URL" || faqUrl.isEmpty { faqUrl = "https://telegram.org/faq#general" } - return resolveInstantViewUrl(account: account, url: faqUrl) + return resolveInstantViewUrl(account: context.account, url: faqUrl) } var switchToAccountImpl: ((AccountRecordId) -> Void)? @@ -640,14 +640,14 @@ public func settingsController(account currentAccount: Account, accountManager: return } - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - let _ = (account.postbox.loadedPeerWithId(account.peerId) + |> take(1)).start(next: { context in + let _ = (context.account.postbox.loadedPeerWithId(account.peerId) |> take(1) |> deliverOnMainQueue).start(next: { peer in if peer.smallProfileImage != nil { - let galleryController = AvatarGalleryController(account: 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 @@ -665,86 +665,86 @@ public func settingsController(account currentAccount: Account, accountManager: }, changeProfilePhoto: { changeProfilePhotoImpl?() }, openUsername: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - presentControllerImpl?(usernameSetupController(account: account), nil) + |> take(1)).start(next: { context in + presentControllerImpl?(usernameSetupController(context: context), nil) }) }, openProxy: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue |> take(1)).start(next: { account in - pushControllerImpl?(proxySettingsController(account: account)) + pushControllerImpl?(proxySettingsController(context: context)) }) }, openSavedMessages: { openSavedMessagesImpl?() }, openRecentCalls: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue |> take(1)).start(next: { account in - pushControllerImpl?(CallListController(account: account, mode: .navigation)) + pushControllerImpl?(CallListController(context: context, mode: .navigation)) }) }, openPrivacyAndSecurity: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - pushControllerImpl?(privacyAndSecurityController(account: account, initialSettings: .single(nil) |> then(requestAccountPrivacySettings(account: account) |> map(Optional.init)))) + |> take(1)).start(next: { context in + pushControllerImpl?(privacyAndSecurityController(context: context, initialSettings: .single(nil) |> then(requestAccountPrivacySettings(account: context.account) |> map(Optional.init)))) }) }, openDataAndStorage: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - pushControllerImpl?(dataAndStorageController(account: account)) + |> take(1)).start(next: { context in + pushControllerImpl?(dataAndStorageController(context: context)) }) }, openStickerPacks: { archivedPacksValue in - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - pushControllerImpl?(installedStickerPacksController(account: account, mode: .general, archivedPacks: archivedPacksValue, updatedPacks: { packs in + |> take(1)).start(next: { context in + pushControllerImpl?(installedStickerPacksController(context: context, mode: .general, archivedPacks: archivedPacksValue, updatedPacks: { packs in archivedPacks.set(.single(packs)) })) }) }, openNotificationsAndSounds: { exceptionsList in - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - pushControllerImpl?(notificationsAndSoundsController(account: account, exceptionsList: exceptionsList)) + |> take(1)).start(next: { context in + pushControllerImpl?(notificationsAndSoundsController(context: context, exceptionsList: exceptionsList)) }) }, openThemes: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - pushControllerImpl?(themeSettingsController(account: account)) + |> take(1)).start(next: { context in + pushControllerImpl?(themeSettingsController(context: context)) }) }, pushController: { controller in pushControllerImpl?(controller) }, openLanguage: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - pushControllerImpl?(LocalizationListController(account: account)) + |> take(1)).start(next: { context in + pushControllerImpl?(LocalizationListController(context: context)) }) }, openPassport: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - let controller = SecureIdAuthController(account: account, mode: .list) + |> take(1)).start(next: { context in + let controller = SecureIdAuthController(context: context, mode: .list) presentControllerImpl?(controller, nil) }) }, openWatch: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - let controller = watchSettingsController(account: account) + |> take(1)).start(next: { context in + let controller = watchSettingsController(context: context) pushControllerImpl?(controller) }) }, openSupport: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in + |> take(1)).start(next: { context in let supportPeer = Promise() - supportPeer.set(supportPeerId(account: account)) - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + supportPeer.set(supportPeerId(account: context.account)) + let presentationData = context.currentPresentationData.with { $0 } let resolvedUrlPromise = Promise() resolvedUrlPromise.set(resolvedUrl) @@ -768,11 +768,11 @@ public func settingsController(account currentAccount: Account, accountManager: openFaq(resolvedUrlPromise) }, openEditing: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in + |> take(1)).start(next: { context in var cancelImpl: (() -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let progressSignal = Signal { subscriber in let controller = OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .loading(cancelled: { cancelImpl?() @@ -788,14 +788,14 @@ public func settingsController(account currentAccount: Account, accountManager: |> delay(0.15, queue: Queue.mainQueue()) let progressDisposable = progressSignal.start() - let peerKey: PostboxViewKey = .peer(peerId: account.peerId, components: []) + let peerKey: PostboxViewKey = .peer(peerId: context.account.peerId, components: []) let cachedDataKey: PostboxViewKey = .cachedPeerData(peerId: account.peerId) - let signal = (account.postbox.combinedView(keys: [peerKey, cachedDataKey]) + 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 { return .complete() } - guard let peerView = view.views[peerKey] as? PeerView, let peer = peerView.peers[account.peerId] as? TelegramUser else { + guard let peerView = view.views[peerKey] as? PeerView, let peer = peerView.peers[context.account.peerId] as? TelegramUser else { return .complete() } return .single((peer, cachedData)) @@ -811,15 +811,15 @@ public func settingsController(account currentAccount: Account, accountManager: } openEditingDisposable.set((signal |> deliverOnMainQueue).start(next: { peer, cachedData in - pushControllerImpl?(editSettingsController(account: account, currentName: .personName(firstName: peer.firstName ?? "", lastName: peer.lastName ?? ""), currentBioText: cachedData.about ?? "", accountManager: accountManager)) + pushControllerImpl?(editSettingsController(context: context, currentName: .personName(firstName: peer.firstName ?? "", lastName: peer.lastName ?? ""), currentBioText: cachedData.about ?? "", accountManager: accountManager)) })) }) }, displayCopyContextMenu: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - let _ = (account.postbox.transaction { transaction -> (Peer?) in - return transaction.getPeer(account.peerId) + |> take(1)).start(next: { context in + let _ = (context.account.postbox.transaction { transaction -> (Peer?) in + return transaction.getPeer(context.account.peerId) } |> deliverOnMainQueue).start(next: { peer in if let peer = peer { @@ -830,10 +830,10 @@ public func settingsController(account currentAccount: Account, accountManager: }, switchToAccount: { id in switchToAccountImpl?(id) }, addAccount: { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - let isTestingEnvironment = account.testingEnvironment + |> take(1)).start(next: { context in + let isTestingEnvironment = context.account.testingEnvironment let _ = accountManager.transaction({ transaction -> Void in let id = transaction.createRecord([AccountEnvironmentAttribute(environment: isTestingEnvironment ? .test : .production)]) transaction.setCurrentId(id) @@ -842,14 +842,14 @@ public func settingsController(account currentAccount: Account, accountManager: }) changeProfilePhotoImpl = { - let _ = (accountValue.get() + let _ = (contextValue.get() |> deliverOnMainQueue - |> take(1)).start(next: { account in - let _ = (account.postbox.transaction { transaction -> (Peer?, SearchBotsConfiguration) in - return (transaction.getPeer(account.peerId), currentSearchBotsConfiguration(transaction: transaction)) + |> take(1)).start(next: { context 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 = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let legacyController = LegacyController(presentation: .custom, theme: presentationData.theme) legacyController.statusBar.statusBarStyle = .Ignore @@ -871,13 +871,13 @@ public func settingsController(account currentAccount: Account, accountManager: 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) updateState { $0.withUpdatedUpdatingAvatar(.image(representation, true)) } - updateAvatarDisposable.set((updateAccountPhoto(account: account, resource: resource, mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) + updateAvatarDisposable.set((updateAccountPhoto(account: context.account, resource: resource, mapResourceToAvatarSizes: { resource, representations in + return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations) }) |> deliverOnMainQueue).start(next: { result in switch result { case .complete: @@ -894,7 +894,7 @@ public func settingsController(account currentAccount: Account, accountManager: let mixin = TGMediaAvatarMenuMixin(context: legacyController.context, parentController: emptyController, hasSearchButton: true, hasDeleteButton: hasPhotos, hasViewButton: false, personalPhoto: true, 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: nil, completion: { result in + let controller = WebSearchController(context: context, peer: peer, configuration: searchBotsConfiguration, mode: .avatar(initialQuery: nil, completion: { result in assetsController?.dismiss() completedImpl(result) })) @@ -914,8 +914,8 @@ public func settingsController(account currentAccount: Account, accountManager: return $0.withUpdatedUpdatingAvatar(.none) } } - updateAvatarDisposable.set((updateAccountPhoto(account: account, resource: nil, mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: account.postbox, resource: resource, representations: representations) + updateAvatarDisposable.set((updateAccountPhoto(account: context.account, resource: nil, mapResourceToAvatarSizes: { resource, representations in + return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations) }) |> deliverOnMainQueue).start(next: { result in switch result { case .complete: @@ -941,17 +941,17 @@ public func settingsController(account currentAccount: Account, accountManager: }) } - let peerView = accountValue.get() - |> mapToSignal { account -> Signal in - return account.viewTracker.peerView(account.peerId) + let peerView = contextValue.get() + |> mapToSignal { context -> Signal in + return context.account.viewTracker.peerView(context.account.peerId) } archivedPacks.set( .single(nil) |> then( - accountValue.get() - |> mapToSignal { account -> Signal<[ArchivedStickerPackItem]?, NoError> in - archivedStickerPacks(account: account) + contextValue.get() + |> mapToSignal { context -> Signal<[ArchivedStickerPackItem]?, NoError> in + archivedStickerPacks(account: context.account) |> map(Optional.init) } ) @@ -960,10 +960,10 @@ public func settingsController(account currentAccount: Account, accountManager: let hasPassport = ValuePromise(false) let updatePassport: () -> Void = { updatePassportDisposable.set(( - accountValue.get() + contextValue.get() |> take(1) - |> mapToSignal { account -> Signal in - return twoStepAuthData(account.network) + |> mapToSignal { context -> Signal in + return twoStepAuthData(context.account.network) |> map { value -> Bool in return value.hasSecretValues } @@ -982,9 +982,9 @@ public func settingsController(account currentAccount: Account, accountManager: notificationsAuthorizationStatus.set( .single(.allowed) |> then( - accountValue.get() - |> mapToSignal { account -> Signal in - return DeviceAccess.authorizationStatus(account: account, subject: .notifications) + contextValue.get() + |> mapToSignal { context -> Signal in + return DeviceAccess.authorizationStatus(account: context.account, subject: .notifications) } ) ) @@ -996,9 +996,9 @@ public func settingsController(account currentAccount: Account, accountManager: notificationsWarningSuppressed.set( .single(true) |> then( - accountValue.get() - |> mapToSignal { account -> Signal in - return account.postbox.combinedView(keys: [warningKey]) + contextValue.get() + |> mapToSignal { context -> Signal in + return context.account.postbox.combinedView(keys: [warningKey]) |> map { combined -> Bool in let timestamp = (combined.views[warningKey] as? NoticeEntryView)?.value.flatMap({ ApplicationSpecificNotice.getTimestampValue($0) }) if let timestamp = timestamp, timestamp > 0 { @@ -1015,10 +1015,10 @@ public func settingsController(account currentAccount: Account, accountManager: let notifyExceptions = Promise(nil) let updateNotifyExceptions: () -> Void = { notifyExceptions.set( - accountValue.get() + contextValue.get() |> take(1) - |> mapToSignal { account -> Signal in - return notificationExceptionsList(network: account.network) + |> mapToSignal { context -> Signal in + return notificationExceptionsList(network: context.account.network) |> map(Optional.init) } ) @@ -1026,9 +1026,9 @@ public func settingsController(account currentAccount: Account, accountManager: let hasWatchApp = Promise(false) hasWatchApp.set( - accountValue.get() - |> mapToSignal { account -> Signal in - if let context = account.applicationContext as? TelegramApplicationContext, let watchManager = context.watchManager { + contextValue.get() + |> mapToSignal { context -> Signal in + if let watchManager = context.watchManager { return watchManager.watchAppInstalled } else { return .single(false) @@ -1036,23 +1036,23 @@ public func settingsController(account currentAccount: Account, accountManager: } ) - let updatedPresentationData = accountValue.get() - |> mapToSignal { account -> Signal in - return account.telegramApplicationContext.presentationData + let updatedPresentationData = contextValue.get() + |> mapToSignal { context -> Signal in + return context.presentationData } - let proxyPreferences = accountValue.get() - |> mapToSignal { account in - return account.postbox.preferencesView(keys: [PreferencesKeys.proxySettings]) + let proxyPreferences = contextValue.get() + |> mapToSignal { context in + return context.account.postbox.preferencesView(keys: [PreferencesKeys.proxySettings]) } - let featuredStickerPacks = accountValue.get() - |> mapToSignal { account in - return account.viewTracker.featuredStickerPacks() + let featuredStickerPacks = contextValue.get() + |> mapToSignal { context in + return context.account.viewTracker.featuredStickerPacks() } - let signal = combineLatest(queue: Queue.mainQueue(), accountValue.get(), updatedPresentationData, statePromise.get(), peerView, combineLatest(queue: Queue.mainQueue(), proxyPreferences, notifyExceptions.get(), notificationsAuthorizationStatus.get(), notificationsWarningSuppressed.get()), combineLatest(featuredStickerPacks, archivedPacks.get()), combineLatest(hasPassport.get(), hasWatchApp.get()), accountsAndPeers) - |> map { account, presentationData, state, view, preferencesAndExceptions, featuredAndArchived, hasPassportAndWatch, accountsAndPeers -> (ItemListControllerState, (ItemListNodeState, SettingsEntry.ItemGenerationArguments)) in + let signal = combineLatest(queue: Queue.mainQueue(), contextValue.get(), updatedPresentationData, statePromise.get(), peerView, combineLatest(queue: Queue.mainQueue(), proxyPreferences, notifyExceptions.get(), notificationsAuthorizationStatus.get(), notificationsWarningSuppressed.get()), combineLatest(featuredStickerPacks, archivedPacks.get()), combineLatest(hasPassport.get(), hasWatchApp.get()), accountsAndPeers) + |> map { context, presentationData, state, view, preferencesAndExceptions, featuredAndArchived, hasPassportAndWatch, accountsAndPeers -> (ItemListControllerState, (ItemListNodeState, SettingsEntry.ItemGenerationArguments)) in let proxySettings: ProxySettings = preferencesAndExceptions.0.values[PreferencesKeys.proxySettings] as? ProxySettings ?? ProxySettings.defaultSettings let rightNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Edit), style: .regular, enabled: true, action: { @@ -1069,7 +1069,7 @@ public func settingsController(account currentAccount: Account, accountManager: } let (hasPassport, hasWatchApp) = hasPassportAndWatch - let listState = ItemListNodeState(entries: settingsEntries(account: account, presentationData: presentationData, state: state, view: view, proxySettings: proxySettings, notifyExceptions: preferencesAndExceptions.1, notificationsAuthorizationStatus: preferencesAndExceptions.2, notificationsWarningSuppressed: preferencesAndExceptions.3, unreadTrendingStickerPacks: unreadTrendingStickerPacks, archivedPacks: featuredAndArchived.1, hasPassport: hasPassport, hasWatchApp: hasWatchApp, accountsAndPeers: accountsAndPeers), style: .blocks) + let listState = ItemListNodeState(entries: settingsEntries(account: context.account, presentationData: presentationData, state: state, view: view, proxySettings: proxySettings, notifyExceptions: preferencesAndExceptions.1, notificationsAuthorizationStatus: preferencesAndExceptions.2, notificationsWarningSuppressed: preferencesAndExceptions.3, unreadTrendingStickerPacks: unreadTrendingStickerPacks, archivedPacks: featuredAndArchived.1, hasPassport: hasPassport, hasWatchApp: hasWatchApp, accountsAndPeers: accountsAndPeers), style: .blocks) return (controllerState, (listState, arguments)) } @@ -1084,7 +1084,7 @@ public func settingsController(account currentAccount: Account, accountManager: icon = UIImage(bundleImageName: "Chat List/Tabs/IconSettings") } - let controller = SettingsControllerImpl(currentAccount: currentAccount, accountValue: accountValue, state: signal, tabBarItem: combineLatest(updatedPresentationData, notificationsAuthorizationStatus.get(), notificationsWarningSuppressed.get()) |> map { presentationData, notificationsAuthorizationStatus, notificationsWarningSuppressed in + let controller = SettingsControllerImpl(currentContext: context, contextValue: contextValue, state: signal, tabBarItem: combineLatest(updatedPresentationData, notificationsAuthorizationStatus.get(), notificationsWarningSuppressed.get()) |> map { presentationData, notificationsAuthorizationStatus, notificationsWarningSuppressed in let notificationsWarning = shouldDisplayNotificationsPermissionWarning(status: notificationsAuthorizationStatus, suppressed: notificationsWarningSuppressed) return ItemListControllerTabBarItem(title: presentationData.strings.Settings_Title, image: icon, selectedImage: icon, badgeValue: notificationsWarning ? "!" : nil) }) @@ -1122,7 +1122,7 @@ public func settingsController(account currentAccount: Account, accountManager: } } openSavedMessagesImpl = { [weak controller] in - let _ = (accountValue.get() + let _ = (contextValue.get() |> take(1) |> deliverOnMainQueue).start(next: { account in if let controller = controller, let navigationController = controller.navigationController as? NavigationController { @@ -1131,7 +1131,7 @@ public func settingsController(account currentAccount: Account, accountManager: }) } controller.tabBarItemDebugTapAction = { - let _ = (accountValue.get() + let _ = (contextValue.get() |> take(1) |> deliverOnMainQueue).start(next: { account in pushControllerImpl?(debugController(account: account, accountManager: accountManager)) @@ -1139,11 +1139,11 @@ public func settingsController(account currentAccount: Account, accountManager: } displayCopyContextMenuImpl = { [weak controller] peer in - let _ = (accountValue.get() + let _ = (contextValue.get() |> take(1) - |> deliverOnMainQueue).start(next: { account in + |> deliverOnMainQueue).start(next: { context 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? ItemListAvatarAndNameInfoItemNode { diff --git a/TelegramUI/SetupTwoStepVerificationController.swift b/TelegramUI/SetupTwoStepVerificationController.swift index c39a7f011c..7bf7fe19b6 100644 --- a/TelegramUI/SetupTwoStepVerificationController.swift +++ b/TelegramUI/SetupTwoStepVerificationController.swift @@ -6,7 +6,7 @@ import SwiftSignalKit import TelegramCore class SetupTwoStepVerificationController: ViewController { - private let account: Account + private let context: AccountContext private let initialState: SetupTwoStepVerificationInitialState private let stateUpdated: (SetupTwoStepVerificationStateUpdate, Bool, SetupTwoStepVerificationController) -> Void @@ -27,12 +27,12 @@ class SetupTwoStepVerificationController: ViewController { private var presentationData: PresentationData private var presentationDataDisposable: Disposable? - init(account: Account, initialState: SetupTwoStepVerificationInitialState, stateUpdated: @escaping (SetupTwoStepVerificationStateUpdate, Bool, SetupTwoStepVerificationController) -> Void) { - self.account = account + init(context: AccountContext, initialState: SetupTwoStepVerificationInitialState, stateUpdated: @escaping (SetupTwoStepVerificationStateUpdate, Bool, SetupTwoStepVerificationController) -> Void) { + self.context = context self.initialState = initialState self.stateUpdated = stateUpdated - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(theme: NavigationBarTheme(buttonColor: self.presentationData.theme.rootController.navigationBar.accentTextColor, disabledButtonColor: self.presentationData.theme.rootController.navigationBar.disabledButtonColor, primaryTextColor: self.presentationData.theme.rootController.navigationBar.primaryTextColor, backgroundColor: .clear, separatorColor: .clear, badgeBackgroundColor: .clear, badgeStrokeColor: .clear, badgeTextColor: .clear), strings: NavigationBarStrings(presentationStrings: self.presentationData.strings))) @@ -40,7 +40,7 @@ class SetupTwoStepVerificationController: ViewController { self.navigationItem.setLeftBarButton(UIBarButtonItem(title: self.presentationData.strings.Common_Cancel, style: .plain, target: self, action: #selector(self.cancelPressed)), animated: false) - 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 @@ -98,7 +98,7 @@ class SetupTwoStepVerificationController: ViewController { } override public func loadDisplayNode() { - self.displayNode = SetupTwoStepVerificationControllerNode(account: self.account, updateBackAction: { [weak self] action in + self.displayNode = SetupTwoStepVerificationControllerNode(context: self.context, updateBackAction: { [weak self] action in guard let strongSelf = self else { return } diff --git a/TelegramUI/SetupTwoStepVerificationControllerNode.swift b/TelegramUI/SetupTwoStepVerificationControllerNode.swift index 4d12babf43..400a90a17c 100644 --- a/TelegramUI/SetupTwoStepVerificationControllerNode.swift +++ b/TelegramUI/SetupTwoStepVerificationControllerNode.swift @@ -134,7 +134,7 @@ enum SetupTwoStepVerificationStateUpdate { } final class SetupTwoStepVerificationControllerNode: ViewControllerTracingNode { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let updateBackAction: (Bool) -> Void private let updateNextAction: (SetupTwoStepVerificationNextAction) -> Void @@ -147,14 +147,14 @@ final class SetupTwoStepVerificationControllerNode: ViewControllerTracingNode { private var contentNode: SetupTwoStepVerificationContentNode? private let actionDisposable = MetaDisposable() - init(account: Account, updateBackAction: @escaping (Bool) -> Void, updateNextAction: @escaping (SetupTwoStepVerificationNextAction) -> Void, stateUpdated: @escaping (SetupTwoStepVerificationStateUpdate, Bool) -> Void, present: @escaping (ViewController, Any?) -> Void, dismiss: @escaping () -> Void, initialState: SetupTwoStepVerificationInitialState) { - self.account = account + init(context: AccountContext, updateBackAction: @escaping (Bool) -> Void, updateNextAction: @escaping (SetupTwoStepVerificationNextAction) -> Void, stateUpdated: @escaping (SetupTwoStepVerificationStateUpdate, Bool) -> Void, present: @escaping (ViewController, Any?) -> Void, dismiss: @escaping () -> Void, initialState: SetupTwoStepVerificationInitialState) { + self.context = context self.updateBackAction = updateBackAction self.updateNextAction = updateNextAction self.stateUpdated = stateUpdated self.present = present self.dismiss = dismiss - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.innerState = SetupTwoStepVerificationControllerInnerState(layout: nil, data: SetupTwoStepVerificationControllerDataState(activity: false, state: SetupTwoStepVerificationState(initialState: initialState))) self.activityIndicator = ActivityIndicator(type: .custom(self.presentationData.theme.list.itemAccentColor, 22.0, 2.0, false)) @@ -164,7 +164,7 @@ final class SetupTwoStepVerificationControllerNode: ViewControllerTracingNode { self.processStateUpdated() if self.innerState.data.state == nil { - self.actionDisposable.set((twoStepAuthData(account.network) + self.actionDisposable.set((twoStepAuthData(context.account.network) |> deliverOnMainQueue).start(next: { [weak self] data in guard let strongSelf = self else { return @@ -334,7 +334,7 @@ final class SetupTwoStepVerificationControllerNode: ViewControllerTracingNode { state.data.activity = true return state }, transition: .animated(duration: 0.5, curve: .spring)) - strongSelf.actionDisposable.set((updateTwoStepVerificationPassword(network: strongSelf.account.network, currentPassword: nil, updatedPassword: .none) + strongSelf.actionDisposable.set((updateTwoStepVerificationPassword(network: strongSelf.context.account.network, currentPassword: nil, updatedPassword: .none) |> deliverOnMainQueue).start(next: { _ in guard let strongSelf = self else { return @@ -387,7 +387,7 @@ final class SetupTwoStepVerificationControllerNode: ViewControllerTracingNode { state.data.activity = true return state }, transition: .animated(duration: 0.5, curve: .spring)) - strongSelf.actionDisposable.set((resendTwoStepRecoveryEmail(network: strongSelf.account.network) + strongSelf.actionDisposable.set((resendTwoStepRecoveryEmail(network: strongSelf.context.account.network) |> deliverOnMainQueue).start(error: { error in guard let strongSelf = self else { return @@ -528,7 +528,7 @@ final class SetupTwoStepVerificationControllerNode: ViewControllerTracingNode { state.data.state = .enterEmail(state: .create(password: password, hint: hint), email: "") case let .update(current, hasRecoveryEmail, hasSecureValues): state.data.activity = true - strongSelf.actionDisposable.set((updateTwoStepVerificationPassword(network: strongSelf.account.network, currentPassword: current, updatedPassword: .password(password: password, hint: hint, email: nil)) + strongSelf.actionDisposable.set((updateTwoStepVerificationPassword(network: strongSelf.context.account.network, currentPassword: current, updatedPassword: .password(password: password, hint: hint, email: nil)) |> deliverOnMainQueue).start(next: { result in guard let strongSelf = self else { return @@ -564,7 +564,7 @@ final class SetupTwoStepVerificationControllerNode: ViewControllerTracingNode { state.data.activity = true switch enterState { case let .create(password, hint): - strongSelf.actionDisposable.set((updateTwoStepVerificationPassword(network: strongSelf.account.network, currentPassword: nil, updatedPassword: .password(password: password, hint: hint, email: email)) + strongSelf.actionDisposable.set((updateTwoStepVerificationPassword(network: strongSelf.context.account.network, currentPassword: nil, updatedPassword: .password(password: password, hint: hint, email: email)) |> deliverOnMainQueue).start(next: { result in guard let strongSelf = self else { return @@ -612,7 +612,7 @@ final class SetupTwoStepVerificationControllerNode: ViewControllerTracingNode { state.data.activity = true return state }, transition: .animated(duration: 0.5, curve: .spring)) - strongSelf.actionDisposable.set((updateTwoStepVerificationEmail(account: strongSelf.account, currentPassword: password, updatedEmail: email) + strongSelf.actionDisposable.set((updateTwoStepVerificationEmail(account: strongSelf.context.account, currentPassword: password, updatedEmail: email) |> deliverOnMainQueue).start(next: { result in guard let strongSelf = self else { return @@ -648,7 +648,7 @@ final class SetupTwoStepVerificationControllerNode: ViewControllerTracingNode { } case let .confirmEmail(confirmState, _, _, code): state.data.activity = true - strongSelf.actionDisposable.set((confirmTwoStepRecoveryEmail(network: strongSelf.account.network, code: code) + strongSelf.actionDisposable.set((confirmTwoStepRecoveryEmail(network: strongSelf.context.account.network, code: code) |> deliverOnMainQueue).start(error: { error in guard let strongSelf = self else { return diff --git a/TelegramUI/ShareController.swift b/TelegramUI/ShareController.swift index f004eee332..5294a1a050 100644 --- a/TelegramUI/ShareController.swift +++ b/TelegramUI/ShareController.swift @@ -189,7 +189,7 @@ public final class ShareController: ViewController { private var animatedIn = false - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private var presentationDataDisposable: Disposable? @@ -204,13 +204,13 @@ public final class ShareController: ViewController { public var dismissed: ((Bool) -> Void)? - public init(account: Account, subject: ShareControllerSubject, preferredAction: ShareControllerPreferredAction = .default, showInChat: ((Message) -> Void)? = nil, externalShare: Bool = true, immediateExternalShare: Bool = false) { - self.account = account + public init(context: AccountContext, subject: ShareControllerSubject, preferredAction: ShareControllerPreferredAction = .default, showInChat: ((Message) -> Void)? = nil, externalShare: Bool = true, immediateExternalShare: Bool = false) { + self.context = context self.externalShare = externalShare self.immediateExternalShare = immediateExternalShare self.subject = subject - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: nil) @@ -275,7 +275,7 @@ public final class ShareController: ViewController { else if let chatPeer = message.peers[message.id.peerId] as? TelegramChannel, messages.count == 1 || sameGroupingKey { if message.id.namespace == Namespaces.Message.Cloud, let addressName = chatPeer.addressName, !addressName.isEmpty { self.defaultAction = ShareControllerAction(title: self.presentationData.strings.ShareMenu_CopyShareLink, action: { [weak self] in - let _ = (exportMessageLink(account: account, peerId: chatPeer.id, messageId: message.id) + let _ = (exportMessageLink(account: context.account, peerId: chatPeer.id, messageId: message.id) |> map { result -> String in return result ?? "https://t.me/\(addressName)/\(message.id.id)" } @@ -298,8 +298,8 @@ public final class ShareController: ViewController { }) } - self.peers.set(combineLatest(account.postbox.loadedPeerWithId(account.peerId) - |> take(1), account.viewTracker.tailChatListView(groupId: nil, count: 150) + self.peers.set(combineLatest(context.account.postbox.loadedPeerWithId(context.account.peerId) + |> take(1), context.account.viewTracker.tailChatListView(groupId: nil, count: 150) |> take(1)) |> map { accountPeer, view -> ([RenderedPeer], Peer) in var peers: [RenderedPeer] = [] @@ -316,7 +316,7 @@ public final class ShareController: ViewController { return (peers, accountPeer) }) - self.presentationDataDisposable = (self.account.telegramApplicationContext.presentationData + self.presentationDataDisposable = (self.context.presentationData |> deliverOnMainQueue).start(next: { [weak self] presentationData in if let strongSelf = self, strongSelf.isNodeLoaded { strongSelf.controllerNode.updatePresentationData(presentationData) @@ -333,7 +333,7 @@ public final class ShareController: ViewController { } override public func loadDisplayNode() { - self.displayNode = ShareControllerNode(account: self.account, defaultAction: self.defaultAction, requestLayout: { [weak self] transition in + self.displayNode = ShareControllerNode(context: self.context, defaultAction: self.defaultAction, requestLayout: { [weak self] transition in self?.requestLayout(transition: transition) }, externalShare: self.externalShare, immediateExternalShare: self.immediateExternalShare) self.controllerNode.dismiss = { [weak self] shared in @@ -354,7 +354,7 @@ public final class ShareController: ViewController { messages.append(.message(text: text, attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)) } messages.append(.message(text: url, attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)) - let _ = enqueueMessages(account: strongSelf.account, peerId: peerId, messages: messages).start() + let _ = enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: messages).start() } return .complete() case let .text(string): @@ -364,7 +364,7 @@ public final class ShareController: ViewController { messages.append(.message(text: text, attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)) } messages.append(.message(text: string, attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)) - let _ = enqueueMessages(account: strongSelf.account, peerId: peerId, messages: messages).start() + let _ = enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: messages).start() } return .complete() case let .quote(string, url): @@ -377,7 +377,7 @@ public final class ShareController: ViewController { attributedText.append(NSAttributedString(string: "\n\n\(url)")) let entities = generateChatInputTextEntities(attributedText) messages.append(.message(text: attributedText.string, attributes: [TextEntitiesMessageAttribute(entities: entities)], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)) - let _ = enqueueMessages(account: strongSelf.account, peerId: peerId, messages: messages).start() + let _ = enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: messages).start() } return .complete() case let .image(representations): @@ -387,7 +387,7 @@ public final class ShareController: ViewController { messages.append(.message(text: text, attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)) } messages.append(.message(text: "", attributes: [], mediaReference: .standalone(media: TelegramMediaImage(imageId: MediaId(namespace: Namespaces.Media.LocalImage, id: arc4random64()), representations: representations.map({ $0.representation }), immediateThumbnailData: nil, reference: nil, partialReference: nil)), replyToMessageId: nil, localGroupingKey: nil)) - let _ = enqueueMessages(account: strongSelf.account, peerId: peerId, messages: messages).start() + let _ = enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: messages).start() } return .complete() case let .media(mediaReference): @@ -397,7 +397,7 @@ public final class ShareController: ViewController { messages.append(.message(text: text, attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)) } messages.append(.message(text: "", attributes: [], mediaReference: mediaReference, replyToMessageId: nil, localGroupingKey: nil)) - let _ = enqueueMessages(account: strongSelf.account, peerId: peerId, messages: messages).start() + let _ = enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: messages).start() } return .complete() case let .mapMedia(media): @@ -407,7 +407,7 @@ public final class ShareController: ViewController { messages.append(.message(text: text, attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)) } messages.append(.message(text: "", attributes: [], mediaReference: .standalone(media: media), replyToMessageId: nil, localGroupingKey: nil)) - let _ = enqueueMessages(account: strongSelf.account, peerId: peerId, messages: messages).start() + let _ = enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: messages).start() } return .complete() case let .messages(messages): @@ -419,7 +419,7 @@ public final class ShareController: ViewController { for message in messages { messagesToEnqueue.append(.forward(source: message.id, grouping: .auto)) } - let _ = enqueueMessages(account: strongSelf.account, peerId: peerId, messages: messagesToEnqueue).start() + let _ = enqueueMessages(account: strongSelf.context.account, peerId: peerId, messages: messagesToEnqueue).start() } return .single(.done) case let .fromExternal(f): @@ -473,7 +473,7 @@ public final class ShareController: ViewController { selectedMedia = image } } - case let _ as TelegramMediaPoll: + case _ as TelegramMediaPoll: selectedMedia = media break loop default: @@ -490,7 +490,7 @@ public final class ShareController: ViewController { case .fromExternal: break } - return (collectExternalShareItems(strings: strongSelf.presentationData.strings, postbox: strongSelf.account.postbox, collectableItems: collectableItems) |> deliverOnMainQueue) |> map { state in + return (collectExternalShareItems(strings: strongSelf.presentationData.strings, postbox: strongSelf.context.account.postbox, collectableItems: collectableItems) |> deliverOnMainQueue) |> map { state in switch state { case .progress: return .preparing @@ -561,10 +561,10 @@ public final class ShareController: ViewController { } private func saveToCameraRoll(messages: [Message]) { - let postbox = self.account.postbox + let postbox = self.context.account.postbox let signals: [Signal] = messages.compactMap { message -> Signal? in if let media = message.media.first { - return TelegramUI.saveToCameraRoll(applicationContext: self.account.telegramApplicationContext, postbox: postbox, mediaReference: .message(message: MessageReference(message), media: media)) + return TelegramUI.saveToCameraRoll(context: self.context, postbox: postbox, mediaReference: .message(message: MessageReference(message), media: media)) } else { return nil } @@ -585,10 +585,10 @@ public final class ShareController: ViewController { private func saveToCameraRoll(representations: [ImageRepresentationWithReference]) { let media = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: representations.map({ $0.representation }), immediateThumbnailData: nil, reference: nil, partialReference: nil) - self.controllerNode.transitionToProgressWithValue(signal: TelegramUI.saveToCameraRoll(applicationContext: self.account.telegramApplicationContext, postbox: self.account.postbox, mediaReference: .standalone(media: media)) |> map(Optional.init)) + self.controllerNode.transitionToProgressWithValue(signal: TelegramUI.saveToCameraRoll(context: self.context, postbox: self.context.account.postbox, mediaReference: .standalone(media: media)) |> map(Optional.init)) } private func saveToCameraRoll(mediaReference: AnyMediaReference) { - self.controllerNode.transitionToProgressWithValue(signal: TelegramUI.saveToCameraRoll(applicationContext: self.account.telegramApplicationContext, postbox: self.account.postbox, mediaReference: mediaReference) |> map(Optional.init)) + self.controllerNode.transitionToProgressWithValue(signal: TelegramUI.saveToCameraRoll(context: self.context, postbox: self.context.account.postbox, mediaReference: mediaReference) |> map(Optional.init)) } } diff --git a/TelegramUI/ShareControllerNode.swift b/TelegramUI/ShareControllerNode.swift index ec46e4487a..3b433458a1 100644 --- a/TelegramUI/ShareControllerNode.swift +++ b/TelegramUI/ShareControllerNode.swift @@ -21,7 +21,7 @@ func openExternalShare(state: () -> Signal) { } final class ShareControllerNode: ViewControllerTracingNode, UIScrollViewDelegate { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let externalShare: Bool private let immediateExternalShare: Bool @@ -67,9 +67,9 @@ final class ShareControllerNode: ViewControllerTracingNode, UIScrollViewDelegate private var hapticFeedback: HapticFeedback? - init(account: Account, defaultAction: ShareControllerAction?, requestLayout: @escaping (ContainedViewLayoutTransition) -> Void, externalShare: Bool, immediateExternalShare: Bool) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, defaultAction: ShareControllerAction?, requestLayout: @escaping (ContainedViewLayoutTransition) -> Void, externalShare: Bool, immediateExternalShare: Bool) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.externalShare = externalShare self.immediateExternalShare = immediateExternalShare @@ -584,15 +584,15 @@ final class ShareControllerNode: ViewControllerTracingNode, UIScrollViewDelegate } func updatePeers(peers: [RenderedPeer], accountPeer: Peer, defaultAction: ShareControllerAction?) { - let peersContentNode = SharePeersContainerNode(account: self.account, theme: self.presentationData.theme, strings: self.presentationData.strings, peers: peers, accountPeer: accountPeer, controllerInteraction: self.controllerInteraction!, externalShare: self.externalShare) + let peersContentNode = SharePeersContainerNode(context: self.context, theme: self.presentationData.theme, strings: self.presentationData.strings, peers: peers, accountPeer: accountPeer, controllerInteraction: self.controllerInteraction!, externalShare: self.externalShare) self.peersContentNode = peersContentNode peersContentNode.openSearch = { [weak self] in if let strongSelf = self { - let _ = (recentlySearchedPeers(postbox: strongSelf.account.postbox) + let _ = (recentlySearchedPeers(postbox: strongSelf.context.account.postbox) |> take(1) |> deliverOnMainQueue).start(next: { peers in if let strongSelf = self { - let searchContentNode = ShareSearchContainerNode(account: strongSelf.account, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, controllerInteraction: strongSelf.controllerInteraction!, recentPeers: peers.filter({ $0.peer.peerId.namespace != Namespaces.Peer.SecretChat }).map({ $0.peer })) + let searchContentNode = ShareSearchContainerNode(context: strongSelf.context, theme: strongSelf.presentationData.theme, strings: strongSelf.presentationData.strings, controllerInteraction: strongSelf.controllerInteraction!, recentPeers: peers.filter({ $0.peer.peerId.namespace != Namespaces.Peer.SecretChat }).map({ $0.peer })) searchContentNode.cancel = { if let strongSelf = self, let peersContentNode = strongSelf.peersContentNode { strongSelf.transitionToContentNode(peersContentNode) diff --git a/TelegramUI/SharePeersContainerNode.swift b/TelegramUI/SharePeersContainerNode.swift index a94c4a97a8..83433fbb88 100644 --- a/TelegramUI/SharePeersContainerNode.swift +++ b/TelegramUI/SharePeersContainerNode.swift @@ -54,7 +54,7 @@ private func preparedGridEntryTransition(account: Account, from fromEntries: [Sh } final class SharePeersContainerNode: ASDisplayNode, ShareContentContainerNode { - private let account: Account + private let context: AccountContext private let theme: PresentationTheme private let strings: PresentationStrings private let controllerInteraction: ShareControllerInteraction @@ -82,8 +82,8 @@ final class SharePeersContainerNode: ASDisplayNode, ShareContentContainerNode { private var validLayout: (CGSize, CGFloat)? private var overrideGridOffsetTransition: ContainedViewLayoutTransition? - init(account: Account, theme: PresentationTheme, strings: PresentationStrings, peers: [RenderedPeer], accountPeer: Peer, controllerInteraction: ShareControllerInteraction, externalShare: Bool) { - self.account = account + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings, peers: [RenderedPeer], accountPeer: Peer, controllerInteraction: ShareControllerInteraction, externalShare: Bool) { + self.context = context self.theme = theme self.strings = strings self.controllerInteraction = controllerInteraction @@ -157,7 +157,7 @@ final class SharePeersContainerNode: ASDisplayNode, ShareContentContainerNode { strongSelf.entries = entries let firstTime = previousEntries == nil - let transition = preparedGridEntryTransition(account: account, from: previousEntries ?? [], to: entries, interfaceInteraction: controllerInteraction) + let transition = preparedGridEntryTransition(account: context.account, from: previousEntries ?? [], to: entries, interfaceInteraction: controllerInteraction) strongSelf.enqueueTransition(transition, firstTime: firstTime) } })) diff --git a/TelegramUI/ShareSearchContainerNode.swift b/TelegramUI/ShareSearchContainerNode.swift index f76a2946be..a5cd9c3b1a 100644 --- a/TelegramUI/ShareSearchContainerNode.swift +++ b/TelegramUI/ShareSearchContainerNode.swift @@ -161,7 +161,7 @@ private func preparedRecentEntryTransition(account: Account, from fromEntries: [ } final class ShareSearchContainerNode: ASDisplayNode, ShareContentContainerNode { - private let account: Account + private let context: AccountContext private let strings: PresentationStrings private let controllerInteraction: ShareControllerInteraction @@ -191,8 +191,8 @@ final class ShareSearchContainerNode: ASDisplayNode, ShareContentContainerNode { private let searchQuery = ValuePromise("", ignoreRepeated: true) private let searchDisposable = MetaDisposable() - init(account: Account, theme: PresentationTheme, strings: PresentationStrings, controllerInteraction: ShareControllerInteraction, recentPeers: [RenderedPeer]) { - self.account = account + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings, controllerInteraction: ShareControllerInteraction, recentPeers: [RenderedPeer]) { + self.context = context self.strings = strings self.controllerInteraction = controllerInteraction @@ -237,10 +237,13 @@ final class ShareSearchContainerNode: ASDisplayNode, ShareContentContainerNode { let foundItems = searchQuery.get() |> mapToSignal { query -> Signal<[ShareSearchPeerEntry]?, NoError> in if !query.isEmpty { - let accountPeer = account.postbox.loadedPeerWithId(account.peerId) |> take(1) - let foundLocalPeers = account.postbox.searchPeers(query: query.lowercased(), groupId: nil) - let foundRemotePeers: Signal<([FoundPeer], [FoundPeer]), NoError> = .single(([], [])) |> then(searchPeers(account: account, query: query) - |> delay(0.2, queue: Queue.concurrentDefaultQueue())) + let accountPeer = context.account.postbox.loadedPeerWithId(context.account.peerId) |> take(1) + let foundLocalPeers = context.account.postbox.searchPeers(query: query.lowercased(), groupId: nil) + let foundRemotePeers: Signal<([FoundPeer], [FoundPeer]), NoError> = .single(([], [])) + |> then( + searchPeers(account: context.account, query: query) + |> delay(0.2, queue: Queue.concurrentDefaultQueue()) + ) return combineLatest(accountPeer, foundLocalPeers, foundRemotePeers) |> map { accountPeer, foundLocalPeers, foundRemotePeers -> [ShareSearchPeerEntry]? in @@ -301,7 +304,7 @@ final class ShareSearchContainerNode: ASDisplayNode, ShareContentContainerNode { strongSelf.entries = entries ?? [] let firstTime = previousEntries == nil - let transition = preparedGridEntryTransition(account: account, from: previousEntries ?? [], to: entries ?? [], interfaceInteraction: controllerInteraction) + let transition = preparedGridEntryTransition(account: context.account, from: previousEntries ?? [], to: entries ?? [], interfaceInteraction: controllerInteraction) strongSelf.enqueueTransition(transition, firstTime: firstTime) if (previousEntries == nil) != (entries == nil) { @@ -341,7 +344,7 @@ final class ShareSearchContainerNode: ASDisplayNode, ShareContentContainerNode { strongSelf.recentEntries = entries let firstTime = previousEntries == nil - let transition = preparedRecentEntryTransition(account: account, from: previousEntries ?? [], to: entries, interfaceInteraction: controllerInteraction) + let transition = preparedRecentEntryTransition(account: context.account, from: previousEntries ?? [], to: entries, interfaceInteraction: controllerInteraction) strongSelf.enqueueRecentTransition(transition, firstTime: firstTime) } })) diff --git a/TelegramUI/SoftwareVideoThumbnailLayer.swift b/TelegramUI/SoftwareVideoThumbnailLayer.swift index bb88d3c1ea..c082abf425 100644 --- a/TelegramUI/SoftwareVideoThumbnailLayer.swift +++ b/TelegramUI/SoftwareVideoThumbnailLayer.swift @@ -28,7 +28,7 @@ final class SoftwareVideoThumbnailLayer: CALayer { self.masksToBounds = true if let dimensions = fileReference.media.dimensions { - self.disposable = (mediaGridMessageVideo(postbox: account.postbox, videoReference: fileReference) |> deliverOn(account.graphicsThreadPool)).start(next: { [weak self] transform in + self.disposable = (mediaGridMessageVideo(postbox: account.postbox, videoReference: fileReference) |> deliverOn(Queue.concurrentDefaultQueue())).start(next: { [weak self] transform in var boundingSize = dimensions.aspectFilled(CGSize(width: 93.0, height: 93.0)) let imageSize = boundingSize boundingSize.width = min(200.0, boundingSize.width) diff --git a/TelegramUI/StickerPackPreviewController.swift b/TelegramUI/StickerPackPreviewController.swift index 1d32d045ff..fc26fd8584 100644 --- a/TelegramUI/StickerPackPreviewController.swift +++ b/TelegramUI/StickerPackPreviewController.swift @@ -18,7 +18,7 @@ final class StickerPackPreviewController: ViewController { private var animatedIn = false private var dismissed = false - private let account: Account + private let context: AccountContext private let mode: StickerPackPreviewControllerMode private weak var parentNavigationController: NavigationController? @@ -51,8 +51,8 @@ final class StickerPackPreviewController: ViewController { } } - init(account: Account, stickerPack: StickerPackReference, mode: StickerPackPreviewControllerMode = .default, parentNavigationController: NavigationController?) { - self.account = account + init(context: AccountContext, stickerPack: StickerPackReference, mode: StickerPackPreviewControllerMode = .default, parentNavigationController: NavigationController?) { + self.context = context self.mode = mode self.parentNavigationController = parentNavigationController @@ -62,9 +62,9 @@ final class StickerPackPreviewController: ViewController { self.statusBar.statusBarStyle = .Ignore - self.stickerPackContents.set(loadedStickerPack(postbox: account.postbox, network: account.network, reference: stickerPack, forceActualized: true)) + self.stickerPackContents.set(loadedStickerPack(postbox: context.account.postbox, network: context.account.network, reference: stickerPack, forceActualized: true)) - self.presentationDataDisposable = (self.account.telegramApplicationContext.presentationData + self.presentationDataDisposable = (context.presentationData |> deliverOnMainQueue).start(next: { [weak self] presentationData in if let strongSelf = self, strongSelf.isNodeLoaded { strongSelf.controllerNode.updatePresentationData(presentationData) @@ -92,18 +92,18 @@ final class StickerPackPreviewController: ViewController { } if let stickerPackContentsValue = strongSelf.stickerPackContentsValue, case let .result(info, _, _) = stickerPackContentsValue, !info.shortName.isEmpty { - strongSelf.present(ShareController(account: strongSelf.account, subject: .url("https://t.me/addstickers/\(info.shortName)"), externalShare: true), in: .window(.root)) + strongSelf.present(ShareController(context: strongSelf.context, subject: .url("https://t.me/addstickers/\(info.shortName)"), externalShare: true), in: .window(.root)) strongSelf.dismiss() } } } - self.displayNode = StickerPackPreviewControllerNode(account: self.account, openShare: openShareImpl, openMention: { [weak self] mention in + self.displayNode = StickerPackPreviewControllerNode(context: self.context, openShare: openShareImpl, openMention: { [weak self] mention in guard let strongSelf = self else { return } - let account = strongSelf.account - strongSelf.openMentionDisposable.set((resolvePeerByName(account: strongSelf.account, name: mention) + let account = strongSelf.context.account + strongSelf.openMentionDisposable.set((resolvePeerByName(account: strongSelf.context.account, name: mention) |> mapToSignal { peerId -> Signal in if let peerId = peerId { return account.postbox.loadedPeerWithId(peerId) @@ -118,7 +118,7 @@ final class StickerPackPreviewController: ViewController { } if let peer = peer { strongSelf.dismiss() - strongSelf.parentNavigationController?.pushViewController(ChatController(account: strongSelf.account, chatLocation: .peer(peer.id), messageId: nil)) + strongSelf.parentNavigationController?.pushViewController(ChatController(context: strongSelf.context, chatLocation: .peer(peer.id), messageId: nil)) } })) }) @@ -141,7 +141,7 @@ final class StickerPackPreviewController: ViewController { self.stickerPackDisposable.set((self.stickerPackContents.get() |> deliverOnMainQueue).start(next: { [weak self] next in if let strongSelf = self { if case .none = next { - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } strongSelf.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: presentationData.strings.StickerPack_ErrorNotFound, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), in: .window(.root)) strongSelf.dismiss() } else { diff --git a/TelegramUI/StickerPackPreviewControllerNode.swift b/TelegramUI/StickerPackPreviewControllerNode.swift index 3a58a6b8d5..7f408c5d80 100644 --- a/TelegramUI/StickerPackPreviewControllerNode.swift +++ b/TelegramUI/StickerPackPreviewControllerNode.swift @@ -37,7 +37,7 @@ private struct StickerPackPreviewGridTransaction { } final class StickerPackPreviewControllerNode: ViewControllerTracingNode, UIScrollViewDelegate { - private let account: Account + private let context: AccountContext private let openShare: (() -> Void)? private var presentationData: PresentationData @@ -78,10 +78,10 @@ final class StickerPackPreviewControllerNode: ViewControllerTracingNode, UIScrol private var hapticFeedback: HapticFeedback? - init(account: Account, openShare: (() -> Void)?, openMention: @escaping (String) -> Void) { - self.account = account + init(context: AccountContext, openShare: (() -> Void)?, openMention: @escaping (String) -> Void) { + self.context = context self.openShare = openShare - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.wrappingScrollNode = ASScrollNode() self.wrappingScrollNode.view.alwaysBounceVertical = true @@ -192,7 +192,7 @@ final class StickerPackPreviewControllerNode: ViewControllerTracingNode, UIScrol self.contentGridNode.view.addGestureRecognizer(PeekControllerGestureRecognizer(contentAtPoint: { [weak self] point -> Signal<(ASDisplayNode, PeekControllerContent)?, NoError>? in if let strongSelf = self { if let itemNode = strongSelf.contentGridNode.itemNodeAtPoint(point) as? StickerPackPreviewGridItemNode, let item = itemNode.stickerPackItem { - return strongSelf.account.postbox.transaction { transaction -> Bool in + return strongSelf.context.account.postbox.transaction { transaction -> Bool in return getIsStickerSaved(transaction: transaction, fileId: item.file.fileId) } |> deliverOnMainQueue @@ -210,15 +210,15 @@ final class StickerPackPreviewControllerNode: ViewControllerTracingNode, UIScrol menuItems.append(PeekControllerMenuItem(title: isStarred ? strongSelf.presentationData.strings.Stickers_RemoveFromFavorites : strongSelf.presentationData.strings.Stickers_AddToFavorites, color: isStarred ? .destructive : .accent, action: { if let strongSelf = self { if isStarred { - let _ = removeSavedSticker(postbox: strongSelf.account.postbox, mediaId: item.file.fileId).start() + let _ = removeSavedSticker(postbox: strongSelf.context.account.postbox, mediaId: item.file.fileId).start() } else { - let _ = addSavedSticker(postbox: strongSelf.account.postbox, network: strongSelf.account.network, file: item.file).start() + let _ = addSavedSticker(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network, file: item.file).start() } } })) menuItems.append(PeekControllerMenuItem(title: strongSelf.presentationData.strings.Common_Cancel, color: .accent, action: {})) } - return (itemNode, StickerPreviewPeekContent(account: strongSelf.account, item: .pack(item), menu: menuItems)) + return (itemNode, StickerPreviewPeekContent(account: strongSelf.context.account, item: .pack(item), menu: menuItems)) } else { return nil } @@ -375,7 +375,7 @@ final class StickerPackPreviewControllerNode: ViewControllerTracingNode, UIScrol self.contentTitleNode.attributedText = stringWithAppliedEntities(info.title, entities: entities, baseColor: self.presentationData.theme.actionSheet.primaryTextColor, linkColor: self.presentationData.theme.actionSheet.controlAccentColor, baseFont: Font.medium(20.0), linkFont: Font.medium(20.0), boldFont: Font.medium(20.0), italicFont: Font.medium(20.0), fixedFont: Font.medium(20.0)) animateIn = true } - transaction = StickerPackPreviewGridTransaction(previousList: self.currentItems, list: updatedItems, account: self.account, interaction: self.interaction) + transaction = StickerPackPreviewGridTransaction(previousList: self.currentItems, list: updatedItems, account: self.context.account, interaction: self.interaction) self.currentItems = updatedItems } } @@ -509,10 +509,10 @@ final class StickerPackPreviewControllerNode: ViewControllerTracingNode, UIScrol switch stickerPack { case let .result(info, items, installed): if installed { - let _ = removeStickerPackInteractively(postbox: self.account.postbox, id: info.id, option: .delete).start() + let _ = removeStickerPackInteractively(postbox: self.context.account.postbox, id: info.id, option: .delete).start() updateStickerPack(.result(info: info, items: items, installed: false)) } else { - let _ = addStickerPackInteractively(postbox: self.account.postbox, info: info, items: items).start() + let _ = addStickerPackInteractively(postbox: self.context.account.postbox, info: info, items: items).start() if !dismissOnAction { updateStickerPack(.result(info: info, items: items, installed: true)) } diff --git a/TelegramUI/StickerPaneSearchContainerNode.swift b/TelegramUI/StickerPaneSearchContainerNode.swift index 7a3c5ec1e3..9d76367590 100644 --- a/TelegramUI/StickerPaneSearchContainerNode.swift +++ b/TelegramUI/StickerPaneSearchContainerNode.swift @@ -134,7 +134,7 @@ private func preparedChatMediaInputGridEntryTransition(account: Account, theme: } final class StickerPaneSearchContainerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private let controllerInteraction: ChatControllerInteraction private let inputNodeInteraction: ChatMediaInputNodeInteraction @@ -156,14 +156,14 @@ final class StickerPaneSearchContainerNode: ASDisplayNode { return self._ready.get() } - init(account: Account, theme: PresentationTheme, strings: PresentationStrings, controllerInteraction: ChatControllerInteraction, inputNodeInteraction: ChatMediaInputNodeInteraction, cancel: @escaping () -> Void) { - self.account = account + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings, controllerInteraction: ChatControllerInteraction, inputNodeInteraction: ChatMediaInputNodeInteraction, cancel: @escaping () -> Void) { + self.context = context self.controllerInteraction = controllerInteraction self.inputNodeInteraction = inputNodeInteraction self.backgroundNode = ASDisplayNode() - self.trendingPane = ChatMediaInputTrendingPane(account: account, controllerInteraction: controllerInteraction, getItemIsPreviewed: { [weak inputNodeInteraction] item in + self.trendingPane = ChatMediaInputTrendingPane(account: context.account, controllerInteraction: controllerInteraction, getItemIsPreviewed: { [weak inputNodeInteraction] item in return inputNodeInteraction?.previewedStickerPackItem == .pack(item) }) @@ -210,7 +210,7 @@ final class StickerPaneSearchContainerNode: ASDisplayNode { let interaction = StickerPaneSearchInteraction(open: { [weak self] info in if let strongSelf = self { strongSelf.view.endEditing(true) - strongSelf.controllerInteraction.presentController(StickerPackPreviewController(account: strongSelf.account, stickerPack: .id(id: info.id.id, accessHash: info.accessHash), parentNavigationController: strongSelf.controllerInteraction.navigationController()), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) + strongSelf.controllerInteraction.presentController(StickerPackPreviewController(context: strongSelf.context, stickerPack: .id(id: info.id.id, accessHash: info.accessHash), parentNavigationController: strongSelf.controllerInteraction.navigationController()), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } }, install: { [weak self] info in if let strongSelf = self { diff --git a/TelegramUI/StickerPreviewController.swift b/TelegramUI/StickerPreviewController.swift index 366d5b6575..98da923b46 100644 --- a/TelegramUI/StickerPreviewController.swift +++ b/TelegramUI/StickerPreviewController.swift @@ -20,11 +20,11 @@ final class StickerPreviewController: ViewController { private var animatedIn = false - private let account: Account + private let context: AccountContext private var item: StickerPackItem - init(account: Account, item: StickerPackItem) { - self.account = account + init(context: AccountContext, item: StickerPackItem) { + self.context = context self.item = item super.init(navigationBarPresentationData: nil) @@ -37,7 +37,7 @@ final class StickerPreviewController: ViewController { } override func loadDisplayNode() { - self.displayNode = StickerPreviewControllerNode(account: self.account) + self.displayNode = StickerPreviewControllerNode(context: self.context) self.controllerNode.dismiss = { [weak self] in self?.presentingViewController?.dismiss(animated: false, completion: nil) } diff --git a/TelegramUI/StickerPreviewControllerNode.swift b/TelegramUI/StickerPreviewControllerNode.swift index 8e32912988..ee306110b0 100644 --- a/TelegramUI/StickerPreviewControllerNode.swift +++ b/TelegramUI/StickerPreviewControllerNode.swift @@ -6,7 +6,7 @@ import Postbox import TelegramCore final class StickerPreviewControllerNode: ASDisplayNode, UIScrollViewDelegate { - private let account: Account + private let context: AccountContext private let presentationData: PresentationData private let dimNode: ASDisplayNode @@ -20,9 +20,9 @@ final class StickerPreviewControllerNode: ASDisplayNode, UIScrollViewDelegate { var dismiss: (() -> Void)? var cancel: (() -> Void)? - init(account: Account) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.dimNode = ASDisplayNode() self.dimNode.backgroundColor = presentationData.theme.list.plainBackgroundColor.withAlphaComponent(0.6) @@ -133,7 +133,7 @@ final class StickerPreviewControllerNode: ASDisplayNode, UIScrollViewDelegate { self.textNode.attributedText = NSAttributedString(string: text, font: Font.regular(32.0), textColor: .black) break } - self.imageNode.setSignal(chatMessageSticker(account: account, file: item.file, small: false)) + self.imageNode.setSignal(chatMessageSticker(account: context.account, file: item.file, small: false)) if let (layout, navigationBarHeight) = self.containerLayout { self.containerLayoutUpdated(layout, navigationBarHeight: navigationBarHeight, transition: .immediate) diff --git a/TelegramUI/StorageUsageController.swift b/TelegramUI/StorageUsageController.swift index 2c908fbb1c..443b3bba89 100644 --- a/TelegramUI/StorageUsageController.swift +++ b/TelegramUI/StorageUsageController.swift @@ -261,9 +261,9 @@ private func stringForCategory(strings: PresentationStrings, category: PeerCache } } -func storageUsageController(account: Account, isModal: Bool = false) -> ViewController { +func storageUsageController(context: context, isModal: Bool = false) -> ViewController { let cacheSettingsPromise = Promise() - cacheSettingsPromise.set(account.postbox.preferencesView(keys: [PreferencesKeys.cacheStorageSettings]) + cacheSettingsPromise.set(context.account.postbox.preferencesView(keys: [PreferencesKeys.cacheStorageSettings]) |> map { view -> CacheStorageSettings in let cacheSettings: CacheStorageSettings if let value = view.values[PreferencesKeys.cacheStorageSettings] as? CacheStorageSettings { @@ -279,7 +279,7 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont let statsPromise = Promise() let resetStats: () -> Void = { - let containerPath = account.telegramApplicationContext.applicationBindings.containerPath + let containerPath = context.applicationBindings.containerPath let additionalPaths: [String] = [ NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0], containerPath + "/Documents/files", @@ -289,7 +289,7 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont containerPath + "/Documents/tempcache_v1/store", ] statsPromise.set(.single(nil) - |> then(collectCacheUsageStats(account: account, additionalCachePaths: additionalPaths, logFilesPath: account.telegramApplicationContext.applicationBindings.containerPath + "/telegram-data/logs") + |> then(collectCacheUsageStats(account: context.account, additionalCachePaths: additionalPaths, logFilesPath: context.applicationBindings.containerPath + "/telegram-data/logs") |> map(Optional.init))) } resetStats() @@ -299,14 +299,14 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont let clearDisposable = MetaDisposable() actionDisposables.add(clearDisposable) - let arguments = StorageUsageControllerArguments(account: account, updateKeepMedia: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let arguments = StorageUsageControllerArguments(account: context.account, updateKeepMedia: { + let presentationData = context.currentPresentationData.with { $0 } let controller = ActionSheetController(presentationTheme: presentationData.theme) let dismissAction: () -> Void = { [weak controller] in controller?.dismissAnimated() } let timeoutAction: (Int32) -> Void = { timeout in - let _ = updateCacheStorageSettingsInteractively(postbox: account.postbox, { current in + let _ = updateCacheStorageSettingsInteractively(postbox: context.account.postbox, { current in return current.withUpdatedDefaultCacheStorageTimeout(timeout) }).start() } @@ -335,7 +335,7 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont |> take(1) |> deliverOnMainQueue).start(next: { [weak statsPromise] result in if let result = result, case let .result(stats) = result { - 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() @@ -464,7 +464,7 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont var updatedTempPaths = stats.tempPaths var updatedTempSize = stats.tempSize - var signal: Signal = clearCachedMediaResources(account: account, mediaResourceIds: clearResourceIds) + var signal: Signal = clearCachedMediaResources(account: context.account, mediaResourceIds: clearResourceIds) if otherSize.0 { let removeTempFiles: Signal = Signal { subscriber in let fileManager = FileManager.default @@ -476,7 +476,7 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont return EmptyDisposable } |> runOn(Queue.concurrentDefaultQueue()) signal = signal - |> then(account.postbox.mediaBox.removeOtherCachedResources(paths: stats.otherPaths)) + |> then(context.account.postbox.mediaBox.removeOtherCachedResources(paths: stats.otherPaths)) |> then(removeTempFiles) } @@ -491,7 +491,7 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont let resultStats = CacheUsageStats(media: media, mediaResourceIds: stats.mediaResourceIds, peers: stats.peers, otherSize: updatedOtherSize, otherPaths: updatedOtherPaths, cacheSize: updatedCacheSize, tempPaths: updatedTempPaths, tempSize: updatedTempSize, immutableSize: stats.immutableSize) var cancelImpl: (() -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let progressSignal = Signal { subscriber in let controller = OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .loading(cancelled: { cancelImpl?() @@ -554,7 +554,7 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont } } - 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() @@ -661,12 +661,12 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont } } - var signal = clearCachedMediaResources(account: account, mediaResourceIds: clearResourceIds) + var signal = clearCachedMediaResources(account: context.account, mediaResourceIds: clearResourceIds) let resultStats = CacheUsageStats(media: media, mediaResourceIds: stats.mediaResourceIds, peers: stats.peers, otherSize: stats.otherSize, otherPaths: stats.otherPaths, cacheSize: stats.cacheSize, tempPaths: stats.tempPaths, tempSize: stats.tempSize, immutableSize: stats.immutableSize) var cancelImpl: (() -> Void)? - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let progressSignal = Signal { subscriber in let controller = OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .loading(cancelled: { cancelImpl?() @@ -714,7 +714,7 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont var dismissImpl: (() -> Void)? - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, cacheSettingsPromise.get(), statsPromise.get()) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, cacheSettingsPromise.get(), statsPromise.get()) |> deliverOnMainQueue |> map { presentationData, cacheSettings, cacheStats -> (ItemListControllerState, (ItemListNodeState, StorageUsageEntry.ItemGenerationArguments)) in let leftNavigationButton = isModal ? ItemListNavigationButton(content: .text(presentationData.strings.Common_Cancel), style: .regular, enabled: true, action: { dismissImpl?() @@ -728,7 +728,7 @@ func storageUsageController(account: Account, isModal: Bool = false) -> ViewCont actionDisposables.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c in controller?.present(c, in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } diff --git a/TelegramUI/SuppressContactsWarning.swift b/TelegramUI/SuppressContactsWarning.swift index c16fd40fe8..cceefb551c 100644 --- a/TelegramUI/SuppressContactsWarning.swift +++ b/TelegramUI/SuppressContactsWarning.swift @@ -4,10 +4,10 @@ import Display import SwiftSignalKit import TelegramCore -func presentContactsWarningSuppression(account: Account, present: (ViewController, Any?) -> Void) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - present(textAlertController(account: account, title: presentationData.strings.Contacts_PermissionsSuppressWarningTitle, text: presentationData.strings.Contacts_PermissionsSuppressWarningText, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Contacts_PermissionsKeepDisabled, action: { - ApplicationSpecificNotice.setContactsPermissionWarning(postbox: account.postbox, value: Int32(Date().timeIntervalSince1970)) +func presentContactsWarningSuppression(context: AccountContext, present: (ViewController, Any?) -> Void) { + let presentationData = context.currentPresentationData.with { $0 } + 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) |> take(1) diff --git a/TelegramUI/TelegramController.swift b/TelegramUI/TelegramController.swift index 0e68b0e99b..3543033ec1 100644 --- a/TelegramUI/TelegramController.swift +++ b/TelegramUI/TelegramController.swift @@ -16,10 +16,10 @@ enum LocationBroadcastPanelSource { case peer(PeerId) } -private func presentLiveLocationController(account: Account, peerId: PeerId, controller: ViewController) { +private func presentLiveLocationController(context: AccountContext, peerId: PeerId, controller: ViewController) { let presentImpl: (Message?) -> Void = { [weak controller] message in if let message = message, let strongController = controller { - let _ = openChatMessage(account: account, message: message, standalone: false, reverseMessageGalleryOrder: false, navigationController: strongController.navigationController as? NavigationController, modal: true, dismissInput: { + let _ = openChatMessage(context: context, message: message, standalone: false, reverseMessageGalleryOrder: false, navigationController: strongController.navigationController as? NavigationController, modal: true, dismissInput: { controller?.view.endEditing(true) }, present: { c, a in controller?.present(c, in: .window(.root), with: a, blockInteraction: true) @@ -33,11 +33,11 @@ private func presentLiveLocationController(account: Account, peerId: PeerId, con }, sendSticker: nil, setupTemporaryHiddenMedia: { _, _, _ in }, chatAvatarHiddenMedia: { _, _ in}) } } - if let id = account.telegramApplicationContext.liveLocationManager?.internalMessageForPeerId(peerId) { - let _ = (account.postbox.transaction { transaction -> Message? in + if let id = context.liveLocationManager?.internalMessageForPeerId(peerId) { + let _ = (context.account.postbox.transaction { transaction -> Message? in return transaction.getMessage(id) } |> deliverOnMainQueue).start(next: presentImpl) - } else if let liveLocationManager = account.telegramApplicationContext.liveLocationManager { + } else if let liveLocationManager = context.liveLocationManager { let _ = (liveLocationManager.summaryManager.peersBroadcastingTo(peerId: peerId) |> take(1) |> map { peersAndMessages -> Message? in @@ -47,7 +47,7 @@ private func presentLiveLocationController(account: Account, peerId: PeerId, con } public class TelegramController: ViewController { - private let account: Account + private let context: AccountContext let mediaAccessoryPanelVisibility: MediaAccessoryPanelVisibility let locationBroadcastPanelSource: LocationBroadcastPanelSource @@ -96,17 +96,17 @@ public class TelegramController: ViewController { return super.navigationHeight } - init(account: Account, navigationBarPresentationData: NavigationBarPresentationData?, mediaAccessoryPanelVisibility: MediaAccessoryPanelVisibility, locationBroadcastPanelSource: LocationBroadcastPanelSource) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, navigationBarPresentationData: NavigationBarPresentationData?, mediaAccessoryPanelVisibility: MediaAccessoryPanelVisibility, locationBroadcastPanelSource: LocationBroadcastPanelSource) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.mediaAccessoryPanelVisibility = mediaAccessoryPanelVisibility self.locationBroadcastPanelSource = locationBroadcastPanelSource super.init(navigationBarPresentationData: navigationBarPresentationData) if case .none = mediaAccessoryPanelVisibility { - } else if let mediaManager = account.telegramApplicationContext.mediaManager { - self.mediaStatusDisposable = (mediaManager.globalMediaPlayerState + } else { + self.mediaStatusDisposable = (context.mediaManager.globalMediaPlayerState |> mapToSignal { playlistStateAndType -> Signal<(SharedMediaPlayerItemPlaybackState, MediaManagerPlayerType)?, NoError> in if let (state, type) = playlistStateAndType { switch state { @@ -153,7 +153,7 @@ public class TelegramController: ViewController { }) } - if let liveLocationManager = account.telegramApplicationContext.liveLocationManager { + if let liveLocationManager = context.liveLocationManager { switch locationBroadcastPanelSource { case .none: self.locationBroadcastMode = nil @@ -220,7 +220,7 @@ public class TelegramController: 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 @@ -268,8 +268,8 @@ public class TelegramController: ViewController { transition.updateFrame(node: locationBroadcastAccessoryPanel, frame: panelFrame) locationBroadcastAccessoryPanel.updateLayout(size: panelFrame.size, leftInset: layout.safeInsets.left, rightInset: layout.safeInsets.right, transition: transition) } else { - let presentationData = self.account.telegramApplicationContext.currentPresentationData.with { $0 } - locationBroadcastAccessoryPanel = LocationBroadcastNavigationAccessoryPanel(accountPeerId: self.account.peerId, theme: presentationData.theme, strings: presentationData.strings, tapAction: { [weak self] in + let presentationData = self.context.currentPresentationData.with { $0 } + locationBroadcastAccessoryPanel = LocationBroadcastNavigationAccessoryPanel(accountPeerId: self.context.account.peerId, theme: presentationData.theme, strings: presentationData.strings, tapAction: { [weak self] in if let strongSelf = self { switch strongSelf.locationBroadcastPanelSource { case .none: @@ -279,9 +279,9 @@ public class TelegramController: ViewController { let messages = locationBroadcastMessages.values.sorted(by: { MessageIndex($0) > MessageIndex($1) }) if messages.count == 1 { - presentLiveLocationController(account: strongSelf.account, peerId: messages[0].id.peerId, controller: strongSelf) + presentLiveLocationController(context: strongSelf.context, peerId: messages[0].id.peerId, controller: strongSelf) } else { - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } let controller = ActionSheetController(presentationTheme: presentationData.theme) let dismissAction: () -> Void = { [weak controller] in controller?.dismissAnimated() @@ -299,10 +299,10 @@ public class TelegramController: ViewController { } if let beginTimeAndTimeout = beginTimeAndTimeout { - items.append(LocationBroadcastActionSheetItem(account: strongSelf.account, peer: peer, title: peer.displayTitle, beginTimestamp: beginTimeAndTimeout.0, timeout: beginTimeAndTimeout.1, strings: presentationData.strings, action: { + items.append(LocationBroadcastActionSheetItem(context: strongSelf.context, peer: peer, title: peer.displayTitle, beginTimestamp: beginTimeAndTimeout.0, timeout: beginTimeAndTimeout.1, strings: presentationData.strings, action: { dismissAction() if let strongSelf = self { - presentLiveLocationController(account: strongSelf.account, peerId: peer.id, controller: strongSelf) + presentLiveLocationController(context: strongSelf.context, peerId: peer.id, controller: strongSelf) } })) } @@ -312,7 +312,7 @@ public class TelegramController: ViewController { dismissAction() if let locationBroadcastPeers = strongSelf.locationBroadcastPeers { for peer in locationBroadcastPeers { - self?.account.telegramApplicationContext.liveLocationManager?.cancelLiveLocation(peerId: peer.id) + self?.context.liveLocationManager?.cancelLiveLocation(peerId: peer.id) } } })) @@ -326,7 +326,7 @@ public class TelegramController: ViewController { } } case let .peer(peerId): - presentLiveLocationController(account: strongSelf.account, peerId: peerId, controller: strongSelf) + presentLiveLocationController(context: strongSelf.context, peerId: peerId, controller: strongSelf) } } }, close: { [weak self] in @@ -347,7 +347,7 @@ public class TelegramController: ViewController { case let .peer(peerId): closePeerId = peerId } - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } let controller = ActionSheetController(presentationTheme: presentationData.theme) let dismissAction: () -> Void = { [weak controller] in controller?.dismissAnimated() @@ -359,20 +359,20 @@ public class TelegramController: ViewController { items.append(ActionSheetButtonItem(title: peer.displayTitle, action: { dismissAction() if let strongSelf = self { - presentLiveLocationController(account: strongSelf.account, peerId: peer.id, controller: strongSelf) + presentLiveLocationController(context: strongSelf.context, peerId: peer.id, controller: strongSelf) } })) } items.append(ActionSheetButtonItem(title: presentationData.strings.LiveLocation_MenuStopAll, color: .destructive, action: { dismissAction() for peer in closePeers { - self?.account.telegramApplicationContext.liveLocationManager?.cancelLiveLocation(peerId: peer.id) + self?.context.liveLocationManager?.cancelLiveLocation(peerId: peer.id) } })) } else if let closePeerId = closePeerId { items.append(ActionSheetButtonItem(title: presentationData.strings.Map_StopLiveLocation, color: .destructive, action: { dismissAction() - self?.account.telegramApplicationContext.liveLocationManager?.cancelLiveLocation(peerId: closePeerId) + self?.context.liveLocationManager?.cancelLiveLocation(peerId: closePeerId) })) } controller.setItemGroups([ @@ -425,27 +425,25 @@ public class TelegramController: ViewController { mediaAccessoryPanel.updateLayout(size: panelFrame.size, leftInset: layout.safeInsets.left, rightInset: layout.safeInsets.right, transition: transition) mediaAccessoryPanel.containerNode.headerNode.playbackItem = item - if let mediaManager = self.account.telegramApplicationContext.mediaManager { - let delayedStatus = mediaManager.globalMediaPlayerState - |> mapToSignal { value -> Signal<(SharedMediaPlayerItemPlaybackStateOrLoading, MediaManagerPlayerType)?, NoError> in - guard let value = value else { - return .single(nil) - } - switch value.0 { - case .state: - return .single(value) - case .loading: - return .single(value) |> delay(0.1, queue: .mainQueue()) - } + let delayedStatus = self.context.mediaManager.globalMediaPlayerState + |> mapToSignal { value -> Signal<(SharedMediaPlayerItemPlaybackStateOrLoading, MediaManagerPlayerType)?, NoError> in + guard let value = value else { + return .single(nil) } - - mediaAccessoryPanel.containerNode.headerNode.playbackStatus = delayedStatus - |> map { state -> MediaPlayerStatus in - if let stateOrLoading = state?.0, case let .state(state) = stateOrLoading { - return state.status - } else { - return MediaPlayerStatus(generationTimestamp: 0.0, duration: 0.0, dimensions: CGSize(), timestamp: 0.0, baseRate: 1.0, seekId: 0, status: .paused) - } + switch value.0 { + case .state: + return .single(value) + case .loading: + return .single(value) |> delay(0.1, queue: .mainQueue()) + } + } + + mediaAccessoryPanel.containerNode.headerNode.playbackStatus = delayedStatus + |> map { state -> MediaPlayerStatus in + if let stateOrLoading = state?.0, case let .state(state) = stateOrLoading { + return state.status + } else { + return MediaPlayerStatus(generationTimestamp: 0.0, duration: 0.0, dimensions: CGSize(), timestamp: 0.0, baseRate: 1.0, seekId: 0, status: .paused) } } } else { @@ -460,11 +458,11 @@ public class TelegramController: ViewController { }) } - let mediaAccessoryPanel = MediaNavigationAccessoryPanel(account: self.account) + let mediaAccessoryPanel = MediaNavigationAccessoryPanel(context: self.context) mediaAccessoryPanel.containerNode.headerNode.displayScrubber = type != .voice mediaAccessoryPanel.close = { [weak self] in if let strongSelf = self, let (_, _, type) = strongSelf.playlistStateAndType { - strongSelf.account.telegramApplicationContext.mediaManager?.setPlaylist(nil, type: type) + strongSelf.context.mediaManager.setPlaylist(nil, type: type) } } mediaAccessoryPanel.toggleRate = { @@ -472,7 +470,7 @@ public class TelegramController: ViewController { guard let strongSelf = self else { return } - let _ = (strongSelf.account.postbox.transaction { transaction -> AudioPlaybackRate in + let _ = (strongSelf.context.account.postbox.transaction { transaction -> AudioPlaybackRate in let settings = transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.musicPlaybackSettings) as? MusicPlaybackSettings ?? MusicPlaybackSettings.defaultSettings let nextRate: AudioPlaybackRate @@ -490,12 +488,12 @@ public class TelegramController: ViewController { return } - strongSelf.account.telegramApplicationContext.mediaManager?.playlistControl(.setBaseRate(baseRate), type: type) + strongSelf.context.mediaManager.playlistControl(.setBaseRate(baseRate), type: type) }) } mediaAccessoryPanel.togglePlayPause = { [weak self] in if let strongSelf = self, let (_, _, type) = strongSelf.playlistStateAndType { - strongSelf.account.telegramApplicationContext.mediaManager?.playlistControl(.playback(.togglePlayPause), type: type) + strongSelf.context.mediaManager.playlistControl(.playback(.togglePlayPause), type: type) } } mediaAccessoryPanel.tapAction = { [weak self] in @@ -504,7 +502,7 @@ public class TelegramController: ViewController { } if let id = state.id as? PeerMessagesMediaPlaylistItemId { if type == .music { - let historyView = chatHistoryViewForLocation(.InitialSearch(location: .id(id.messageId), count: 60), account: strongSelf.account, chatLocation: .peer(id.messageId.peerId), fixedCombinedReadStates: nil, tagMask: MessageTags.music, additionalData: []) + let historyView = chatHistoryViewForLocation(.InitialSearch(location: .id(id.messageId), count: 60), account: strongSelf.context.account, chatLocation: .peer(id.messageId.peerId), fixedCombinedReadStates: nil, tagMask: MessageTags.music, additionalData: []) let signal = historyView |> mapToSignal { historyView -> Signal<(MessageIndex?, Bool), NoError> in switch historyView { @@ -526,7 +524,7 @@ public class TelegramController: ViewController { }) var cancelImpl: (() -> Void)? - let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = strongSelf.context.currentPresentationData.with { $0 } let progressSignal = Signal { subscriber in let controller = OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .loading(cancelled: { cancelImpl?() @@ -554,7 +552,7 @@ public class TelegramController: ViewController { return } if let _ = index.0 { - let controller = OverlayPlayerController(account: strongSelf.account, peerId: id.messageId.peerId, type: type, initialMessageId: id.messageId, initialOrder: order, parentNavigationController: strongSelf.navigationController as? NavigationController) + let controller = OverlayPlayerController(context: strongSelf.context, peerId: id.messageId.peerId, type: type, initialMessageId: id.messageId, initialOrder: order, parentNavigationController: strongSelf.navigationController as? NavigationController) strongSelf.displayNode.view.window?.endEditing(true) strongSelf.present(controller, in: .window(.root)) } else if index.1 { @@ -569,7 +567,7 @@ public class TelegramController: ViewController { self?.playlistPreloadDisposable?.dispose() } } else { - navigateToChatController(navigationController: navigationController, account: strongSelf.account, chatLocation: .peer(id.messageId.peerId), messageId: id.messageId) + navigateToChatController(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(id.messageId.peerId), messageId: id.messageId) } } } @@ -584,14 +582,13 @@ public class TelegramController: ViewController { self.mediaAccessoryPanel = (mediaAccessoryPanel, type) mediaAccessoryPanel.updateLayout(size: panelFrame.size, leftInset: layout.safeInsets.left, rightInset: layout.safeInsets.right, transition: .immediate) mediaAccessoryPanel.containerNode.headerNode.playbackItem = item - if let mediaManager = self.account.telegramApplicationContext.mediaManager { - mediaAccessoryPanel.containerNode.headerNode.playbackStatus = mediaManager.globalMediaPlayerState - |> map { state -> MediaPlayerStatus in - if let stateOrLoading = state?.0, case let .state(state) = stateOrLoading { - return state.status - } else { - return MediaPlayerStatus(generationTimestamp: 0.0, duration: 0.0, dimensions: CGSize(), timestamp: 0.0, baseRate: 1.0, seekId: 0, status: .paused) - } + let mediaManager = self.context.mediaManager + mediaAccessoryPanel.containerNode.headerNode.playbackStatus = mediaManager.globalMediaPlayerState + |> map { state -> MediaPlayerStatus in + if let stateOrLoading = state?.0, case let .state(state) = stateOrLoading { + return state.status + } else { + return MediaPlayerStatus(generationTimestamp: 0.0, duration: 0.0, dimensions: CGSize(), timestamp: 0.0, baseRate: 1.0, seekId: 0, status: .paused) } } mediaAccessoryPanel.animateIn(transition: transition) diff --git a/TelegramUI/TelegramRootController.swift b/TelegramUI/TelegramRootController.swift index fcfbdbeb1c..0e28f72433 100644 --- a/TelegramUI/TelegramRootController.swift +++ b/TelegramUI/TelegramRootController.swift @@ -5,7 +5,7 @@ import TelegramCore import SwiftSignalKit public final class TelegramRootController: NavigationController { - private let account: Account + private let context: AccountContext public var rootTabController: TabBarController? @@ -18,17 +18,15 @@ public final class TelegramRootController: NavigationController { private var presentationDataDisposable: Disposable? private var presentationData: PresentationData - public init(account: Account) { - self.account = account + public init(context: AccountContext) { + self.context = context - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(mode: .automaticMasterDetail, theme: NavigationControllerTheme(presentationTheme: self.presentationData.theme)) - //self.permissionsDisposable = - - self.presentationDataDisposable = (account.telegramApplicationContext.presentationData - |> deliverOnMainQueue).start(next: { [weak self] presentationData in + self.presentationDataDisposable = (context.presentationData + |> deliverOnMainQueue).start(next: { [weak self] presentationData in if let strongSelf = self { let previousTheme = strongSelf.presentationData.theme strongSelf.presentationData = presentationData @@ -51,12 +49,12 @@ public final class TelegramRootController: NavigationController { public func addRootControllers(showCallsTab: Bool) { let tabBarController = TabBarController(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData), theme: TabBarControllerTheme(rootControllerTheme: self.presentationData.theme)) - let chatListController = ChatListController(account: self.account, groupId: nil, controlsHistoryPreload: true) - let callListController = CallListController(account: self.account, mode: .tab) + let chatListController = ChatListController(context: self.context, groupId: nil, controlsHistoryPreload: true) + let callListController = CallListController(context: self.context, mode: .tab) var controllers: [ViewController] = [] - let contactsController = ContactsController(account: self.account) + let contactsController = ContactsController(context: self.context) controllers.append(contactsController) if showCallsTab { @@ -65,10 +63,10 @@ public final class TelegramRootController: NavigationController { controllers.append(chatListController) let restoreSettignsController = AccountStore.switchingSettingsController - restoreSettignsController?.updateAccount(account: self.account) + restoreSettignsController?.updateContext(context: self.context) AccountStore.switchingSettingsController = nil - let accountSettingsController = restoreSettignsController ?? settingsController(account: self.account, accountManager: self.account.telegramApplicationContext.accountManager) + let accountSettingsController = restoreSettignsController ?? settingsController(context: self.context, accountManager: context.accountManager) controllers.append(accountSettingsController) tabBarController.setControllers(controllers, selectedIndex: restoreSettignsController != nil ? (controllers.count - 1) : (controllers.count - 2)) @@ -118,6 +116,6 @@ public final class TelegramRootController: NavigationController { guard let controller = self.viewControllers.last as? ViewController else { return } - presentedLegacyShortcutCamera(account: self.account, saveCapturedMedia: false, saveEditedPhotos: false, mediaGrouping: true, parentController: controller) + presentedLegacyShortcutCamera(context: self.context, saveCapturedMedia: false, saveEditedPhotos: false, mediaGrouping: true, parentController: controller) } } diff --git a/TelegramUI/ThemeAutoNightSettingsController.swift b/TelegramUI/ThemeAutoNightSettingsController.swift index 189c2c990d..cde8b04ff0 100644 --- a/TelegramUI/ThemeAutoNightSettingsController.swift +++ b/TelegramUI/ThemeAutoNightSettingsController.swift @@ -321,7 +321,7 @@ private func areSettingsValid(_ settings: AutomaticThemeSwitchSetting) -> Bool { } } -public func themeAutoNightSettingsController(account: Account) -> ViewController { +public func themeAutoNightSettingsController(context: AccountContext) -> ViewController { var pushControllerImpl: ((ViewController) -> Void)? var presentControllerImpl: ((ViewController) -> Void)? @@ -331,7 +331,7 @@ public func themeAutoNightSettingsController(account: Account) -> ViewController let stagingSettingsPromise = ValuePromise(nil) let themeSettingsKey = ApplicationSpecificPreferencesKeys.presentationThemeSettings let localizationSettingsKey = PreferencesKeys.localizationSettings - let preferences = account.postbox.preferencesView(keys: [themeSettingsKey, localizationSettingsKey]) + let preferences = context.account.postbox.preferencesView(keys: [themeSettingsKey, localizationSettingsKey]) let updateLocationDisposable = MetaDisposable() actionsDisposable.add(updateLocationDisposable) @@ -344,7 +344,7 @@ public func themeAutoNightSettingsController(account: Account) -> ViewController let updated = f(stagingSettings ?? settings.automaticThemeSwitchSetting) stagingSettingsPromise.set(updated) if areSettingsValid(updated) { - let _ = updatePresentationThemeSettingsInteractively(postbox: account.postbox, { current in + let _ = updatePresentationThemeSettingsInteractively(postbox: context.account.postbox, { current in var current = current current.automaticThemeSwitchSetting = updated return current @@ -355,7 +355,7 @@ public func themeAutoNightSettingsController(account: Account) -> ViewController let forceUpdateLocation: () -> Void = { let locationCoordinates = Signal<(Double, Double), NoError> { subscriber in - return account.telegramApplicationContext.locationManager!.push(mode: DeviceLocationMode.precise, updated: { coordinate in + return context.locationManager!.push(mode: DeviceLocationMode.precise, updated: { coordinate in subscriber.putNext((coordinate.latitude, coordinate.longitude)) subscriber.putCompletion() }) @@ -459,8 +459,8 @@ public func themeAutoNightSettingsController(account: Account) -> ViewController break } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - presentControllerImpl?(ThemeAutoNightTimeSelectionActionSheet(account: account, currentValue: currentValue, applyValue: { value in + let presentationData = context.currentPresentationData.with { $0 } + presentControllerImpl?(ThemeAutoNightTimeSelectionActionSheet(context: context, currentValue: currentValue, applyValue: { value in guard let value = value else { return } @@ -513,7 +513,7 @@ public func themeAutoNightSettingsController(account: Account) -> ViewController } }) - let signal = combineLatest(account.telegramApplicationContext.presentationData, preferences, stagingSettingsPromise.get()) + let signal = combineLatest(context.presentationData, preferences, stagingSettingsPromise.get()) |> deliverOnMainQueue |> map { presentationData, preferences, stagingSettings -> (ItemListControllerState, (ItemListNodeState, ThemeAutoNightSettingsControllerEntry.ItemGenerationArguments)) in let settings = (preferences.values[themeSettingsKey] as? PresentationThemeSettings) ?? PresentationThemeSettings.defaultSettings @@ -527,7 +527,7 @@ public func themeAutoNightSettingsController(account: Account) -> ViewController actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] c in (controller?.navigationController as? NavigationController)?.pushViewController(c) } diff --git a/TelegramUI/ThemeAutoNightTimeSelectionActionSheet.swift b/TelegramUI/ThemeAutoNightTimeSelectionActionSheet.swift index ec711b4336..4e9bcf385f 100644 --- a/TelegramUI/ThemeAutoNightTimeSelectionActionSheet.swift +++ b/TelegramUI/ThemeAutoNightTimeSelectionActionSheet.swift @@ -13,14 +13,14 @@ final class ThemeAutoNightTimeSelectionActionSheet: ActionSheetController { return self._ready } - init(account: Account, currentValue: Int32, emptyTitle: String? = nil, applyValue: @escaping (Int32?) -> Void) { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, currentValue: Int32, emptyTitle: String? = nil, 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.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/ThemeColorsGridController.swift b/TelegramUI/ThemeColorsGridController.swift index 0a3007c2a1..b56ab0b08a 100644 --- a/TelegramUI/ThemeColorsGridController.swift +++ b/TelegramUI/ThemeColorsGridController.swift @@ -59,16 +59,16 @@ final class ThemeColorsGridController: ViewController { return self._ready } - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private var presentationDataDisposable: Disposable? private var validLayout: ContainerViewLayout? - init(account: Account) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -81,7 +81,7 @@ final class ThemeColorsGridController: 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 @@ -115,7 +115,7 @@ final class ThemeColorsGridController: ViewController { } override func loadDisplayNode() { - self.displayNode = ThemeColorsGridControllerNode(account: self.account, presentationData: self.presentationData, colors: availableColors(), present: { [weak self] controller, arguments in + self.displayNode = ThemeColorsGridControllerNode(context: self.context, presentationData: self.presentationData, colors: availableColors(), present: { [weak self] controller, arguments in self?.present(controller, in: .window(.root), with: arguments, blockInteraction: true) }, pop: { [weak self] in if let strongSelf = self, let navigationController = strongSelf.navigationController as? NavigationController { @@ -123,7 +123,7 @@ final class ThemeColorsGridController: ViewController { } }, presentColorPicker: { [weak self] in if let strongSelf = self { - let controller = WallpaperListPreviewController(account: strongSelf.account, source: .customColor(randomColor())) + let controller = WallpaperListPreviewController(context: strongSelf.context, source: .customColor(randomColor())) controller.apply = { _, _, _ in if let strongSelf = self, let navigationController = strongSelf.navigationController as? NavigationController { let _ = navigationController.popViewController(animated: true) diff --git a/TelegramUI/ThemeColorsGridControllerNode.swift b/TelegramUI/ThemeColorsGridControllerNode.swift index a757f0f61a..b799193bfb 100644 --- a/TelegramUI/ThemeColorsGridControllerNode.swift +++ b/TelegramUI/ThemeColorsGridControllerNode.swift @@ -58,7 +58,7 @@ private func preparedThemeColorsGridEntryTransition(account: Account, from fromE } final class ThemeColorsGridControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private var controllerInteraction: ThemeColorsGridControllerInteraction? private let present: (ViewController, Any?) -> Void @@ -79,8 +79,8 @@ final class ThemeColorsGridControllerNode: ASDisplayNode { private var disposable: Disposable? - init(account: Account, presentationData: PresentationData, colors: [Int32], present: @escaping (ViewController, Any?) -> Void, pop: @escaping () -> Void, presentColorPicker: @escaping () -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, colors: [Int32], present: @escaping (ViewController, Any?) -> Void, pop: @escaping () -> Void, presentColorPicker: @escaping () -> Void) { + self.context = context self.presentationData = presentationData self.present = present self.presentColorPicker = presentColorPicker @@ -119,7 +119,7 @@ final class ThemeColorsGridControllerNode: ASDisplayNode { let entries = previousEntries.with { $0 } if let entries = entries, !entries.isEmpty { let wallpapers = entries.map { $0.wallpaper } - let controller = WallpaperGalleryController(account: account, source: .list(wallpapers: wallpapers, central: wallpaper, type: .colors)) + let controller = WallpaperGalleryController(context: context, source: .list(wallpapers: wallpapers, central: wallpaper, type: .colors)) controller.apply = { _, _, _ in pop() } @@ -131,7 +131,7 @@ final class ThemeColorsGridControllerNode: ASDisplayNode { self.controllerInteraction = interaction let wallpapers = colors.map { TelegramWallpaper.color($0) } - let transition = account.telegramApplicationContext.presentationData + let transition = context.presentationData |> map { presentationData -> (ThemeColorsGridEntryTransition, Bool) in var entries: [ThemeColorsGridControllerEntry] = [] var index = 0 @@ -143,7 +143,7 @@ final class ThemeColorsGridControllerNode: ASDisplayNode { } let previous = previousEntries.swap(entries) - return (preparedThemeColorsGridEntryTransition(account: account, from: previous ?? [], to: entries, interaction: interaction), previous == nil) + return (preparedThemeColorsGridEntryTransition(account: context.account, 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 19b5976528..21e046cec3 100644 --- a/TelegramUI/ThemeGalleryController.swift +++ b/TelegramUI/ThemeGalleryController.swift @@ -34,7 +34,7 @@ class ThemeGalleryController: ViewController { return self.displayNode as! GalleryControllerNode } - private let account: Account + private let context: AccountContext private let _ready = Promise() override var ready: Promise { @@ -65,9 +65,9 @@ class ThemeGalleryController: ViewController { return self._hiddenMedia.get() } - init(account: Account, wallpapers: [TelegramWallpaper], at centralWallpaper: TelegramWallpaper) { + init(context: AccountContext, wallpapers: [TelegramWallpaper], at centralWallpaper: TelegramWallpaper) { self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: presentationData)) @@ -83,7 +83,7 @@ class ThemeGalleryController: ViewController { strongSelf.entries = entries strongSelf.centralEntryIndex = wallpapers.index(of: centralWallpaper)! if strongSelf.isViewLoaded { - strongSelf.galleryNode.pager.replaceItems(strongSelf.entries.map({ ThemeGalleryItem(account: account, entry: $0) }), centralItemIndex: strongSelf.centralEntryIndex, keepFirst: true) + strongSelf.galleryNode.pager.replaceItems(strongSelf.entries.map({ ThemeGalleryItem(context: context, entry: $0) }), centralItemIndex: strongSelf.centralEntryIndex, keepFirst: true) let ready = strongSelf.galleryNode.pager.ready() |> timeout(2.0, queue: Queue.mainQueue(), alternate: .single(Void())) |> afterNext { [weak strongSelf] _ in strongSelf?.didSetReady = true @@ -93,7 +93,7 @@ class ThemeGalleryController: 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 @@ -202,7 +202,7 @@ class ThemeGalleryController: ViewController { self.galleryNode.backgroundNode.isOpaque = false self.galleryNode.isBackgroundExtendedOverNavigationBar = true - let presentationData = self.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = self.context.currentPresentationData.with { $0 } let toolbarNode = ThemeGalleryToolbarNode(theme: presentationData.theme, strings: presentationData.strings) self.toolbarNode = toolbarNode self.galleryNode.addSubnode(toolbarNode) @@ -219,7 +219,7 @@ class ThemeGalleryController: ViewController { case let .wallpaper(value): wallpaper = value } - let _ = (updatePresentationThemeSettingsInteractively(postbox: strongSelf.account.postbox, { current in + let _ = (updatePresentationThemeSettingsInteractively(postbox: strongSelf.context.account.postbox, { current in return PresentationThemeSettings(chatWallpaper: wallpaper, chatWallpaperOptions: [], theme: current.theme, themeAccentColor: current.themeAccentColor, fontSize: current.fontSize, automaticThemeSwitchSetting: current.automaticThemeSwitchSetting, disableAnimations: current.disableAnimations) }) |> deliverOnMainQueue).start(completed: { self?.dismiss(forceAway: true) @@ -254,7 +254,7 @@ class ThemeGalleryController: ViewController { self.validLayout = (layout, 0.0) if replace { - self.galleryNode.pager.replaceItems(self.entries.map({ ThemeGalleryItem(account: self.account, entry: $0) }), centralItemIndex: self.centralEntryIndex) + self.galleryNode.pager.replaceItems(self.entries.map({ ThemeGalleryItem(context: self.context, entry: $0) }), centralItemIndex: self.centralEntryIndex) } } } diff --git a/TelegramUI/ThemeGalleryItem.swift b/TelegramUI/ThemeGalleryItem.swift index 36920ab51b..7c2f69a66d 100644 --- a/TelegramUI/ThemeGalleryItem.swift +++ b/TelegramUI/ThemeGalleryItem.swift @@ -6,16 +6,16 @@ import Postbox import TelegramCore class ThemeGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let entry: ThemeGalleryEntry - init(account: Account, entry: ThemeGalleryEntry) { - self.account = account + init(context: AccountContext, entry: ThemeGalleryEntry) { + self.context = context self.entry = entry } func node() -> GalleryItemNode { - let node = ThemeGalleryItemNode(account: self.account) + let node = ThemeGalleryItemNode(context: self.context) node.setEntry(self.entry) return node } @@ -32,7 +32,7 @@ class ThemeGalleryItem: GalleryItem { } final class ThemeGalleryItemNode: ZoomableContentGalleryItemNode { - private let account: Account + private let context: AccountContext private var entry: ThemeGalleryEntry? @@ -42,8 +42,8 @@ final class ThemeGalleryItemNode: ZoomableContentGalleryItemNode { private var fetchDisposable = MetaDisposable() - init(account: Account) { - self.account = account + init(context: AccountContext) { + self.context = context self.imageNode = TransformImageNode() @@ -81,7 +81,7 @@ final class ThemeGalleryItemNode: ZoomableContentGalleryItemNode { case .builtin: let displaySize = CGSize(width: 640.0, height: 1136.0) self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: displaySize, boundingSize: displaySize, intrinsicInsets: UIEdgeInsets()))() - self.imageNode.setSignal(settingsBuiltinWallpaperImage(account: self.account), dispatchOnDisplayLink: false) + self.imageNode.setSignal(settingsBuiltinWallpaperImage(account: self.context.account), dispatchOnDisplayLink: false) self.zoomableContent = (displaySize, self.imageNode) case let .color(color): self.imageNode.isHidden = true @@ -92,11 +92,11 @@ final class ThemeGalleryItemNode: ZoomableContentGalleryItemNode { self.imageNode.asyncLayout()(TransformImageArguments(corners: ImageCorners(), imageSize: displaySize, boundingSize: displaySize, intrinsicInsets: UIEdgeInsets()))() let convertedRepresentations: [ImageRepresentationWithReference] = representations.map({ ImageRepresentationWithReference(representation: $0, reference: .wallpaper(resource: $0.resource)) }) - self.imageNode.setSignal(chatAvatarGalleryPhoto(account: account, representations: convertedRepresentations), dispatchOnDisplayLink: false) + self.imageNode.setSignal(chatAvatarGalleryPhoto(account: context.account, representations: convertedRepresentations), dispatchOnDisplayLink: false) self.zoomableContent = (largestSize.dimensions, self.imageNode) if let largestIndex = convertedRepresentations.index(where: { $0.representation == largestSize }) { - self.fetchDisposable.set(fetchedMediaResource(postbox: self.account.postbox, reference: convertedRepresentations[largestIndex].reference).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: self.context.account.postbox, reference: convertedRepresentations[largestIndex].reference).start()) } } else { self._ready.set(.single(Void())) @@ -111,10 +111,10 @@ final class ThemeGalleryItemNode: ZoomableContentGalleryItemNode { convertedRepresentations.append(ImageRepresentationWithReference(representation: representation, reference: .standalone(resource: representation.resource))) } convertedRepresentations.append(ImageRepresentationWithReference(representation: .init(dimensions: dimensions, resource: file.file.resource), reference: .standalone(resource: file.file.resource))) - self.imageNode.setSignal(chatAvatarGalleryPhoto(account: account, representations: convertedRepresentations), dispatchOnDisplayLink: false) + self.imageNode.setSignal(chatAvatarGalleryPhoto(account: context.account, representations: convertedRepresentations), dispatchOnDisplayLink: false) self.zoomableContent = (dimensions, self.imageNode) - self.fetchDisposable.set(fetchedMediaResource(postbox: self.account.postbox, reference: convertedRepresentations[convertedRepresentations.count - 1].reference).start()) + self.fetchDisposable.set(fetchedMediaResource(postbox: self.context.account.postbox, reference: convertedRepresentations[convertedRepresentations.count - 1].reference).start()) } } } diff --git a/TelegramUI/ThemeGridController.swift b/TelegramUI/ThemeGridController.swift index 48dae36458..e56899fb2e 100644 --- a/TelegramUI/ThemeGridController.swift +++ b/TelegramUI/ThemeGridController.swift @@ -16,7 +16,7 @@ final class ThemeGridController: ViewController { return self._ready } - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let presentationDataPromise = Promise() @@ -29,9 +29,9 @@ final class ThemeGridController: ViewController { private var validLayout: ContainerViewLayout? - init(account: Account) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.presentationDataPromise.set(.single(self.presentationData)) super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) @@ -49,7 +49,7 @@ final class ThemeGridController: 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 @@ -101,9 +101,9 @@ final class ThemeGridController: ViewController { } override func loadDisplayNode() { - self.displayNode = ThemeGridControllerNode(account: self.account, presentationData: self.presentationData, presentPreviewController: { [weak self] source in + self.displayNode = ThemeGridControllerNode(context: self.context, presentationData: self.presentationData, presentPreviewController: { [weak self] source in if let strongSelf = self { - let controller = WallpaperGalleryController(account: strongSelf.account, source: source) + let controller = WallpaperGalleryController(context: strongSelf.context, source: source) self?.present(controller, in: .window(.root), with: nil, blockInteraction: true) // let controller = WallpaperListPreviewController(account: strongSelf.account, source: source) // controller.apply = { [weak self, weak controller] wallpaper, mode, cropRect in @@ -119,7 +119,7 @@ final class ThemeGridController: ViewController { } }, presentGallery: { [weak self] in if let strongSelf = self { - let _ = legacyWallpaperPicker(applicationContext: strongSelf.account.telegramApplicationContext, presentationData: strongSelf.presentationData).start(next: { generator in + let _ = legacyWallpaperPicker(context: strongSelf.context, presentationData: strongSelf.presentationData).start(next: { generator in if let strongSelf = self { let legacyController = LegacyController(presentation: .modal(animateIn: true), theme: strongSelf.presentationData.theme, initialLayout: strongSelf.validLayout) legacyController.statusBar.statusBarStyle = strongSelf.presentationData.theme.rootController.statusBar.style.style @@ -129,7 +129,7 @@ final class ThemeGridController: ViewController { legacyController.deferScreenEdgeGestures = [.top] controller.selectionBlock = { [weak self, weak legacyController] asset, thumbnailImage in if let strongSelf = self, let asset = asset { - let controller = WallpaperListPreviewController(account: strongSelf.account, source: .asset(asset.backingAsset, thumbnailImage)) + let controller = WallpaperListPreviewController(context: strongSelf.context, source: .asset(asset.backingAsset, thumbnailImage)) controller.apply = { [weak self, weak legacyController, weak controller] wallpaper, mode, cropRect in if let strongSelf = self, let legacyController = legacyController, let controller = controller { strongSelf.uploadCustomWallpaper(wallpaper, mode: mode, cropRect: cropRect, completion: { [weak legacyController, weak controller] in @@ -154,7 +154,7 @@ final class ThemeGridController: ViewController { } }, presentColors: { [weak self] in if let strongSelf = self { - let controller = ThemeColorsGridController(account: strongSelf.account) + let controller = ThemeColorsGridController(context: strongSelf.context) (strongSelf.navigationController as? NavigationController)?.pushViewController(controller) } }, emptyStateUpdated: { [weak self] empty in @@ -186,10 +186,10 @@ final class ThemeGridController: ViewController { } for wallpaper in wallpapers { - let _ = deleteWallpaper(account: strongSelf.account, wallpaper: wallpaper).start() + let _ = deleteWallpaper(account: strongSelf.context.account, wallpaper: wallpaper).start() } - let _ = telegramWallpapers(postbox: strongSelf.account.postbox, network: strongSelf.account.network).start() + let _ = telegramWallpapers(postbox: strongSelf.context.account.postbox, network: strongSelf.context.account.network).start() strongSelf.donePressed() })) @@ -272,7 +272,7 @@ final class ThemeGridController: ViewController { } if let imageResource = imageResource { - imageSignal = .single(self.account.postbox.mediaBox.completedResourcePath(imageResource)) + imageSignal = .single(self.context.account.postbox.mediaBox.completedResourcePath(imageResource)) |> mapToSignal { path -> Signal in if let path = path, let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: [.mappedIfSafe]), let image = UIImage(data: data) { return .single(image) @@ -303,9 +303,9 @@ final class ThemeGridController: ViewController { if let data = UIImageJPEGRepresentation(croppedImage, 0.85) { let resource = LocalFileMediaResource(fileId: arc4random64()) - self.account.postbox.mediaBox.storeResourceData(resource.id, data: data) + self.context.account.postbox.mediaBox.storeResourceData(resource.id, data: data) - let account = self.account + let account = self.context.account let updateWallpaper: (TelegramWallpaper) -> Void = { wallpaper in let _ = (updatePresentationThemeSettingsInteractively(postbox: account.postbox, { current in return PresentationThemeSettings(chatWallpaper: wallpaper, chatWallpaperOptions: mode, theme: current.theme, themeAccentColor: current.themeAccentColor, fontSize: current.fontSize, automaticThemeSwitchSetting: current.automaticThemeSwitchSetting, disableAnimations: current.disableAnimations) @@ -332,7 +332,7 @@ final class ThemeGridController: ViewController { } if mode.contains(.blur) { - let _ = account.postbox.mediaBox.cachedResourceRepresentation(resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true).start(completed: { + let _ = context.account.postbox.mediaBox.cachedResourceRepresentation(resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true).start(completed: { apply() }) } else { @@ -369,7 +369,7 @@ final class ThemeGridController: ViewController { } else { subject = .text(string) } - let shareController = ShareController(account: account, subject: subject) + let shareController = ShareController(context: context, subject: subject) self.present(shareController, in: .window(.root), blockInteraction: true) self.donePressed() diff --git a/TelegramUI/ThemeGridControllerNode.swift b/TelegramUI/ThemeGridControllerNode.swift index 92623b10e4..40c528fedf 100644 --- a/TelegramUI/ThemeGridControllerNode.swift +++ b/TelegramUI/ThemeGridControllerNode.swift @@ -146,7 +146,7 @@ private func selectedWallpapers(entries: [ThemeGridControllerEntry]?, state: The } final class ThemeGridControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private var controllerInteraction: ThemeGridControllerInteraction? @@ -190,8 +190,8 @@ final class ThemeGridControllerNode: ASDisplayNode { private var disposable: Disposable? - init(account: Account, presentationData: PresentationData, presentPreviewController: @escaping (WallpaperListSource) -> Void, presentGallery: @escaping () -> Void, presentColors: @escaping () -> Void, emptyStateUpdated: @escaping (Bool) -> Void, deleteWallpapers: @escaping ([TelegramWallpaper], @escaping () -> Void) -> Void, shareWallpapers: @escaping ([TelegramWallpaper]) -> Void, popViewController: @escaping () -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, presentPreviewController: @escaping (WallpaperListSource) -> Void, presentGallery: @escaping () -> Void, presentColors: @escaping () -> Void, emptyStateUpdated: @escaping (Bool) -> Void, deleteWallpapers: @escaping ([TelegramWallpaper], @escaping () -> Void) -> Void, shareWallpapers: @escaping ([TelegramWallpaper]) -> Void, popViewController: @escaping () -> Void) { + self.context = context self.presentationData = presentationData self.presentPreviewController = presentPreviewController self.presentGallery = presentGallery @@ -237,7 +237,7 @@ final class ThemeGridControllerNode: ASDisplayNode { self.addSubnode(self.gridNode) let wallpapersPromise: Promise<[TelegramWallpaper]> = Promise() - wallpapersPromise.set(telegramWallpapers(postbox: account.postbox, network: account.network)) + wallpapersPromise.set(telegramWallpapers(postbox: context.account.postbox, network: context.account.network)) let previousEntries = Atomic<[ThemeGridControllerEntry]?>(value: nil) let interaction = ThemeGridControllerInteraction(openWallpaper: { [weak self] wallpaper in @@ -289,7 +289,7 @@ final class ThemeGridControllerNode: ASDisplayNode { }) self.controllerInteraction = interaction - let transition = combineLatest(wallpapersPromise.get(), account.telegramApplicationContext.presentationData) + let transition = combineLatest(wallpapersPromise.get(), context.presentationData) |> map { wallpapers, presentationData -> (ThemeGridEntryTransition, Bool) in var entries: [ThemeGridControllerEntry] = [] var index = 1 @@ -307,7 +307,7 @@ final class ThemeGridControllerNode: ASDisplayNode { } let previous = previousEntries.swap(entries) - return (preparedThemeGridEntryTransition(account: account, from: previous ?? [], to: entries, interaction: interaction), previous == nil) + return (preparedThemeGridEntryTransition(account: context.account, from: previous ?? [], to: entries, interaction: interaction), previous == nil) } self.disposable = (transition |> deliverOnMainQueue).start(next: { [weak self] (transition, _) in if let strongSelf = self { @@ -559,7 +559,7 @@ final class ThemeGridControllerNode: ASDisplayNode { return } - self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ThemeGridSearchContentNode(account: account, openResult: { [weak self] result in + self.searchDisplayController = SearchDisplayController(presentationData: self.presentationData, contentNode: ThemeGridSearchContentNode(context: context, openResult: { [weak self] result in if let strongSelf = self { strongSelf.presentPreviewController(.contextResult(result)) } diff --git a/TelegramUI/ThemeGridSearchContentNode.swift b/TelegramUI/ThemeGridSearchContentNode.swift index d41eea5638..b732001b74 100644 --- a/TelegramUI/ThemeGridSearchContentNode.swift +++ b/TelegramUI/ThemeGridSearchContentNode.swift @@ -303,7 +303,7 @@ private struct ThemeGridSearchContext { } final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { - private let account: Account + private let context: AccountContext private let recentListNode: ListView private let gridNode: GridNode @@ -327,11 +327,11 @@ final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { return self._isSearching.get() } - init(account: Account, openResult: @escaping (ChatContextResult) -> Void) { - self.account = account + init(context: AccountContext, openResult: @escaping (ChatContextResult) -> Void) { + self.context = context self.queryPromise = Promise(self.queryValue) - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } self.presentationDataPromise = Promise(self.presentationData) self.dimNode = ASDisplayNode() @@ -397,7 +397,7 @@ final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { let query = strongSelf.queryValue.query if !query.isEmpty { - let _ = addRecentWallpaperSearchQuery(postbox: strongSelf.account.postbox, string: query).start() + let _ = addRecentWallpaperSearchQuery(postbox: strongSelf.context.account.postbox, string: query).start() } } }, selectColor: { [weak self] color in @@ -407,10 +407,10 @@ final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { return query }, updateInterface: true) }, deleteRecentQuery: { query in - let _ = removeRecentWallpaperSearchQuery(postbox: account.postbox, string: query).start() + let _ = removeRecentWallpaperSearchQuery(postbox: context.account.postbox, string: query).start() }) - let configuration = self.account.postbox.transaction { transaction -> SearchBotsConfiguration in + let configuration = self.context.account.postbox.transaction { transaction -> SearchBotsConfiguration in return currentSearchBotsConfiguration(transaction: transaction) } @@ -433,10 +433,10 @@ final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { guard let name = configuration.imageBotUsername else { return .single(nil) } - return resolvePeerByName(account: account, name: name) + return resolvePeerByName(account: context.account, name: name) |> mapToSignal { peerId -> Signal in if let peerId = peerId { - return account.postbox.loadedPeerWithId(peerId) + return context.account.postbox.loadedPeerWithId(peerId) |> map { peer -> Peer? in return peer } @@ -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: account, botId: user.id, query: wallpaperQuery, peerId: account.peerId, limit: 16) + requestContextResults(account: context.account, botId: user.id, query: wallpaperQuery, peerId: account.peerId, limit: 16) |> map { collection -> ([ThemeGridSearchEntry], Bool)? in guard let collection = collection else { return nil @@ -475,7 +475,7 @@ final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { } let previousRecentItems = Atomic<[ThemeGridRecentEntry]?>(value: nil) - self.recentDisposable = (combineLatest(wallpaperSearchRecentQueries(postbox: self.account.postbox), self.presentationDataPromise.get()) + self.recentDisposable = (combineLatest(wallpaperSearchRecentQueries(postbox: self.context.account.postbox), self.presentationDataPromise.get()) |> deliverOnMainQueue).start(next: { [weak self] queries, presentationData in if let strongSelf = self { var entries: [ThemeGridRecentEntry] = [] @@ -486,11 +486,11 @@ final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { } let header = ChatListSearchItemHeader(type: .recentPeers, theme: presentationData.theme, strings: presentationData.strings, actionTitle: presentationData.strings.WebSearch_RecentSectionClear.uppercased(), action: { - _ = clearRecentWallpaperSearchQueries(postbox: strongSelf.account.postbox).start() + _ = clearRecentWallpaperSearchQueries(postbox: strongSelf.context.account.postbox).start() }) let previousEntries = previousRecentItems.swap(entries) - let transition = themeGridSearchContainerPreparedRecentTransition(from: previousEntries ?? [], to: entries, account: account, theme: presentationData.theme, strings: presentationData.strings, interaction: interaction, header: header) + let transition = themeGridSearchContainerPreparedRecentTransition(from: previousEntries ?? [], to: entries, account: context.account, theme: presentationData.theme, strings: presentationData.strings, interaction: interaction, header: header) strongSelf.enqueueRecentTransition(transition, firstTime: previousEntries == nil) } }) @@ -503,12 +503,12 @@ final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { let previousEntries = previousSearchItems.swap(entriesAndFlags?.0) let firstTime = previousEntries == nil - let transition = themeGridSearchContainerPreparedTransition(from: previousEntries ?? [], to: entriesAndFlags?.0 ?? [], displayingResults: entriesAndFlags?.0 != nil, account: account, theme: presentationData.theme, interaction: interaction) + let transition = themeGridSearchContainerPreparedTransition(from: previousEntries ?? [], to: entriesAndFlags?.0 ?? [], displayingResults: entriesAndFlags?.0 != nil, account: context.account, theme: presentationData.theme, interaction: interaction) strongSelf.enqueueTransition(transition, firstTime: firstTime) } })) - 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 @@ -700,7 +700,7 @@ final class ThemeGridSearchContentNode: SearchDisplayControllerContentNode { } private func clearRecentSearch() { - let _ = (clearRecentlySearchedPeers(postbox: self.account.postbox) |> deliverOnMainQueue).start() + let _ = (clearRecentlySearchedPeers(postbox: self.context.account.postbox) |> deliverOnMainQueue).start() } override func scrollToTop() { diff --git a/TelegramUI/ThemeSettingsController.swift b/TelegramUI/ThemeSettingsController.swift index 57c35e5616..30296744c8 100644 --- a/TelegramUI/ThemeSettingsController.swift +++ b/TelegramUI/ThemeSettingsController.swift @@ -247,14 +247,14 @@ private func themeSettingsControllerEntries(presentationData: PresentationData, return entries } -public func themeSettingsController(account: Account) -> ViewController { +public func themeSettingsController(context: AccountContext) -> ViewController { var pushControllerImpl: ((ViewController) -> Void)? var presentControllerImpl: ((ViewController) -> Void)? - let _ = telegramWallpapers(postbox: account.postbox, network: account.network).start() + let _ = telegramWallpapers(postbox: context.account.postbox, network: context.account.network).start() - let arguments = ThemeSettingsControllerArguments(account: account, selectTheme: { index in - let _ = updatePresentationThemeSettingsInteractively(postbox: account.postbox, { current in + let arguments = ThemeSettingsControllerArguments(account: context.account, selectTheme: { index in + let _ = updatePresentationThemeSettingsInteractively(postbox: context.account.postbox, { current in let wallpaper: TelegramWallpaper let theme: PresentationThemeReference if index == 0 { @@ -273,32 +273,32 @@ public func themeSettingsController(account: Account) -> ViewController { return PresentationThemeSettings(chatWallpaper: wallpaper, chatWallpaperOptions: [], theme: theme, themeAccentColor: current.themeAccentColor, fontSize: current.fontSize, automaticThemeSwitchSetting: current.automaticThemeSwitchSetting, disableAnimations: current.disableAnimations) }).start() }, selectFontSize: { size in - let _ = updatePresentationThemeSettingsInteractively(postbox: account.postbox, { current in + let _ = updatePresentationThemeSettingsInteractively(postbox: context.account.postbox, { current in return PresentationThemeSettings(chatWallpaper: current.chatWallpaper, chatWallpaperOptions: current.chatWallpaperOptions, theme: current.theme, themeAccentColor: current.themeAccentColor, fontSize: size, automaticThemeSwitchSetting: current.automaticThemeSwitchSetting, disableAnimations: current.disableAnimations) }).start() }, openWallpaperSettings: { - pushControllerImpl?(ThemeGridController(account: account)) + pushControllerImpl?(ThemeGridController(context: context)) }, openAccentColor: { color in - presentControllerImpl?(ThemeAccentColorActionSheet(account: account, currentValue: color, applyValue: { color in - let _ = updatePresentationThemeSettingsInteractively(postbox: account.postbox, { current in + presentControllerImpl?(ThemeAccentColorActionSheet(context: context, currentValue: color, applyValue: { color in + let _ = updatePresentationThemeSettingsInteractively(postbox: context.account.postbox, { current in return PresentationThemeSettings(chatWallpaper: current.chatWallpaper, chatWallpaperOptions: current.chatWallpaperOptions, theme: current.theme, themeAccentColor: color, fontSize: current.fontSize, automaticThemeSwitchSetting: current.automaticThemeSwitchSetting, disableAnimations: current.disableAnimations) }).start() })) }, openAutoNightTheme: { - pushControllerImpl?(themeAutoNightSettingsController(account: account)) + pushControllerImpl?(themeAutoNightSettingsController(context: context)) }, disableAnimations: { disabled in - let _ = updatePresentationThemeSettingsInteractively(postbox: account.postbox, { current in + let _ = updatePresentationThemeSettingsInteractively(postbox: context.account.postbox, { current in return PresentationThemeSettings(chatWallpaper: current.chatWallpaper, chatWallpaperOptions: current.chatWallpaperOptions, theme: current.theme, themeAccentColor: current.themeAccentColor, fontSize: current.fontSize, automaticThemeSwitchSetting: current.automaticThemeSwitchSetting, disableAnimations: disabled) }).start() }) let themeSettingsKey = ApplicationSpecificPreferencesKeys.presentationThemeSettings let localizationSettingsKey = PreferencesKeys.localizationSettings - let preferences = account.postbox.preferencesView(keys: [themeSettingsKey, localizationSettingsKey]) + let preferences = context.account.postbox.preferencesView(keys: [themeSettingsKey, localizationSettingsKey]) let previousTheme = Atomic(value: nil) - let signal = combineLatest(account.telegramApplicationContext.presentationData, preferences) + let signal = combineLatest(context.presentationData, preferences) |> deliverOnMainQueue |> map { presentationData, preferences -> (ItemListControllerState, (ItemListNodeState, ThemeSettingsControllerEntry.ItemGenerationArguments)) in let theme: PresentationTheme @@ -346,7 +346,7 @@ public func themeSettingsController(account: Account) -> ViewController { return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] c in (controller?.navigationController as? NavigationController)?.pushViewController(c) } diff --git a/TelegramUI/ThemedTextAlertController.swift b/TelegramUI/ThemedTextAlertController.swift index c4bcad8f64..2e4321862d 100644 --- a/TelegramUI/ThemedTextAlertController.swift +++ b/TelegramUI/ThemedTextAlertController.swift @@ -2,12 +2,12 @@ import Foundation import Display import TelegramCore -public func textAlertController(account: Account, title: String?, text: String, actions: [TextAlertAction], actionLayout: TextAlertContentActionLayout = .horizontal) -> AlertController { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } +public func textAlertController(context: AccountContext, title: String?, text: String, actions: [TextAlertAction], actionLayout: TextAlertContentActionLayout = .horizontal) -> AlertController { + let presentationData = context.currentPresentationData.with { $0 } let theme = presentationData.theme let controller = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: theme), title: title, text: text, actions: actions) - _ = account.telegramApplicationContext.presentationData.start(next: { [weak controller] presentationData in + _ = context.presentationData.start(next: { [weak controller] presentationData in if let strongController = controller { strongController.theme = AlertControllerTheme(presentationTheme: presentationData.theme) } diff --git a/TelegramUI/TwoStepVerificationPasswordEntryController.swift b/TelegramUI/TwoStepVerificationPasswordEntryController.swift index a1420b7db1..527dfad8d8 100644 --- a/TelegramUI/TwoStepVerificationPasswordEntryController.swift +++ b/TelegramUI/TwoStepVerificationPasswordEntryController.swift @@ -253,7 +253,7 @@ struct TwoStepVerificationPasswordEntryResult { let pendingEmail: TwoStepVerificationPendingEmail? } -func twoStepVerificationPasswordEntryController(account: Account, mode: TwoStepVerificationPasswordEntryMode, result: Promise) -> ViewController { +func twoStepVerificationPasswordEntryController(context: AccountContext, mode: TwoStepVerificationPasswordEntryMode, result: Promise) -> ViewController { let initialStage: PasswordEntryStage switch mode { case .setup, .change: @@ -323,7 +323,7 @@ func twoStepVerificationPasswordEntryController(account: Account, mode: TwoStepV if case let .change(current) = mode { currentPassword = current } - updatePasswordDisposable.set((updateTwoStepVerificationPassword(network: account.network, currentPassword: currentPassword, updatedPassword: .password(password: password, hint: hint, email: email)) |> deliverOnMainQueue).start(next: { update in + updatePasswordDisposable.set((updateTwoStepVerificationPassword(network: context.account.network, currentPassword: currentPassword, updatedPassword: .password(password: password, hint: hint, email: email)) |> deliverOnMainQueue).start(next: { update in updateState { $0.withUpdatedUpdating(false) } @@ -337,7 +337,7 @@ func twoStepVerificationPasswordEntryController(account: Account, mode: TwoStepV updateState { $0.withUpdatedUpdating(false) } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let alertText: String switch error { case .generic: @@ -348,7 +348,7 @@ func twoStepVerificationPasswordEntryController(account: Account, mode: TwoStepV presentControllerImpl?(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: alertText, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) })) case let .setupEmail(password): - updatePasswordDisposable.set((updateTwoStepVerificationEmail(account: account, currentPassword: password, updatedEmail: email) |> deliverOnMainQueue).start(next: { update in + updatePasswordDisposable.set((updateTwoStepVerificationEmail(account: context.account, currentPassword: password, updatedEmail: email) |> deliverOnMainQueue).start(next: { update in updateState { $0.withUpdatedUpdating(false) } @@ -362,7 +362,7 @@ func twoStepVerificationPasswordEntryController(account: Account, mode: TwoStepV updateState { $0.withUpdatedUpdating(false) } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let alertText: String switch error { case .generic: @@ -374,7 +374,7 @@ func twoStepVerificationPasswordEntryController(account: Account, mode: TwoStepV })) } } else if invalidReentry { - 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.TwoStepAuth_SetupPasswordConfirmFailed, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } } @@ -387,7 +387,7 @@ func twoStepVerificationPasswordEntryController(account: Account, mode: TwoStepV checkPassword() }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get()) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, statePromise.get()) |> deliverOnMainQueue |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, TwoStepVerificationPasswordEntryEntry.ItemGenerationArguments)) in let leftNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Cancel), style: .regular, enabled: true, action: { @@ -432,7 +432,7 @@ func twoStepVerificationPasswordEntryController(account: Account, mode: TwoStepV actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, p in if let controller = controller { controller.present(c, in: .window(.root), with: p) diff --git a/TelegramUI/TwoStepVerificationResetController.swift b/TelegramUI/TwoStepVerificationResetController.swift index 4adf3053d5..c384d34983 100644 --- a/TelegramUI/TwoStepVerificationResetController.swift +++ b/TelegramUI/TwoStepVerificationResetController.swift @@ -129,7 +129,7 @@ private func twoStepVerificationResetControllerEntries(presentationData: Present return entries } -func twoStepVerificationResetController(account: Account, emailPattern: String, result: Promise) -> ViewController { +func twoStepVerificationResetController(context: AccountContext, emailPattern: String, result: Promise) -> ViewController { let initialState = TwoStepVerificationResetControllerState(codeText: "", checking: false) let statePromise = ValuePromise(initialState, ignoreRepeated: true) @@ -157,11 +157,11 @@ func twoStepVerificationResetController(account: Account, emailPattern: String, } } if let code = code { - resetPasswordDisposable.set((recoverTwoStepVerificationPassword(network: account.network, code: code) |> deliverOnMainQueue).start(error: { error in + resetPasswordDisposable.set((recoverTwoStepVerificationPassword(network: context.account.network, code: code) |> deliverOnMainQueue).start(error: { error in updateState { return $0.withUpdatedChecking(false) } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let alertText: String switch error { case .generic: @@ -190,11 +190,11 @@ func twoStepVerificationResetController(account: Account, emailPattern: String, }, next: { checkCode() }, openEmailInaccessible: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: "Your remaining options are either to remember your password or to reset your account.", actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get()) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, statePromise.get()) |> deliverOnMainQueue |> map { presentationData, state -> (ItemListControllerState, (ItemListNodeState, TwoStepVerificationResetEntry.ItemGenerationArguments)) in let leftNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Cancel), style: .regular, enabled: true, action: { @@ -222,7 +222,7 @@ func twoStepVerificationResetController(account: Account, emailPattern: String, actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) presentControllerImpl = { [weak controller] c, p in if let controller = controller { controller.present(c, in: .window(.root), with: p) diff --git a/TelegramUI/TwoStepVerificationUnlockController.swift b/TelegramUI/TwoStepVerificationUnlockController.swift index c31a442bda..0252633fe5 100644 --- a/TelegramUI/TwoStepVerificationUnlockController.swift +++ b/TelegramUI/TwoStepVerificationUnlockController.swift @@ -244,7 +244,7 @@ private enum TwoStepVerificationUnlockSettingsControllerData { case manage(password: String, emailSet: Bool, pendingEmail: TwoStepVerificationPendingEmail?, hasSecureValues: Bool) } -func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStepVerificationUnlockSettingsControllerMode) -> ViewController { +func twoStepVerificationUnlockSettingsController(context: AccountContext, mode: TwoStepVerificationUnlockSettingsControllerMode) -> ViewController { let initialState = TwoStepVerificationUnlockSettingsControllerState() let statePromise = ValuePromise(initialState, ignoreRepeated: true) @@ -272,7 +272,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep switch mode { case .access: dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.access(configuration: nil)) - |> then(twoStepVerificationConfiguration(account: account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: nil)) })) + |> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: nil)) })) case let .manage(password, email, pendingEmail, hasSecureValues): dataPromise.set(.single(.manage(password: password, emailSet: !email.isEmpty, pendingEmail: pendingEmail, hasSecureValues: hasSecureValues))) } @@ -309,14 +309,14 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep return state } if let code = code { - setupDisposable.set((confirmTwoStepRecoveryEmail(network: account.network, code: code) + setupDisposable.set((confirmTwoStepRecoveryEmail(network: context.account.network, code: code) |> deliverOnMainQueue).start(error: { error in updateState { state in var state = state state.checking = false return state } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let text: String switch error { case .invalidEmail: @@ -358,7 +358,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.manage(password: password, emailSet: true, pendingEmail: nil, hasSecureValues: false))) } else { dataPromise.set(.single(.access(configuration: nil)) - |> then(twoStepVerificationConfiguration(account: account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: pendingEmail.password)) })) + |> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: pendingEmail.password)) })) } case let .manage(manage): dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.manage(password: manage.password, emailSet: true, pendingEmail: nil, hasSecureValues: manage.hasSecureValues))) @@ -395,9 +395,9 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep } if let password = password, !password.isEmpty, !wasChecking { - checkDisposable.set((requestTwoStepVerifiationSettings(network: account.network, password: password) + checkDisposable.set((requestTwoStepVerifiationSettings(network: context.account.network, password: password) |> mapToSignal { settings -> Signal<(TwoStepVerificationSettings, TwoStepVerificationPendingEmail?), AuthorizationPasswordVerificationError> in - return twoStepVerificationConfiguration(account: account) + return twoStepVerificationConfiguration(account: context.account) |> mapError { _ -> AuthorizationPasswordVerificationError in return .generic } @@ -416,7 +416,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep return state } - replaceControllerImpl?(twoStepVerificationUnlockSettingsController(account: account, mode: .manage(password: password, email: settings.email, pendingEmail: pendingEmail, hasSecureValues: settings.secureSecret != nil))) + replaceControllerImpl?(twoStepVerificationUnlockSettingsController(context: context, mode: .manage(password: password, email: settings.email, pendingEmail: pendingEmail, hasSecureValues: settings.secureSecret != nil))) }, error: { error in updateState { state in var state = state @@ -424,7 +424,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep return state } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let text: String switch error { @@ -446,7 +446,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep switch data { case let .access(configuration): if let configuration = configuration { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } switch configuration { case let .set(_, hasRecoveryEmail, _): if hasRecoveryEmail { @@ -455,7 +455,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep state.checking = true return state } - setupResultDisposable.set((requestTwoStepVerificationPasswordRecoveryCode(network: account.network) + setupResultDisposable.set((requestTwoStepVerificationPasswordRecoveryCode(network: context.account.network) |> deliverOnMainQueue).start(next: { emailPattern in updateState { state in var state = state @@ -464,7 +464,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep } var completionImpl: (() -> Void)? - let controller = resetPasswordController(account: account, emailPattern: emailPattern, completion: { + let controller = resetPasswordController(context: context, emailPattern: emailPattern, completion: { completionImpl?() }) completionImpl = { [weak controller] in @@ -472,7 +472,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep controller?.view.endEditing(true) controller?.dismiss() - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .genericSuccess(presentationData.strings.TwoStepAuth_DisableSuccess)), nil) } presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) @@ -504,7 +504,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep if let configuration = configuration { switch configuration { case .notSet: - let controller = SetupTwoStepVerificationController(account: account, initialState: .createPassword, stateUpdated: { update, shouldDismiss, controller in + let controller = SetupTwoStepVerificationController(context: context, initialState: .createPassword, stateUpdated: { update, shouldDismiss, controller in switch update { case .noPassword: dataPromise.set(.single(.access(configuration: .notSet(pendingEmail: nil)))) @@ -513,11 +513,11 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep case let .passwordSet(password, hasRecoveryEmail, hasSecureValues): if let password = password { dataPromise.set(.single(.manage(password: password, emailSet: hasRecoveryEmail, pendingEmail: nil, hasSecureValues: hasSecureValues))) - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .genericSuccess(presentationData.strings.TwoStepAuth_EnabledSuccess)), nil) } else { dataPromise.set(.single(.access(configuration: nil)) - |> then(twoStepVerificationConfiguration(account: account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: password)) })) + |> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: password)) })) } } if shouldDismiss { @@ -530,7 +530,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep } } case let .manage(password, hasRecovery, pendingEmail, hasSecureValues): - let controller = SetupTwoStepVerificationController(account: account, initialState: .updatePassword(current: password, hasRecoveryEmail: hasRecovery, hasSecureValues: hasSecureValues), stateUpdated: { update, shouldDismiss, controller in + let controller = SetupTwoStepVerificationController(context: context, initialState: .updatePassword(current: password, hasRecoveryEmail: hasRecovery, hasSecureValues: hasSecureValues), stateUpdated: { update, shouldDismiss, controller in switch update { case .noPassword: dataPromise.set(.single(.access(configuration: .notSet(pendingEmail: nil)))) @@ -540,11 +540,11 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep case let .passwordSet(password, hasRecoveryEmail, hasSecureValues): if let password = password { dataPromise.set(.single(.manage(password: password, emailSet: hasRecoveryEmail, pendingEmail: nil, hasSecureValues: hasSecureValues))) - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .genericSuccess(presentationData.strings.TwoStepAuth_PasswordChangeSuccess)), nil) } else { dataPromise.set(.single(.access(configuration: nil)) - |> then(twoStepVerificationConfiguration(account: account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: password)) })) + |> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: password)) })) } } if shouldDismiss { @@ -558,7 +558,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep setupDisposable.set((dataPromise.get() |> take(1) |> deliverOnMainQueue).start(next: { data in switch data { case let .manage(_, _, _, hasSecureValues): - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } var text = presentationData.strings.TwoStepAuth_PasswordRemoveConfirmation if hasSecureValues { text = presentationData.strings.TwoStepAuth_PasswordRemovePassportConfirmation @@ -584,9 +584,9 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep case .access: return .complete() case let .manage(password, _, _, _): - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .genericSuccess(presentationData.strings.TwoStepAuth_DisableSuccess)), nil) - return updateTwoStepVerificationPassword(network: account.network, currentPassword: password, updatedPassword: .none) + return updateTwoStepVerificationPassword(network: context.account.network, currentPassword: password, updatedPassword: .none) |> mapToSignal { _ -> Signal in return .complete() } @@ -620,7 +620,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep case .access: break case let .manage(password, emailSet, _, hasSecureValues): - let controller = SetupTwoStepVerificationController(account: account, initialState: .addEmail(hadRecoveryEmail: emailSet, hasSecureValues: hasSecureValues, password: password), stateUpdated: { update, shouldDismiss, controller in + let controller = SetupTwoStepVerificationController(context: context, initialState: .addEmail(hadRecoveryEmail: emailSet, hasSecureValues: hasSecureValues, password: password), stateUpdated: { update, shouldDismiss, controller in switch update { case .noPassword: assertionFailure() @@ -632,11 +632,11 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep if let password = password { let data: TwoStepVerificationUnlockSettingsControllerData = .manage(password: password, emailSet: hasRecoveryEmail, pendingEmail: nil, hasSecureValues: hasSecureValues) dataPromise.set(.single(data)) - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .genericSuccess(emailSet ? presentationData.strings.TwoStepAuth_EmailChangeSuccess : presentationData.strings.TwoStepAuth_EmailAddSuccess)), nil) } else { dataPromise.set(.single(.access(configuration: nil)) - |> then(twoStepVerificationConfiguration(account: account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: password)) })) + |> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: password)) })) } } if shouldDismiss { @@ -652,7 +652,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep state.checking = true return state } - setupDisposable.set((updateTwoStepVerificationPassword(network: account.network, currentPassword: nil, updatedPassword: .none) + setupDisposable.set((updateTwoStepVerificationPassword(network: context.account.network, currentPassword: nil, updatedPassword: .none) |> deliverOnMainQueue).start(next: { _ in updateState { state in var state = state @@ -707,7 +707,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep guard let pendingEmail = pendingEmail else { return } - let controller = SetupTwoStepVerificationController(account: account, initialState: .confirmEmail(password: password, hasSecureValues: hasSecureValues, pattern: pendingEmail.pattern, codeLength: pendingEmail.codeLength), stateUpdated: { update, shouldDismiss, controller in + let controller = SetupTwoStepVerificationController(context: context, initialState: .confirmEmail(password: password, hasSecureValues: hasSecureValues, pattern: pendingEmail.pattern, codeLength: pendingEmail.codeLength), stateUpdated: { update, shouldDismiss, controller in switch update { case .noPassword: assertionFailure() @@ -716,14 +716,14 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep let data: TwoStepVerificationUnlockSettingsControllerData = .manage(password: password, emailSet: emailSet, pendingEmail: TwoStepVerificationPendingEmail(pattern: pattern, codeLength: codeLength), hasSecureValues: hasSecureValues) dataPromise.set(.single(data)) case let .passwordSet(password, hasRecoveryEmail, hasSecureValues): - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .genericSuccess(emailSet ? presentationData.strings.TwoStepAuth_EmailChangeSuccess : presentationData.strings.TwoStepAuth_EmailAddSuccess)), nil) if let password = password { let data: TwoStepVerificationUnlockSettingsControllerData = .manage(password: password, emailSet: hasRecoveryEmail, pendingEmail: nil, hasSecureValues: hasSecureValues) dataPromise.set(.single(data)) } else { dataPromise.set(.single(.access(configuration: nil)) - |> then(twoStepVerificationConfiguration(account: account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: password)) })) + |> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVeriticationAccessConfiguration(configuration: $0, password: password)) })) } } if shouldDismiss { @@ -738,7 +738,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep var initialFocusImpl: (() -> Void)? var didAppear = false - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), dataPromise.get() |> deliverOnMainQueue) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, statePromise.get(), dataPromise.get() |> deliverOnMainQueue) |> deliverOnMainQueue |> map { presentationData, state, data -> (ItemListControllerState, (ItemListNodeState, TwoStepVerificationUnlockSettingsEntry.ItemGenerationArguments)) in var rightNavigationButton: ItemListNavigationButton? var emptyStateItem: ItemListControllerEmptyStateItem? @@ -789,7 +789,7 @@ func twoStepVerificationUnlockSettingsController(account: Account, mode: TwoStep actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) replaceControllerImpl = { [weak controller] c in (controller?.navigationController as? NavigationController)?.replaceTopController(c, animated: true) } diff --git a/TelegramUI/UndoOverlayController.swift b/TelegramUI/UndoOverlayController.swift index ec621ac4c7..916c8efbbf 100644 --- a/TelegramUI/UndoOverlayController.swift +++ b/TelegramUI/UndoOverlayController.swift @@ -3,16 +3,16 @@ import Display import TelegramCore final class UndoOverlayController: ViewController { - private let account: Account + private let context: AccountContext private let presentationData: PresentationData private let text: String private let action: (Bool) -> Void private var didPlayPresentationAnimation = false - init(account: Account, text: String, action: @escaping (Bool) -> Void) { - self.account = account - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + init(context: AccountContext, text: String, action: @escaping (Bool) -> Void) { + self.context = context + self.presentationData = context.currentPresentationData.with { $0 } self.text = text self.action = action diff --git a/TelegramUI/UniversalVideoGalleryItem.swift b/TelegramUI/UniversalVideoGalleryItem.swift index 99d79e4394..f0bf12e686 100644 --- a/TelegramUI/UniversalVideoGalleryItem.swift +++ b/TelegramUI/UniversalVideoGalleryItem.swift @@ -12,7 +12,7 @@ enum UniversalVideoGalleryItemContentInfo { } class UniversalVideoGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let presentationData: PresentationData let content: UniversalVideoContent let originData: GalleryItemOriginData? @@ -25,8 +25,8 @@ class UniversalVideoGalleryItem: GalleryItem { let performAction: (GalleryControllerInteractionTapAction) -> Void let openActionOptions: (GalleryControllerInteractionTapAction) -> Void - init(account: Account, presentationData: PresentationData, content: UniversalVideoContent, originData: GalleryItemOriginData?, indexData: GalleryItemIndexData?, contentInfo: UniversalVideoGalleryItemContentInfo?, caption: NSAttributedString, credit: NSAttributedString? = nil, hideControls: Bool = false, playbackCompleted: @escaping () -> Void = {}, performAction: @escaping (GalleryControllerInteractionTapAction) -> Void, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, content: UniversalVideoContent, originData: GalleryItemOriginData?, indexData: GalleryItemIndexData?, contentInfo: UniversalVideoGalleryItemContentInfo?, caption: NSAttributedString, credit: NSAttributedString? = nil, hideControls: Bool = false, playbackCompleted: @escaping () -> Void = {}, performAction: @escaping (GalleryControllerInteractionTapAction) -> Void, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void) { + self.context = context self.presentationData = presentationData self.content = content self.originData = originData @@ -41,7 +41,7 @@ class UniversalVideoGalleryItem: GalleryItem { } func node() -> GalleryItemNode { - let node = UniversalVideoGalleryItemNode(account: self.account, presentationData: self.presentationData, performAction: self.performAction, openActionOptions: self.openActionOptions) + let node = UniversalVideoGalleryItemNode(context: self.context, presentationData: self.presentationData, performAction: self.performAction, openActionOptions: self.openActionOptions) if let indexData = self.indexData { node._title.set(.single("\(indexData.position + 1) \(self.presentationData.strings.Common_of) \(indexData.totalCount)")) @@ -77,13 +77,13 @@ class UniversalVideoGalleryItem: GalleryItem { } } if let mediaReference = mediaReference { - if let item = ChatMediaGalleryThumbnailItem(account: self.account, mediaReference: mediaReference) { + if let item = ChatMediaGalleryThumbnailItem(account: self.context.account, mediaReference: mediaReference) { return (Int64(id), item) } } } } else if case let .webPage(webPage, media) = contentInfo, let file = media as? TelegramMediaFile { - if let item = ChatMediaGalleryThumbnailItem(account: self.account, mediaReference: .webPage(webPage: WebpageReference(webPage), media: file)) { + if let item = ChatMediaGalleryThumbnailItem(account: self.context.account, mediaReference: .webPage(webPage: WebpageReference(webPage), media: file)) { return (0, item) } } @@ -134,7 +134,7 @@ private struct FetchControls { } final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { - private let account: Account + private let context: AccountContext private let strings: PresentationStrings fileprivate let _ready = Promise() @@ -167,12 +167,12 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { var playbackCompleted: (() -> Void)? - init(account: Account, presentationData: PresentationData, performAction: @escaping (GalleryControllerInteractionTapAction) -> Void, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, performAction: @escaping (GalleryControllerInteractionTapAction) -> Void, openActionOptions: @escaping (GalleryControllerInteractionTapAction) -> Void) { + self.context = context self.strings = presentationData.strings self.scrubberView = ChatVideoGalleryItemScrubberView() - self.footerContentNode = ChatItemGalleryFooterContentNode(account: account, presentationData: presentationData) + self.footerContentNode = ChatItemGalleryFooterContentNode(context: context, presentationData: presentationData) self.footerContentNode.scrubberView = self.scrubberView self.footerContentNode.performAction = performAction self.footerContentNode.openActionOptions = openActionOptions @@ -289,11 +289,9 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { self.footerContentNode.scrubberView = nil } - guard let mediaManager = item.account.telegramApplicationContext.mediaManager else { - preconditionFailure() - } + let mediaManager = item.context.mediaManager - let videoNode = UniversalVideoNode(postbox: item.account.postbox, audioSession: mediaManager.audioSession, manager: mediaManager.universalVideoManager, decoration: GalleryVideoDecoration(), content: item.content, priority: .gallery) + let videoNode = UniversalVideoNode(postbox: item.context.account.postbox, audioSession: mediaManager.audioSession, manager: mediaManager.universalVideoManager, decoration: GalleryVideoDecoration(), content: item.content, priority: .gallery) let videoSize = CGSize(width: item.content.dimensions.width * 2.0, height: item.content.dimensions.height * 2.0) videoNode.updateLayout(size: videoSize, transition: .immediate) videoNode.ownsContentNodeUpdated = { [weak self] value in @@ -333,7 +331,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { } } if let file = file { - let status = messageMediaFileStatus(account: item.account, messageId: message.id, file: file) + let status = messageMediaFileStatus(account: item.context.account, messageId: message.id, file: file) if !isWebpage { self.scrubberView.setFetchStatusSignal(status, strings: self.strings, fileSize: file.size) } @@ -342,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.account, message: message, file: file, userInitiated: true).start()) + strongSelf.fetchDisposable.set(messageMediaFileInteractiveFetched(account: item.context.account, message: message, file: file, userInitiated: true).start()) } }, cancel: { - messageMediaFileCancelInteractiveFetch(account: item.account, messageId: message.id, file: file) + messageMediaFileCancelInteractiveFetch(account: item.context.account, messageId: message.id, file: file) }) } } @@ -539,7 +537,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { let transform = CATransform3DScale(videoNode.layer.transform, transformedFrame.size.width / videoNode.layer.bounds.size.width, transformedFrame.size.height / videoNode.layer.bounds.size.height, 1.0) videoNode.layer.animate(from: NSValue(caTransform3D: transform), to: NSValue(caTransform3D: videoNode.layer.transform), keyPath: "transform", timingFunction: kCAMediaTimingFunctionSpring, duration: 0.25) - self.account.telegramApplicationContext.mediaManager?.setOverlayVideoNode(nil) + self.context.mediaManager.setOverlayVideoNode(nil) } else { var transformedFrame = node.0.view.convert(node.0.view.bounds, to: videoNode.view) let transformedSuperFrame = node.0.view.convert(node.0.view.bounds, to: videoNode.view.superview) @@ -813,11 +811,11 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { @objc func pictureInPictureButtonPressed() { if let item = self.item, let _ = self.videoNode { - let account = self.account + let context = self.context let baseNavigationController = self.baseNavigationController() - let mediaManager = self.account.telegramApplicationContext.mediaManager! + let mediaManager = self.context.mediaManager var expandImpl: (() -> Void)? - let overlayNode = OverlayUniversalVideoNode(account: self.account, audioSession: self.account.telegramApplicationContext.mediaManager!.audioSession, manager: self.account.telegramApplicationContext.mediaManager!.universalVideoManager, content: item.content, expand: { + let overlayNode = OverlayUniversalVideoNode(postbox: self.context.account.postbox, audioSession: context.mediaManager.audioSession, manager: context.mediaManager.universalVideoManager, content: item.content, expand: { expandImpl?() }, close: { [weak mediaManager] in mediaManager?.setOverlayVideoNode(nil) @@ -829,7 +827,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { switch contentInfo { case let .message(message): - let gallery = GalleryController(account: account, source: .peerMessagesAtId(message.id), replaceRootController: { controller, ready in + let gallery = GalleryController(context: context, source: .peerMessagesAtId(message.id), replaceRootController: { controller, ready in if let baseNavigationController = baseNavigationController { baseNavigationController.replaceTopController(controller, animated: false, ready: ready) } @@ -846,7 +844,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { overlaySupernode?.view.addSubview(view) overlayNode?.canAttachContent = false }) - } else if let info = account.telegramApplicationContext.mediaManager?.galleryHiddenMediaManager.findTarget(messageId: id, media: media) { + } else if let info = context.mediaManager.galleryHiddenMediaManager.findTarget(messageId: id, media: media) { return GalleryTransitionArguments(transitionNode: (info.1, info.2), addToTransitionSurface: info.0) } return nil @@ -855,7 +853,7 @@ final class UniversalVideoGalleryItemNode: ZoomableContentGalleryItemNode { break } } - account.telegramApplicationContext.mediaManager?.setOverlayVideoNode(overlayNode) + context.mediaManager.setOverlayVideoNode(overlayNode) if overlayNode.supernode != nil { self.beginCustomDismiss() self.animateOut(toOverlay: overlayNode, completion: { [weak self] in diff --git a/TelegramUI/UserInfoController.swift b/TelegramUI/UserInfoController.swift index 8e7ecd2861..272c25526b 100644 --- a/TelegramUI/UserInfoController.swift +++ b/TelegramUI/UserInfoController.swift @@ -719,7 +719,7 @@ public enum UserInfoControllerMode { case calls(messages: [Message]) } -public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoControllerMode = .generic) -> ViewController { +public func userInfoController(context: AccountContext, peerId: PeerId, mode: UserInfoControllerMode = .generic) -> ViewController { let statePromise = ValuePromise(UserInfoState(), ignoreRepeated: true) let stateValue = Atomic(value: UserInfoState()) let updateState: ((UserInfoState) -> UserInfoState) -> Void = { f in @@ -767,10 +767,10 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC let cachedAvatarEntries = Atomic?>(value: nil) let peerView = Promise<(PeerView, CachedPeerData?)>() - peerView.set(account.viewTracker.peerView(peerId) |> mapToSignal({ view -> Signal<(PeerView, CachedPeerData?), NoError> in + peerView.set(context.account.viewTracker.peerView(peerId) |> mapToSignal({ view -> Signal<(PeerView, CachedPeerData?), NoError> in if peerId.namespace == Namespaces.Peer.SecretChat { if let peer = peerViewMainPeer(view) { - return account.viewTracker.peerView(peer.id) |> map({ secretChatView -> (PeerView, CachedPeerData?) in + return context.account.viewTracker.peerView(peer.id) |> map({ secretChatView -> (PeerView, CachedPeerData?) in return (view, secretChatView.cachedData) }) } @@ -787,23 +787,23 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC } if let cachedUserData = view.1 as? CachedUserData, cachedUserData.callsPrivate { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } presentControllerImpl?(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: presentationData.strings.Call_ConnectionErrorTitle, text: presentationData.strings.Call_PrivacyErrorMessage(peer.compactDisplayTitle).0, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil) return } - let callResult = account.telegramApplicationContext.callManager?.requestCall(peerId: peer.id, endCurrentIfAny: false) + let callResult = context.callManager?.requestCall(peerId: peer.id, endCurrentIfAny: false) if let callResult = callResult, case let .alreadyInProgress(currentPeerId) = callResult { if currentPeerId == peer.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(peer.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) } }) @@ -812,7 +812,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC }) } - let arguments = UserInfoControllerArguments(account: account, avatarAndNameInfoContext: avatarAndNameInfoContext, updateEditingName: { editingName in + let arguments = UserInfoControllerArguments(account: context.account, avatarAndNameInfoContext: avatarAndNameInfoContext, updateEditingName: { editingName in updateState { state in if let _ = state.editingState { return state.withUpdatedEditingState(UserInfoEditingState(editingName: editingName)) @@ -821,7 +821,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC } } }, tapAvatarAction: { - let _ = (getUserPeer(postbox: account.postbox, peerId: peerId) |> deliverOnMainQueue).start(next: { peer in + let _ = (getUserPeer(postbox: context.account.postbox, peerId: peerId) |> deliverOnMainQueue).start(next: { peer in guard let peer = peer else { return } @@ -830,7 +830,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC return } - let galleryController = AvatarGalleryController(account: account, peer: peer, remoteEntries: cachedAvatarEntries.with { $0 }, replaceRootController: { controller, ready in + let galleryController = AvatarGalleryController(context: context, peer: peer, remoteEntries: cachedAvatarEntries.with { $0 }, replaceRootController: { controller, ready in }) hiddenAvatarRepresentationDisposable.set((galleryController.hiddenMedia |> deliverOnMainQueue).start(next: { entry in avatarAndNameInfoContext.hiddenAvatarRepresentation = entry?.representations.first?.representation @@ -843,10 +843,10 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC }, openChat: { openChatImpl?() }, addContact: { - let _ = (getUserPeer(postbox: account.postbox, peerId: peerId) + let _ = (getUserPeer(postbox: context.account.postbox, peerId: peerId) |> deliverOnMainQueue).start(next: { peer in if let user = peer as? TelegramUser, let phone = user.phone, !phone.isEmpty { - let _ = (addContactPeerInteractively(account: account, peerId: user.id, phone: phone) + let _ = (addContactPeerInteractively(account: context.account, peerId: user.id, phone: phone) |> deliverOnMainQueue).start(completed: { }) } @@ -858,8 +858,8 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC }, startSecretChat: { startSecretChatImpl?() }, changeNotificationMuteSettings: { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } - let _ = (account.postbox.transaction { transaction -> (TelegramPeerNotificationSettings, GlobalNotificationSettings) in + let presentationData = context.currentPresentationData.with { $0 } + let _ = (context.account.postbox.transaction { transaction -> (TelegramPeerNotificationSettings, GlobalNotificationSettings) in let peerSettings: TelegramPeerNotificationSettings = (transaction.getPeerNotificationSettings(peerId) as? TelegramPeerNotificationSettings) ?? TelegramPeerNotificationSettings.defaultSettings let globalSettings: GlobalNotificationSettings = (transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications) as? GlobalNotificationSettings) ?? GlobalNotificationSettings.defaultSettings return (peerSettings, globalSettings) @@ -872,42 +872,42 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC soundSettings = NotificationSoundSettings(value: peerSettings.messageSound) } let controller = notificationMuteSettingsController(presentationData: presentationData, notificationSettings: globalSettings.effective.groupChats, soundSettings: soundSettings, openSoundSettings: { - let controller = notificationSoundSelectionController(account: account, isModal: true, currentSound: peerSettings.messageSound, defaultSound: globalSettings.effective.groupChats.sound, completion: { sound in - let _ = updatePeerNotificationSoundInteractive(account: account, peerId: peerId, sound: sound).start() + let controller = notificationSoundSelectionController(context: context, isModal: true, currentSound: peerSettings.messageSound, defaultSound: globalSettings.effective.groupChats.sound, completion: { sound in + let _ = updatePeerNotificationSoundInteractive(account: context.account, peerId: peerId, sound: sound).start() }) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, updateSettings: { value in - changeMuteSettingsDisposable.set(updatePeerMuteSetting(account: account, peerId: peerId, muteInterval: value).start()) + changeMuteSettingsDisposable.set(updatePeerMuteSetting(account: context.account, peerId: peerId, muteInterval: value).start()) }) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }) }, openSharedMedia: { - if let controller = peerSharedMediaController(account: account, peerId: peerId) { + if let controller = peerSharedMediaController(context: context, peerId: peerId) { pushControllerImpl?(controller) } }, openGroupsInCommon: { - let _ = (getUserPeer(postbox: account.postbox, peerId: peerId) + let _ = (getUserPeer(postbox: context.account.postbox, peerId: peerId) |> take(1) |> deliverOnMainQueue).start(next: { peer in guard let peer = peer else { return } - pushControllerImpl?(groupsInCommonController(account: account, peerId: peer.id)) + pushControllerImpl?(groupsInCommonController(context: context, peerId: peer.id)) }) }, updatePeerBlocked: { value in - let _ = (getUserPeer(postbox: account.postbox, peerId: peerId) + let _ = (getUserPeer(postbox: context.account.postbox, peerId: peerId) |> take(1) |> deliverOnMainQueue).start(next: { peer in guard let peer = peer else { return } - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } if let peer = peer as? TelegramUser, let _ = peer.botInfo { - updatePeerBlockedDisposable.set(requestUpdatePeerIsBlocked(account: account, peerId: peer.id, isBlocked: value).start()) + updatePeerBlockedDisposable.set(requestUpdatePeerIsBlocked(account: context.account, peerId: peer.id, isBlocked: value).start()) if !value { - let _ = enqueueMessages(account: account, peerId: peer.id, messages: [.message(text: "/start", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() + let _ = enqueueMessages(account: context.account, peerId: peer.id, messages: [.message(text: "/start", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() openChatImpl?() } } else { @@ -917,13 +917,13 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC } else { text = presentationData.strings.UserInfo_UnblockConfirmation(peer.displayTitle).0 } - presentControllerImpl?(textAlertController(account: account, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_No, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Yes, action: { - updatePeerBlockedDisposable.set(requestUpdatePeerIsBlocked(account: account, peerId: peer.id, isBlocked: value).start()) + presentControllerImpl?(textAlertController(context: context, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_No, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Yes, action: { + updatePeerBlockedDisposable.set(requestUpdatePeerIsBlocked(account: context.account, peerId: peer.id, isBlocked: value).start()) })]), nil) } }) }, deleteContact: { - 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() @@ -932,12 +932,12 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC ActionSheetItemGroup(items: [ ActionSheetButtonItem(title: presentationData.strings.UserInfo_DeleteContact, color: .destructive, action: { dismissAction() - let _ = (getUserPeer(postbox: account.postbox, peerId: peerId) + let _ = (getUserPeer(postbox: context.account.postbox, peerId: peerId) |> deliverOnMainQueue).start(next: { peer in guard let peer = peer else { return } - updatePeerBlockedDisposable.set(deleteContactPeerInteractively(account: account, peerId: peer.id).start()) + updatePeerBlockedDisposable.set(deleteContactPeerInteractively(account: context.account, peerId: peer.id).start()) }) }) ]), @@ -945,17 +945,17 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC ]) presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) }, displayUsernameContextMenu: { text in - let shareController = ShareController(account: account, subject: .url("\(text)")) + let shareController = ShareController(context: context, subject: .url("\(text)")) presentControllerImpl?(shareController, nil) }, displayCopyContextMenu: { tag, phone in displayCopyContextMenuImpl?(tag, phone) }, call: { requestCallImpl() }, openCallMenu: { number in - let _ = (getUserPeer(postbox: account.postbox, peerId: peerId) + let _ = (getUserPeer(postbox: context.account.postbox, peerId: peerId) |> deliverOnMainQueue).start(next: { peer in if let peer = peer as? TelegramUser, let peerPhoneNumber = peer.phone, formatPhoneNumber(number) == formatPhoneNumber(peerPhoneNumber) { - 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() @@ -968,14 +968,14 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC }), 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: ""))") } }) }, aboutLinkAction: { action, itemLink in @@ -983,7 +983,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC }, displayAboutContextMenu: { text in displayAboutContextMenuImpl?(text) }, openEncryptionKey: { fingerprint in - let _ = (account.postbox.transaction { transaction -> Peer? in + let _ = (context.account.postbox.transaction { transaction -> Peer? in if let peer = transaction.getPeer(peerId) as? TelegramSecretChat { if let userPeer = transaction.getPeer(peer.regularPeerId) { return userPeer @@ -992,7 +992,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC return nil } |> deliverOnMainQueue).start(next: { peer in if let peer = peer { - pushControllerImpl?(SecretChatKeyController(account: account, fingerprint: fingerprint, peer: peer)) + pushControllerImpl?(SecretChatKeyController(context: context, fingerprint: fingerprint, peer: peer)) } }) }, addBotToGroup: { @@ -1000,25 +1000,25 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC }, shareBot: { shareBotImpl?() }, botSettings: { - let _ = (account.postbox.loadedPeerWithId(peerId) + let _ = (context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { peer in - let _ = enqueueMessages(account: account, peerId: peer.id, messages: [.message(text: "/settings", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() + let _ = enqueueMessages(account: context.account, peerId: peer.id, messages: [.message(text: "/settings", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() openChatImpl?() }) }, botHelp: { - let _ = (account.postbox.loadedPeerWithId(peerId) + let _ = (context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { peer in - let _ = enqueueMessages(account: account, peerId: peer.id, messages: [.message(text: "/help", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() + let _ = enqueueMessages(account: context.account, peerId: peer.id, messages: [.message(text: "/help", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() openChatImpl?() }) }, botPrivacy: { - let _ = (account.postbox.loadedPeerWithId(peerId) + let _ = (context.account.postbox.loadedPeerWithId(peerId) |> deliverOnMainQueue).start(next: { peer in - let _ = enqueueMessages(account: account, peerId: peer.id, messages: [.message(text: "/privacy", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() + let _ = enqueueMessages(account: context.account, peerId: peer.id, messages: [.message(text: "/privacy", attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)]).start() openChatImpl?() }) }, report: { - presentControllerImpl?(peerReportOptionsController(account: account, subject: .peer(peerId), present: { c, a in + presentControllerImpl?(peerReportOptionsController(context: context, subject: .peer(peerId), present: { c, a in presentControllerImpl?(c, a) }), nil) }) @@ -1035,12 +1035,12 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC if number.isEmpty { return .single([]) } else { - return account.telegramApplicationContext.contactDataManager.basicDataForNormalizedPhoneNumber(DeviceContactNormalizedPhoneNumber(rawValue: formatPhoneNumber(number))) + return context.contactDataManager.basicDataForNormalizedPhoneNumber(DeviceContactNormalizedPhoneNumber(rawValue: formatPhoneNumber(number))) } } let globalNotificationsKey: PostboxViewKey = .preferences(keys: Set([PreferencesKeys.globalNotifications])) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get(), peerView.get(), deviceContacts, account.postbox.combinedView(keys: [.peerChatState(peerId: peerId), globalNotificationsKey])) + let signal = combineLatest(context.presentationData, statePromise.get(), peerView.get(), deviceContacts, context.account.postbox.combinedView(keys: [.peerChatState(peerId: peerId), globalNotificationsKey])) |> map { presentationData, state, view, deviceContacts, combinedView -> (ItemListControllerState, (ItemListNodeState, UserInfoEntry.ItemGenerationArguments)) in let peer = peerViewMainPeer(view.0) @@ -1057,7 +1057,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC return value } else { let promise = Promise<[AvatarGalleryEntry]>() - promise.set(fetchedAvatarGalleryEntries(account: account, peer: peer)) + promise.set(fetchedAvatarGalleryEntries(account: context.account, peer: peer)) return promise } } @@ -1097,7 +1097,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC } if let updateName = updateName, case let .personName(firstName, lastName) = updateName { - updatePeerNameDisposable.set((updateContactName(account: account, peerId: peerId, firstName: firstName, lastName: lastName) + updatePeerNameDisposable.set((updateContactName(account: context.account, peerId: peerId, firstName: firstName, lastName: lastName) |> deliverOnMainQueue).start(error: { _ in updateState { state in return state.withUpdatedSavingData(false) @@ -1107,17 +1107,17 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC return state.withUpdatedSavingData(false).withUpdatedEditingState(nil) } - let _ = (getUserPeer(postbox: account.postbox, peerId: peerId) + let _ = (getUserPeer(postbox: context.account.postbox, peerId: peerId) |> mapToSignal { peer -> Signal in guard let peer = peer as? TelegramUser, let phone = peer.phone, !phone.isEmpty else { return .complete() } - return account.telegramApplicationContext.contactDataManager.basicDataForNormalizedPhoneNumber(DeviceContactNormalizedPhoneNumber(rawValue: formatPhoneNumber(phone))) + return context.contactDataManager.basicDataForNormalizedPhoneNumber(DeviceContactNormalizedPhoneNumber(rawValue: formatPhoneNumber(phone))) |> take(1) |> mapToSignal { records -> Signal in var signals: [Signal] = [] for (id, basicData) in records { - signals.append(account.telegramApplicationContext.contactDataManager.appendContactData(DeviceContactExtendedData(basicData: DeviceContactBasicData(firstName: firstName, lastName: lastName, phoneNumbers: basicData.phoneNumbers), middleName: "", prefix: "", suffix: "", organization: "", jobTitle: "", department: "", emailAddresses: [], urls: [], addresses: [], birthdayDate: nil, socialProfiles: [], instantMessagingProfiles: []), to: id)) + signals.append(context.contactDataManager.appendContactData(DeviceContactExtendedData(basicData: DeviceContactBasicData(firstName: firstName, lastName: lastName, phoneNumbers: basicData.phoneNumbers), middleName: "", prefix: "", suffix: "", organization: "", jobTitle: "", department: "", emailAddresses: [], urls: [], addresses: [], birthdayDate: nil, socialProfiles: [], instantMessagingProfiles: []), to: id)) } return combineLatest(signals) |> mapToSignal { _ -> Signal in @@ -1140,14 +1140,14 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC } let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.UserInfo_Title), leftNavigationButton: leftNavigationButton, rightNavigationButton: rightNavigationButton, backNavigationButton: nil) - let listState = ItemListNodeState(entries: userInfoEntries(account: account, presentationData: presentationData, view: view.0, cachedPeerData: view.1, deviceContacts: deviceContacts, mode: mode, state: state, peerChatState: (combinedView.views[.peerChatState(peerId: peerId)] as? PeerChatStateView)?.chatState, globalNotificationSettings: globalNotificationSettings), style: .plain) + let listState = ItemListNodeState(entries: userInfoEntries(account: context.account, presentationData: presentationData, view: view.0, cachedPeerData: view.1, deviceContacts: deviceContacts, mode: mode, state: state, peerChatState: (combinedView.views[.peerChatState(peerId: peerId)] as? PeerChatStateView)?.chatState, globalNotificationSettings: globalNotificationSettings), style: .plain) return (controllerState, (listState, arguments)) } |> afterDisposed { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] value in (controller?.navigationController as? NavigationController)?.pushViewController(value) @@ -1160,36 +1160,36 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC } openChatImpl = { [weak controller] in if let navigationController = (controller?.navigationController as? NavigationController) { - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(peerId)) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(peerId)) } } shareContactImpl = { [weak controller] in - let _ = (getUserPeer(postbox: account.postbox, peerId: peerId) + let _ = (getUserPeer(postbox: context.account.postbox, peerId: peerId) |> deliverOnMainQueue).start(next: { peer in if let peer = peer as? TelegramUser, let phone = peer.phone { let contact = TelegramMediaContact(firstName: peer.firstName ?? "", lastName: peer.lastName ?? "", phoneNumber: phone, peerId: peer.id, vCardData: nil) - let shareController = ShareController(account: account, subject: .media(.standalone(media: contact))) + let shareController = ShareController(context: context, subject: .media(.standalone(media: contact))) controller?.present(shareController, in: .window(.root)) } }) } shareMyContactImpl = { [weak controller] in - let _ = (getUserPeer(postbox: account.postbox, peerId: account.peerId) + let _ = (getUserPeer(postbox: context.account.postbox, peerId: context.account.peerId) |> deliverOnMainQueue).start(next: { peer in guard let peer = peer as? TelegramUser, let phone = peer.phone else { return } let contact = TelegramMediaContact(firstName: peer.firstName ?? "", lastName: peer.lastName ?? "", phoneNumber: phone, peerId: peer.id, vCardData: nil) - let _ = (enqueueMessages(account: account, peerId: peerId, messages: [.message(text: "", attributes: [], mediaReference: .standalone(media: contact), replyToMessageId: nil, localGroupingKey: nil)]) + let _ = (enqueueMessages(account: context.account, peerId: peerId, messages: [.message(text: "", attributes: [], mediaReference: .standalone(media: contact), replyToMessageId: nil, localGroupingKey: nil)]) |> deliverOnMainQueue).start(next: { [weak controller] _ in - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } controller?.present(OverlayStatusController(theme: presentationData.theme, strings: presentationData.strings, type: .success), in: .window(.root)) }) }) } startSecretChatImpl = { [weak controller] in - let _ = (account.postbox.transaction { transaction -> PeerId? in + let _ = (context.account.postbox.transaction { transaction -> PeerId? in let filteredPeerIds = Array(transaction.getAssociatedPeerIds(peerId)).filter { $0.namespace == Namespaces.Peer.SecretChat } var activeIndices: [ChatListIndex] = [] for associatedId in filteredPeerIds { @@ -1213,13 +1213,13 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC } |> deliverOnMainQueue).start(next: { currentPeerId in if let currentPeerId = currentPeerId { if let navigationController = (controller?.navigationController as? NavigationController) { - navigateToChatController(navigationController: navigationController, account: account, chatLocation: .peer(currentPeerId)) + navigateToChatController(navigationController: navigationController, context: context, chatLocation: .peer(currentPeerId)) } } else { - var createSignal = createSecretChat(account: account, peerId: peerId) + var createSignal = createSecretChat(account: context.account, peerId: peerId) var cancelImpl: (() -> Void)? let progressSignal = Signal { subscriber in - 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: { cancelImpl?() })) @@ -1246,11 +1246,11 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC createSecretChatDisposable.set((createSignal |> deliverOnMainQueue).start(next: { 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)) } }, error: { _ in if let controller = controller { - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } 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)) } })) @@ -1261,7 +1261,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC guard let controller = controller else { return } - openResolvedUrl(.groupBotStart(peerId: peerId, payload: ""), account: account, navigationController: controller.navigationController as? NavigationController, openPeer: { id, navigation in + openResolvedUrl(.groupBotStart(peerId: peerId, payload: ""), context: context, navigationController: controller.navigationController as? NavigationController, openPeer: { id, navigation in }, present: { c, a in presentControllerImpl?(c, a) @@ -1270,10 +1270,10 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC }) } shareBotImpl = { [weak controller] in - let _ = (getUserPeer(postbox: account.postbox, peerId: peerId) + let _ = (getUserPeer(postbox: context.account.postbox, peerId: peerId) |> deliverOnMainQueue).start(next: { peer in if let peer = peer as? TelegramUser, let username = peer.username { - let shareController = ShareController(account: account, subject: .url("https://t.me/\(username)")) + let shareController = ShareController(context: context, subject: .url("https://t.me/\(username)")) controller?.present(shareController, in: .window(.root)) } }) @@ -1304,12 +1304,12 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC } aboutLinkActionImpl = { [weak controller] action, itemLink in if let controller = controller { - handlePeerInfoAboutTextAction(account: account, peerId: peerId, navigateDisposable: navigateDisposable, controller: controller, action: action, itemLink: itemLink) + handlePeerInfoAboutTextAction(context: context, peerId: peerId, navigateDisposable: navigateDisposable, controller: controller, action: action, itemLink: itemLink) } } displayAboutContextMenuImpl = { [weak controller] text 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 { @@ -1340,7 +1340,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC 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 { @@ -1382,7 +1382,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC return false }) if let resultItemNode = resultItemNode, let callButtonFrame = resultItemNode.callButtonFrame { - let _ = (ApplicationSpecificNotice.getProfileCallTips(postbox: account.postbox) + let _ = (ApplicationSpecificNotice.getProfileCallTips(postbox: context.account.postbox) |> deliverOnMainQueue).start(next: { [weak controller] counter in guard let controller = controller else { return @@ -1397,9 +1397,9 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC if !displayTip { return } - let _ = ApplicationSpecificNotice.incrementProfileCallTips(postbox: account.postbox).start() + let _ = ApplicationSpecificNotice.incrementProfileCallTips(postbox: context.account.postbox).start() - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let text: String = presentationData.strings.UserInfo_TapToCall let tooltipController = TooltipController(text: text, dismissByTapOutside: true) @@ -1415,7 +1415,7 @@ public func userInfoController(account: Account, peerId: PeerId, mode: UserInfoC } } - controller.navigationItem.backBarButtonItem = UIBarButtonItem(title: account.telegramApplicationContext.currentPresentationData.with{ $0 }.strings.Common_Back, style: .plain, target: nil, action: nil) + controller.navigationItem.backBarButtonItem = UIBarButtonItem(title: context.currentPresentationData.with{ $0 }.strings.Common_Back, style: .plain, target: nil, action: nil) return controller } diff --git a/TelegramUI/UsernameSetupController.swift b/TelegramUI/UsernameSetupController.swift index c9f02e0b76..6b2fa5a028 100644 --- a/TelegramUI/UsernameSetupController.swift +++ b/TelegramUI/UsernameSetupController.swift @@ -204,7 +204,7 @@ private func usernameSetupControllerEntries(presentationData: PresentationData, return entries } -public func usernameSetupController(account: Account) -> ViewController { +public func usernameSetupController(context: AccountContext) -> ViewController { let statePromise = ValuePromise(UsernameSetupControllerState(), ignoreRepeated: true) let stateValue = Atomic(value: UsernameSetupControllerState()) let updateState: ((UsernameSetupControllerState) -> UsernameSetupControllerState) -> Void = { f in @@ -222,7 +222,7 @@ public func usernameSetupController(account: Account) -> ViewController { let updateAddressNameDisposable = MetaDisposable() actionsDisposable.add(updateAddressNameDisposable) - let arguments = UsernameSetupControllerArguments(account: account, updatePublicLinkText: { currentText, text in + let arguments = UsernameSetupControllerArguments(account: context.account, updatePublicLinkText: { currentText, text in if text.isEmpty { checkAddressNameDisposable.set(nil) updateState { state in @@ -238,7 +238,7 @@ public func usernameSetupController(account: Account) -> ViewController { return state.withUpdatedEditingPublicLinkText(text) } - checkAddressNameDisposable.set((validateAddressNameInteractive(account: account, domain: .account, name: text) + checkAddressNameDisposable.set((validateAddressNameInteractive(account: context.account, domain: .account, name: text) |> deliverOnMainQueue).start(next: { result in updateState { state in return state.withUpdatedAddressNameValidationStatus(result) @@ -246,7 +246,7 @@ public func usernameSetupController(account: Account) -> ViewController { })) } }, shareLink: { - let _ = (account.postbox.loadedPeerWithId(account.peerId) + let _ = (context.account.postbox.loadedPeerWithId(context.account.peerId) |> take(1) |> deliverOnMainQueue).start(next: { peer in var currentAddressName: String = peer.addressName ?? "" @@ -257,15 +257,15 @@ public func usernameSetupController(account: Account) -> ViewController { return state } if !currentAddressName.isEmpty { - presentControllerImpl?(ShareController(account: account, subject: .url("https://t.me/\(currentAddressName)")), nil) + presentControllerImpl?(ShareController(context: context, subject: .url("https://t.me/\(currentAddressName)")), nil) } }) }) - let peerView = account.viewTracker.peerView(account.peerId) + let peerView = context.account.viewTracker.peerView(context.account.peerId) |> deliverOnMainQueue - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, statePromise.get() |> deliverOnMainQueue, peerView) + let signal = combineLatest(context.presentationData, statePromise.get() |> deliverOnMainQueue, peerView) |> map { presentationData, state, view -> (ItemListControllerState, (ItemListNodeState, UsernameSetupEntry.ItemGenerationArguments)) in let peer = peerViewMainPeer(view) @@ -297,7 +297,7 @@ public func usernameSetupController(account: Account) -> ViewController { } if let updatedAddressNameValue = updatedAddressNameValue { - updateAddressNameDisposable.set((updateAddressName(account: account, domain: .account, name: updatedAddressNameValue.isEmpty ? nil : updatedAddressNameValue) + updateAddressNameDisposable.set((updateAddressName(account: context.account, domain: .account, name: updatedAddressNameValue.isEmpty ? nil : updatedAddressNameValue) |> deliverOnMainQueue).start(error: { _ in updateState { state in return state.withUpdatedUpdatingAddressName(false) @@ -327,7 +327,7 @@ public func usernameSetupController(account: Account) -> ViewController { actionsDisposable.dispose() } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) controller.enableInteractiveDismiss = true dismissImpl = { [weak controller] in controller?.view.endEditing(true) diff --git a/TelegramUI/VerticalListContextResultsChatInputContextPanelNode.swift b/TelegramUI/VerticalListContextResultsChatInputContextPanelNode.swift index c5593558ac..b1729c8ff7 100644 --- a/TelegramUI/VerticalListContextResultsChatInputContextPanelNode.swift +++ b/TelegramUI/VerticalListContextResultsChatInputContextPanelNode.swift @@ -123,8 +123,7 @@ final class VerticalListContextResultsChatInputContextPanelNode: ChatInputContex 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 @@ -133,7 +132,7 @@ final class VerticalListContextResultsChatInputContextPanelNode: ChatInputContex self.listView.isHidden = 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 @@ -167,7 +166,7 @@ final class VerticalListContextResultsChatInputContextPanelNode: ChatInputContex private func prepareTransition(from: [VerticalListContextResultsChatInputContextPanelEntry]?, to: [VerticalListContextResultsChatInputContextPanelEntry], results: ChatContextResultCollection) { let firstTime = self.currentEntries == nil - let transition = preparedTransition(from: from ?? [], to: to, account: self.account, actionSelected: { [weak self] in + let transition = preparedTransition(from: from ?? [], to: to, account: self.context.account, actionSelected: { [weak self] in if let strongSelf = self, let interfaceInteraction = strongSelf.interfaceInteraction, let switchPeer = results.switchPeer { interfaceInteraction.botSwitchChatWithPayload(results.botId, switchPeer.startParam) } diff --git a/TelegramUI/VoiceCallDataSavingController.swift b/TelegramUI/VoiceCallDataSavingController.swift index 3b3814aa4b..0cd262579e 100644 --- a/TelegramUI/VoiceCallDataSavingController.swift +++ b/TelegramUI/VoiceCallDataSavingController.swift @@ -114,9 +114,9 @@ private func voiceCallDataSavingControllerEntries(presentationData: Presentation return entries } -func voiceCallDataSavingController(account: Account) -> ViewController { +func voiceCallDataSavingController(context: AccountContext) -> ViewController { let voiceCallSettingsPromise = Promise() - voiceCallSettingsPromise.set(account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.voiceCallSettings]) + voiceCallSettingsPromise.set(context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.voiceCallSettings]) |> map { view -> VoiceCallSettings in let voiceCallSettings: VoiceCallSettings if let value = view.values[ApplicationSpecificPreferencesKeys.voiceCallSettings] as? VoiceCallSettings { @@ -129,14 +129,14 @@ func voiceCallDataSavingController(account: Account) -> ViewController { }) let arguments = VoiceCallDataSavingControllerArguments(updateSelection: { option in - let _ = updateVoiceCallSettingsSettingsInteractively(postbox: account.postbox, { current in + let _ = updateVoiceCallSettingsSettingsInteractively(postbox: context.account.postbox, { current in var current = current current.dataSaving = option return current }).start() }) - let signal = combineLatest((account.applicationContext as! TelegramApplicationContext).presentationData, voiceCallSettingsPromise.get()) |> deliverOnMainQueue + let signal = combineLatest(context.presentationData, voiceCallSettingsPromise.get()) |> deliverOnMainQueue |> map { presentationData, data -> (ItemListControllerState, (ItemListNodeState, VoiceCallDataSavingEntry.ItemGenerationArguments)) in let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.CallSettings_Title), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: false) @@ -145,6 +145,6 @@ func voiceCallDataSavingController(account: Account) -> ViewController { return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) return controller } diff --git a/TelegramUI/WallpaperGalleryController.swift b/TelegramUI/WallpaperGalleryController.swift index e717a72da1..ce424d1eb8 100644 --- a/TelegramUI/WallpaperGalleryController.swift +++ b/TelegramUI/WallpaperGalleryController.swift @@ -66,7 +66,7 @@ class WallpaperGalleryController: ViewController { return self.displayNode as! GalleryControllerNode } - private let account: Account + private let context: AccountContext private let source: WallpaperListSource var apply: ((WallpaperGalleryEntry, WallpaperPresentationOptions, CGRect?) -> Void)? @@ -94,10 +94,10 @@ class WallpaperGalleryController: ViewController { private var messageNodes: [ListViewItemNode]? private var toolbarNode: ThemeGalleryToolbarNode? - init(account: Account, source: WallpaperListSource) { - self.account = account + init(context: AccountContext, source: WallpaperListSource) { + self.context = context self.source = source - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: presentationData)) @@ -132,7 +132,7 @@ class WallpaperGalleryController: ViewController { self.centralEntryIndex = 0 } - 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 @@ -213,7 +213,7 @@ class WallpaperGalleryController: ViewController { self.galleryNode.backgroundNode.isOpaque = false self.galleryNode.isBackgroundExtendedOverNavigationBar = true - let presentationData = self.account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } let toolbarNode = ThemeGalleryToolbarNode(theme: presentationData.theme, strings: presentationData.strings) let overlayNode = WallpaperGalleryOverlayNode() self.overlayNode = overlayNode @@ -233,7 +233,7 @@ class WallpaperGalleryController: ViewController { let entry = strongSelf.entries[centralItemNode.index] switch entry { case let .wallpaper(wallpaper): - let _ = (updatePresentationThemeSettingsInteractively(postbox: strongSelf.account.postbox, { current in + let _ = (updatePresentationThemeSettingsInteractively(postbox: strongSelf.context.account.postbox, { current in return PresentationThemeSettings(chatWallpaper: wallpaper, chatWallpaperOptions: [], theme: current.theme, themeAccentColor: current.themeAccentColor, fontSize: current.fontSize, automaticThemeSwitchSetting: current.automaticThemeSwitchSetting, disableAnimations: current.disableAnimations) }) |> deliverOnMainQueue).start(completed: { self?.dismiss(forceAway: true) @@ -272,7 +272,7 @@ class WallpaperGalleryController: ViewController { var items: [ChatMessageItem] = [] let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 1) - let otherPeerId = self.account.peerId + let otherPeerId = self.context.account.peerId var peers = SimpleDictionary() let messages = SimpleDictionary() peers[peerId] = TelegramUser(id: peerId, accessHash: nil, firstName: self.presentationData.strings.Appearance_PreviewReplyAuthor, lastName: "", username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) @@ -320,9 +320,9 @@ class WallpaperGalleryController: ViewController { bottomMessageText = presentationData.strings.WallpaperPreview_CustomColorBottomText } - items.append(ChatMessageItem(presentationData: chatPresentationData, account: self.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: peers[otherPeerId], text: bottomMessageText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true)) + items.append(ChatMessageItem(presentationData: chatPresentationData, context: self.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: peers[otherPeerId], text: bottomMessageText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true)) - items.append(ChatMessageItem(presentationData: chatPresentationData, account: self.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: peers[peerId], text: topMessageText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true)) + items.append(ChatMessageItem(presentationData: chatPresentationData, context: self.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: peers[peerId], text: topMessageText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true)) let params = ListViewItemLayoutParams(width: layout.size.width, leftInset: layout.safeInsets.left, rightInset: layout.safeInsets.right) if let messageNodes = self.messageNodes { @@ -395,7 +395,7 @@ class WallpaperGalleryController: ViewController { self.validLayout = (layout, 0.0) if replace { - self.galleryNode.pager.replaceItems(self.entries.map({ WallpaperGalleryItem(account: self.account, entry: $0) }), centralItemIndex: self.centralEntryIndex) + self.galleryNode.pager.replaceItems(self.entries.map({ WallpaperGalleryItem(context: self.context, entry: $0) }), centralItemIndex: self.centralEntryIndex) } } } diff --git a/TelegramUI/WallpaperGalleryItem.swift b/TelegramUI/WallpaperGalleryItem.swift index 3c4855ae39..fcb3404b11 100644 --- a/TelegramUI/WallpaperGalleryItem.swift +++ b/TelegramUI/WallpaperGalleryItem.swift @@ -7,16 +7,16 @@ import TelegramCore import LegacyComponents class WallpaperGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let entry: WallpaperGalleryEntry - init(account: Account, entry: WallpaperGalleryEntry) { - self.account = account + init(context: AccountContext, entry: WallpaperGalleryEntry) { + self.context = context self.entry = entry } func node() -> GalleryItemNode { - let node = WallpaperGalleryItemNode(account: self.account) + let node = WallpaperGalleryItemNode(context: self.context) node.setEntry(self.entry) return node } @@ -35,7 +35,7 @@ class WallpaperGalleryItem: GalleryItem { let progressDiameter: CGFloat = 50.0 final class WallpaperGalleryItemNode: GalleryItemNode { - private let account: Account + private let context: AccountContext private var entry: WallpaperGalleryEntry? private var contentSize: CGSize? @@ -52,8 +52,8 @@ final class WallpaperGalleryItemNode: GalleryItemNode { let controlsColor = Promise(.white) let status = Promise(.Local) - init(account: Account) { - self.account = account + init(context: AccountContext) { + self.context = context self.wrapperNode = ASDisplayNode() self.imageNode = TransformImageNode() @@ -118,7 +118,7 @@ final class WallpaperGalleryItemNode: GalleryItemNode { case .builtin: displaySize = CGSize(width: 1308.0, height: 2688.0).fitted(CGSize(width: 1280.0, height: 1280.0)).dividedByScreenScale().integralFloor contentSize = displaySize - signal = settingsBuiltinWallpaperImage(account: account) + signal = settingsBuiltinWallpaperImage(account: context.account) fetchSignal = .complete() statusSignal = .single(.Local) case let .color(color): @@ -138,23 +138,23 @@ final class WallpaperGalleryItemNode: GalleryItemNode { convertedRepresentations.append(ImageRepresentationWithReference(representation: representation, reference: .wallpaper(resource: representation.resource))) } convertedRepresentations.append(ImageRepresentationWithReference(representation: .init(dimensions: dimensions, resource: file.file.resource), reference: .wallpaper(resource: file.file.resource))) - signal = chatAvatarGalleryPhoto(account: account, fileReference: .standalone(media: file.file), representations: convertedRepresentations, alwaysShowThumbnailFirst: true, autoFetchFullSize: false) - fetchSignal = fetchedMediaResource(postbox: account.postbox, reference: convertedRepresentations[convertedRepresentations.count - 1].reference) - statusSignal = account.postbox.mediaBox.resourceStatus(file.file.resource) + signal = chatAvatarGalleryPhoto(account: context.account, fileReference: .standalone(media: file.file), representations: convertedRepresentations, alwaysShowThumbnailFirst: true, autoFetchFullSize: false) + fetchSignal = fetchedMediaResource(postbox: context.account.postbox, reference: convertedRepresentations[convertedRepresentations.count - 1].reference) + statusSignal = context.account.postbox.mediaBox.resourceStatus(file.file.resource) case let .image(representations): if let largestSize = largestImageRepresentation(representations) { contentSize = largestSize.dimensions displaySize = largestSize.dimensions.dividedByScreenScale().integralFloor let convertedRepresentations: [ImageRepresentationWithReference] = representations.map({ ImageRepresentationWithReference(representation: $0, reference: .wallpaper(resource: $0.resource)) }) - signal = chatAvatarGalleryPhoto(account: account, representations: convertedRepresentations) + signal = chatAvatarGalleryPhoto(account: context.account, representations: convertedRepresentations) if let largestIndex = convertedRepresentations.index(where: { $0.representation == largestSize }) { - fetchSignal = fetchedMediaResource(postbox: account.postbox, reference: convertedRepresentations[largestIndex].reference) + fetchSignal = fetchedMediaResource(postbox: context.account.postbox, reference: convertedRepresentations[largestIndex].reference) } else { fetchSignal = .complete() } - statusSignal = account.postbox.mediaBox.resourceStatus(largestSize.resource) + statusSignal = context.account.postbox.mediaBox.resourceStatus(largestSize.resource) } else { displaySize = CGSize(width: 1.0, height: 1.0) contentSize = displaySize @@ -168,7 +168,7 @@ final class WallpaperGalleryItemNode: GalleryItemNode { let dimensions = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) contentSize = dimensions displaySize = dimensions.dividedByScreenScale().integralFloor - signal = photoWallpaper(postbox: account.postbox, photoLibraryResource: PhotoLibraryMediaResource(localIdentifier: asset.localIdentifier, uniqueId: arc4random64())) + signal = photoWallpaper(postbox: context.account.postbox, photoLibraryResource: PhotoLibraryMediaResource(localIdentifier: asset.localIdentifier, uniqueId: arc4random64())) fetchSignal = .complete() statusSignal = .single(.Local) self.wrapperNode.addSubnode(self.cropNode) @@ -213,9 +213,9 @@ final class WallpaperGalleryItemNode: GalleryItemNode { representations.append(TelegramMediaImageRepresentation(dimensions: imageDimensions, resource: imageResource)) let tmpImage = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: representations, immediateThumbnailData: nil, reference: nil, partialReference: nil) - signal = chatMessagePhoto(postbox: account.postbox, photoReference: .standalone(media: tmpImage)) - fetchSignal = fetchedMediaResource(postbox: account.postbox, reference: .media(media: .standalone(media: tmpImage), resource: imageResource)) - statusSignal = account.postbox.mediaBox.resourceStatus(imageResource) + signal = chatMessagePhoto(postbox: context.account.postbox, photoReference: .standalone(media: tmpImage)) + fetchSignal = fetchedMediaResource(postbox: context.account.postbox, reference: .media(media: .standalone(media: tmpImage), resource: imageResource)) + statusSignal = context.account.postbox.mediaBox.resourceStatus(imageResource) } else { displaySize = CGSize(width: 1.0, height: 1.0) contentSize = displaySize @@ -271,7 +271,7 @@ final class WallpaperGalleryItemNode: GalleryItemNode { let controlsColorSignal: Signal if case let .wallpaper(wallpaper) = entry { - controlsColorSignal = chatBackgroundContrastColor(wallpaper: wallpaper, postbox: account.postbox) + controlsColorSignal = chatBackgroundContrastColor(wallpaper: wallpaper, postbox: context.account.postbox) } else { controlsColorSignal = backgroundContrastColor(for: imagePromise.get()) } diff --git a/TelegramUI/WallpaperListPreviewController.swift b/TelegramUI/WallpaperListPreviewController.swift index d7ccaecea1..4e24464487 100644 --- a/TelegramUI/WallpaperListPreviewController.swift +++ b/TelegramUI/WallpaperListPreviewController.swift @@ -16,7 +16,7 @@ final class WallpaperListPreviewController: ViewController { return self._ready } - private let account: Account + private let context: AccountContext private let source: WallpaperListSource private var presentationData: PresentationData @@ -29,18 +29,18 @@ final class WallpaperListPreviewController: ViewController { var apply: ((WallpaperEntry, WallpaperPresentationOptions, CGRect?) -> Void)? - init(account: Account, source: WallpaperListSource) { - self.account = account + init(context: AccountContext, source: WallpaperListSource) { + self.context = context self.source = source - self.presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + self.presentationData = context.currentPresentationData.with { $0 } super.init(navigationBarPresentationData: NavigationBarPresentationData(presentationData: self.presentationData)) self.supportedOrientations = ViewControllerSupportedOrientations(regularSize: .all, compactSize: .portrait) self.statusBar.statusBarStyle = self.presentationData.theme.rootController.statusBar.style.style - 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 @@ -96,7 +96,7 @@ final class WallpaperListPreviewController: ViewController { } override public func loadDisplayNode() { - self.displayNode = WallpaperListPreviewControllerNode(account: self.account, presentationData: self.presentationData, source: self.source, dismiss: { [weak self] in + self.displayNode = WallpaperListPreviewControllerNode(context: self.context, presentationData: self.presentationData, source: self.source, dismiss: { [weak self] in self?.dismiss() }, apply: { [weak self] wallpaper, mode, cropRect in guard let strongSelf = self else { @@ -106,7 +106,7 @@ final class WallpaperListPreviewController: ViewController { switch wallpaper { case let .wallpaper(wallpaper): let completion: () -> Void = { - let _ = (updatePresentationThemeSettingsInteractively(postbox: strongSelf.account.postbox, { current in + let _ = (updatePresentationThemeSettingsInteractively(postbox: strongSelf.context.account.postbox, { current in return PresentationThemeSettings(chatWallpaper: wallpaper, chatWallpaperOptions: mode, theme: current.theme, themeAccentColor: current.themeAccentColor, fontSize: current.fontSize, automaticThemeSwitchSetting: current.automaticThemeSwitchSetting, disableAnimations: current.disableAnimations) }) |> deliverOnMainQueue).start(completed: { @@ -114,9 +114,9 @@ final class WallpaperListPreviewController: ViewController { }) if case .wallpaper = strongSelf.source { - let _ = saveWallpaper(account: strongSelf.account, wallpaper: wallpaper).start() + let _ = saveWallpaper(account: strongSelf.context.account, wallpaper: wallpaper).start() } - let _ = installWallpaper(account: strongSelf.account, wallpaper: wallpaper).start() + let _ = installWallpaper(account: strongSelf.context.account, wallpaper: wallpaper).start() } if mode.contains(.blur) { @@ -133,7 +133,7 @@ final class WallpaperListPreviewController: ViewController { } if let resource = resource { - let _ = strongSelf.account.postbox.mediaBox.cachedResourceRepresentation(resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true).start(completed: { + let _ = strongSelf.context.account.postbox.mediaBox.cachedResourceRepresentation(resource, representation: CachedBlurredWallpaperRepresentation(), complete: true, fetch: true).start(completed: { completion() }) } @@ -181,9 +181,9 @@ final class WallpaperListPreviewController: ViewController { var controller: ShareController? switch wallpaper { case let .file(_, _, _, _, slug, _): - controller = ShareController(account: account, subject: .url("https://t.me/bg/\(slug)")) + controller = ShareController(context: context, subject: .url("https://t.me/bg/\(slug)")) case let .color(color): - controller = ShareController(account: account, subject: .url("https://t.me/bg/\(String(UInt32(bitPattern: color), radix: 16, uppercase: false).rightJustified(width: 6, pad: "0"))")) + controller = ShareController(context: context, subject: .url("https://t.me/bg/\(String(UInt32(bitPattern: color), radix: 16, uppercase: false).rightJustified(width: 6, pad: "0"))")) default: break } diff --git a/TelegramUI/WallpaperListPreviewControllerNode.swift b/TelegramUI/WallpaperListPreviewControllerNode.swift index efa13e69ef..334b7d6edc 100644 --- a/TelegramUI/WallpaperListPreviewControllerNode.swift +++ b/TelegramUI/WallpaperListPreviewControllerNode.swift @@ -51,7 +51,7 @@ private final class WallpaperBackgroundNode: ASDisplayNode { let controlsColor = Promise(.white) let status = Promise(.Local) - init(account: Account, wallpaper: WallpaperEntry) { + init(context: AccountContext, wallpaper: WallpaperEntry) { self.wallpaper = wallpaper self.wrapperNode = ASDisplayNode() self.imageNode = TransformImageNode() @@ -82,7 +82,7 @@ private final class WallpaperBackgroundNode: ASDisplayNode { case .builtin: displaySize = CGSize(width: 640.0, height: 1136.0) contentSize = displaySize - signal = settingsBuiltinWallpaperImage(account: account) + signal = settingsBuiltinWallpaperImage(account: context.account) fetchSignal = .complete() statusSignal = .single(.Local) case let .color(color): @@ -102,23 +102,23 @@ private final class WallpaperBackgroundNode: ASDisplayNode { convertedRepresentations.append(ImageRepresentationWithReference(representation: representation, reference: .standalone(resource: representation.resource))) } convertedRepresentations.append(ImageRepresentationWithReference(representation: .init(dimensions: dimensions, resource: file.file.resource), reference: .standalone(resource: file.file.resource))) - signal = chatMessageImageFile(account: account, fileReference: .standalone(media: file.file), thumbnail: false) - fetchSignal = fetchedMediaResource(postbox: account.postbox, reference: convertedRepresentations[convertedRepresentations.count - 1].reference) - statusSignal = account.postbox.mediaBox.resourceStatus(file.file.resource) + signal = chatMessageImageFile(account: context.account, fileReference: .standalone(media: file.file), thumbnail: false) + fetchSignal = fetchedMediaResource(postbox: context.account.postbox, reference: convertedRepresentations[convertedRepresentations.count - 1].reference) + statusSignal = context.account.postbox.mediaBox.resourceStatus(file.file.resource) case let .image(representations): if let largestSize = largestImageRepresentation(representations) { contentSize = largestSize.dimensions displaySize = largestSize.dimensions.dividedByScreenScale().integralFloor let convertedRepresentations: [ImageRepresentationWithReference] = representations.map({ ImageRepresentationWithReference(representation: $0, reference: .wallpaper(resource: $0.resource)) }) - signal = chatAvatarGalleryPhoto(account: account, representations: convertedRepresentations) + signal = chatAvatarGalleryPhoto(account: context.account, representations: convertedRepresentations) if let largestIndex = convertedRepresentations.index(where: { $0.representation == largestSize }) { - fetchSignal = fetchedMediaResource(postbox: account.postbox, reference: convertedRepresentations[largestIndex].reference) + fetchSignal = fetchedMediaResource(postbox: context.account.postbox, reference: convertedRepresentations[largestIndex].reference) } else { fetchSignal = .complete() } - statusSignal = account.postbox.mediaBox.resourceStatus(largestSize.resource) + statusSignal = context.account.postbox.mediaBox.resourceStatus(largestSize.resource) } else { displaySize = CGSize(width: 1.0, height: 1.0) contentSize = displaySize @@ -131,7 +131,7 @@ private final class WallpaperBackgroundNode: ASDisplayNode { let dimensions = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) contentSize = dimensions displaySize = dimensions.dividedByScreenScale().integralFloor - signal = photoWallpaper(postbox: account.postbox, photoLibraryResource: PhotoLibraryMediaResource(localIdentifier: asset.localIdentifier, uniqueId: arc4random64())) + signal = photoWallpaper(postbox: context.account.postbox, photoLibraryResource: PhotoLibraryMediaResource(localIdentifier: asset.localIdentifier, uniqueId: arc4random64())) fetchSignal = .complete() statusSignal = .single(.Local) self.wrapperNode.addSubnode(self.cropNode) @@ -176,9 +176,9 @@ private final class WallpaperBackgroundNode: ASDisplayNode { representations.append(TelegramMediaImageRepresentation(dimensions: imageDimensions, resource: imageResource)) let tmpImage = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: representations, immediateThumbnailData: nil, reference: nil, partialReference: nil) - signal = chatMessagePhoto(postbox: account.postbox, photoReference: .standalone(media: tmpImage)) - fetchSignal = fetchedMediaResource(postbox: account.postbox, reference: .media(media: .standalone(media: tmpImage), resource: imageResource)) - statusSignal = account.postbox.mediaBox.resourceStatus(imageResource) + signal = chatMessagePhoto(postbox: context.account.postbox, photoReference: .standalone(media: tmpImage)) + fetchSignal = fetchedMediaResource(postbox: context.account.postbox, reference: .media(media: .standalone(media: tmpImage), resource: imageResource)) + statusSignal = context.account.postbox.mediaBox.resourceStatus(imageResource) } else { displaySize = CGSize(width: 1.0, height: 1.0) contentSize = displaySize @@ -234,7 +234,7 @@ private final class WallpaperBackgroundNode: ASDisplayNode { let controlsColorSignal: Signal if case let .wallpaper(wallpaper) = wallpaper { - controlsColorSignal = chatBackgroundContrastColor(wallpaper: wallpaper, postbox: account.postbox) + controlsColorSignal = chatBackgroundContrastColor(wallpaper: wallpaper, postbox: context.account.postbox) } else { controlsColorSignal = backgroundContrastColor(for: imagePromise.get()) } @@ -340,7 +340,7 @@ private final class WallpaperBackgroundNode: ASDisplayNode { } final class WallpaperListPreviewControllerNode: ViewControllerTracingNode { - private let account: Account + private let context: AccountContext private var presentationData: PresentationData private let source: WallpaperListSource private let dismiss: () -> Void @@ -380,8 +380,8 @@ final class WallpaperListPreviewControllerNode: ViewControllerTracingNode { } private var visibleBackgroundNodesOffset: CGFloat = 0.0 - init(account: Account, presentationData: PresentationData, source: WallpaperListSource, dismiss: @escaping () -> Void, apply: @escaping (WallpaperEntry, WallpaperPresentationOptions, CGRect?) -> Void) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, source: WallpaperListSource, dismiss: @escaping () -> Void, apply: @escaping (WallpaperEntry, WallpaperPresentationOptions, CGRect?) -> Void) { + self.context = context self.presentationData = presentationData self.source = source self.dismiss = dismiss @@ -611,7 +611,7 @@ final class WallpaperListPreviewControllerNode: ViewControllerTracingNode { var items: [ChatMessageItem] = [] let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: 1) - let otherPeerId = self.account.peerId + let otherPeerId = self.context.account.peerId var peers = SimpleDictionary() let messages = SimpleDictionary() peers[peerId] = TelegramUser(id: peerId, accessHash: nil, firstName: self.presentationData.strings.Appearance_PreviewReplyAuthor, lastName: "", username: nil, phone: nil, photo: [], botInfo: nil, restrictionInfo: nil, flags: []) @@ -659,9 +659,9 @@ final class WallpaperListPreviewControllerNode: ViewControllerTracingNode { bottomMessageText = presentationData.strings.WallpaperPreview_CustomColorBottomText } - items.append(ChatMessageItem(presentationData: chatPresentationData, account: self.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: peers[otherPeerId], text: bottomMessageText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true)) + items.append(ChatMessageItem(presentationData: chatPresentationData, context: self.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: peers[otherPeerId], text: bottomMessageText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true)) - items.append(ChatMessageItem(presentationData: chatPresentationData, account: self.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: peers[peerId], text: topMessageText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true)) + items.append(ChatMessageItem(presentationData: chatPresentationData, context: self.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: peers[peerId], text: topMessageText, attributes: [], media: [], peers: peers, associatedMessages: messages, associatedMessageIds: []), read: true, selection: .none, isAdmin: false), disableDate: true)) let params = ListViewItemLayoutParams(width: layout.size.width, leftInset: layout.safeInsets.left, rightInset: layout.safeInsets.right) if let messageNodes = self.messageNodes { @@ -772,7 +772,7 @@ final class WallpaperListPreviewControllerNode: ViewControllerTracingNode { break inner } } - let itemNode = currentItemNode ?? WallpaperBackgroundNode(account: self.account, wallpaper: wallpapers[j]) + let itemNode = currentItemNode ?? WallpaperBackgroundNode(account: self.context.account, wallpaper: wallpapers[j]) visibleBackgroundNodes.append(itemNode) let itemNodeTransition: ContainedViewLayoutTransition if itemNode.supernode == nil { diff --git a/TelegramUI/WatchSettingsController.swift b/TelegramUI/WatchSettingsController.swift index 385619f3ff..138f97c643 100644 --- a/TelegramUI/WatchSettingsController.swift +++ b/TelegramUI/WatchSettingsController.swift @@ -105,13 +105,13 @@ private func watchSettingsControllerEntries(presentationData: PresentationData, return entries } -public func watchSettingsController(account: Account) -> ViewController { +public func watchSettingsController(context: AccountContext) -> ViewController { var pushControllerImpl: ((ViewController) -> Void)? var presentControllerImpl: ((ViewController) -> Void)? let updateDisposable = MetaDisposable() let arguments = WatchSettingsControllerArguments(updatePreset: { identifier, text in - updateDisposable.set((.complete() |> delay(1.0, queue: Queue.mainQueue()) |> then(updateWatchPresetSettingsInteractively(postbox: account.postbox, { current in + updateDisposable.set((.complete() |> delay(1.0, queue: Queue.mainQueue()) |> then(updateWatchPresetSettingsInteractively(postbox: context.account.postbox, { current in var updatedPresets = current.customPresets if !text.isEmpty { updatedPresets[identifier] = text @@ -123,9 +123,9 @@ public func watchSettingsController(account: Account) -> ViewController { }) let watchPresetSettingsKey = ApplicationSpecificPreferencesKeys.watchPresetSettings - let preferences = account.postbox.preferencesView(keys: [watchPresetSettingsKey]) + let preferences = context.account.postbox.preferencesView(keys: [watchPresetSettingsKey]) - let signal = combineLatest(account.telegramApplicationContext.presentationData, preferences) + let signal = combineLatest(context.presentationData, preferences) |> deliverOnMainQueue |> map { presentationData, preferences -> (ItemListControllerState, (ItemListNodeState, WatchSettingsControllerEntry.ItemGenerationArguments)) in let settings = (preferences.values[watchPresetSettingsKey] as? WatchPresetSettings) ?? WatchPresetSettings.defaultSettings @@ -136,7 +136,7 @@ public func watchSettingsController(account: Account) -> ViewController { return (controllerState, (listState, arguments)) } - let controller = ItemListController(account: account, state: signal) + let controller = ItemListController(context: context, state: signal) pushControllerImpl = { [weak controller] c in (controller?.navigationController as? NavigationController)?.pushViewController(c) } diff --git a/TelegramUI/WebSearchController.swift b/TelegramUI/WebSearchController.swift index 69106367b7..0d04fde21e 100644 --- a/TelegramUI/WebSearchController.swift +++ b/TelegramUI/WebSearchController.swift @@ -97,7 +97,7 @@ private func selectionChangedSignal(selectionState: TGMediaSelectionContext) -> final class WebSearchController: ViewController { private var validLayout: ContainerViewLayout? - private let account: Account + private let context: AccountContext private let mode: WebSearchControllerMode private let peer: Peer? private let configuration: SearchBotsConfiguration @@ -123,13 +123,13 @@ final class WebSearchController: ViewController { private var navigationContentNode: WebSearchNavigationContentNode? - init(account: Account, peer: Peer?, configuration: SearchBotsConfiguration, mode: WebSearchControllerMode) { - self.account = account + init(context: AccountContext, peer: Peer?, configuration: SearchBotsConfiguration, mode: WebSearchControllerMode) { + self.context = context self.mode = mode self.peer = peer self.configuration = configuration - let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 } + let presentationData = context.currentPresentationData.with { $0 } self.interfaceState = WebSearchInterfaceState(presentationData: presentationData) var searchQuery: String? @@ -147,7 +147,7 @@ final class WebSearchController: ViewController { } } - let settings = self.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.webSearchSettings]) + let settings = self.context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.webSearchSettings]) |> map { view -> WebSearchSettings in if let current = view.values[ApplicationSpecificPreferencesKeys.webSearchSettings] as? WebSearchSettings { return current @@ -156,7 +156,7 @@ final class WebSearchController: ViewController { } } - self.disposable = ((combineLatest(settings, account.telegramApplicationContext.presentationData)) + self.disposable = ((combineLatest(settings, context.presentationData)) |> deliverOnMainQueue).start(next: { [weak self] settings, presentationData in guard let strongSelf = self else { return @@ -209,7 +209,7 @@ final class WebSearchController: ViewController { } }, deleteRecentQuery: { [weak self] query in if let strongSelf = self { - _ = removeRecentWebSearchQuery(postbox: strongSelf.account.postbox, string: query).start() + _ = removeRecentWebSearchQuery(postbox: strongSelf.context.account.postbox, string: query).start() } }, toggleSelection: { [weak self] result, value in if let strongSelf = self { @@ -274,7 +274,7 @@ final class WebSearchController: ViewController { } override public func loadDisplayNode() { - self.displayNode = WebSearchControllerNode(account: self.account, theme: self.interfaceState.presentationData.theme, strings: interfaceState.presentationData.strings, controllerInteraction: self.controllerInteraction!, peer: self.peer, mode: self.mode.mode) + self.displayNode = WebSearchControllerNode(context: self.context, theme: self.interfaceState.presentationData.theme, strings: interfaceState.presentationData.strings, controllerInteraction: self.controllerInteraction!, peer: self.peer, mode: self.mode.mode) self.controllerNode.requestUpdateInterfaceState = { [weak self] animated, f in if let strongSelf = self { strongSelf.updateInterfaceState(f) @@ -317,7 +317,7 @@ final class WebSearchController: ViewController { private func updateSearchQuery(_ query: String) { if !query.isEmpty { - let _ = addRecentWebSearchQuery(postbox: self.account.postbox, string: query).start() + let _ = addRecentWebSearchQuery(postbox: self.context.account.postbox, string: query).start() } let scope: Signal @@ -396,7 +396,7 @@ final class WebSearchController: ViewController { return .single({ _ in return .contextRequestResult(nil, nil) }) } - let account = self.account + let account = self.context.account let contextBot = resolvePeerByName(account: account, name: name) |> mapToSignal { peerId -> Signal in if let peerId = peerId { diff --git a/TelegramUI/WebSearchControllerNode.swift b/TelegramUI/WebSearchControllerNode.swift index 4e4c94c62f..8806c97744 100644 --- a/TelegramUI/WebSearchControllerNode.swift +++ b/TelegramUI/WebSearchControllerNode.swift @@ -116,7 +116,7 @@ private func preparedWebSearchRecentTransition(from fromEntries: [WebSearchRecen } class WebSearchControllerNode: ASDisplayNode { - private let account: Account + private let context: AccountContext private let peer: Peer? private var theme: PresentationTheme private var strings: PresentationStrings @@ -168,15 +168,15 @@ class WebSearchControllerNode: ASDisplayNode { var cancel: (() -> Void)? var dismissInput: (() -> Void)? - init(account: Account, theme: PresentationTheme, strings: PresentationStrings, controllerInteraction: WebSearchControllerInteraction, peer: Peer?, mode: WebSearchMode) { - self.account = account + init(context: AccountContext, theme: PresentationTheme, strings: PresentationStrings, controllerInteraction: WebSearchControllerInteraction, peer: Peer?, mode: WebSearchMode) { + self.context = context self.theme = theme self.strings = strings self.controllerInteraction = controllerInteraction self.peer = peer self.mode = mode - self.webSearchInterfaceState = WebSearchInterfaceState(presentationData: account.telegramApplicationContext.currentPresentationData.with { $0 }) + self.webSearchInterfaceState = WebSearchInterfaceState(presentationData: context.currentPresentationData.with { $0 }) self.webSearchInterfaceStatePromise = ValuePromise(self.webSearchInterfaceState, ignoreRepeated: true) self.segmentedBackgroundNode = ASDisplayNode() @@ -237,7 +237,7 @@ class WebSearchControllerNode: ASDisplayNode { })) let previousRecentItems = Atomic<[WebSearchRecentQueryEntry]?>(value: nil) - self.recentDisposable = (combineLatest(webSearchRecentQueries(postbox: self.account.postbox), self.webSearchInterfaceStatePromise.get()) + self.recentDisposable = (combineLatest(webSearchRecentQueries(postbox: self.context.account.postbox), self.webSearchInterfaceStatePromise.get()) |> deliverOnMainQueue).start(next: { [weak self] queries, interfaceState in if let strongSelf = self { var entries: [WebSearchRecentQueryEntry] = [] @@ -246,12 +246,12 @@ class WebSearchControllerNode: ASDisplayNode { } let header = ChatListSearchItemHeader(type: .recentPeers, theme: interfaceState.presentationData.theme, strings:interfaceState.presentationData.strings, actionTitle: strings.WebSearch_RecentSectionClear.uppercased(), action: { - _ = clearRecentWebSearchQueries(postbox: strongSelf.account.postbox).start() + _ = clearRecentWebSearchQueries(postbox: strongSelf.context.account.postbox).start() }) let previousEntries = previousRecentItems.swap(entries) - let transition = preparedWebSearchRecentTransition(from: previousEntries ?? [], to: entries, account: strongSelf.account, theme: interfaceState.presentationData.theme, strings: interfaceState.presentationData.strings, controllerInteraction: strongSelf.controllerInteraction, header: header) + let transition = preparedWebSearchRecentTransition(from: previousEntries ?? [], to: entries, account: strongSelf.context.account, theme: interfaceState.presentationData.theme, strings: interfaceState.presentationData.strings, controllerInteraction: strongSelf.controllerInteraction, header: header) strongSelf.enqueueRecentTransition(transition, firstTime: previousEntries == nil) } }) @@ -548,7 +548,7 @@ class WebSearchControllerNode: ASDisplayNode { return } self.isLoadingMore = true - self.loadMoreDisposable.set((requestChatContextResults(account: self.account, botId: currentProcessedResults.botId, peerId: currentProcessedResults.peerId, query: currentProcessedResults.query, location: .single(currentProcessedResults.geoPoint), offset: nextOffset) + self.loadMoreDisposable.set((requestChatContextResults(account: self.context.account, botId: currentProcessedResults.botId, peerId: currentProcessedResults.peerId, query: currentProcessedResults.query, location: .single(currentProcessedResults.geoPoint), offset: nextOffset) |> deliverOnMainQueue).start(next: { [weak self] nextResults in guard let strongSelf = self, let nextResults = nextResults else { return @@ -594,7 +594,7 @@ class WebSearchControllerNode: ASDisplayNode { } let firstTime = self.currentEntries == nil - let transition = preparedTransition(from: self.currentEntries ?? [], to: entries, hasMore: hasMore, account: self.account, theme: interfaceState.presentationData.theme, interfaceState: interfaceState, controllerInteraction: self.controllerInteraction) + let transition = preparedTransition(from: self.currentEntries ?? [], to: entries, hasMore: hasMore, account: self.context.account, theme: interfaceState.presentationData.theme, interfaceState: interfaceState, controllerInteraction: self.controllerInteraction) self.currentEntries = entries self.enqueueTransition(transition, firstTime: firstTime) @@ -656,7 +656,7 @@ class WebSearchControllerNode: ASDisplayNode { @objc private func indexChanged() { if let scope = WebSearchScope(rawValue: Int32(self.segmentedControl.selectedSegmentIndex)) { - let _ = updateWebSearchSettingsInteractively(postbox: self.account.postbox) { _ -> WebSearchSettings in + let _ = updateWebSearchSettingsInteractively(postbox: self.context.account.postbox) { _ -> WebSearchSettings in return WebSearchSettings(scope: scope) }.start() self.requestUpdateInterfaceState(true) { current in @@ -686,7 +686,7 @@ class WebSearchControllerNode: ASDisplayNode { if self.controllerInteraction.selectionState != nil { if let state = self.webSearchInterfaceState.state, state.scope == .images { if let results = self.currentProcessedResults?.results { - presentLegacyWebSearchGallery(account: self.account, peer: self.peer, theme: self.theme, results: results, current: currentResult, selectionContext: self.controllerInteraction.selectionState, editingContext: self.controllerInteraction.editingState, updateHiddenMedia: { [weak self] id in + presentLegacyWebSearchGallery(context: self.context, peer: self.peer, theme: self.theme, results: results, current: currentResult, selectionContext: self.controllerInteraction.selectionState, editingContext: self.controllerInteraction.editingState, updateHiddenMedia: { [weak self] id in self?.hiddenMediaId.set(.single(id)) }, initialLayout: self.containerLayout?.0, transitionHostView: { [weak self] in return self?.gridNode.view @@ -710,7 +710,7 @@ class WebSearchControllerNode: ASDisplayNode { } } - let controller = WebSearchGalleryController(account: self.account, peer: self.peer, selectionState: self.controllerInteraction.selectionState, editingState: self.controllerInteraction.editingState, entries: entries, centralIndex: centralIndex, replaceRootController: { (controller, _) in + let controller = WebSearchGalleryController(context: self.context, peer: self.peer, selectionState: self.controllerInteraction.selectionState, editingState: self.controllerInteraction.editingState, entries: entries, centralIndex: centralIndex, replaceRootController: { (controller, _) in }, baseNavigationController: nil, sendCurrent: { [weak self] result in if let strongSelf = self, let results = strongSelf.currentExternalResults { @@ -745,7 +745,7 @@ class WebSearchControllerNode: ASDisplayNode { } } } else { - presentLegacyWebSearchEditor(account: self.account, theme: self.theme, result: currentResult, initialLayout: self.containerLayout?.0, updateHiddenMedia: { [weak self] id in + presentLegacyWebSearchEditor(context: self.context, theme: self.theme, result: currentResult, initialLayout: self.containerLayout?.0, updateHiddenMedia: { [weak self] id in self?.hiddenMediaId.set(.single(id)) }, transitionHostView: { [weak self] in return self?.gridNode.view diff --git a/TelegramUI/WebSearchGalleryFooterContentNode.swift b/TelegramUI/WebSearchGalleryFooterContentNode.swift index 2600d8a6ac..b05586e518 100644 --- a/TelegramUI/WebSearchGalleryFooterContentNode.swift +++ b/TelegramUI/WebSearchGalleryFooterContentNode.swift @@ -7,7 +7,7 @@ import SwiftSignalKit import LegacyComponents final class WebSearchGalleryFooterContentNode: GalleryFooterContentNode { - private let account: Account + private let context: AccountContext private var theme: PresentationTheme private var strings: PresentationStrings @@ -17,8 +17,8 @@ final class WebSearchGalleryFooterContentNode: GalleryFooterContentNode { var cancel: (() -> Void)? var send: (() -> Void)? - init(account: Account, presentationData: PresentationData) { - self.account = account + init(context: AccountContext, presentationData: PresentationData) { + self.context = context self.theme = presentationData.theme self.strings = presentationData.strings diff --git a/TelegramUI/WebSearchVideoGalleryItem.swift b/TelegramUI/WebSearchVideoGalleryItem.swift index 882df3c5b4..0b5654a83a 100644 --- a/TelegramUI/WebSearchVideoGalleryItem.swift +++ b/TelegramUI/WebSearchVideoGalleryItem.swift @@ -7,14 +7,14 @@ import Display import Postbox class WebSearchVideoGalleryItem: GalleryItem { - let account: Account + let context: AccountContext let presentationData: PresentationData let result: ChatContextResult let content: UniversalVideoContent let controllerInteraction: WebSearchGalleryControllerInteraction? - init(account: Account, presentationData: PresentationData, result: ChatContextResult, content: UniversalVideoContent, controllerInteraction: WebSearchGalleryControllerInteraction?) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, result: ChatContextResult, content: UniversalVideoContent, controllerInteraction: WebSearchGalleryControllerInteraction?) { + self.context = context self.presentationData = presentationData self.result = result self.content = content @@ -22,7 +22,7 @@ class WebSearchVideoGalleryItem: GalleryItem { } func node() -> GalleryItemNode { - let node = WebSearchVideoGalleryItemNode(account: self.account, presentationData: self.presentationData, controllerInteraction: self.controllerInteraction) + let node = WebSearchVideoGalleryItemNode(context: self.context, presentationData: self.presentationData, controllerInteraction: self.controllerInteraction) node.setupItem(self) return node } @@ -44,7 +44,7 @@ private struct FetchControls { } final class WebSearchVideoGalleryItemNode: ZoomableContentGalleryItemNode { - private let account: Account + private let context: AccountContext private let strings: PresentationStrings private let controllerInteraction: WebSearchGalleryControllerInteraction? @@ -73,12 +73,12 @@ final class WebSearchVideoGalleryItemNode: ZoomableContentGalleryItemNode { var playbackCompleted: (() -> Void)? - init(account: Account, presentationData: PresentationData, controllerInteraction: WebSearchGalleryControllerInteraction?) { - self.account = account + init(context: AccountContext, presentationData: PresentationData, controllerInteraction: WebSearchGalleryControllerInteraction?) { + self.context = context self.strings = presentationData.strings self.controllerInteraction = controllerInteraction - self.footerContentNode = WebSearchGalleryFooterContentNode(account: account, presentationData: presentationData) + self.footerContentNode = WebSearchGalleryFooterContentNode(context: context, presentationData: presentationData) self.statusButtonNode = HighlightableButtonNode() self.statusNode = RadialStatusNode(backgroundNodeColor: UIColor(white: 0.0, alpha: 0.5)) @@ -110,7 +110,7 @@ final class WebSearchVideoGalleryItemNode: ZoomableContentGalleryItemNode { switch gesture { case .tap: if let item = self.item, let selectionState = item.controllerInteraction?.selectionState { - let legacyItem = legacyWebSearchItem(account: item.account, result: item.result) + let legacyItem = legacyWebSearchItem(account: item.context.account, result: item.result) selectionState.toggleItemSelection(legacyItem) } case .doubleTap: @@ -151,11 +151,9 @@ final class WebSearchVideoGalleryItemNode: ZoomableContentGalleryItemNode { videoNode.removeFromSupernode() } - guard let mediaManager = item.account.telegramApplicationContext.mediaManager else { - preconditionFailure() - } + let mediaManager = item.context.mediaManager - let videoNode = UniversalVideoNode(postbox: item.account.postbox, audioSession: mediaManager.audioSession, manager: mediaManager.universalVideoManager, decoration: GalleryVideoDecoration(), content: item.content, priority: .gallery) + let videoNode = UniversalVideoNode(postbox: item.context.account.postbox, audioSession: mediaManager.audioSession, manager: mediaManager.universalVideoManager, decoration: GalleryVideoDecoration(), content: item.content, priority: .gallery) let videoSize = CGSize(width: item.content.dimensions.width * 2.0, height: item.content.dimensions.height * 2.0) videoNode.updateLayout(size: videoSize, transition: .immediate) self.videoNode = videoNode @@ -166,7 +164,7 @@ final class WebSearchVideoGalleryItemNode: ZoomableContentGalleryItemNode { self.requiresDownload = true var mediaFileStatus: Signal = .single(nil) if let mediaResource = mediaResource { - mediaFileStatus = item.account.postbox.mediaBox.resourceStatus(mediaResource) + mediaFileStatus = item.context.account.postbox.mediaBox.resourceStatus(mediaResource) |> map(Optional.init) } @@ -295,7 +293,7 @@ final class WebSearchVideoGalleryItemNode: ZoomableContentGalleryItemNode { let transform = CATransform3DScale(videoNode.layer.transform, transformedFrame.size.width / videoNode.layer.bounds.size.width, transformedFrame.size.height / videoNode.layer.bounds.size.height, 1.0) videoNode.layer.animate(from: NSValue(caTransform3D: transform), to: NSValue(caTransform3D: videoNode.layer.transform), keyPath: "transform", timingFunction: kCAMediaTimingFunctionSpring, duration: 0.25) - self.account.telegramApplicationContext.mediaManager?.setOverlayVideoNode(nil) + self.context.mediaManager.setOverlayVideoNode(nil) } else { var transformedFrame = node.0.view.convert(node.0.view.bounds, to: videoNode.view) let transformedSuperFrame = node.0.view.convert(node.0.view.bounds, to: videoNode.view.superview) diff --git a/TelegramUI/WebpagePreviewAccessoryPanelNode.swift b/TelegramUI/WebpagePreviewAccessoryPanelNode.swift index e7aa2bed1e..a2ab7134f4 100644 --- a/TelegramUI/WebpagePreviewAccessoryPanelNode.swift +++ b/TelegramUI/WebpagePreviewAccessoryPanelNode.swift @@ -22,7 +22,7 @@ final class WebpagePreviewAccessoryPanelNode: AccessoryPanelNode { var theme: PresentationTheme var strings: PresentationStrings - init(account: Account, url: String, webpage: TelegramMediaWebpage, theme: PresentationTheme, strings: PresentationStrings) { + init(context: AccountContext, url: String, webpage: TelegramMediaWebpage, theme: PresentationTheme, strings: PresentationStrings) { self.url = url self.webpage = webpage self.theme = theme